mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-16 07:35:16 +00:00
Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| cf6f1c2878 | |||
| e38caf78ff | |||
| 0a8dd67541 | |||
| ed684c19a9 | |||
| 52ab3681e3 | |||
| 9cc5a787e9 | |||
| 0003030bf5 | |||
| 9ad8f45d38 | |||
| a3855257c8 | |||
| 9169c2f053 | |||
| abe028bd38 | |||
| 12c2451f4f | |||
| 8daede5427 | |||
| 4c89aa60eb | |||
| d0a3f64ae4 |
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': minor
|
||||
---
|
||||
|
||||
Implement AI actions dropdown
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Reposition AI Actions dropdown
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Ensure all content links are resolved relatively to preview.
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'gitbook': patch
|
||||
---
|
||||
|
||||
Move AI Actions markdown fetching to client-side
|
||||
@@ -0,0 +1,5 @@
|
||||
---
|
||||
"gitbook": patch
|
||||
---
|
||||
|
||||
Generalise keyboard shortcuts, add Cmd+J to AI Chat
|
||||
@@ -37,7 +37,7 @@
|
||||
},
|
||||
"packages/fonts": {
|
||||
"name": "@gitbook/fonts",
|
||||
"version": "0.0.0",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"@gitbook/api": "catalog:",
|
||||
},
|
||||
@@ -48,7 +48,7 @@
|
||||
},
|
||||
"packages/gitbook": {
|
||||
"name": "gitbook",
|
||||
"version": "0.12.0",
|
||||
"version": "0.13.1",
|
||||
"dependencies": {
|
||||
"@gitbook/api": "catalog:",
|
||||
"@gitbook/cache-tags": "workspace:*",
|
||||
@@ -60,7 +60,7 @@
|
||||
"@gitbook/react-contentkit": "workspace:*",
|
||||
"@gitbook/react-math": "workspace:*",
|
||||
"@gitbook/react-openapi": "workspace:*",
|
||||
"@opennextjs/cloudflare": "1.2.1",
|
||||
"@opennextjs/cloudflare": "^1.4.0",
|
||||
"@radix-ui/react-checkbox": "^1.0.4",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.12",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.3",
|
||||
@@ -69,6 +69,7 @@
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tailwindcss/typography": "^0.5.16",
|
||||
"@tusbar/cache-control": "^1.0.2",
|
||||
"ai": "^4.2.2",
|
||||
"assert-never": "^1.2.1",
|
||||
"bun-types": "^1.1.20",
|
||||
@@ -96,9 +97,6 @@
|
||||
"object-identity": "^0.1.2",
|
||||
"openapi-types": "^12.1.3",
|
||||
"p-map": "^7.0.3",
|
||||
"parse-cache-control": "^1.0.1",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"react-hotkeys-hook": "^4.4.1",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"rehype-stringify": "^10.0.1",
|
||||
@@ -167,7 +165,7 @@
|
||||
},
|
||||
"packages/openapi-parser": {
|
||||
"name": "@gitbook/openapi-parser",
|
||||
"version": "2.1.4",
|
||||
"version": "2.2.0",
|
||||
"dependencies": {
|
||||
"@scalar/openapi-parser": "^0.18.0",
|
||||
"@scalar/openapi-types": "^0.1.9",
|
||||
@@ -182,7 +180,7 @@
|
||||
},
|
||||
"packages/react-contentkit": {
|
||||
"name": "@gitbook/react-contentkit",
|
||||
"version": "0.7.0",
|
||||
"version": "0.7.1",
|
||||
"dependencies": {
|
||||
"@gitbook/api": "catalog:",
|
||||
"@gitbook/icons": "workspace:*",
|
||||
@@ -214,7 +212,7 @@
|
||||
},
|
||||
"packages/react-openapi": {
|
||||
"name": "@gitbook/react-openapi",
|
||||
"version": "1.3.0",
|
||||
"version": "1.3.2",
|
||||
"dependencies": {
|
||||
"@gitbook/openapi-parser": "workspace:*",
|
||||
"@scalar/api-client-react": "^1.3.16",
|
||||
@@ -788,9 +786,9 @@
|
||||
|
||||
"@octokit/types": ["@octokit/types@14.1.0", "", { "dependencies": { "@octokit/openapi-types": "^25.1.0" } }, "sha512-1y6DgTy8Jomcpu33N+p5w58l6xyt55Ar2I91RPiIA0xCJBXyUAhXCcmZaDWSANiha7R9a6qJJ2CRomGPZ6f46g=="],
|
||||
|
||||
"@opennextjs/aws": ["@opennextjs/aws@3.6.5", "", { "dependencies": { "@ast-grep/napi": "^0.35.0", "@aws-sdk/client-cloudfront": "3.398.0", "@aws-sdk/client-dynamodb": "^3.398.0", "@aws-sdk/client-lambda": "^3.398.0", "@aws-sdk/client-s3": "^3.398.0", "@aws-sdk/client-sqs": "^3.398.0", "@node-minify/core": "^8.0.6", "@node-minify/terser": "^8.0.6", "@tsconfig/node18": "^1.0.1", "aws4fetch": "^1.0.18", "chalk": "^5.3.0", "cookie": "^1.0.2", "esbuild": "0.25.4", "express": "5.0.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.0.0", "yaml": "^2.7.0" }, "bin": { "open-next": "dist/index.js" } }, "sha512-wni+CWlRCyWfhNfekQBBPPkrDDnaGdZLN9hMybKI0wKOKTO+zhPOqR65Eh3V0pzWAi84Sureb5mdMuLwCxAAcw=="],
|
||||
"@opennextjs/aws": ["@opennextjs/aws@3.7.0", "", { "dependencies": { "@ast-grep/napi": "^0.35.0", "@aws-sdk/client-cloudfront": "3.398.0", "@aws-sdk/client-dynamodb": "^3.398.0", "@aws-sdk/client-lambda": "^3.398.0", "@aws-sdk/client-s3": "^3.398.0", "@aws-sdk/client-sqs": "^3.398.0", "@node-minify/core": "^8.0.6", "@node-minify/terser": "^8.0.6", "@tsconfig/node18": "^1.0.1", "aws4fetch": "^1.0.18", "chalk": "^5.3.0", "cookie": "^1.0.2", "esbuild": "0.25.4", "express": "5.0.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.0.0", "yaml": "^2.7.0" }, "bin": { "open-next": "dist/index.js" } }, "sha512-JXUZice+CedEQW20hnBVqzBEj+jfr4Oe2LVYSE4RNKdfHVIeYG+WJAop14TxRJ+NugKWGcJx6opf944l+ZG7XQ=="],
|
||||
|
||||
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.2.1", "", { "dependencies": { "@dotenvx/dotenvx": "1.31.0", "@opennextjs/aws": "3.6.5", "enquirer": "^2.4.1", "glob": "^11.0.0", "ts-tqdm": "^0.8.6" }, "peerDependencies": { "wrangler": "^4.19.1" }, "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-cOco+nHwlo/PLB1bThF8IIvaS8PgAT9MEI5ZttFO/qt6spgvr2lUaPkpjgSIQmI3sBIEG2cLUykvQ2nbbZEcVw=="],
|
||||
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.4.0", "", { "dependencies": { "@dotenvx/dotenvx": "1.31.0", "@opennextjs/aws": "3.7.0", "enquirer": "^2.4.1", "glob": "^11.0.0", "ts-tqdm": "^0.8.6" }, "peerDependencies": { "wrangler": "^4.19.1" }, "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-nEtxmSo6/y83Qw2TSU8rBpljaGl3NUl5GenD/c71h6YqgbP4QURSxMh7ySe7KK+vtQbilD7WePXovqL4Y6D6dw=="],
|
||||
|
||||
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
|
||||
|
||||
@@ -1272,6 +1270,8 @@
|
||||
|
||||
"@tsconfig/strictest": ["@tsconfig/strictest@2.0.5", "", {}, "sha512-ec4tjL2Rr0pkZ5hww65c+EEPYwxOi4Ryv+0MtjeaSQRJyq322Q27eOQiFbuNgw2hpL4hB1/W/HBGk3VKS43osg=="],
|
||||
|
||||
"@tusbar/cache-control": ["@tusbar/cache-control@1.0.2", "", {}, "sha512-PXfjYTYBVvMPYCLDWj+xIOA9ITFbbhWCHzLcqUCJ5TPGm4JO4cxpGb7x3K8Q1K1ADgNgfBxLsDcTMVRydtZB9A=="],
|
||||
|
||||
"@types/debug": ["@types/debug@4.1.12", "", { "dependencies": { "@types/ms": "*" } }, "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ=="],
|
||||
|
||||
"@types/diff-match-patch": ["@types/diff-match-patch@1.0.36", "", {}, "sha512-xFdR6tkm0MWvBfO8xXCSsinYxHcqkQUlcHeSpMC2ukzOb6lwQAfDmW+Qt0AvlGd8HpsS28qKsB+oPeJn9I39jg=="],
|
||||
@@ -2412,8 +2412,6 @@
|
||||
|
||||
"parent-module": ["parent-module@1.0.1", "", { "dependencies": { "callsites": "^3.0.0" } }, "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g=="],
|
||||
|
||||
"parse-cache-control": ["parse-cache-control@1.0.1", "", {}, "sha512-60zvsJReQPX5/QP0Kzfd/VrpjScIQ7SHBW6bFCYfEP+fp0Eppr1SHhIO5nd1PjZtvclzSzES9D/p5nFJurwfWg=="],
|
||||
|
||||
"parse-json": ["parse-json@5.2.0", "", { "dependencies": { "@babel/code-frame": "^7.0.0", "error-ex": "^1.3.1", "json-parse-even-better-errors": "^2.3.0", "lines-and-columns": "^1.1.6" } }, "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg=="],
|
||||
|
||||
"parse-ms": ["parse-ms@2.1.0", "", {}, "sha512-kHt7kzLoS9VBZfUsiKjv43mr91ea+U05EyKkEtqp7vNbHxmaVuEqN7XxeEVnGrMtYOAxGrDElSi96K7EgO1zCA=="],
|
||||
|
||||
@@ -415,6 +415,28 @@ const testCases: TestsCase[] = [
|
||||
await expect(page.locator('[data-testid="table-of-contents"]')).toBeVisible();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'With sections',
|
||||
url: async () => {
|
||||
const data = await getSiteAPIToken('https://gitbook.com/docs');
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('token', data.apiToken);
|
||||
|
||||
return `url/preview/${data.site}/?${searchParams.toString()}`;
|
||||
},
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const sectionTabs = page.getByLabel('Sections');
|
||||
await expect(sectionTabs).toBeVisible();
|
||||
|
||||
const sectionTabLinks = sectionTabs.getByRole('link');
|
||||
for (const link of await sectionTabLinks.all()) {
|
||||
const href = await link.getAttribute('href');
|
||||
expect(href).toMatch(/^\/url\/preview\/site_p4Xo4\/?/);
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
|
||||
@@ -16,7 +16,8 @@
|
||||
"env": {
|
||||
"dev": {
|
||||
"vars": {
|
||||
"STAGE": "dev"
|
||||
"STAGE": "dev",
|
||||
"OPEN_NEXT_REQUEST_ID_HEADER": "true"
|
||||
},
|
||||
"r2_buckets": [
|
||||
{
|
||||
@@ -84,6 +85,9 @@
|
||||
}
|
||||
},
|
||||
"staging": {
|
||||
"vars": {
|
||||
"OPEN_NEXT_REQUEST_ID_HEADER": "true"
|
||||
},
|
||||
"r2_buckets": [
|
||||
{
|
||||
"binding": "NEXT_INC_CACHE_R2_BUCKET",
|
||||
@@ -125,7 +129,8 @@
|
||||
"vars": {
|
||||
// This is a bit misleading, but it means that we can have 500 concurrent revalidations
|
||||
// This means that we'll have up to 100 durable objects instance running at the same time
|
||||
"MAX_REVALIDATE_CONCURRENCY": "100"
|
||||
"MAX_REVALIDATE_CONCURRENCY": "100",
|
||||
"OPEN_NEXT_REQUEST_ID_HEADER": "true"
|
||||
},
|
||||
"r2_buckets": [
|
||||
{
|
||||
|
||||
@@ -21,7 +21,8 @@
|
||||
"dev": {
|
||||
"vars": {
|
||||
"STAGE": "dev",
|
||||
"NEXT_PRIVATE_DEBUG_CACHE": "true"
|
||||
"NEXT_PRIVATE_DEBUG_CACHE": "true",
|
||||
"OPEN_NEXT_REQUEST_ID_HEADER": "true"
|
||||
},
|
||||
"r2_buckets": [
|
||||
{
|
||||
@@ -85,7 +86,8 @@
|
||||
"staging": {
|
||||
"vars": {
|
||||
"STAGE": "staging",
|
||||
"WORKER_VERSION_ID": "TO_REPLACE"
|
||||
"WORKER_VERSION_ID": "TO_REPLACE",
|
||||
"OPEN_NEXT_REQUEST_ID_HEADER": "true"
|
||||
},
|
||||
"routes": [
|
||||
{
|
||||
@@ -153,7 +155,8 @@
|
||||
// TODO: remove this once the issue is fixed
|
||||
"DEBUG_CLOUDFLARE": "true",
|
||||
"WORKER_VERSION_ID": "TO_REPLACE",
|
||||
"STAGE": "production"
|
||||
"STAGE": "production",
|
||||
"OPEN_NEXT_REQUEST_ID_HEADER": "true"
|
||||
},
|
||||
"routes": [
|
||||
{
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import { trace } from '@/lib/tracing';
|
||||
import type {
|
||||
CacheEntryType,
|
||||
CacheValue,
|
||||
@@ -34,41 +32,31 @@ class GitbookIncrementalCache implements IncrementalCache {
|
||||
cacheType?: CacheType
|
||||
): Promise<WithLastModified<CacheValue<CacheType>> | null> {
|
||||
const cacheKey = this.getR2Key(key, cacheType);
|
||||
return trace(
|
||||
{
|
||||
operation: 'openNextIncrementalCacheGet',
|
||||
name: cacheKey,
|
||||
},
|
||||
async (span) => {
|
||||
span.setAttribute('cacheType', cacheType ?? 'cache');
|
||||
const r2 = getCloudflareContext().env[BINDING_NAME];
|
||||
const localCache = await this.getCacheInstance();
|
||||
if (!r2) throw new Error('No R2 bucket');
|
||||
try {
|
||||
// Check local cache first if available
|
||||
const localCacheEntry = await localCache.match(this.getCacheUrlKey(cacheKey));
|
||||
if (localCacheEntry) {
|
||||
span.setAttribute('cacheHit', 'local');
|
||||
const result = (await localCacheEntry.json()) as WithLastModified<
|
||||
CacheValue<CacheType>
|
||||
>;
|
||||
return this.returnNullOn404(result);
|
||||
}
|
||||
|
||||
const r2Object = await r2.get(cacheKey);
|
||||
if (!r2Object) return null;
|
||||
|
||||
span.setAttribute('cacheHit', 'r2');
|
||||
return this.returnNullOn404({
|
||||
value: await r2Object.json(),
|
||||
lastModified: r2Object.uploaded.getTime(),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to get from cache', e);
|
||||
return null;
|
||||
}
|
||||
const r2 = getCloudflareContext().env[BINDING_NAME];
|
||||
const localCache = await this.getCacheInstance();
|
||||
if (!r2) throw new Error('No R2 bucket');
|
||||
try {
|
||||
// Check local cache first if available
|
||||
const localCacheEntry = await localCache.match(this.getCacheUrlKey(cacheKey));
|
||||
if (localCacheEntry) {
|
||||
const result = (await localCacheEntry.json()) as WithLastModified<
|
||||
CacheValue<CacheType>
|
||||
>;
|
||||
return this.returnNullOn404(result);
|
||||
}
|
||||
);
|
||||
|
||||
const r2Object = await r2.get(cacheKey);
|
||||
if (!r2Object) return null;
|
||||
|
||||
return this.returnNullOn404({
|
||||
value: await r2Object.json(),
|
||||
lastModified: r2Object.uploaded.getTime(),
|
||||
});
|
||||
} catch (e) {
|
||||
console.error('Failed to get from cache', e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: This is a workaround to handle 404 responses in the cache.
|
||||
@@ -89,75 +77,60 @@ class GitbookIncrementalCache implements IncrementalCache {
|
||||
cacheType?: CacheType
|
||||
): Promise<void> {
|
||||
const cacheKey = this.getR2Key(key, cacheType);
|
||||
return trace(
|
||||
{
|
||||
operation: 'openNextIncrementalCacheSet',
|
||||
name: cacheKey,
|
||||
},
|
||||
async (span) => {
|
||||
span.setAttribute('cacheType', cacheType ?? 'cache');
|
||||
const localCache = await this.getCacheInstance();
|
||||
|
||||
try {
|
||||
await this.writeToR2(cacheKey, JSON.stringify(value));
|
||||
const localCache = await this.getCacheInstance();
|
||||
|
||||
//TODO: Check if there is any places where we don't have tags
|
||||
// Ideally we should always have tags, but in case we don't, we need to decide how to handle it
|
||||
// For now we default to a build ID tag, which allow us to invalidate the cache in case something is wrong in this deployment
|
||||
const tags = this.getTagsFromCacheEntry(value) ?? [
|
||||
`build_id/${process.env.NEXT_BUILD_ID}`,
|
||||
];
|
||||
try {
|
||||
await this.writeToR2(cacheKey, JSON.stringify(value));
|
||||
|
||||
// We consider R2 as the source of truth, so we update the local cache
|
||||
// only after a successful R2 write
|
||||
await localCache.put(
|
||||
this.getCacheUrlKey(cacheKey),
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
value,
|
||||
// Note: `Date.now()` returns the time of the last IO rather than the actual time.
|
||||
// See https://developers.cloudflare.com/workers/reference/security-model/
|
||||
lastModified: Date.now(),
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
// Cache-Control default to 30 minutes, will be overridden by `revalidate`
|
||||
// In theory we should always get the `revalidate` value
|
||||
'cache-control': `max-age=${value.revalidate ?? 60 * 30}`,
|
||||
'cache-tag': tags.join(','),
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
} catch (e) {
|
||||
console.error('Failed to set to cache', e);
|
||||
}
|
||||
}
|
||||
);
|
||||
//TODO: Check if there is any places where we don't have tags
|
||||
// Ideally we should always have tags, but in case we don't, we need to decide how to handle it
|
||||
// For now we default to a build ID tag, which allow us to invalidate the cache in case something is wrong in this deployment
|
||||
const tags = this.getTagsFromCacheEntry(value) ?? [
|
||||
`build_id/${process.env.NEXT_BUILD_ID}`,
|
||||
];
|
||||
|
||||
// We consider R2 as the source of truth, so we update the local cache
|
||||
// only after a successful R2 write
|
||||
await localCache.put(
|
||||
this.getCacheUrlKey(cacheKey),
|
||||
new Response(
|
||||
JSON.stringify({
|
||||
value,
|
||||
// Note: `Date.now()` returns the time of the last IO rather than the actual time.
|
||||
// See https://developers.cloudflare.com/workers/reference/security-model/
|
||||
lastModified: Date.now(),
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
// Cache-Control default to 30 minutes, will be overridden by `revalidate`
|
||||
// In theory we should always get the `revalidate` value
|
||||
'cache-control': `max-age=${value.revalidate ?? 60 * 30}`,
|
||||
'cache-tag': tags.join(','),
|
||||
},
|
||||
}
|
||||
)
|
||||
);
|
||||
} catch (e) {
|
||||
console.error('Failed to set to cache', e);
|
||||
}
|
||||
}
|
||||
|
||||
async delete(key: string): Promise<void> {
|
||||
const cacheKey = this.getR2Key(key);
|
||||
return trace(
|
||||
{
|
||||
operation: 'openNextIncrementalCacheDelete',
|
||||
name: cacheKey,
|
||||
},
|
||||
async () => {
|
||||
const r2 = getCloudflareContext().env[BINDING_NAME];
|
||||
const localCache = await this.getCacheInstance();
|
||||
if (!r2) throw new Error('No R2 bucket');
|
||||
|
||||
try {
|
||||
await r2.delete(cacheKey);
|
||||
const r2 = getCloudflareContext().env[BINDING_NAME];
|
||||
const localCache = await this.getCacheInstance();
|
||||
if (!r2) throw new Error('No R2 bucket');
|
||||
|
||||
// Here again R2 is the source of truth, so we delete from local cache first
|
||||
await localCache.delete(this.getCacheUrlKey(cacheKey));
|
||||
} catch (e) {
|
||||
console.error('Failed to delete from cache', e);
|
||||
}
|
||||
}
|
||||
);
|
||||
try {
|
||||
await r2.delete(cacheKey);
|
||||
|
||||
// Here again R2 is the source of truth, so we delete from local cache first
|
||||
await localCache.delete(this.getCacheUrlKey(cacheKey));
|
||||
} catch (e) {
|
||||
console.error('Failed to delete from cache', e);
|
||||
}
|
||||
}
|
||||
|
||||
async writeToR2(key: string, value: string): Promise<void> {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { trace } from '@/lib/tracing';
|
||||
import type { Queue } from '@opennextjs/aws/types/overrides.js';
|
||||
import { getCloudflareContext } from '@opennextjs/cloudflare';
|
||||
import doQueue from '@opennextjs/cloudflare/overrides/queue/do-queue';
|
||||
@@ -6,9 +5,7 @@ import doQueue from '@opennextjs/cloudflare/overrides/queue/do-queue';
|
||||
export default {
|
||||
name: 'GitbookISRQueue',
|
||||
send: async (msg) => {
|
||||
return trace({ operation: 'gitbookISRQueueSend', name: msg.MessageBody.url }, async () => {
|
||||
const { ctx } = getCloudflareContext();
|
||||
ctx.waitUntil(doQueue.send(msg));
|
||||
});
|
||||
const { ctx } = getCloudflareContext();
|
||||
ctx.waitUntil(doQueue.send(msg));
|
||||
},
|
||||
} satisfies Queue;
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import type { Queue } from '@opennextjs/aws/types/overrides.js';
|
||||
|
||||
export default {
|
||||
name: 'GitbookISRQueue',
|
||||
send: async (msg) => {
|
||||
const logger = getLogger().subLogger('GitbookISRQueue');
|
||||
// We should never reach this point in the server. If that's the case, we should log it.
|
||||
console.warn('GitbookISRQueue: send called on server side, this should not happen.', msg);
|
||||
logger.warn('send called on server side, this should not happen.', msg);
|
||||
},
|
||||
} satisfies Queue;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { trace } from '@/lib/tracing';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import type { NextModeTagCache } from '@opennextjs/aws/types/overrides.js';
|
||||
import doShardedTagCache from '@opennextjs/cloudflare/overrides/tag-cache/do-sharded-tag-cache';
|
||||
import { softTagFilter } from '@opennextjs/cloudflare/overrides/tag-cache/tag-cache-filter';
|
||||
@@ -23,59 +23,27 @@ export default {
|
||||
getLastRevalidated: async (tags: string[]) => {
|
||||
const tagsToCheck = tags.filter(softTagFilter);
|
||||
if (tagsToCheck.length === 0) {
|
||||
// If we reach here, it probably means that there is an issue that we'll need to address.
|
||||
console.warn(
|
||||
'getLastRevalidated - No valid tags to check for last revalidation, original tags:',
|
||||
tags
|
||||
);
|
||||
return 0; // If no tags to check, return 0
|
||||
}
|
||||
return trace(
|
||||
{
|
||||
operation: 'gitbookTagCacheGetLastRevalidated',
|
||||
name: tagsToCheck.join(', '),
|
||||
},
|
||||
async () => {
|
||||
return await originalTagCache.getLastRevalidated(tagsToCheck);
|
||||
}
|
||||
);
|
||||
|
||||
return await originalTagCache.getLastRevalidated(tagsToCheck);
|
||||
},
|
||||
hasBeenRevalidated: async (tags: string[], lastModified?: number) => {
|
||||
const tagsToCheck = tags.filter(softTagFilter);
|
||||
if (tagsToCheck.length === 0) {
|
||||
// If we reach here, it probably means that there is an issue that we'll need to address.
|
||||
console.warn(
|
||||
'hasBeenRevalidated - No valid tags to check for revalidation, original tags:',
|
||||
tags
|
||||
);
|
||||
return false; // If no tags to check, return false
|
||||
}
|
||||
return trace(
|
||||
{
|
||||
operation: 'gitbookTagCacheHasBeenRevalidated',
|
||||
name: tagsToCheck.join(', '),
|
||||
},
|
||||
async () => {
|
||||
const result = await originalTagCache.hasBeenRevalidated(tagsToCheck, lastModified);
|
||||
return result;
|
||||
}
|
||||
);
|
||||
|
||||
return await originalTagCache.hasBeenRevalidated(tagsToCheck, lastModified);
|
||||
},
|
||||
writeTags: async (tags: string[]) => {
|
||||
return trace(
|
||||
{
|
||||
operation: 'gitbookTagCacheWriteTags',
|
||||
name: tags.join(', '),
|
||||
},
|
||||
async () => {
|
||||
const tagsToWrite = tags.filter(softTagFilter);
|
||||
if (tagsToWrite.length === 0) {
|
||||
console.warn('writeTags - No valid tags to write');
|
||||
return; // If no tags to write, exit early
|
||||
}
|
||||
// Write only the filtered tags
|
||||
await originalTagCache.writeTags(tagsToWrite);
|
||||
}
|
||||
);
|
||||
const tagsToWrite = tags.filter(softTagFilter);
|
||||
if (tagsToWrite.length === 0) {
|
||||
const logger = getLogger().subLogger('gitbookTagCache');
|
||||
logger.warn('writeTags - No valid tags to write');
|
||||
return; // If no tags to write, exit early
|
||||
}
|
||||
// Write only the filtered tags
|
||||
await originalTagCache.writeTags(tagsToWrite);
|
||||
},
|
||||
} satisfies NextModeTagCache;
|
||||
|
||||
@@ -5,71 +5,69 @@
|
||||
"dependencies": {
|
||||
"@gitbook/api": "catalog:",
|
||||
"@gitbook/cache-tags": "workspace:*",
|
||||
"@opennextjs/cloudflare": "1.2.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"assert-never": "^1.2.1",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"next": "^15.3.2",
|
||||
"react": "^19.0.0",
|
||||
"react-dom": "^19.0.0",
|
||||
"rison": "^0.1.1",
|
||||
"server-only": "^0.0.1",
|
||||
"warn-once": "^0.1.1",
|
||||
"object-identity": "^0.1.2",
|
||||
"@gitbook/colors": "workspace:*",
|
||||
"@gitbook/emoji-codepoints": "workspace:*",
|
||||
"@gitbook/icons": "workspace:*",
|
||||
"@gitbook/fonts": "workspace:*",
|
||||
"@gitbook/icons": "workspace:*",
|
||||
"@gitbook/openapi-parser": "workspace:*",
|
||||
"@gitbook/react-contentkit": "workspace:*",
|
||||
"@gitbook/react-math": "workspace:*",
|
||||
"@gitbook/react-openapi": "workspace:*",
|
||||
"@opennextjs/cloudflare": "^1.4.0",
|
||||
"@radix-ui/react-checkbox": "^1.0.4",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.12",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.3",
|
||||
"@radix-ui/react-popover": "^1.0.7",
|
||||
"@radix-ui/react-tooltip": "^1.1.8",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tailwindcss/typography": "^0.5.16",
|
||||
"ai": "^4.2.2",
|
||||
"assert-never": "^1.2.1",
|
||||
"bun-types": "^1.1.20",
|
||||
"classnames": "^2.5.1",
|
||||
"direction": "^2.0.1",
|
||||
"event-iterator": "^2.0.0",
|
||||
"framer-motion": "^10.16.14",
|
||||
"image-size": "^2.0.2",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jsontoxml": "^1.0.1",
|
||||
"jwt-decode": "^4.0.0",
|
||||
"katex": "^0.16.9",
|
||||
"mathjax": "^3.2.2",
|
||||
"mdast-util-to-markdown": "^2.1.2",
|
||||
"mdast-util-from-markdown": "^2.0.2",
|
||||
"mdast-util-frontmatter": "^2.0.1",
|
||||
"mdast-util-gfm": "^3.1.0",
|
||||
"micromark-extension-gfm": "^3.0.0",
|
||||
"micromark-extension-frontmatter": "^2.0.0",
|
||||
"unist-util-remove": "^4.0.0",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"mdast-util-to-markdown": "^2.1.2",
|
||||
"memoizee": "^0.4.17",
|
||||
"micromark-extension-frontmatter": "^2.0.0",
|
||||
"micromark-extension-gfm": "^3.0.0",
|
||||
"next": "^15.3.2",
|
||||
"next-themes": "^0.2.1",
|
||||
"nuqs": "^2.2.3",
|
||||
"object-hash": "^3.0.0",
|
||||
"object-identity": "^0.1.2",
|
||||
"openapi-types": "^12.1.3",
|
||||
"p-map": "^7.0.3",
|
||||
"parse-cache-control": "^1.0.1",
|
||||
"@tusbar/cache-control": "^1.0.2",
|
||||
"react-hotkeys-hook": "^4.4.1",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"rehype-stringify": "^10.0.1",
|
||||
"remark-gfm": "^4.0.1",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.1",
|
||||
"rison": "^0.1.1",
|
||||
"server-only": "^0.0.1",
|
||||
"shiki": "^3.2.0",
|
||||
"tailwind-merge": "^2.2.0",
|
||||
"tailwind-shades": "^1.1.2",
|
||||
"unified": "^11.0.5",
|
||||
"unist-util-remove": "^4.0.0",
|
||||
"unist-util-visit": "^5.0.0",
|
||||
"url-join": "^5.0.0",
|
||||
"usehooks-ts": "^3.1.0",
|
||||
"zustand": "^5.0.3",
|
||||
"image-size": "^2.0.2",
|
||||
"direction": "^2.0.1"
|
||||
"warn-once": "^0.1.1",
|
||||
"zustand": "^5.0.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^5.0.5",
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { type NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { withVerifySignature } from '@/lib/routes';
|
||||
import { revalidateTag } from 'next/cache';
|
||||
|
||||
@@ -12,6 +13,7 @@ interface JsonBody {
|
||||
* The body should be a JSON with { tags: string[] }
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const logger = getLogger().subLogger('revalidate');
|
||||
return withVerifySignature<JsonBody>(req, async (body) => {
|
||||
if (!body.tags || !Array.isArray(body.tags)) {
|
||||
return NextResponse.json(
|
||||
@@ -23,8 +25,7 @@ export async function POST(req: NextRequest) {
|
||||
}
|
||||
|
||||
body.tags.forEach((tag) => {
|
||||
// biome-ignore lint/suspicious/noConsole: we want to log here
|
||||
console.log(`Revalidating tag: ${tag}`);
|
||||
logger.log(`Revalidating tag: ${tag}`);
|
||||
revalidateTag(tag);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
'use client';
|
||||
|
||||
import { useAIChatController } from '@/components/AI/useAIChat';
|
||||
import { useAIChatState } from '@/components/AI/useAIChat';
|
||||
import { ChatGPTIcon } from '@/components/AIActions/assets/ChatGPTIcon';
|
||||
import { ClaudeIcon } from '@/components/AIActions/assets/ClaudeIcon';
|
||||
import { MarkdownIcon } from '@/components/AIActions/assets/MarkdownIcon';
|
||||
import { getAIChatName } from '@/components/AIChat';
|
||||
import AIChatIcon from '@/components/AIChat/AIChatIcon';
|
||||
import { Button } from '@/components/primitives/Button';
|
||||
import { DropdownMenuItem } from '@/components/primitives/DropdownMenu';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import type { TranslationLanguage } from '@/intl/translations';
|
||||
import { Icon, type IconName, IconStyle } from '@gitbook/icons';
|
||||
import assertNever from 'assert-never';
|
||||
import type React from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { create } from 'zustand';
|
||||
|
||||
type AIActionType = 'button' | 'dropdown-menu-item';
|
||||
|
||||
/**
|
||||
* Opens our AI Docs Assistant.
|
||||
*/
|
||||
export function OpenDocsAssistant(props: { type: AIActionType; trademark: boolean }) {
|
||||
const { type, trademark } = props;
|
||||
const chatController = useAIChatController();
|
||||
const chat = useAIChatState();
|
||||
const language = useLanguage();
|
||||
|
||||
return (
|
||||
<AIActionWrapper
|
||||
type={type}
|
||||
icon={
|
||||
<AIChatIcon state={chat.loading ? 'thinking' : 'default'} trademark={trademark} />
|
||||
}
|
||||
label={tString(language, 'ai_chat_ask', getAIChatName(trademark))}
|
||||
shortLabel={tString(language, 'ask')}
|
||||
description={tString(language, 'ai_chat_ask_about_page', getAIChatName(trademark))}
|
||||
disabled={chat.loading}
|
||||
onClick={() => {
|
||||
// Open the chat if it's not already open
|
||||
if (!chat.opened) {
|
||||
chatController.open();
|
||||
}
|
||||
|
||||
// Send the "What is this page about?" message
|
||||
chatController.postMessage({
|
||||
message: tString(language, 'ai_chat_suggested_questions_about_this_page'),
|
||||
});
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// We need to store the copied state in a store to share the state between the
|
||||
// copy button and the dropdown menu item.
|
||||
const useCopiedStore = create<{
|
||||
copied: boolean;
|
||||
setCopied: (copied: boolean) => void;
|
||||
loading: boolean;
|
||||
setLoading: (loading: boolean) => void;
|
||||
}>((set) => ({
|
||||
copied: false,
|
||||
setCopied: (copied: boolean) => set({ copied }),
|
||||
loading: false,
|
||||
setLoading: (loading: boolean) => set({ loading }),
|
||||
}));
|
||||
|
||||
/**
|
||||
* Copies the markdown version of the page to the clipboard.
|
||||
*/
|
||||
export function CopyMarkdown(props: {
|
||||
markdownPageUrl: string;
|
||||
type: AIActionType;
|
||||
isDefaultAction?: boolean;
|
||||
}) {
|
||||
const { markdownPageUrl, type, isDefaultAction } = props;
|
||||
const language = useLanguage();
|
||||
const { copied, setCopied, loading, setLoading } = useCopiedStore();
|
||||
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
|
||||
// Close the dropdown menu manually after the copy button is clicked
|
||||
const closeDropdownMenu = () => {
|
||||
const dropdownMenu = document.querySelector('div[data-radix-popper-content-wrapper]');
|
||||
|
||||
// Cancel if no dropdown menu is open
|
||||
if (!dropdownMenu) return;
|
||||
|
||||
// Dispatch on `document` so that the event is captured by Radix's
|
||||
// dismissable-layer listener regardless of focus location.
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
|
||||
};
|
||||
|
||||
// Fetch the markdown from the page
|
||||
const fetchMarkdown = async () => {
|
||||
setLoading(true);
|
||||
|
||||
return fetch(markdownPageUrl)
|
||||
.then((res) => res.text())
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
// Reset the copied state when the component unmounts
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
if (timeoutRef.current) {
|
||||
clearTimeout(timeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []);
|
||||
|
||||
const onClick = async (e: React.MouseEvent) => {
|
||||
// Prevent default behavior for non-default actions to avoid closing the dropdown.
|
||||
// This allows showing transient UI (e.g., a "copied" state) inside the menu item.
|
||||
// Default action buttons are excluded from this behavior.
|
||||
if (!isDefaultAction) {
|
||||
e.preventDefault();
|
||||
}
|
||||
|
||||
const markdown = await fetchMarkdown();
|
||||
|
||||
navigator.clipboard.writeText(markdown);
|
||||
setCopied(true);
|
||||
|
||||
// Reset the copied state after 2 seconds
|
||||
timeoutRef.current = setTimeout(() => {
|
||||
// Close the dropdown menu if it's a dropdown menu item and not the default action
|
||||
if (type === 'dropdown-menu-item' && !isDefaultAction) {
|
||||
closeDropdownMenu();
|
||||
}
|
||||
|
||||
setCopied(false);
|
||||
}, 2000);
|
||||
};
|
||||
|
||||
return (
|
||||
<AIActionWrapper
|
||||
type={type}
|
||||
icon={copied ? 'check' : 'copy'}
|
||||
label={copied ? tString(language, 'code_copied') : tString(language, 'copy_page')}
|
||||
shortLabel={copied ? tString(language, 'code_copied') : tString(language, 'code_copy')}
|
||||
description={tString(language, 'copy_page_markdown')}
|
||||
onClick={onClick}
|
||||
loading={loading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirects to the markdown version of the page.
|
||||
*/
|
||||
export function ViewAsMarkdown(props: { markdownPageUrl: string; type: AIActionType }) {
|
||||
const { markdownPageUrl, type } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
return (
|
||||
<AIActionWrapper
|
||||
type={type}
|
||||
icon={<MarkdownIcon className="size-4 fill-current" />}
|
||||
label={tString(language, 'view_page_markdown')}
|
||||
description={tString(language, 'view_page_plaintext')}
|
||||
href={markdownPageUrl}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the page in a LLM with a pre-filled prompt. Either ChatGPT or Claude.
|
||||
*/
|
||||
export function OpenInLLM(props: {
|
||||
provider: 'chatgpt' | 'claude';
|
||||
url: string;
|
||||
type: AIActionType;
|
||||
}) {
|
||||
const { provider, url, type } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
const providerLabel = provider === 'chatgpt' ? 'ChatGPT' : 'Claude';
|
||||
|
||||
return (
|
||||
<AIActionWrapper
|
||||
type={type}
|
||||
icon={
|
||||
provider === 'chatgpt' ? (
|
||||
<ChatGPTIcon className="size-3.5 fill-current" />
|
||||
) : (
|
||||
<ClaudeIcon className="size-3.5 fill-current" />
|
||||
)
|
||||
}
|
||||
label={tString(language, 'open_in', providerLabel)}
|
||||
shortLabel={providerLabel}
|
||||
description={tString(language, 'ai_chat_ask_about_page', providerLabel)}
|
||||
href={getLLMURL(provider, url, language)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps an action in a button (for the default action) or dropdown menu item.
|
||||
*/
|
||||
function AIActionWrapper(props: {
|
||||
type: AIActionType;
|
||||
icon: IconName | React.ReactNode;
|
||||
label: string;
|
||||
/**
|
||||
* The label to display in the button. If not provided, the `label` will be used.
|
||||
*/
|
||||
shortLabel?: string;
|
||||
onClick?: (e: React.MouseEvent) => void;
|
||||
description?: string;
|
||||
href?: string;
|
||||
disabled?: boolean;
|
||||
loading?: boolean;
|
||||
}) {
|
||||
const { type, icon, label, shortLabel, onClick, href, description, disabled, loading } = props;
|
||||
|
||||
if (type === 'button') {
|
||||
return (
|
||||
<Button
|
||||
icon={
|
||||
loading ? <Icon icon="spinner-third" className="size-4 animate-spin" /> : icon
|
||||
}
|
||||
size="xsmall"
|
||||
variant="secondary"
|
||||
label={shortLabel || label}
|
||||
className="hover:!scale-100 !shadow-none !rounded-r-none border-r-0 bg-tint-base text-sm"
|
||||
onClick={onClick}
|
||||
href={href}
|
||||
target={href ? '_blank' : undefined}
|
||||
disabled={disabled || loading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
className="flex items-stretch gap-2.5 p-2"
|
||||
href={href}
|
||||
target="_blank"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
>
|
||||
{icon ? (
|
||||
<div className="flex size-5 items-center justify-center text-tint">
|
||||
{typeof icon === 'string' ? (
|
||||
<Icon
|
||||
icon={icon as IconName}
|
||||
iconStyle={IconStyle.Regular}
|
||||
className="size-4 fill-transparent stroke-current"
|
||||
/>
|
||||
) : (
|
||||
icon
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="flex flex-1 flex-col gap-0.5">
|
||||
<span className="flex items-center gap-2 text-tint-strong">
|
||||
<span className="truncate font-medium text-sm">{label}</span>
|
||||
{href ? <Icon icon="arrow-up-right" className="size-3" /> : null}
|
||||
</span>
|
||||
{description && <span className="truncate text-tint text-xs">{description}</span>}
|
||||
</div>
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the URL to open the page in a LLM with a pre-filled prompt.
|
||||
*/
|
||||
function getLLMURL(provider: 'chatgpt' | 'claude', url: string, language: TranslationLanguage) {
|
||||
const prompt = encodeURIComponent(tString(language, 'open_in_llms_pre_prompt', url));
|
||||
|
||||
switch (provider) {
|
||||
case 'chatgpt':
|
||||
return `https://chat.openai.com/?q=${prompt}`;
|
||||
case 'claude':
|
||||
return `https://claude.ai/new?q=${prompt}`;
|
||||
default:
|
||||
assertNever(provider);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
'use client';
|
||||
|
||||
import {
|
||||
CopyMarkdown,
|
||||
OpenDocsAssistant,
|
||||
OpenInLLM,
|
||||
ViewAsMarkdown,
|
||||
} from '@/components/AIActions/AIActions';
|
||||
import { Button } from '@/components/primitives/Button';
|
||||
import { DropdownMenu } from '@/components/primitives/DropdownMenu';
|
||||
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { useRef } from 'react';
|
||||
|
||||
/**
|
||||
* Dropdown menu for the AI Actions (Ask Docs Assistant, Copy page, View as Markdown, Open in LLM).
|
||||
*/
|
||||
export function AIActionsDropdown(props: {
|
||||
markdownPageUrl: string;
|
||||
/**
|
||||
* Whether to include the "Ask Docs Assistant" entry in the dropdown menu.
|
||||
*/
|
||||
withAIChat?: boolean;
|
||||
pageURL: string;
|
||||
trademark: boolean;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
return (
|
||||
<div ref={ref} className="flex h-fit items-stretch justify-start">
|
||||
<DefaultAction {...props} />
|
||||
<DropdownMenu
|
||||
align="end"
|
||||
className="!min-w-60 max-w-max"
|
||||
button={
|
||||
<Button
|
||||
icon={
|
||||
<Icon
|
||||
icon="chevron-down"
|
||||
className="size-3 transition-transform group-data-[state=open]/button:rotate-180"
|
||||
/>
|
||||
}
|
||||
iconOnly
|
||||
size="xsmall"
|
||||
variant="secondary"
|
||||
className="hover:!scale-100 !shadow-none !rounded-l-none bg-tint-base text-sm"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<AIActionsDropdownMenuContent {...props} />
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The content of the dropdown menu.
|
||||
*/
|
||||
function AIActionsDropdownMenuContent(props: {
|
||||
markdownPageUrl: string;
|
||||
withAIChat?: boolean;
|
||||
pageURL: string;
|
||||
trademark: boolean;
|
||||
}) {
|
||||
const { markdownPageUrl, withAIChat, pageURL, trademark } = props;
|
||||
|
||||
return (
|
||||
<>
|
||||
{withAIChat ? (
|
||||
<OpenDocsAssistant trademark={trademark} type="dropdown-menu-item" />
|
||||
) : null}
|
||||
|
||||
<CopyMarkdown
|
||||
isDefaultAction={!withAIChat}
|
||||
markdownPageUrl={markdownPageUrl}
|
||||
type="dropdown-menu-item"
|
||||
/>
|
||||
<ViewAsMarkdown markdownPageUrl={markdownPageUrl} type="dropdown-menu-item" />
|
||||
|
||||
<OpenInLLM provider="chatgpt" url={pageURL} type="dropdown-menu-item" />
|
||||
<OpenInLLM provider="claude" url={pageURL} type="dropdown-menu-item" />
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A default action shown as a quick-access button beside the dropdown menu
|
||||
*/
|
||||
function DefaultAction(props: {
|
||||
markdownPageUrl: string;
|
||||
withAIChat?: boolean;
|
||||
trademark: boolean;
|
||||
}) {
|
||||
const { markdownPageUrl, withAIChat, trademark } = props;
|
||||
|
||||
if (withAIChat) {
|
||||
return <OpenDocsAssistant trademark={trademark} type="button" />;
|
||||
}
|
||||
|
||||
return (
|
||||
<CopyMarkdown
|
||||
isDefaultAction={!withAIChat}
|
||||
markdownPageUrl={markdownPageUrl}
|
||||
type="button"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
export function ChatGPTIcon(props: React.SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 320 320" {...props}>
|
||||
<title>ChatGPT</title>
|
||||
<path d="m297.06 130.97c7.26-21.79 4.76-45.66-6.85-65.48-17.46-30.4-52.56-46.04-86.84-38.68-15.25-17.18-37.16-26.95-60.13-26.81-35.04-.08-66.13 22.48-76.91 55.82-22.51 4.61-41.94 18.7-53.31 38.67-17.59 30.32-13.58 68.54 9.92 94.54-7.26 21.79-4.76 45.66 6.85 65.48 17.46 30.4 52.56 46.04 86.84 38.68 15.24 17.18 37.16 26.95 60.13 26.8 35.06.09 66.16-22.49 76.94-55.86 22.51-4.61 41.94-18.7 53.31-38.67 17.57-30.32 13.55-68.51-9.94-94.51zm-120.28 168.11c-14.03.02-27.62-4.89-38.39-13.88.49-.26 1.34-.73 1.89-1.07l63.72-36.8c3.26-1.85 5.26-5.32 5.24-9.07v-89.83l26.93 15.55c.29.14.48.42.52.74v74.39c-.04 33.08-26.83 59.9-59.91 59.97zm-128.84-55.03c-7.03-12.14-9.56-26.37-7.15-40.18.47.28 1.3.79 1.89 1.13l63.72 36.8c3.23 1.89 7.23 1.89 10.47 0l77.79-44.92v31.1c.02.32-.13.63-.38.83l-64.41 37.19c-28.69 16.52-65.33 6.7-81.92-21.95zm-16.77-139.09c7-12.16 18.05-21.46 31.21-26.29 0 .55-.03 1.52-.03 2.2v73.61c-.02 3.74 1.98 7.21 5.23 9.06l77.79 44.91-26.93 15.55c-.27.18-.61.21-.91.08l-64.42-37.22c-28.63-16.58-38.45-53.21-21.95-81.89zm221.26 51.49-77.79-44.92 26.93-15.54c.27-.18.61-.21.91-.08l64.42 37.19c28.68 16.57 38.51 53.26 21.94 81.94-7.01 12.14-18.05 21.44-31.2 26.28v-75.81c.03-3.74-1.96-7.2-5.2-9.06zm26.8-40.34c-.47-.29-1.3-.79-1.89-1.13l-63.72-36.8c-3.23-1.89-7.23-1.89-10.47 0l-77.79 44.92v-31.1c-.02-.32.13-.63.38-.83l64.41-37.16c28.69-16.55 65.37-6.7 81.91 22 6.99 12.12 9.52 26.31 7.15 40.1zm-168.51 55.43-26.94-15.55c-.29-.14-.48-.42-.52-.74v-74.39c.02-33.12 26.89-59.96 60.01-59.94 14.01 0 27.57 4.92 38.34 13.88-.49.26-1.33.73-1.89 1.07l-63.72 36.8c-3.26 1.85-5.26 5.31-5.24 9.06l-.04 89.79zm14.63-31.54 34.65-20.01 34.65 20v40.01l-34.65 20-34.65-20z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
export function ClaudeIcon(props: React.SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 256 257"
|
||||
version="1.1"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
preserveAspectRatio="xMidYMid"
|
||||
{...props}
|
||||
>
|
||||
<title>Claude</title>
|
||||
<g>
|
||||
<path
|
||||
d="M50.2278481,170.321013 L100.585316,142.063797 L101.427848,139.601013 L100.585316,138.24 L98.1225316,138.24 L89.6972152,137.721519 L60.921519,136.943797 L35.9696203,135.906835 L11.795443,134.610633 L5.70329114,133.31443 L0,125.796456 L0.583291139,122.037468 L5.70329114,118.602532 L13.0268354,119.250633 L29.2293671,120.352405 L53.5331646,122.037468 L71.161519,123.07443 L97.28,125.796456 L101.427848,125.796456 L102.011139,124.111392 L100.585316,123.07443 L99.4835443,122.037468 L74.3372152,104.992405 L47.116962,86.9751899 L32.8587342,76.6055696 L25.1463291,71.3559494 L21.2577215,66.4303797 L19.5726582,55.6718987 L26.5721519,47.9594937 L35.9696203,48.6075949 L38.3675949,49.2556962 L47.8946835,56.5792405 L68.2450633,72.3281013 L94.8172152,91.9007595 L98.7058228,95.1412658 L100.261266,94.0394937 L100.455696,93.2617722 L98.7058228,90.3453165 L84.2531646,64.2268354 L68.8283544,37.6546835 L61.958481,26.636962 L60.1437975,20.0263291 C59.4956962,17.3043038 59.0420253,15.0359494 59.0420253,12.2491139 L67.0136709,1.42582278 L71.4207595,-1.42108547e-14 L82.0496203,1.42582278 L86.521519,5.31443038 L93.1321519,20.4151899 L103.825823,44.2005063 L120.417215,76.5407595 L125.277975,86.1326582 L127.87038,95.0116456 L128.842532,97.7336709 L130.527595,97.7336709 L130.527595,96.1782278 L131.888608,77.9665823 L134.416203,55.6070886 L136.878987,26.8313924 L137.721519,18.7301266 L141.739747,9.00860759 L149.711392,3.75898734 L155.933165,6.74025316 L161.053165,14.0637975 L160.340253,18.7949367 L157.294177,38.5620253 L151.331646,69.5412658 L147.443038,90.2805063 L149.711392,90.2805063 L152.303797,87.6881013 L162.803038,73.7539241 L180.431392,51.718481 L188.208608,42.9691139 L197.282025,33.3124051 L203.114937,28.7108861 L214.132658,28.7108861 L222.233924,40.7655696 L218.604557,53.2091139 L207.262785,67.596962 L197.865316,79.7812658 L184.38481,97.9281013 L175.959494,112.44557 L176.737215,113.612152 L178.746329,113.417722 L209.207089,106.936709 L225.668861,103.955443 L245.306329,100.585316 L254.185316,104.733165 L255.157468,108.945823 L251.657722,117.56557 L230.659241,122.75038 L206.031392,127.675949 L169.348861,136.360506 L168.89519,136.684557 L169.413671,137.332658 L185.940253,138.888101 L193.004557,139.276962 L210.308861,139.276962 L242.519494,141.674937 L250.94481,147.248608 L256,154.053671 L255.157468,159.238481 L242.195443,165.849114 L224.696709,161.701266 L183.866329,151.979747 L169.867342,148.48 L167.923038,148.48 L167.923038,149.646582 L179.588861,161.053165 L200.976203,180.366582 L227.742785,205.253671 L229.103797,211.410633 L225.668861,216.271392 L222.039494,215.752911 L198.513418,198.059747 L189.44,190.088101 L168.89519,172.783797 L167.534177,172.783797 L167.534177,174.598481 L172.265316,181.533165 L197.282025,219.123038 L198.578228,230.659241 L196.763544,234.418228 L190.282532,236.686582 L183.153418,235.39038 L168.506329,214.84557 L153.40557,191.708354 L141.221266,170.969114 L139.730633,171.811646 L132.536709,249.259747 L129.166582,253.213165 L121.389367,256.19443 L114.908354,251.268861 L111.473418,243.297215 L114.908354,227.548354 L119.056203,207.003544 L122.426329,190.671392 L125.472405,170.385823 L127.287089,163.64557 L127.157468,163.191899 L125.666835,163.386329 L110.371646,184.38481 L87.1048101,215.817722 L68.6987342,235.52 L64.2916456,237.269873 L56.6440506,233.316456 L57.356962,226.252152 L61.6344304,219.96557 L87.1048101,187.560506 L102.46481,167.469367 L112.380759,155.868354 L112.315949,154.183291 L111.732658,154.183291 L44.0708861,198.124557 L32.0162025,199.68 L26.8313924,194.819241 L27.4794937,186.847595 L29.9422785,184.25519 L50.2926582,170.256203 L50.2278481,170.321013 Z"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
export function MarkdownIcon(props: React.SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 471 289.85" {...props}>
|
||||
<title>Markdown</title>
|
||||
<path d="M437,289.85H34a34,34,0,0,1-34-34V34A34,34,0,0,1,34,0H437a34,34,0,0,1,34,34V255.88A34,34,0,0,1,437,289.85ZM34,22.64A11.34,11.34,0,0,0,22.64,34V255.88A11.34,11.34,0,0,0,34,267.2H437a11.34,11.34,0,0,0,11.33-11.32V34A11.34,11.34,0,0,0,437,22.64Z" />
|
||||
<path d="M67.93,221.91v-154h45.29l45.29,56.61L203.8,67.93h45.29v154H203.8V133.6l-45.29,56.61L113.22,133.6v88.31Zm283.06,0-67.94-74.72h45.29V67.93h45.29v79.26h45.29Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
import { t, tString, useLanguage } from '@/intl/client';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import React from 'react';
|
||||
import { useHotkeys } from 'react-hotkeys-hook';
|
||||
import {
|
||||
type AIChatController,
|
||||
type AIChatState,
|
||||
@@ -17,21 +18,43 @@ import { AIChatInput } from './AIChatInput';
|
||||
import { AIChatMessages } from './AIChatMessages';
|
||||
import AIChatSuggestedQuestions from './AIChatSuggestedQuestions';
|
||||
|
||||
export function AIChat() {
|
||||
export function AIChat(props: { trademark: boolean }) {
|
||||
const { trademark } = props;
|
||||
const chat = useAIChatState();
|
||||
const chatController = useAIChatController();
|
||||
|
||||
useHotkeys(
|
||||
'mod+j',
|
||||
(e) => {
|
||||
e.preventDefault();
|
||||
chatController.open();
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
useHotkeys(
|
||||
'esc',
|
||||
() => {
|
||||
chatController.close();
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
if (!chat.opened) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <AIChatWindow chat={chat} />;
|
||||
return <AIChatWindow trademark={trademark} chatController={chatController} chat={chat} />;
|
||||
}
|
||||
|
||||
export function AIChatWindow(props: { chat: AIChatState }) {
|
||||
const { chat } = props;
|
||||
export function AIChatWindow(props: {
|
||||
chatController: AIChatController;
|
||||
chat: AIChatState;
|
||||
trademark: boolean;
|
||||
}) {
|
||||
const { chatController, chat, trademark } = props;
|
||||
|
||||
const [input, setInput] = React.useState('');
|
||||
const chatController = useAIChatController();
|
||||
|
||||
const containerRef = React.useRef<HTMLDivElement>(null);
|
||||
const scrollContainerRef = React.useRef<HTMLDivElement>(null);
|
||||
@@ -91,11 +114,22 @@ export function AIChatWindow(props: { chat: AIChatState }) {
|
||||
<div className="relative flex h-full grow flex-col overflow-hidden circular-corners:rounded-3xl rounded-corners:rounded-md bg-tint-base text-sm text-tint depth-subtle:shadow-lg shadow-tint ring-1 ring-tint-subtle">
|
||||
<div className="flex items-center gap-2 border-tint-subtle border-b bg-tint-subtle px-4 py-2 text-tint-strong">
|
||||
<AIChatIcon
|
||||
className={`size-5 text-tint ${chat.loading ? 'animate-pulse' : ''}`}
|
||||
state={chat.loading ? 'thinking' : 'default'}
|
||||
className="size-5 text-tint"
|
||||
trademark={trademark}
|
||||
state={
|
||||
chat.error
|
||||
? 'error'
|
||||
: chat.loading
|
||||
? chat.messages[chat.messages.length - 1].content
|
||||
? 'working'
|
||||
: 'thinking'
|
||||
: chat.messages.length > 0
|
||||
? 'done'
|
||||
: 'default'
|
||||
}
|
||||
/>
|
||||
<div className="flex flex-col">
|
||||
<div className="font-bold">Docs Assistant</div>
|
||||
<div className="font-bold">{getAIChatName(trademark)}</div>
|
||||
<div
|
||||
className={`text-tint text-xs leading-none transition-all duration-500 ${
|
||||
chat.loading ? 'h-3 opacity-11' : 'h-0 opacity-0'
|
||||
@@ -153,7 +187,11 @@ export function AIChatWindow(props: { chat: AIChatState }) {
|
||||
{isEmpty ? (
|
||||
<div className="flex min-h-full w-full shrink-0 flex-col items-center justify-center gap-6 py-4">
|
||||
<div className="flex size-32 animate-[fadeIn_500ms_both] items-center justify-center rounded-full bg-tint-subtle">
|
||||
<AIChatIcon className="size-16 animate-[present_500ms_200ms_both]" />
|
||||
<AIChatIcon
|
||||
state="intro"
|
||||
trademark={trademark}
|
||||
className="size-16 animate-[present_500ms_200ms_both]"
|
||||
/>
|
||||
</div>
|
||||
<div className="animate-[fadeIn_500ms_400ms_both]">
|
||||
<h5 className=" text-center font-bold text-lg text-tint-strong">
|
||||
@@ -223,3 +261,11 @@ function AIChatError(props: { chatController: AIChatController }) {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function getAIChatName(trademark: boolean) {
|
||||
const language = useLanguage();
|
||||
|
||||
return trademark
|
||||
? tString(language, 'ai_chat_assistant_name')
|
||||
: tString(language, 'ai_chat_assistant_name_unbranded');
|
||||
}
|
||||
|
||||
@@ -1,13 +1,15 @@
|
||||
'use client';
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { t, useLanguage } from '@/intl/client';
|
||||
import { useAIChatController, useAIChatState } from '../AI/useAIChat';
|
||||
import { Button } from '../primitives';
|
||||
import { KeyboardShortcut } from '../primitives/KeyboardShortcut';
|
||||
import AIChatIcon from './AIChatIcon';
|
||||
|
||||
/**
|
||||
* Button to open/close the AI chat.
|
||||
*/
|
||||
export function AIChatButton() {
|
||||
export function AIChatButton(props: { trademark: boolean }) {
|
||||
const { trademark } = props;
|
||||
const chatController = useAIChatController();
|
||||
const chat = useAIChatState();
|
||||
|
||||
@@ -15,12 +17,19 @@ export function AIChatButton() {
|
||||
|
||||
return (
|
||||
<Button
|
||||
icon={<AIChatIcon />}
|
||||
icon={<AIChatIcon trademark={trademark} />}
|
||||
iconOnly
|
||||
size="default"
|
||||
variant="secondary"
|
||||
className="!px-3 bg-tint-base py-2.5"
|
||||
label={tString(language, 'ai_chat_assistant_name')}
|
||||
label={
|
||||
<div className="flex items-center gap-2">
|
||||
{trademark
|
||||
? t(language, 'ai_chat_assistant_name')
|
||||
: t(language, 'ai_chat_assistant_name_unbranded')}
|
||||
<KeyboardShortcut keys={['mod', 'j']} className="border-tint-11 text-tint-1" />
|
||||
</div>
|
||||
}
|
||||
onClick={() => {
|
||||
if (chat.opened) {
|
||||
chatController.close();
|
||||
|
||||
@@ -1,62 +1,150 @@
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import type React from 'react';
|
||||
|
||||
interface AIChatIconProps extends React.SVGProps<SVGSVGElement> {
|
||||
className?: string;
|
||||
size?: number;
|
||||
state?: 'thinking' | 'default';
|
||||
state?: 'default' | 'intro' | 'thinking' | 'working' | 'done' | 'error';
|
||||
trademark?: boolean;
|
||||
}
|
||||
|
||||
const AIChatIcon = ({
|
||||
className = 'size-4',
|
||||
size,
|
||||
trademark = true,
|
||||
state = 'default',
|
||||
...props
|
||||
}: AIChatIconProps) => {
|
||||
if (!trademark) {
|
||||
return (
|
||||
<Icon
|
||||
icon="sparkle"
|
||||
className={tcls(
|
||||
className,
|
||||
(state === 'thinking' || state === 'working') &&
|
||||
'animate-[spin_2s_infinite_forwards_cubic-bezier(0.16,1,0.3,1)]',
|
||||
state === 'intro' && 'animate-[spin_2s_forwards_cubic-bezier(0.16,1,0.3,1)]'
|
||||
)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<svg
|
||||
width="16"
|
||||
height="16"
|
||||
viewBox="0 0 16 16"
|
||||
preserveAspectRatio="xMaxYMid meet"
|
||||
className={className}
|
||||
aria-busy={state === 'thinking'}
|
||||
{...props}
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className={className}
|
||||
{...(size && { width: size, height: size })}
|
||||
{...props}
|
||||
>
|
||||
<title>Docs Assistant</title>
|
||||
<title>GitBook Assistant</title>
|
||||
|
||||
{/* Sparkle */}
|
||||
<path
|
||||
d="M12.8916 1.06265C12.921 0.979101 13.0392 0.979127 13.0685 1.06267C13.239 1.5478 13.3439 1.84646 13.516 2.1032C13.6683 2.33042 13.8578 2.53033 14.0766 2.6945C14.3239 2.88 14.6165 3.00068 15.0919 3.19671C15.1761 3.23142 15.1761 3.3506 15.0919 3.38531C14.6165 3.58134 14.3239 3.70203 14.0766 3.88752C13.8578 4.05169 13.6683 4.2516 13.516 4.47882C13.3439 4.73556 13.239 5.03423 13.0685 5.51937C13.0392 5.60291 12.921 5.60292 12.8916 5.51938C12.7212 5.03423 12.6162 4.73557 12.4442 4.47882C12.2919 4.2516 12.1023 4.05169 11.8835 3.88752C11.6363 3.70202 11.3436 3.58134 10.8682 3.38531C10.7841 3.3506 10.7841 3.23141 10.8683 3.1967C11.3436 3.00067 11.6363 2.87999 11.8835 2.6945C12.1023 2.53033 12.2919 2.33042 12.4442 2.1032C12.6162 1.84646 12.7212 1.54779 12.8916 1.06265Z"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinejoin="round"
|
||||
className={state === 'thinking' ? 'animate-spin' : ''}
|
||||
className={tcls(
|
||||
state === 'intro' &&
|
||||
'animate-[fadeIn_.5s_.7s_both,spin_2s_1s_forwards_cubic-bezier(.43,1.54,.64,1)]',
|
||||
(state === 'working' || state === 'thinking') &&
|
||||
'animate-[fadeIn_.5s_.3s_both,spin_2s_infinite_forwards_cubic-bezier(0.16,1,0.3,1)]',
|
||||
state === 'done' && 'animate-[fadeOut_.5s_both]',
|
||||
state === 'default' && 'animate-[fadeIn_0s_both]',
|
||||
state === 'error' && 'hidden'
|
||||
)}
|
||||
style={{ transformOrigin: '13px 3.5px' }}
|
||||
/>
|
||||
|
||||
{/* Error */}
|
||||
<g
|
||||
clipPath="url(#clip0_153_2034)"
|
||||
className={tcls(
|
||||
'text-danger-subtle',
|
||||
state === 'error' ? 'animate-[fadeIn_.5s_.3s_both]' : 'hidden'
|
||||
)}
|
||||
>
|
||||
<path
|
||||
d="M13.0312 1.42059L13.0312 3.95184"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M13.0312 6.00253V6.00263"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
</g>
|
||||
|
||||
{/* Check */}
|
||||
<path
|
||||
d="M9.479 10.2734C9.479 11.2369 8.6115 11.2578 7.54138 11.2578C6.47126 11.2578 5.60376 11.2369 5.60376 10.2734"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M9.47913 6.77344L9.47913 7.77344"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M5.60388 6.77344L5.60388 7.77344"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
/>
|
||||
<path
|
||||
d="M13.2813 8.875L13.2813 10.125C13.2813 12.3341 11.4904 14.125 9.28125 14.125L1.80165 14.125L1.80165 6.78125C1.80165 4.57211 3.59251 2.78125 5.80165 2.78125L7.67889 2.78125"
|
||||
d="M10.8051 3.71161L12.2401 5.27411L14.823 2.14911"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={tcls(
|
||||
state === 'done'
|
||||
? 'animate-[fadeIn_.5s_.3s_both]'
|
||||
: 'animate-[fadeOut_.5s_both]',
|
||||
state === 'intro' && 'hidden'
|
||||
)}
|
||||
/>
|
||||
|
||||
{/* Background */}
|
||||
<path
|
||||
d="M3.5625 8.78512L7.26347 10.9219C7.88227 11.2791 8.64467 11.2791 9.26347 10.9219L14.25 8.0429C14.5833 7.85045 15 8.09101 15 8.47591V10.2777C15 10.4563 14.9047 10.6214 14.75 10.7107L9.26347 13.8784C8.64467 14.2356 7.88228 14.2356 7.26347 13.8784L3.5625 11.7416C2.70833 11.2978 1 9.93199 1 8.01949M1 8.01949C1 6.6448 1.84765 5.98698 2.62903 5.71701C3.15426 5.53555 3.71577 5.70568 4.19701 5.98353L7.26347 7.75395C7.88228 8.11122 8.64467 8.11122 9.26347 7.75395L10.9095 6.80362M1 8.01949C1 6.4945 2.03973 5.30731 2.5596 4.90434L7.37937 2.12165C7.79013 1.88449 8.26417 1.80476 8.71747 1.88245"
|
||||
stroke="currentColor"
|
||||
strokeOpacity="0.25"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={tcls(state === 'intro' && 'animate-[fadeIn_2s_forwards]')}
|
||||
/>
|
||||
|
||||
{/* Logo */}
|
||||
<mask
|
||||
id="mask0_220_25"
|
||||
style={{ maskType: 'alpha' }}
|
||||
maskUnits="userSpaceOnUse"
|
||||
x="0"
|
||||
y="1"
|
||||
width="16"
|
||||
height="14"
|
||||
>
|
||||
<path
|
||||
d="M3.5625 8.78512L7.26347 10.9219C7.88227 11.2791 8.64467 11.2791 9.26347 10.9219L14.25 8.0429C14.5833 7.85045 15 8.09101 15 8.47591V10.2777C15 10.4563 14.9047 10.6214 14.75 10.7107L9.26347 13.8784C8.64467 14.2356 7.88228 14.2356 7.26347 13.8784L3.5625 11.7416C2.70833 11.2978 1 9.93199 1 8.01949M1 8.01949C1 6.6448 1.84765 5.98698 2.62903 5.71701C3.15426 5.53555 3.71577 5.70568 4.19701 5.98353L7.26347 7.75395C7.88228 8.11122 8.64467 8.11122 9.26347 7.75395L10.9095 6.80362M1 8.01949C1 6.4945 2.03973 5.30731 2.5596 4.90434L7.37937 2.12165C7.79013 1.88449 8.26417 1.80476 8.71747 1.88245"
|
||||
stroke="currentColor"
|
||||
pathLength="100"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
/>
|
||||
</mask>
|
||||
<g mask="url(#mask0_220_25)">
|
||||
<path
|
||||
d="M3.5625 8.78512L7.26347 10.9219C7.88227 11.2791 8.64467 11.2791 9.26347 10.9219L14.25 8.0429C14.5833 7.85045 15 8.09101 15 8.47591V10.2777C15 10.4563 14.9047 10.6214 14.75 10.7107L9.26347 13.8784C8.64467 14.2356 7.88228 14.2356 7.26347 13.8784L3.5625 11.7416C2.70833 11.2978 1 9.93199 1 8.01949C1 6.6448 1.84765 5.98698 2.62903 5.71701C3.15426 5.53555 3.71577 5.70568 4.19701 5.98353L7.26347 7.75395C7.88228 8.11122 8.64467 8.11122 9.26347 7.75395L14.1991 4.90434L9.37937 2.12165C8.76057 1.76438 7.99907 1.76386 7.38027 2.12113C5.89314 2.97972 3.20298 4.53289 2.5596 4.90434C1.77376 5.35804 1 6.11597 1.00148 7.9207"
|
||||
stroke="currentColor"
|
||||
pathLength="100"
|
||||
strokeWidth="1.2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={tcls(
|
||||
(state === 'thinking' || state === 'working') &&
|
||||
'animate-[pathLoading_2s_infinite_both]',
|
||||
state === 'intro' && 'animate-[pathEnter_2s_both]',
|
||||
state === 'done' && 'animate-[pathEnter_1s_forwards_ease]'
|
||||
)}
|
||||
/>
|
||||
</g>
|
||||
</svg>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -2,7 +2,9 @@ import { t, tString, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useHotkeys } from 'react-hotkeys-hook';
|
||||
import { Button } from '../primitives';
|
||||
import { KeyboardShortcut } from '../primitives/KeyboardShortcut';
|
||||
import { Tooltip } from '../primitives/Tooltip';
|
||||
|
||||
export function AIChatInput(props: {
|
||||
@@ -31,12 +33,19 @@ export function AIChatInput(props: {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!disabled) {
|
||||
setTimeout(() => {
|
||||
inputRef.current?.focus();
|
||||
}, 300);
|
||||
if (!disabled && !loading) {
|
||||
inputRef.current?.focus();
|
||||
}
|
||||
}, [disabled]);
|
||||
}, [disabled, loading]);
|
||||
|
||||
useHotkeys(
|
||||
'mod+j',
|
||||
(e) => {
|
||||
e.preventDefault();
|
||||
inputRef.current?.focus();
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="relative flex flex-col overflow-hidden circular-corners:rounded-2xl rounded-corners:rounded-md bg-tint-base/9 ring-1 ring-tint-subtle backdrop-blur-lg transition-all depth-subtle:has-[textarea:focus]:shadow-lg has-[textarea:focus]:ring-2 has-[textarea:focus]:ring-primary-hover contrast-more:bg-tint-base">
|
||||
@@ -54,6 +63,7 @@ export function AIChatInput(props: {
|
||||
'pb-12',
|
||||
'h-auto',
|
||||
'bg-transparent',
|
||||
'peer',
|
||||
'max-h-64',
|
||||
'placeholder:text-tint/8',
|
||||
'transition-colors',
|
||||
@@ -69,6 +79,12 @@ export function AIChatInput(props: {
|
||||
placeholder={tString(language, 'ai_chat_input_placeholder')}
|
||||
onChange={handleInput}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
event.currentTarget.blur();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === 'Enter' && !event.shiftKey && value.trim()) {
|
||||
event.preventDefault();
|
||||
event.currentTarget.style.height = 'auto';
|
||||
@@ -76,6 +92,9 @@ export function AIChatInput(props: {
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className="absolute top-2.5 right-4 animate-[fadeIn_0.2s_0.5s_ease-in-out_both] peer-focus:hidden">
|
||||
<KeyboardShortcut keys={['mod', 'j']} />
|
||||
</div>
|
||||
<div className="absolute inset-x-0 bottom-0 flex items-center px-2 py-2">
|
||||
<Tooltip
|
||||
label={
|
||||
|
||||
@@ -166,7 +166,11 @@ export function Header(props: {
|
||||
</span>
|
||||
</SearchButton>
|
||||
</Suspense>
|
||||
{withAIChat && <AIChatButton />}
|
||||
{withAIChat && (
|
||||
<AIChatButton
|
||||
trademark={context.customization.trademark.enabled}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{customization.header.links.length > 0 && (
|
||||
|
||||
@@ -20,7 +20,7 @@ export async function HeaderLogo(props: HeaderLogoProps) {
|
||||
|
||||
return (
|
||||
<Link
|
||||
href={linker.toAbsoluteURL(linker.toPathInSite(''))}
|
||||
href={linker.toPathInSite('')}
|
||||
className={tcls('group/headerlogo', 'min-w-0', 'shrink', 'flex', 'items-center')}
|
||||
>
|
||||
{customization.header.logo ? (
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { Fragment } from 'react';
|
||||
|
||||
import { AIActionsDropdown } from '@/components/AIActions/AIActionsDropdown';
|
||||
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import type { AncestorRevisionPage } from '@/lib/pages';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import type { RevisionPageDocument } from '@gitbook/api';
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { PageIcon } from '../PageIcon';
|
||||
import { StyledLink } from '../primitives';
|
||||
|
||||
@@ -21,6 +20,8 @@ export async function PageHeader(props: {
|
||||
return null;
|
||||
}
|
||||
|
||||
const withAIChat = isAIChatEnabled(context);
|
||||
|
||||
return (
|
||||
<header
|
||||
className={tcls(
|
||||
@@ -29,11 +30,32 @@ export async function PageHeader(props: {
|
||||
'mx-auto',
|
||||
'mb-6',
|
||||
'space-y-3',
|
||||
'page-api-block:ml-0'
|
||||
'page-api-block:ml-0',
|
||||
'page-api-block:max-w-full'
|
||||
)}
|
||||
>
|
||||
{page.layout.tableOfContents ? (
|
||||
<div
|
||||
className={tcls(
|
||||
'float-right mb-2 ml-4',
|
||||
ancestors.length > 0 ? '-mt-2' : 'xs:mt-2'
|
||||
)}
|
||||
>
|
||||
<AIActionsDropdown
|
||||
markdownPageUrl={`${context.linker.toPathInSpace(page.path)}.md`}
|
||||
pageURL={context.linker.toAbsoluteURL(
|
||||
context.linker.toPathForPage({
|
||||
pages: context.revision.pages,
|
||||
page,
|
||||
})
|
||||
)}
|
||||
withAIChat={withAIChat}
|
||||
trademark={context.customization.trademark.enabled}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
{ancestors.length > 0 && (
|
||||
<nav>
|
||||
<nav aria-label="Breadcrumb">
|
||||
<ol className={tcls('flex', 'flex-wrap', 'items-center', 'gap-2', 'text-tint')}>
|
||||
{ancestors.map((breadcrumb, index) => {
|
||||
const href = linker.toPathForPage({
|
||||
@@ -41,51 +63,62 @@ export async function PageHeader(props: {
|
||||
page: breadcrumb,
|
||||
});
|
||||
return (
|
||||
<Fragment key={breadcrumb.id}>
|
||||
<li key={breadcrumb.id}>
|
||||
<StyledLink
|
||||
href={href}
|
||||
className={tcls(
|
||||
'no-underline',
|
||||
'hover:underline',
|
||||
'text-xs',
|
||||
'tracking-wide',
|
||||
'font-semibold',
|
||||
'uppercase',
|
||||
'flex',
|
||||
'items-center',
|
||||
'gap-1.5',
|
||||
'contrast-more:underline',
|
||||
'contrast-more:decoration-current'
|
||||
)}
|
||||
>
|
||||
<PageIcon
|
||||
page={breadcrumb}
|
||||
style="flex size-4 items-center justify-center text-base leading-none"
|
||||
/>
|
||||
{breadcrumb.title}
|
||||
</StyledLink>
|
||||
</li>
|
||||
<li key={breadcrumb.id} className="flex items-center gap-2">
|
||||
<StyledLink
|
||||
href={href}
|
||||
className={tcls(
|
||||
'no-underline',
|
||||
'hover:underline',
|
||||
'text-xs',
|
||||
'tracking-wide',
|
||||
'font-semibold',
|
||||
'uppercase',
|
||||
'flex',
|
||||
'items-center',
|
||||
'gap-1.5',
|
||||
'contrast-more:underline',
|
||||
'contrast-more:decoration-current'
|
||||
)}
|
||||
>
|
||||
<PageIcon
|
||||
page={breadcrumb}
|
||||
style="flex size-4 items-center justify-center text-base leading-none"
|
||||
/>
|
||||
{breadcrumb.title}
|
||||
</StyledLink>
|
||||
{index !== ancestors.length - 1 && (
|
||||
<Icon
|
||||
aria-hidden
|
||||
icon="chevron-right"
|
||||
className={tcls('size-3', 'text-tint-subtle')}
|
||||
className="size-3 text-tint-subtle"
|
||||
/>
|
||||
)}
|
||||
</Fragment>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
</nav>
|
||||
)}
|
||||
{page.layout.title ? (
|
||||
<h1 className={tcls('text-4xl', 'font-bold', 'flex', 'items-center', 'gap-4')}>
|
||||
<h1
|
||||
className={tcls(
|
||||
'text-4xl',
|
||||
'font-bold',
|
||||
'flex',
|
||||
'items-center',
|
||||
'gap-4',
|
||||
'grow',
|
||||
'text-pretty',
|
||||
'clear-right',
|
||||
'xs:clear-none'
|
||||
)}
|
||||
>
|
||||
<PageIcon page={page} style={['text-tint-subtle ', 'shrink-0']} />
|
||||
{page.title}
|
||||
</h1>
|
||||
) : null}
|
||||
{page.description && page.layout.description ? (
|
||||
<p className={tcls('text-lg', 'text-tint')}>{page.description}</p>
|
||||
<p className={tcls('text-lg', 'text-tint', 'clear-both')}>{page.description}</p>
|
||||
) : null}
|
||||
</header>
|
||||
);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
'use client';
|
||||
|
||||
import { Icon } from '@gitbook/icons';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
import { tString, useLanguage } from '@/intl/client';
|
||||
import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
import { useTrackEvent } from '../Insights';
|
||||
import { KeyboardShortcut } from '../primitives/KeyboardShortcut';
|
||||
import { useSearch } from './useSearch';
|
||||
|
||||
/**
|
||||
@@ -100,45 +100,10 @@ export function SearchButton(props: { children?: React.ReactNode; style?: ClassV
|
||||
className={tcls('text-tint-subtle', 'shrink-0', 'size-4')}
|
||||
/>
|
||||
<div className={tcls('w-full', 'hidden', 'md:block', 'text-left')}>{children}</div>
|
||||
<Shortcut />
|
||||
<KeyboardShortcut
|
||||
keys={['mod', 'k']}
|
||||
className="theme-bold:border-header-link/5 bg-tint-base theme-bold:bg-header-background"
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function Shortcut() {
|
||||
const [operatingSystem, setOperatingSystem] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
function getOperatingSystem() {
|
||||
const platform = navigator.platform.toLowerCase();
|
||||
|
||||
if (platform.includes('mac')) return 'mac';
|
||||
if (platform.includes('win')) return 'win';
|
||||
|
||||
return 'win';
|
||||
}
|
||||
|
||||
setOperatingSystem(getOperatingSystem());
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-busy={operatingSystem === null ? 'true' : undefined}
|
||||
className={tcls(
|
||||
`shortcut -mr-1 hidden justify-end gap-0.5 whitespace-nowrap text-tint text-xs [font-feature-settings:"calt",_"case"] contrast-more:text-tint-strong md:flex`,
|
||||
operatingSystem
|
||||
? 'motion-safe:animate-fadeIn motion-reduce:opacity-100'
|
||||
: 'opacity-0'
|
||||
)}
|
||||
>
|
||||
<kbd
|
||||
className={`flex h-5 min-w-5 items-center justify-center rounded border border-tint-subtle theme-bold:border-header-link/5 bg-tint-base theme-bold:bg-header-background px-1 ${operatingSystem === 'mac' ? 'text-sm' : ''}`}
|
||||
>
|
||||
{operatingSystem === 'mac' ? '⌘' : 'Ctrl'}
|
||||
</kbd>
|
||||
<kbd className="flex size-5 items-center justify-center rounded border border-tint-subtle theme-bold:border-header-link/5 bg-tint-base theme-bold:bg-header-background">
|
||||
K
|
||||
</kbd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import { redirect } from 'next/navigation';
|
||||
|
||||
import { getDataOrNull } from '@/lib/data';
|
||||
import { resolvePageId, resolvePagePath } from '@/lib/pages';
|
||||
import { withLeadingSlash } from '@/lib/paths';
|
||||
import { withLeadingSlash, withTrailingSlash } from '@/lib/paths';
|
||||
|
||||
export interface PagePathParams {
|
||||
pathname?: string | string[];
|
||||
@@ -71,14 +71,17 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
|
||||
redirectPathname,
|
||||
]);
|
||||
for (const source of redirectSources) {
|
||||
const resolvedSiteRedirect = await getDataOrNull(
|
||||
context.dataFetcher.getSiteRedirectBySource({
|
||||
organizationId,
|
||||
siteId: site.id,
|
||||
source,
|
||||
siteShareKey: shareKey,
|
||||
})
|
||||
);
|
||||
// We try to resolve the site redirect
|
||||
const resolvedSiteRedirect =
|
||||
source.length < 512 &&
|
||||
(await getDataOrNull(
|
||||
context.dataFetcher.getSiteRedirectBySource({
|
||||
organizationId,
|
||||
siteId: site.id,
|
||||
source,
|
||||
siteShareKey: shareKey,
|
||||
})
|
||||
));
|
||||
if (resolvedSiteRedirect) {
|
||||
return redirect(linker.toLinkForContent(resolvedSiteRedirect.target));
|
||||
}
|
||||
@@ -88,15 +91,18 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
|
||||
// If page still can't be found, we try with the API, in case we have a redirect at space level.
|
||||
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
|
||||
// The page rendering will take care of redirecting to a normalized pathname.
|
||||
const resolved = await getDataOrNull(
|
||||
context.dataFetcher.getRevisionPageByPath({
|
||||
spaceId: space.id,
|
||||
revisionId: revisionId,
|
||||
path: rawPathname,
|
||||
})
|
||||
);
|
||||
if (resolved) {
|
||||
return resolvePageId(revision.pages, resolved.id);
|
||||
// We also try with the pathname with a trailing slash, as some redirects might be set up that way.
|
||||
for (const pathname of [rawPathname, withTrailingSlash(rawPathname)]) {
|
||||
const resolved = await getDataOrNull(
|
||||
context.dataFetcher.getRevisionPageByPath({
|
||||
spaceId: space.id,
|
||||
revisionId: revisionId,
|
||||
path: pathname,
|
||||
})
|
||||
);
|
||||
if (resolved) {
|
||||
return resolvePageId(revision.pages, resolved.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ import { getSpaceLanguage } from '@/intl/server';
|
||||
import { t } from '@/intl/translate';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
|
||||
import type { VisitorAuthClaims } from '@/lib/adaptive';
|
||||
import { GITBOOK_API_PUBLIC_URL, GITBOOK_APP_URL } from '@/lib/env';
|
||||
import { AIChat } from '../AIChat';
|
||||
@@ -50,10 +51,7 @@ export function SpaceLayout(props: {
|
||||
customization.footer.logo ||
|
||||
customization.footer.groups?.length;
|
||||
|
||||
// TODO: remove aiSearch and optional chain once the cache has been fully updated (after 11/07/2025)
|
||||
const withAIChat =
|
||||
context.customization.ai?.mode === CustomizationAIMode.Assistant &&
|
||||
(context.site.id === 'site_p4Xo4' || context.site.id === 'site_JOVzv');
|
||||
const withAIChat = isAIChatEnabled(context);
|
||||
|
||||
return (
|
||||
<SpaceLayoutContextProvider basePath={context.linker.toPathInSpace('')}>
|
||||
@@ -79,7 +77,9 @@ export function SpaceLayout(props: {
|
||||
withAIChat={withAIChat}
|
||||
context={context}
|
||||
/>
|
||||
{withAIChat ? <AIChat /> : null}
|
||||
{withAIChat ? (
|
||||
<AIChat trademark={context.customization.trademark.enabled} />
|
||||
) : null}
|
||||
<div className="scroll-nojump">
|
||||
<div className="motion-safe:transition-all motion-safe:duration-300 lg:chat-open:mr-80 xl:chat-open:mr-96">
|
||||
<div
|
||||
|
||||
@@ -14,9 +14,9 @@ type ButtonProps = {
|
||||
variant?: 'primary' | 'secondary' | 'blank';
|
||||
icon?: IconName | React.ReactNode;
|
||||
iconOnly?: boolean;
|
||||
size?: 'default' | 'medium' | 'small';
|
||||
size?: 'default' | 'medium' | 'small' | 'xsmall';
|
||||
className?: ClassValue;
|
||||
label?: string;
|
||||
label?: string | React.ReactNode;
|
||||
} & LinkInsightsProps &
|
||||
HTMLAttributes<HTMLElement>;
|
||||
|
||||
@@ -26,13 +26,13 @@ export const variantClasses = {
|
||||
'text-contrast-primary-solid',
|
||||
'hover:bg-primary-solid-hover',
|
||||
'hover:text-contrast-primary-solid-hover',
|
||||
'ring-0',
|
||||
'contrast-more:ring-1',
|
||||
'border-0',
|
||||
'contrast-more:border-1',
|
||||
],
|
||||
blank: [
|
||||
'bg-transparent',
|
||||
'text-tint',
|
||||
'ring-0',
|
||||
'border-0',
|
||||
'shadow-none',
|
||||
'hover:bg-primary-hover',
|
||||
'hover:text-primary',
|
||||
@@ -67,6 +67,7 @@ export function Button({
|
||||
default: ['text-base', 'font-semibold', 'px-5', 'py-2', 'circular-corners:px-6'],
|
||||
medium: ['text-sm', 'px-3.5', 'py-1.5', 'circular-corners:px-4'],
|
||||
small: ['text-xs', 'py-2', iconOnly ? 'px-2' : 'px-3'],
|
||||
xsmall: ['text-xs', 'py-1', iconOnly ? 'px-1.5' : 'px-2'],
|
||||
};
|
||||
|
||||
const sizeClasses = sizes[size] || sizes.default;
|
||||
@@ -74,36 +75,8 @@ export function Button({
|
||||
const domClassName = tcls(variantClasses[variant], sizeClasses, className);
|
||||
const buttonOnlyClassNames = useClassnames(['ButtonStyles']);
|
||||
|
||||
if (href) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
className={domClassName}
|
||||
classNames={['ButtonStyles']}
|
||||
insights={insights}
|
||||
aria-label={label}
|
||||
target={target}
|
||||
{...rest}
|
||||
>
|
||||
{icon ? (
|
||||
typeof icon === 'string' ? (
|
||||
<Icon icon={icon as IconName} className={tcls('size-[1em]')} />
|
||||
) : (
|
||||
icon
|
||||
)
|
||||
) : null}
|
||||
{iconOnly ? null : label}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
const button = (
|
||||
<button
|
||||
type="button"
|
||||
className={tcls(buttonOnlyClassNames, domClassName)}
|
||||
aria-label={label}
|
||||
{...rest}
|
||||
>
|
||||
const content = (
|
||||
<>
|
||||
{icon ? (
|
||||
typeof icon === 'string' ? (
|
||||
<Icon icon={icon as IconName} className={tcls('size-[1em]')} />
|
||||
@@ -112,8 +85,35 @@ export function Button({
|
||||
)
|
||||
) : null}
|
||||
{iconOnly ? null : label}
|
||||
</>
|
||||
);
|
||||
|
||||
if (href) {
|
||||
return (
|
||||
<Link
|
||||
href={href}
|
||||
className={domClassName}
|
||||
classNames={['ButtonStyles']}
|
||||
insights={insights}
|
||||
aria-label={label?.toString()}
|
||||
target={target}
|
||||
{...rest}
|
||||
>
|
||||
{content}
|
||||
</Link>
|
||||
);
|
||||
}
|
||||
|
||||
const button = (
|
||||
<button
|
||||
type="button"
|
||||
className={tcls(buttonOnlyClassNames, domClassName)}
|
||||
aria-label={label?.toString()}
|
||||
{...rest}
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
);
|
||||
|
||||
return iconOnly ? <Tooltip label={label}>{button}</Tooltip> : button;
|
||||
return iconOnly && label ? <Tooltip label={label}>{button}</Tooltip> : button;
|
||||
}
|
||||
|
||||
@@ -27,8 +27,25 @@ export function DropdownMenu(props: {
|
||||
className?: ClassValue;
|
||||
/** Open the dropdown on hover */
|
||||
openOnHover?: boolean;
|
||||
/**
|
||||
* Side of the dropdown
|
||||
* @default "bottom"
|
||||
*/
|
||||
side?: RadixDropdownMenu.DropdownMenuContentProps['side'];
|
||||
/**
|
||||
* Alignment of the dropdown
|
||||
* @default "start"
|
||||
*/
|
||||
align?: RadixDropdownMenu.DropdownMenuContentProps['align'];
|
||||
}) {
|
||||
const { button, children, className, openOnHover = false } = props;
|
||||
const {
|
||||
button,
|
||||
children,
|
||||
className,
|
||||
openOnHover = false,
|
||||
side = 'bottom',
|
||||
align = 'start',
|
||||
} = props;
|
||||
const [hovered, setHovered] = useState(false);
|
||||
const [clicked, setClicked] = useState(false);
|
||||
|
||||
@@ -55,12 +72,13 @@ export function DropdownMenu(props: {
|
||||
collisionPadding={8}
|
||||
onMouseEnter={() => setHovered(true)}
|
||||
onMouseLeave={() => setHovered(false)}
|
||||
align="start"
|
||||
className="z-40 animate-scaleIn pt-2"
|
||||
align={align}
|
||||
side={side}
|
||||
className="z-40 animate-scaleIn border-tint pt-2"
|
||||
>
|
||||
<div
|
||||
className={tcls(
|
||||
'flex max-h-80 min-w-40 max-w-[40vw] flex-col gap-1 overflow-auto rounded-lg straight-corners:rounded-sm bg-tint-base p-2 shadow-lg ring-1 ring-tint-subtle sm:min-w-52 sm:max-w-80',
|
||||
'flex max-h-80 min-w-40 max-w-[40vw] flex-col gap-1 overflow-auto circular-corners:rounded-xl rounded-md straight-corners:rounded-none border border-tint bg-tint-base p-2 shadow-lg sm:min-w-52 sm:max-w-80',
|
||||
className
|
||||
)}
|
||||
>
|
||||
@@ -116,16 +134,17 @@ export function DropdownButton(props: {
|
||||
export function DropdownMenuItem(
|
||||
props: {
|
||||
href?: string;
|
||||
target?: React.HTMLAttributeAnchorTarget;
|
||||
active?: boolean;
|
||||
className?: ClassValue;
|
||||
children: React.ReactNode;
|
||||
} & LinkInsightsProps &
|
||||
RadixDropdownMenu.DropdownMenuItemProps
|
||||
) {
|
||||
const { children, active = false, href, className, insights, ...rest } = props;
|
||||
const { children, active = false, href, className, insights, target, ...rest } = props;
|
||||
|
||||
const itemClassName = tcls(
|
||||
'rounded straight-corners:rounded-sm px-3 py-1 text-sm flex gap-2 items-center',
|
||||
'rounded straight-corners:rounded-sm circular-corners:rounded-lg px-3 py-1 text-sm flex gap-2 items-center',
|
||||
active
|
||||
? 'bg-primary text-primary-strong data-[highlighted]:bg-primary-hover'
|
||||
: 'data-[highlighted]:bg-tint-hover',
|
||||
@@ -137,7 +156,7 @@ export function DropdownMenuItem(
|
||||
if (href) {
|
||||
return (
|
||||
<RadixDropdownMenu.Item {...rest} asChild>
|
||||
<Link href={href} insights={insights} className={itemClassName}>
|
||||
<Link href={href} insights={insights} className={itemClassName} target={target}>
|
||||
{children}
|
||||
</Link>
|
||||
</RadixDropdownMenu.Item>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client';
|
||||
|
||||
import { type ClassValue, tcls } from '@/lib/tailwind';
|
||||
import * as React from 'react';
|
||||
|
||||
function getOperatingSystem() {
|
||||
const platform = navigator.platform.toLowerCase();
|
||||
|
||||
if (platform.includes('mac')) return 'mac';
|
||||
if (platform.includes('win')) return 'win';
|
||||
|
||||
return 'win';
|
||||
}
|
||||
|
||||
export function KeyboardShortcut(props: { keys: string[]; className?: ClassValue }) {
|
||||
const { keys, className } = props;
|
||||
|
||||
const [operatingSystem, setOperatingSystem] = React.useState<string | null>(null);
|
||||
|
||||
React.useEffect(() => {
|
||||
setOperatingSystem(getOperatingSystem());
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div
|
||||
aria-busy={operatingSystem === null ? 'true' : undefined}
|
||||
className={tcls(
|
||||
'shortcut -mr-1 hidden justify-end gap-0.5 whitespace-nowrap text-tint text-xs [font-feature-settings:"calt",_"case"] contrast-more:text-tint-strong md:flex',
|
||||
operatingSystem
|
||||
? 'motion-safe:animate-fadeIn motion-reduce:opacity-100'
|
||||
: 'opacity-0'
|
||||
)}
|
||||
>
|
||||
{keys.map((key) => (
|
||||
<kbd
|
||||
key={key}
|
||||
className={tcls(
|
||||
'flex h-5 min-w-5 items-center justify-center rounded-md border border-tint-subtle px-1',
|
||||
key === 'mod'
|
||||
? operatingSystem === 'mac'
|
||||
? 'text-sm'
|
||||
: 'text-xs'
|
||||
: 'uppercase',
|
||||
className
|
||||
)}
|
||||
>
|
||||
{key === 'mod' ? (operatingSystem === 'mac' ? '⌘' : 'Ctrl') : key}
|
||||
</kbd>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -40,6 +40,26 @@ export const LinkSettingsContext = React.createContext<{
|
||||
externalLinksTarget: SiteExternalLinksTarget.Self,
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the target and rel props for a link based on the provided props and context.
|
||||
*/
|
||||
function getTargetProps(
|
||||
props: Pick<LinkProps, 'href' | 'rel' | 'target'>,
|
||||
context: {
|
||||
externalLinksTarget: SiteExternalLinksTarget;
|
||||
isExternal: boolean;
|
||||
}
|
||||
) {
|
||||
const target =
|
||||
props.target ??
|
||||
(context.isExternal && context.externalLinksTarget === SiteExternalLinksTarget.Blank
|
||||
? '_blank'
|
||||
: undefined);
|
||||
// Automatically set rel if target is _blank, or use the specified rel.
|
||||
const rel = props.rel ?? (target === '_blank' ? 'noopener noreferrer' : undefined);
|
||||
return { target, rel };
|
||||
}
|
||||
|
||||
/**
|
||||
* Low-level Link component that handles navigation to external urls.
|
||||
* It does not contain any styling.
|
||||
@@ -52,28 +72,33 @@ export const Link = React.forwardRef(function Link(
|
||||
const { externalLinksTarget } = React.useContext(LinkSettingsContext);
|
||||
const trackEvent = useTrackEvent();
|
||||
const forwardedClassNames = useClassnames(classNames || []);
|
||||
|
||||
// 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.
|
||||
const isExternal = URL.canParse ? URL.canParse(props.href) : props.href.startsWith('http');
|
||||
const isExternal = isExternalLink(href);
|
||||
const { target, rel } = getTargetProps(props, { externalLinksTarget, isExternal });
|
||||
|
||||
const onClick = (event: React.MouseEvent<HTMLAnchorElement>) => {
|
||||
const isExternalWithOrigin = isExternalLink(href, window.location.origin);
|
||||
|
||||
if (insights) {
|
||||
trackEvent(insights, undefined, {
|
||||
immediate: isExternal,
|
||||
});
|
||||
trackEvent(insights, undefined, { immediate: isExternalWithOrigin });
|
||||
}
|
||||
|
||||
if (
|
||||
isExternalLink(href, window.location.origin) &&
|
||||
// When the page is embedded in an iframe, for security reasons other urls cannot be opened.
|
||||
// In this case, we open the link in a new tab.
|
||||
(window.self !== window.top ||
|
||||
// If the site is configured to open links in a new tab
|
||||
externalLinksTarget === SiteExternalLinksTarget.Blank)
|
||||
) {
|
||||
const isInIframe = window.self !== window.top;
|
||||
|
||||
// When the page is embedded in an iframe
|
||||
// for security reasons other urls cannot be opened.
|
||||
if (isInIframe && isExternalWithOrigin) {
|
||||
event.preventDefault();
|
||||
window.open(href, '_blank');
|
||||
window.open(href, '_blank', 'noopener noreferrer');
|
||||
} else if (isExternal) {
|
||||
// The external logic server-side is limited
|
||||
// so we use the client-side logic to determine the real target
|
||||
// by default the target is "_self".
|
||||
const { target = '_self' } = getTargetProps(props, {
|
||||
externalLinksTarget,
|
||||
isExternal: isExternalWithOrigin,
|
||||
});
|
||||
event.preventDefault();
|
||||
window.open(href, target, rel);
|
||||
}
|
||||
|
||||
domProps.onClick?.(event);
|
||||
@@ -81,7 +106,7 @@ export const Link = React.forwardRef(function Link(
|
||||
|
||||
// We test if the link is external, without comparing to the origin
|
||||
// as this will be rendered on the server and it could result in a mismatch.
|
||||
if (isExternalLink(href)) {
|
||||
if (isExternal) {
|
||||
return (
|
||||
<a
|
||||
ref={ref}
|
||||
@@ -89,9 +114,8 @@ export const Link = React.forwardRef(function Link(
|
||||
{...domProps}
|
||||
href={href}
|
||||
onClick={onClick}
|
||||
{...(externalLinksTarget === SiteExternalLinksTarget.Blank
|
||||
? { target: '_blank', rel: 'noopener noreferrer' }
|
||||
: {})}
|
||||
target={target}
|
||||
rel={rel}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ClassValue } from '@/lib/tailwind';
|
||||
|
||||
export const ButtonStyles = [
|
||||
'button',
|
||||
'group/button',
|
||||
'inline-flex',
|
||||
'items-center',
|
||||
'gap-2',
|
||||
@@ -10,9 +11,9 @@ export const ButtonStyles = [
|
||||
'circular-corners:rounded-full',
|
||||
// 'place-self-start',
|
||||
|
||||
'ring-1',
|
||||
'ring-tint',
|
||||
'hover:ring-tint-hover',
|
||||
'border',
|
||||
'border-tint',
|
||||
'hover:border-tint-hover',
|
||||
|
||||
'shadow-sm',
|
||||
'shadow-tint',
|
||||
@@ -21,9 +22,9 @@ export const ButtonStyles = [
|
||||
'active:shadow-none',
|
||||
'depth-flat:shadow-none',
|
||||
|
||||
'contrast-more:ring-tint-12',
|
||||
'contrast-more:hover:ring-2',
|
||||
'contrast-more:hover:ring-tint-12',
|
||||
'contrast-more:border-tint-12',
|
||||
'contrast-more:hover:border-2',
|
||||
'contrast-more:hover:border-tint-12',
|
||||
|
||||
'hover:scale-104',
|
||||
'depth-flat:hover:scale-100',
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { CustomizationAIMode } from '@gitbook/api';
|
||||
|
||||
// TODO: remove aiSearch and optional chain once the cache has been fully updated (after 11/07/2025)
|
||||
export const isAIChatEnabled = (context: GitBookSiteContext) =>
|
||||
context.customization.ai?.mode === CustomizationAIMode.Assistant &&
|
||||
(context.site.id === 'site_p4Xo4' || context.site.id === 'site_JOVzv');
|
||||
@@ -64,7 +64,8 @@ export const de = {
|
||||
link_tooltip_external_link: 'Externe Verlinkung zu',
|
||||
link_tooltip_page_anchor: 'Zum Abschnitt springen',
|
||||
open_in_new_tab: 'In neuem Tab öffnen',
|
||||
ai_chat_assistant_name: 'Docs-Assistent',
|
||||
ai_chat_assistant_name: 'GitBook-Assistent',
|
||||
ai_chat_assistant_name_unbranded: 'KI-Assistent',
|
||||
ai_chat_assistant_description: 'Ich helfe Ihnen bei der Dokumentation.',
|
||||
ai_chat_assistant_greeting_morning: 'Guten Morgen',
|
||||
ai_chat_assistant_greeting_afternoon: 'Guten Tag',
|
||||
@@ -77,7 +78,7 @@ export const de = {
|
||||
ai_chat_error: 'Etwas ist schief gelaufen.',
|
||||
ai_chat_context_title: 'Basierend auf Ihrem Kontext',
|
||||
ai_chat_context_description:
|
||||
'Der Docs-Assistent verwendet KI und Ihren Kontext, um Antworten zu generieren und Aktionen durchzuführen.',
|
||||
'Der Assistent verwendet KI und Ihren Kontext, um Antworten zu generieren und Aktionen durchzuführen.',
|
||||
ai_chat_context_pages_youve_read: 'Seiten, die Sie gelesen haben',
|
||||
ai_chat_context_info_provided_by_the_site: 'Von der Website bereitgestellte Informationen',
|
||||
ai_chat_context_previous_messages: 'Vorherige Nachrichten',
|
||||
@@ -92,4 +93,14 @@ export const de = {
|
||||
ai_chat_tools_listed_pages: 'Docs durchsucht',
|
||||
ai_chat_tools_read_page: 'Seite ${1} gelesen',
|
||||
ai_chat_tools_mcp_tool: 'Aufgerufen ${1}',
|
||||
ai_chat_ask: 'Frage ${1}',
|
||||
ai_chat_ask_about_page: 'Frage ${1} zu dieser Seite',
|
||||
copy_for_llms: 'Für LLMs kopieren',
|
||||
copy_page_markdown: 'Seite als Markdown für LLMs kopieren',
|
||||
copy_page: 'Seite kopieren',
|
||||
view_page_markdown: 'Als Markdown anzeigen',
|
||||
view_page_plaintext: 'Diese Seite als Klartext anzeigen',
|
||||
open_in: 'Öffnen in ${1}',
|
||||
open_in_llms_pre_prompt: 'Lies ${1} und beantworte Fragen zum Inhalt.',
|
||||
ask: 'Fragen',
|
||||
};
|
||||
|
||||
@@ -14,6 +14,7 @@ export const en = {
|
||||
search_results_count: '${1} results',
|
||||
search_scope_space: '${1}',
|
||||
search_scope_all: 'All content',
|
||||
ask: 'Ask',
|
||||
search_ask: 'Ask "${1}"',
|
||||
search_ask_description: 'Find the answer with AI',
|
||||
search_ask_sources: 'Sources',
|
||||
@@ -62,7 +63,8 @@ export const en = {
|
||||
link_tooltip_external_link: 'External link to',
|
||||
link_tooltip_page_anchor: 'Jump to section',
|
||||
open_in_new_tab: 'Open in new tab',
|
||||
ai_chat_assistant_name: 'Docs Assistant',
|
||||
ai_chat_assistant_name: 'GitBook Assistant',
|
||||
ai_chat_assistant_name_unbranded: 'AI Assistant',
|
||||
ai_chat_assistant_description: "I'm here to help you with the docs.",
|
||||
ai_chat_assistant_greeting_morning: 'Good morning',
|
||||
ai_chat_assistant_greeting_afternoon: 'Good afternoon',
|
||||
@@ -75,7 +77,7 @@ export const en = {
|
||||
ai_chat_error: 'Something went wrong.',
|
||||
ai_chat_context_title: 'Based on your context',
|
||||
ai_chat_context_description:
|
||||
'Docs Assistant uses AI and your context to generate answers and perform actions.',
|
||||
'The assistant uses AI and your context to generate answers and perform actions.',
|
||||
ai_chat_context_pages_youve_read: "Pages you've read",
|
||||
ai_chat_context_info_provided_by_the_site: 'Info provided by the site',
|
||||
ai_chat_context_previous_messages: 'Previous messages',
|
||||
@@ -90,4 +92,13 @@ export const en = {
|
||||
ai_chat_tools_listed_pages: 'Browsed the docs',
|
||||
ai_chat_tools_read_page: 'Read page ${1}',
|
||||
ai_chat_tools_mcp_tool: 'Called ${1}',
|
||||
ai_chat_ask: 'Ask ${1}',
|
||||
ai_chat_ask_about_page: 'Ask ${1} about this page',
|
||||
copy_for_llms: 'Copy for LLMs',
|
||||
copy_page_markdown: 'Copy page as Markdown for LLMs',
|
||||
copy_page: 'Copy page',
|
||||
view_page_markdown: 'View as Markdown',
|
||||
view_page_plaintext: 'View this page as plain text',
|
||||
open_in: 'Open in ${1}',
|
||||
open_in_llms_pre_prompt: 'Read ${1} and answer questions about the content.',
|
||||
};
|
||||
|
||||
@@ -66,7 +66,8 @@ export const es: TranslationLanguage = {
|
||||
link_tooltip_external_link: 'Enlace externo a',
|
||||
link_tooltip_page_anchor: 'Saltar a la sección',
|
||||
open_in_new_tab: 'Abrir en una nueva pestaña',
|
||||
ai_chat_assistant_name: 'Asistente de Docs',
|
||||
ai_chat_assistant_name: 'Asistente de GitBook',
|
||||
ai_chat_assistant_name_unbranded: 'Asistente de IA',
|
||||
ai_chat_assistant_description: 'Estoy aquí para ayudarte con la documentación.',
|
||||
ai_chat_assistant_greeting_morning: 'Buenos días',
|
||||
ai_chat_assistant_greeting_afternoon: 'Buenas tardes',
|
||||
@@ -79,7 +80,7 @@ export const es: TranslationLanguage = {
|
||||
ai_chat_error: 'Algo salió mal.',
|
||||
ai_chat_context_title: 'Basado en tu contexto',
|
||||
ai_chat_context_description:
|
||||
'El Asistente de Docs usa IA y tu contexto para generar respuestas y realizar acciones.',
|
||||
'El asistente usa IA y tu contexto para generar respuestas y realizar acciones.',
|
||||
ai_chat_context_pages_youve_read: 'Páginas que has leído',
|
||||
ai_chat_context_info_provided_by_the_site: 'Información proporcionada por el sitio',
|
||||
ai_chat_context_previous_messages: 'Mensajes anteriores',
|
||||
@@ -94,4 +95,14 @@ export const es: TranslationLanguage = {
|
||||
ai_chat_tools_listed_pages: 'Exploró los docs',
|
||||
ai_chat_tools_read_page: 'Leyó la página ${1}',
|
||||
ai_chat_tools_mcp_tool: 'Llamó a ${1}',
|
||||
ai_chat_ask: 'Preguntar ${1}',
|
||||
ai_chat_ask_about_page: 'Preguntar a ${1} sobre esta página',
|
||||
copy_for_llms: 'Copiar para LLMs',
|
||||
copy_page_markdown: 'Copiar página como Markdown para LLMs',
|
||||
copy_page: 'Copiar página',
|
||||
view_page_markdown: 'Ver como Markdown',
|
||||
view_page_plaintext: 'Ver esta página como texto plano',
|
||||
open_in: 'Abrir en ${1}',
|
||||
open_in_llms_pre_prompt: 'Lee ${1} y responde preguntas sobre el contenido.',
|
||||
ask: 'Preguntar',
|
||||
};
|
||||
|
||||
@@ -64,7 +64,8 @@ export const fr: TranslationLanguage = {
|
||||
link_tooltip_external_link: 'Lien externe à',
|
||||
link_tooltip_page_anchor: 'Sauter à la section',
|
||||
open_in_new_tab: 'Ouvrir dans un nouvel onglet',
|
||||
ai_chat_assistant_name: 'Assistant Docs',
|
||||
ai_chat_assistant_name: 'Assistant GitBook',
|
||||
ai_chat_assistant_name_unbranded: 'Assistant IA',
|
||||
ai_chat_assistant_description: 'Je suis là pour vous aider avec la documentation.',
|
||||
ai_chat_assistant_greeting_morning: 'Bonjour',
|
||||
ai_chat_assistant_greeting_afternoon: 'Bon après-midi',
|
||||
@@ -77,7 +78,7 @@ export const fr: TranslationLanguage = {
|
||||
ai_chat_error: 'Une erreur est survenue.',
|
||||
ai_chat_context_title: 'Basé sur votre contexte',
|
||||
ai_chat_context_description:
|
||||
"L'Assistant Docs utilise l'IA et votre contexte pour générer des réponses et effectuer des actions.",
|
||||
"L'assistant utilise l'IA et votre contexte pour générer des réponses et effectuer des actions.",
|
||||
ai_chat_context_pages_youve_read: 'Pages que vous avez lues',
|
||||
ai_chat_context_info_provided_by_the_site: 'Informations fournies par le site',
|
||||
ai_chat_context_previous_messages: 'Messages précédents',
|
||||
@@ -92,4 +93,14 @@ export const fr: TranslationLanguage = {
|
||||
ai_chat_tools_listed_pages: 'Parcouru les docs',
|
||||
ai_chat_tools_read_page: 'Lu la page ${1}',
|
||||
ai_chat_tools_mcp_tool: 'Appelé ${1}',
|
||||
ai_chat_ask: 'Demander à ${1}',
|
||||
ai_chat_ask_about_page: 'Demander à ${1} au sujet de cette page',
|
||||
copy_for_llms: 'Copier pour les LLMs',
|
||||
copy_page_markdown: 'Copier la page en Markdown pour les LLMs',
|
||||
copy_page: 'Copier la page',
|
||||
view_page_markdown: 'Voir en Markdown',
|
||||
view_page_plaintext: 'Voir cette page en texte brut',
|
||||
open_in: 'Ouvrir dans ${1}',
|
||||
open_in_llms_pre_prompt: 'Lis ${1} et réponds aux questions sur le contenu.',
|
||||
ask: 'Demander',
|
||||
};
|
||||
|
||||
@@ -64,7 +64,8 @@ export const ja: TranslationLanguage = {
|
||||
link_tooltip_external_link: '外部リンク先',
|
||||
link_tooltip_page_anchor: 'ページ内リンク先',
|
||||
open_in_new_tab: '新しいタブで開く',
|
||||
ai_chat_assistant_name: 'ドキュメントアシスタント',
|
||||
ai_chat_assistant_name: 'GitBookアシスタント',
|
||||
ai_chat_assistant_name_unbranded: 'AIアシスタント',
|
||||
ai_chat_assistant_description: 'ドキュメントについてお手伝いします。',
|
||||
ai_chat_assistant_greeting_morning: 'おはようございます',
|
||||
ai_chat_assistant_greeting_afternoon: 'こんにちは',
|
||||
@@ -77,7 +78,7 @@ export const ja: TranslationLanguage = {
|
||||
ai_chat_error: '何らかのエラーが発生しました。',
|
||||
ai_chat_context_title: 'あなたのコンテキストに基づいて',
|
||||
ai_chat_context_description:
|
||||
'ドキュメントアシスタントはAIとあなたのコンテキストを使用して回答を生成し、アクションを実行します。',
|
||||
'アシスタントはAIとあなたのコンテキストを使用して回答を生成し、アクションを実行します。',
|
||||
ai_chat_context_pages_youve_read: '読んだページ',
|
||||
ai_chat_context_info_provided_by_the_site: 'サイトから提供された情報',
|
||||
ai_chat_context_previous_messages: '以前のメッセージ',
|
||||
@@ -92,4 +93,14 @@ export const ja: TranslationLanguage = {
|
||||
ai_chat_tools_listed_pages: 'ドキュメントを閲覧',
|
||||
ai_chat_tools_read_page: 'ページ ${1} を読みました',
|
||||
ai_chat_tools_mcp_tool: '${1} を呼び出しました',
|
||||
ai_chat_ask: '${1} に質問する',
|
||||
ai_chat_ask_about_page: 'このページについて ${1} に質問する',
|
||||
copy_for_llms: 'LLM 用にコピー',
|
||||
copy_page_markdown: 'ページを Markdown として LLM 用にコピー',
|
||||
copy_page: 'ページをコピー',
|
||||
view_page_markdown: 'Markdown として表示',
|
||||
view_page_plaintext: 'このページをプレーンテキストで表示',
|
||||
open_in: '${1} で開く',
|
||||
open_in_llms_pre_prompt: '${1} を読んで内容に関する質問に答えてください。',
|
||||
ask: '質問する',
|
||||
};
|
||||
|
||||
@@ -64,7 +64,8 @@ export const nl: TranslationLanguage = {
|
||||
link_tooltip_external_link: 'Externe link naar',
|
||||
link_tooltip_page_anchor: 'Spring naar sectie',
|
||||
open_in_new_tab: 'Open in nieuw tabblad',
|
||||
ai_chat_assistant_name: 'Docs Assistent',
|
||||
ai_chat_assistant_name: 'GitBook Assistent',
|
||||
ai_chat_assistant_name_unbranded: 'AI Assistent',
|
||||
ai_chat_assistant_description: 'Ik help je met de documentatie.',
|
||||
ai_chat_assistant_greeting_morning: 'Goedemorgen',
|
||||
ai_chat_assistant_greeting_afternoon: 'Goedemiddag',
|
||||
@@ -77,7 +78,7 @@ export const nl: TranslationLanguage = {
|
||||
ai_chat_error: 'Er is iets misgegaan.',
|
||||
ai_chat_context_title: 'Gebaseerd op je context',
|
||||
ai_chat_context_description:
|
||||
'De Docs Assistent gebruikt AI en je context om antwoorden te genereren en acties uit te voeren.',
|
||||
'De assistent gebruikt AI en je context om antwoorden te genereren en acties uit te voeren.',
|
||||
ai_chat_context_pages_youve_read: "Pagina's die je hebt gelezen",
|
||||
ai_chat_context_info_provided_by_the_site: 'Informatie verstrekt door de site',
|
||||
ai_chat_context_previous_messages: 'Vorige berichten',
|
||||
@@ -92,4 +93,14 @@ export const nl: TranslationLanguage = {
|
||||
ai_chat_tools_listed_pages: 'Docs doorzocht',
|
||||
ai_chat_tools_read_page: 'Pagina ${1} gelezen',
|
||||
ai_chat_tools_mcp_tool: '${1} aangeroepen',
|
||||
ai_chat_ask: 'Vraag ${1}',
|
||||
ai_chat_ask_about_page: 'Vraag ${1} over deze pagina',
|
||||
copy_for_llms: 'Kopiëren voor LLMs',
|
||||
copy_page_markdown: 'Pagina kopiëren als Markdown voor LLMs',
|
||||
copy_page: 'Pagina kopiëren',
|
||||
view_page_markdown: 'Bekijk als Markdown',
|
||||
view_page_plaintext: 'Bekijk deze pagina als platte tekst',
|
||||
open_in: 'Open in ${1}',
|
||||
open_in_llms_pre_prompt: 'Lees ${1} en beantwoord vragen over de inhoud.',
|
||||
ask: 'Vraag',
|
||||
};
|
||||
|
||||
@@ -64,7 +64,8 @@ export const no: TranslationLanguage = {
|
||||
link_tooltip_external_link: 'Ekstern lenke til',
|
||||
link_tooltip_page_anchor: 'Hopp til seksjon',
|
||||
open_in_new_tab: 'Åpne i ny fane',
|
||||
ai_chat_assistant_name: 'Docs-assistent',
|
||||
ai_chat_assistant_name: 'GitBook-assistent',
|
||||
ai_chat_assistant_name_unbranded: 'AI-assistent',
|
||||
ai_chat_assistant_description: 'Jeg er her for å hjelpe deg med docs.',
|
||||
ai_chat_assistant_greeting_morning: 'God morgen',
|
||||
ai_chat_assistant_greeting_afternoon: 'God ettermiddag',
|
||||
@@ -77,7 +78,7 @@ export const no: TranslationLanguage = {
|
||||
ai_chat_error: 'Noe gikk galt.',
|
||||
ai_chat_context_title: 'Basert på din kontekst',
|
||||
ai_chat_context_description:
|
||||
'Docs-assistenten bruker AI og din kontekst til å generere svar og utføre handlinger.',
|
||||
'Assistenten bruker AI og din kontekst til å generere svar og utføre handlinger.',
|
||||
ai_chat_context_pages_youve_read: 'Sider du har lest',
|
||||
ai_chat_context_info_provided_by_the_site: 'Informasjon gitt av nettstedet',
|
||||
ai_chat_context_previous_messages: 'Tidligere meldinger',
|
||||
@@ -92,4 +93,14 @@ export const no: TranslationLanguage = {
|
||||
ai_chat_tools_listed_pages: 'Bladde gjennom docs',
|
||||
ai_chat_tools_read_page: 'Leste side ${1}',
|
||||
ai_chat_tools_mcp_tool: 'Kallte ${1}',
|
||||
ai_chat_ask: 'Spør ${1}',
|
||||
ai_chat_ask_about_page: 'Spør ${1} om denne siden',
|
||||
copy_for_llms: 'Kopier for LLMs',
|
||||
copy_page_markdown: 'Kopier siden som Markdown for LLMs',
|
||||
copy_page: 'Kopier side',
|
||||
view_page_markdown: 'Vis som Markdown',
|
||||
view_page_plaintext: 'Vis denne siden som ren tekst',
|
||||
open_in: 'Åpne i ${1}',
|
||||
open_in_llms_pre_prompt: 'Les ${1} og besvar spørsmål om innholdet.',
|
||||
ask: 'Spør',
|
||||
};
|
||||
|
||||
@@ -64,7 +64,8 @@ export const pt_br = {
|
||||
link_tooltip_external_link: 'Link externo para',
|
||||
link_tooltip_page_anchor: 'Pular para a seção',
|
||||
open_in_new_tab: 'Abrir em uma nova guia',
|
||||
ai_chat_assistant_name: 'Assistente de Docs',
|
||||
ai_chat_assistant_name: 'Assistente do GitBook',
|
||||
ai_chat_assistant_name_unbranded: 'Assistente de IA',
|
||||
ai_chat_assistant_description: 'Estou aqui para ajudá-lo com a documentação.',
|
||||
ai_chat_assistant_greeting_morning: 'Bom dia',
|
||||
ai_chat_assistant_greeting_afternoon: 'Boa tarde',
|
||||
@@ -77,7 +78,7 @@ export const pt_br = {
|
||||
ai_chat_error: 'Algo deu errado.',
|
||||
ai_chat_context_title: 'Baseado no seu contexto',
|
||||
ai_chat_context_description:
|
||||
'O Assistente de Docs usa IA e seu contexto para gerar respostas e realizar ações.',
|
||||
'O assistente usa IA e seu contexto para gerar respostas e realizar ações.',
|
||||
ai_chat_context_pages_youve_read: 'Páginas que você leu',
|
||||
ai_chat_context_info_provided_by_the_site: 'Informações fornecidas pelo site',
|
||||
ai_chat_context_previous_messages: 'Mensagens anteriores',
|
||||
@@ -92,4 +93,14 @@ export const pt_br = {
|
||||
ai_chat_tools_listed_pages: 'Navegou pelos docs',
|
||||
ai_chat_tools_read_page: 'Leu a página ${1}',
|
||||
ai_chat_tools_mcp_tool: 'Chamou ${1}',
|
||||
ai_chat_ask: 'Perguntar a ${1}',
|
||||
ai_chat_ask_about_page: 'Perguntar a ${1} sobre esta página',
|
||||
copy_for_llms: 'Copiar para LLMs',
|
||||
copy_page_markdown: 'Copiar página como Markdown para LLMs',
|
||||
copy_page: 'Copiar página',
|
||||
view_page_markdown: 'Ver como Markdown',
|
||||
view_page_plaintext: 'Ver esta página em texto simples',
|
||||
open_in: 'Abrir no ${1}',
|
||||
open_in_llms_pre_prompt: 'Leia ${1} e responda perguntas sobre o conteúdo.',
|
||||
ask: 'Perguntar',
|
||||
};
|
||||
|
||||
@@ -62,7 +62,8 @@ export const zh: TranslationLanguage = {
|
||||
link_tooltip_external_link: '外部链接到',
|
||||
link_tooltip_page_anchor: '跳转到页面',
|
||||
open_in_new_tab: '在新标签页中打开',
|
||||
ai_chat_assistant_name: '文档助手',
|
||||
ai_chat_assistant_name: 'GitBook 助手',
|
||||
ai_chat_assistant_name_unbranded: 'AI 助手',
|
||||
ai_chat_assistant_description: '我在这里帮助您了解文档。',
|
||||
ai_chat_assistant_greeting_morning: '早上好',
|
||||
ai_chat_assistant_greeting_afternoon: '下午好',
|
||||
@@ -74,7 +75,7 @@ export const zh: TranslationLanguage = {
|
||||
ai_chat_context_badge: 'AI',
|
||||
ai_chat_error: '出了些问题。',
|
||||
ai_chat_context_title: '基于您的上下文',
|
||||
ai_chat_context_description: '文档助手使用人工智能和您的上下文来生成答案并执行操作。',
|
||||
ai_chat_context_description: '助手使用人工智能和您的上下文来生成答案并执行操作。',
|
||||
ai_chat_context_pages_youve_read: '您已阅读的页面',
|
||||
ai_chat_context_info_provided_by_the_site: '网站提供的信息',
|
||||
ai_chat_context_previous_messages: '之前的消息',
|
||||
@@ -89,4 +90,14 @@ export const zh: TranslationLanguage = {
|
||||
ai_chat_tools_listed_pages: '浏览了文档',
|
||||
ai_chat_tools_read_page: '已读取页面 ${1}',
|
||||
ai_chat_tools_mcp_tool: '调用了 ${1}',
|
||||
ai_chat_ask: '向 ${1} 提问',
|
||||
ai_chat_ask_about_page: '向 ${1} 提问有关此页面',
|
||||
copy_for_llms: '为 LLMs 复制',
|
||||
copy_page_markdown: '将页面以 Markdown 格式复制供 LLMs 使用',
|
||||
copy_page: '复制页面',
|
||||
view_page_markdown: '以 Markdown 查看',
|
||||
view_page_plaintext: '以纯文本查看此页面',
|
||||
open_in: '在 ${1} 中打开',
|
||||
open_in_llms_pre_prompt: '阅读 ${1} 并回答内容相关的问题。',
|
||||
ask: '提问',
|
||||
};
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
getDataOrNull,
|
||||
throwIfDataError,
|
||||
} from '@/lib/data';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import { getSiteStructureSections } from '@/lib/sites';
|
||||
import type {
|
||||
ChangeRequest,
|
||||
@@ -24,7 +25,7 @@ import { notFound } from 'next/navigation';
|
||||
import { assert } from 'ts-essentials';
|
||||
import { GITBOOK_URL } from './env';
|
||||
import { type ImageResizer, createImageResizer } from './images';
|
||||
import { type GitBookLinker, createLinker } from './links';
|
||||
import { type GitBookLinker, createLinker, linkerForPublishedURL } from './links';
|
||||
|
||||
/**
|
||||
* Data about the site URL. Provided by the middleware.
|
||||
@@ -290,10 +291,11 @@ export async function fetchSiteContextByIds(
|
||||
return siteSpaceSettings;
|
||||
}
|
||||
|
||||
const logger = getLogger().subLogger('fetchSiteContextByIds', {});
|
||||
// We got the pointer from an API and customizations from another.
|
||||
// It's possible that the two are unsynced leading to not found customizations for the space.
|
||||
// It's better to fallback on customization of the site that displaying an error.
|
||||
console.warn('Customization not found for site space', ids.siteSpace);
|
||||
logger.warn('Customization not found for site space', ids.siteSpace);
|
||||
}
|
||||
|
||||
return customizations.site;
|
||||
@@ -301,6 +303,9 @@ export async function fetchSiteContextByIds(
|
||||
|
||||
return {
|
||||
...spaceContext,
|
||||
linker: site.urls.published
|
||||
? linkerForPublishedURL(spaceContext.linker, site.urls.published)
|
||||
: spaceContext.linker,
|
||||
organizationId: ids.organization,
|
||||
site,
|
||||
siteSpaces,
|
||||
|
||||
@@ -50,124 +50,98 @@ export function createDataFetcher(
|
||||
// API that are tied to the token
|
||||
//
|
||||
getPublishedContentSite(params) {
|
||||
return trace('getPublishedContentSite', () =>
|
||||
getPublishedContentSite(input, {
|
||||
organizationId: params.organizationId,
|
||||
siteId: params.siteId,
|
||||
siteShareKey: params.siteShareKey,
|
||||
})
|
||||
);
|
||||
return getPublishedContentSite(input, {
|
||||
organizationId: params.organizationId,
|
||||
siteId: params.siteId,
|
||||
siteShareKey: params.siteShareKey,
|
||||
});
|
||||
},
|
||||
getSiteRedirectBySource(params) {
|
||||
return trace('getSiteRedirectBySource', () =>
|
||||
getSiteRedirectBySource(input, {
|
||||
organizationId: params.organizationId,
|
||||
siteId: params.siteId,
|
||||
siteShareKey: params.siteShareKey,
|
||||
source: params.source,
|
||||
})
|
||||
);
|
||||
return getSiteRedirectBySource(input, {
|
||||
organizationId: params.organizationId,
|
||||
siteId: params.siteId,
|
||||
siteShareKey: params.siteShareKey,
|
||||
source: params.source,
|
||||
});
|
||||
},
|
||||
getRevision(params) {
|
||||
return trace('getRevision', () =>
|
||||
getRevision(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
})
|
||||
);
|
||||
return getRevision(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
});
|
||||
},
|
||||
getRevisionPageByPath(params) {
|
||||
return trace('getRevisionPageByPath', () =>
|
||||
getRevisionPageByPath(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
path: params.path,
|
||||
})
|
||||
);
|
||||
return getRevisionPageByPath(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
path: params.path,
|
||||
});
|
||||
},
|
||||
getRevisionPageMarkdown(params) {
|
||||
return trace('getRevisionPageMarkdown', () =>
|
||||
getRevisionPageMarkdown(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
})
|
||||
);
|
||||
return getRevisionPageMarkdown(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
});
|
||||
},
|
||||
getRevisionPageDocument(params) {
|
||||
return trace('getRevisionPageDocument', () =>
|
||||
getRevisionPageDocument(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
})
|
||||
);
|
||||
return getRevisionPageDocument(input, {
|
||||
spaceId: params.spaceId,
|
||||
revisionId: params.revisionId,
|
||||
pageId: params.pageId,
|
||||
});
|
||||
},
|
||||
getLatestOpenAPISpecVersionContent(params) {
|
||||
return trace('getLatestOpenAPISpecVersionContent', () =>
|
||||
getLatestOpenAPISpecVersionContent(input, {
|
||||
organizationId: params.organizationId,
|
||||
slug: params.slug,
|
||||
})
|
||||
);
|
||||
return getLatestOpenAPISpecVersionContent(input, {
|
||||
organizationId: params.organizationId,
|
||||
slug: params.slug,
|
||||
});
|
||||
},
|
||||
getSpace(params) {
|
||||
return trace('getSpace', () =>
|
||||
getSpace(input, {
|
||||
spaceId: params.spaceId,
|
||||
shareKey: params.shareKey,
|
||||
})
|
||||
);
|
||||
return getSpace(input, {
|
||||
spaceId: params.spaceId,
|
||||
shareKey: params.shareKey,
|
||||
});
|
||||
},
|
||||
getChangeRequest(params) {
|
||||
return trace('getChangeRequest', () =>
|
||||
getChangeRequest(input, {
|
||||
spaceId: params.spaceId,
|
||||
changeRequestId: params.changeRequestId,
|
||||
})
|
||||
);
|
||||
return getChangeRequest(input, {
|
||||
spaceId: params.spaceId,
|
||||
changeRequestId: params.changeRequestId,
|
||||
});
|
||||
},
|
||||
getDocument(params) {
|
||||
return trace('getDocument', () =>
|
||||
getDocument(input, {
|
||||
spaceId: params.spaceId,
|
||||
documentId: params.documentId,
|
||||
})
|
||||
);
|
||||
return getDocument(input, {
|
||||
spaceId: params.spaceId,
|
||||
documentId: params.documentId,
|
||||
});
|
||||
},
|
||||
getComputedDocument(params) {
|
||||
return trace('getComputedDocument', () =>
|
||||
getComputedDocument(input, {
|
||||
organizationId: params.organizationId,
|
||||
spaceId: params.spaceId,
|
||||
source: params.source,
|
||||
seed: params.seed,
|
||||
})
|
||||
);
|
||||
return getComputedDocument(input, {
|
||||
organizationId: params.organizationId,
|
||||
spaceId: params.spaceId,
|
||||
source: params.source,
|
||||
seed: params.seed,
|
||||
});
|
||||
},
|
||||
getEmbedByUrl(params) {
|
||||
return trace('getEmbedByUrl', () =>
|
||||
getEmbedByUrl(input, {
|
||||
url: params.url,
|
||||
spaceId: params.spaceId,
|
||||
})
|
||||
);
|
||||
return getEmbedByUrl(input, {
|
||||
url: params.url,
|
||||
spaceId: params.spaceId,
|
||||
});
|
||||
},
|
||||
searchSiteContent(params) {
|
||||
return trace('searchSiteContent', () => searchSiteContent(input, params));
|
||||
return searchSiteContent(input, params);
|
||||
},
|
||||
|
||||
renderIntegrationUi(params) {
|
||||
return trace('renderIntegrationUi', () =>
|
||||
renderIntegrationUi(input, {
|
||||
integrationName: params.integrationName,
|
||||
request: params.request,
|
||||
})
|
||||
);
|
||||
return renderIntegrationUi(input, {
|
||||
integrationName: params.integrationName,
|
||||
request: params.request,
|
||||
});
|
||||
},
|
||||
|
||||
getUserById(userId) {
|
||||
return trace('getUserById', () => getUserById(input, { userId }));
|
||||
return getUserById(input, { userId });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
import { GitBookAPIError } from '@gitbook/api';
|
||||
import { parse as parseCacheControl } from '@tusbar/cache-control';
|
||||
import { unstable_cacheLife as cacheLife } from 'next/cache';
|
||||
import type { DataFetcherErrorData, DataFetcherResponse } from './types';
|
||||
|
||||
import parseCacheControl from 'parse-cache-control';
|
||||
|
||||
export class DataFetcherError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
@@ -164,13 +163,8 @@ export function extractCacheControl(error: GitBookAPIError) {
|
||||
}
|
||||
const parsed = parseCacheControl(cacheControl);
|
||||
|
||||
//parseCacheControl does not support stale-while-revalidate, so we need to parse it manually
|
||||
const staleWhileRevalidateMatch = cacheControl.match(/stale-while-revalidate=(\d+)/i);
|
||||
|
||||
const maxAge = parsed?.['max-age'];
|
||||
const staleWhileRevalidate = staleWhileRevalidateMatch
|
||||
? Number.parseInt(staleWhileRevalidateMatch[1], 10)
|
||||
: undefined;
|
||||
const maxAge = parsed?.maxAge ?? parsed?.sharedMaxAge ?? 0;
|
||||
const staleWhileRevalidate = parsed.staleWhileRevalidate ?? undefined;
|
||||
|
||||
return {
|
||||
// If maxAge is 0, we want to apply the default, not 0
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { GITBOOK_IMAGE_RESIZE_URL } from '@/lib/env';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import type { CloudflareImageOptions } from './types';
|
||||
import { copyImageResponse } from './utils';
|
||||
|
||||
@@ -24,8 +25,8 @@ export async function resizeImageWithCDNCgi(
|
||||
resizeOptions
|
||||
)}/${encodeURIComponent(input)}`;
|
||||
|
||||
// biome-ignore lint/suspicious/noConsole: this log is useful for debugging
|
||||
console.log(`resize image using cdn-cgi: ${resizeURL}`);
|
||||
const logger = getLogger().subLogger('imageResizing');
|
||||
logger.log(`resize image using cdn-cgi: ${resizeURL}`);
|
||||
|
||||
return copyImageResponse(
|
||||
await fetch(resizeURL, {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import type { CloudflareImageOptions } from './types';
|
||||
import { copyImageResponse } from './utils';
|
||||
|
||||
@@ -13,8 +14,8 @@ export async function resizeImageWithCFFetch(
|
||||
): Promise<Response> {
|
||||
const { signal, ...resizeOptions } = options;
|
||||
|
||||
// biome-ignore lint/suspicious/noConsole: this log is useful for debugging
|
||||
console.log(`resize image using cf-fetch: ${input}`);
|
||||
const logger = getLogger().subLogger('imageResizing');
|
||||
logger.log(`resize image using cf-fetch: ${input}`);
|
||||
|
||||
return copyImageResponse(
|
||||
await fetch(input, {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'server-only';
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import assertNever from 'assert-never';
|
||||
import { GITBOOK_IMAGE_RESIZE_MODE } from '../../env';
|
||||
import { SizableImageAction, checkIsSizableImageURL } from '../checkIsSizableImageURL';
|
||||
@@ -34,7 +35,8 @@ export async function getImageSize(
|
||||
height: json.original.height,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn(`Error getting image size for ${input}:`, error);
|
||||
const logger = getLogger().subLogger('imageResizing');
|
||||
logger.warn(`Error getting image size for ${input}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import 'server-only';
|
||||
|
||||
import { getLogger } from '@/lib/logger';
|
||||
import fnv1a from '@sindresorhus/fnv1a';
|
||||
import type { MaybePromise } from 'p-map';
|
||||
import { assert } from 'ts-essentials';
|
||||
@@ -33,10 +34,13 @@ export async function verifyImageSignature(
|
||||
const generator = IMAGE_SIGNATURE_FUNCTIONS[version];
|
||||
const generated = await generator(input);
|
||||
|
||||
// biome-ignore lint/suspicious/noConsole: we want to log the signature comparison
|
||||
console.log(
|
||||
`comparing image signature for "${input.url}" on identifier "${input.imagesContextId}": "${generated}" (expected) === "${signature}" (actual)`
|
||||
);
|
||||
const logger = getLogger().subLogger('imageResizing');
|
||||
if (generated !== signature) {
|
||||
// We only log if the signature does not match, to avoid logging useless information
|
||||
logger.log(
|
||||
`comparing image signature for "${input.url}" on identifier "${input.imagesContextId}": "${generated}" (expected) === "${signature}" (actual)`
|
||||
);
|
||||
}
|
||||
return generated === signature;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { createLinker, linkerWithAbsoluteURLs, linkerWithOtherSpaceBasePath } from './links';
|
||||
import {
|
||||
createLinker,
|
||||
linkerForPublishedURL,
|
||||
linkerWithAbsoluteURLs,
|
||||
linkerWithOtherSpaceBasePath,
|
||||
} from './links';
|
||||
|
||||
const root = createLinker({
|
||||
host: 'docs.company.com',
|
||||
@@ -19,6 +24,12 @@ const siteGitBookIO = createLinker({
|
||||
siteBasePath: '/sitename/',
|
||||
});
|
||||
|
||||
const preview = createLinker({
|
||||
host: 'preview',
|
||||
spaceBasePath: '/site_abc/section/space/',
|
||||
siteBasePath: '/site_abc/',
|
||||
});
|
||||
|
||||
describe('toPathInSpace', () => {
|
||||
it('should return the correct path', () => {
|
||||
expect(root.toPathInSpace('some/path')).toBe('/some/path');
|
||||
@@ -88,6 +99,12 @@ describe('toLinkForContent', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('should preserve the search and hash', () => {
|
||||
expect(root.toLinkForContent('https://docs.company.com/some/path?a=b#c')).toBe(
|
||||
'/some/path?a=b#c'
|
||||
);
|
||||
});
|
||||
|
||||
it('should preserve an absolute URL if the site is not the same', () => {
|
||||
expect(siteGitBookIO.toLinkForContent('https://org.gitbook.io/anothersite/some/path')).toBe(
|
||||
'https://org.gitbook.io/anothersite/some/path'
|
||||
@@ -138,3 +155,47 @@ describe('linkerWithOtherSpaceBasePath', () => {
|
||||
expect(otherSpaceBasePathLinker.toPathInSpace('some/path')).toBe('/sitename/a/b/some/path');
|
||||
});
|
||||
});
|
||||
|
||||
describe('linkerForPublishedURL', () => {
|
||||
describe('Root custom domain', () => {
|
||||
it('should rewrite links that belongs to the published site to be part of the preview site', () => {
|
||||
const previewLinker = linkerForPublishedURL(preview, 'https://docs.company.com/');
|
||||
expect(previewLinker.toLinkForContent('https://docs.company.com/some/path')).toBe(
|
||||
'/site_abc/some/path'
|
||||
);
|
||||
expect(
|
||||
previewLinker.toLinkForContent('https://docs.company.com/section/variant/some/path')
|
||||
).toBe('/site_abc/section/variant/some/path');
|
||||
expect(previewLinker.toLinkForContent('https://www.google.com')).toBe(
|
||||
'https://www.google.com'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('gitbook.io domain', () => {
|
||||
it('should rewrite links that belongs to the published site to be part of the preview site', () => {
|
||||
const previewLinker = linkerForPublishedURL(
|
||||
preview,
|
||||
'https://org.gitbook.io/sitename/'
|
||||
);
|
||||
expect(
|
||||
previewLinker.toLinkForContent('https://org.gitbook.io/sitename/some/path')
|
||||
).toBe('/site_abc/some/path');
|
||||
expect(
|
||||
previewLinker.toLinkForContent(
|
||||
'https://org.gitbook.io/sitename/section/variant/some/path'
|
||||
)
|
||||
).toBe('/site_abc/section/variant/some/path');
|
||||
expect(previewLinker.toLinkForContent('https://www.google.com')).toBe(
|
||||
'https://www.google.com'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('should should preserve hash and search', () => {
|
||||
const previewLinker = linkerForPublishedURL(preview, 'https://docs.company.com/');
|
||||
expect(previewLinker.toLinkForContent('https://docs.company.com/some/path?a=b#c')).toBe(
|
||||
'/site_abc/some/path?a=b#c'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -115,7 +115,7 @@ export function createLinker(
|
||||
// If the link points to a content in the same site, we return an absolute path
|
||||
// instead of a full URL; it makes it possible to use router navigation
|
||||
if (url.hostname === servedOn.host && url.pathname.startsWith(servedOn.siteBasePath)) {
|
||||
return url.pathname;
|
||||
return url.pathname + url.search + url.hash;
|
||||
}
|
||||
|
||||
return rawURL;
|
||||
@@ -125,6 +125,37 @@ export function createLinker(
|
||||
return linker;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new linker that intercepts links that belongs to the published site and rewrite them
|
||||
* relative to the URL being served.
|
||||
*
|
||||
* It is needed for preview of site where the served URL (http://preview/site_abc)
|
||||
* is different from the actual published site URL (https://docs.company.com).
|
||||
*/
|
||||
export function linkerForPublishedURL(linker: GitBookLinker, rawSitePublishedURL: string) {
|
||||
const sitePublishedURL = new URL(rawSitePublishedURL);
|
||||
|
||||
return {
|
||||
...linker,
|
||||
toLinkForContent(rawURL: string): string {
|
||||
const url = new URL(rawURL);
|
||||
|
||||
// If the link is part of the published site, we rewrite it to be part of the preview site.
|
||||
if (
|
||||
url.hostname === sitePublishedURL.hostname &&
|
||||
url.pathname.startsWith(sitePublishedURL.pathname)
|
||||
) {
|
||||
// When detecting that the url has been computed as apart of the published site,
|
||||
// we rewrite it to be part of the preview site.
|
||||
const extractedPath = url.pathname.slice(sitePublishedURL.pathname.length);
|
||||
return linker.toPathInSite(extractedPath) + url.search + url.hash;
|
||||
}
|
||||
|
||||
return linker.toLinkForContent(rawURL);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new linker that always returns absolute URLs.
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
export type LogLabelValue = string | number | undefined | boolean;
|
||||
|
||||
export type LogLabels = { [key: string]: LogLabelValue };
|
||||
|
||||
export type SubLoggerOptions = {
|
||||
labels?: LogLabels;
|
||||
};
|
||||
|
||||
export type LoggerOptions = SubLoggerOptions & {
|
||||
requestId?: string;
|
||||
};
|
||||
|
||||
const formatPrefix = (name: string, options: LoggerOptions) => {
|
||||
const { labels } = options;
|
||||
// The tail worker used for extracting the labels expect this format.
|
||||
return `%${JSON.stringify(labels ?? {})}%[${name}]`;
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates a logger with the given name, the logger will prefix all log messages with the name in square brackets.
|
||||
* By default it will include a `requestId` label, and output labels in the log messages.
|
||||
* Format of log messages will be:
|
||||
* `%{"label1":"value1","label2":"value2"}%[loggerName] message...`
|
||||
* @param name The name of the logger, which can be used to create a sub-logger.
|
||||
* @param requestId An optional request ID to include in log messages for better traceability.
|
||||
* @returns A logger object with methods for logging at different levels and creating sub-loggers.
|
||||
*/
|
||||
export const createLogger = (name: string, options: LoggerOptions) => {
|
||||
const { requestId, labels } = options;
|
||||
const finalOptions = { requestId, labels: { ...labels, requestId } };
|
||||
return {
|
||||
subLogger: (subName: string, options?: SubLoggerOptions) =>
|
||||
createLogger(`${name}:${subName}`, {
|
||||
requestId,
|
||||
labels: { ...labels, ...(options?.labels ?? {}) },
|
||||
}),
|
||||
info: (...data: any[]) => console.info(formatPrefix(name, finalOptions), ...data),
|
||||
warn: (...data: any[]) => console.warn(formatPrefix(name, finalOptions), ...data),
|
||||
error: (...data: any[]) => console.error(formatPrefix(name, finalOptions), ...data),
|
||||
debug: (...data: any[]) => console.debug(formatPrefix(name, finalOptions), ...data),
|
||||
log: (...data: any[]) => console.log(formatPrefix(name, finalOptions), ...data),
|
||||
};
|
||||
};
|
||||
|
||||
export type GitbookLogger = ReturnType<typeof createLogger>;
|
||||
|
||||
const getRequestId = (fallbackRequestId?: string) => {
|
||||
// We are in OpenNext and we should have access to the request ID.
|
||||
if ((globalThis as any).__openNextAls) {
|
||||
return (globalThis as any).__openNextAls.getStore()?.requestId;
|
||||
}
|
||||
return fallbackRequestId;
|
||||
};
|
||||
|
||||
export const getLogger =
|
||||
process.env.NEXT_RUNTIME === 'edge'
|
||||
? () => createLogger('GBOV2', { requestId: getRequestId() })
|
||||
: () =>
|
||||
createLogger('GBOV2', {
|
||||
requestId: getRequestId(Math.random().toString(36).substring(2, 15)),
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import type { DataFetcherResponse } from '@/lib/data';
|
||||
import { resolvePagePathDocumentOrGroup } from '@/lib/pages';
|
||||
import { getIndexablePages } from '@/lib/sitemap';
|
||||
import { getMarkdownForPagesTree } from '@/routes/llms';
|
||||
import { type RevisionPageDocument, type RevisionPageGroup, RevisionPageType } from '@gitbook/api';
|
||||
import type { Root } from 'mdast';
|
||||
import { toMarkdown } from 'mdast-util-to-markdown';
|
||||
import remarkParse from 'remark-parse';
|
||||
import { unified } from 'unified';
|
||||
|
||||
type MarkdownResult = DataFetcherResponse<string>;
|
||||
|
||||
/**
|
||||
* Generate a markdown version of a page.
|
||||
* Handles both regular document pages and group pages (pages with child pages).
|
||||
*/
|
||||
export async function getMarkdownForPage(
|
||||
context: GitBookSiteContext,
|
||||
pagePath: string
|
||||
): Promise<MarkdownResult> {
|
||||
const pageLookup = resolvePagePathDocumentOrGroup(context.revision.pages, pagePath);
|
||||
|
||||
if (!pageLookup) {
|
||||
return {
|
||||
error: {
|
||||
message: `Page "${pagePath}" not found`,
|
||||
code: 404,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const { page } = pageLookup;
|
||||
|
||||
// Only handle documents and groups
|
||||
if (page.type !== RevisionPageType.Document && page.type !== RevisionPageType.Group) {
|
||||
return {
|
||||
error: {
|
||||
message: `Page "${pagePath}" is not a document or group`,
|
||||
code: 400,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Handle group pages
|
||||
if (page.type === RevisionPageType.Group) {
|
||||
return servePageGroup(context, page);
|
||||
}
|
||||
|
||||
const { data: markdown, error } = await context.dataFetcher.getRevisionPageMarkdown({
|
||||
spaceId: context.space.id,
|
||||
revisionId: context.revisionId,
|
||||
pageId: page.id,
|
||||
});
|
||||
|
||||
if (error) {
|
||||
return {
|
||||
error: {
|
||||
message: 'An error occurred while fetching the markdown for this page',
|
||||
code: 500,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Handle empty document pages which have children
|
||||
if (isEmptyMarkdownPage(markdown) && page.pages.length > 0) {
|
||||
return servePageGroup(context, page);
|
||||
}
|
||||
|
||||
return {
|
||||
data: markdown,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a page is empty.
|
||||
* A page is empty if it has no content or only a title.
|
||||
*/
|
||||
function isEmptyMarkdownPage(markdown: string): boolean {
|
||||
// Remove frontmatter
|
||||
const stripped = markdown
|
||||
.trim()
|
||||
.replace(/^---\n[\s\S]*?\n---\n?/g, '')
|
||||
.trim();
|
||||
|
||||
// Fast path: try to quickly detect obvious matches
|
||||
if (/^[ \t]*# .+$/m.test(stripped)) {
|
||||
// If there's a single heading line or empty lines, and no other content
|
||||
return (
|
||||
/^#{1,6} .+\s*$/.test(stripped) &&
|
||||
!/\n\S+/g.test(stripped.split('\n').slice(1).join('\n'))
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback: parse with remark for safety
|
||||
const tree = unified().use(remarkParse).parse(stripped) as Root;
|
||||
|
||||
let seenHeading = false;
|
||||
|
||||
for (const node of tree.children) {
|
||||
if (node.type === 'heading') {
|
||||
if (seenHeading) {
|
||||
return false;
|
||||
}
|
||||
seenHeading = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Allow empty whitespace-only text nodes (e.g., extra newlines)
|
||||
if (
|
||||
node.type === 'paragraph' &&
|
||||
node.children.length === 1 &&
|
||||
node.children[0].type === 'text' &&
|
||||
!node.children[0].value.trim()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Anything else is disallowed
|
||||
return false;
|
||||
}
|
||||
|
||||
return seenHeading;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate markdown for a group page by creating a page listing.
|
||||
* Creates a markdown document with the page title as heading and a list of child pages.
|
||||
*/
|
||||
async function servePageGroup(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument | RevisionPageGroup
|
||||
): Promise<MarkdownResult> {
|
||||
const siteSpaceUrl = context.space.urls.published;
|
||||
if (!siteSpaceUrl) {
|
||||
return {
|
||||
error: {
|
||||
message: `Page "${page.title}" is not published`,
|
||||
code: 404,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const indexablePages = getIndexablePages(page.pages);
|
||||
|
||||
// Create a markdown tree with the page title as heading and a list of child pages
|
||||
const markdownTree: Root = {
|
||||
type: 'root',
|
||||
children: [
|
||||
{
|
||||
type: 'heading',
|
||||
depth: 1,
|
||||
children: [{ type: 'text', value: page.title }],
|
||||
},
|
||||
...(await getMarkdownForPagesTree(indexablePages, {
|
||||
siteSpaceUrl,
|
||||
linker: context.linker,
|
||||
withMarkdownPages: true,
|
||||
})),
|
||||
],
|
||||
};
|
||||
|
||||
return {
|
||||
data: toMarkdown(markdownTree, {
|
||||
bullet: '-',
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { OpenAPIParseError, parseOpenAPI } from '@gitbook/openapi-parser';
|
||||
import {
|
||||
type Filesystem,
|
||||
OpenAPIParseError,
|
||||
type OpenAPIParseErrorCode,
|
||||
parseOpenAPI,
|
||||
} from '@gitbook/openapi-parser';
|
||||
|
||||
import { noCacheFetchOptions } from '@/lib/data';
|
||||
import { DataFetcherError, noCacheFetchOptions } from '@/lib/data';
|
||||
import { resolveContentRef } from '@/lib/references';
|
||||
import { unstable_cacheLife as cacheLife } from 'next/cache';
|
||||
import { assert } from 'ts-essentials';
|
||||
@@ -48,18 +53,35 @@ export async function fetchOpenAPIFilesystem(
|
||||
};
|
||||
}
|
||||
|
||||
const fetchFilesystem = async (url: string) => {
|
||||
const fetchFilesystem = async (
|
||||
url: string
|
||||
): Promise<
|
||||
| Filesystem
|
||||
| {
|
||||
error: {
|
||||
code: OpenAPIParseErrorCode;
|
||||
message: string;
|
||||
};
|
||||
}
|
||||
> => {
|
||||
'use cache';
|
||||
try {
|
||||
return await fetchFilesystemUncached(url);
|
||||
} catch (error) {
|
||||
// To avoid hammering the file with requests, we cache the error for around a minute.
|
||||
cacheLife('minutes');
|
||||
// Throwing an error inside a "use cache" function obfuscates the error,
|
||||
// so we need to handle it here and recreates the error outside the cache function.
|
||||
if (error instanceof OpenAPIParseError) {
|
||||
cacheLife('seconds');
|
||||
return { error: { code: error.code, message: error.message } };
|
||||
}
|
||||
throw error;
|
||||
if (error instanceof DataFetcherError) {
|
||||
return { error: { code: 'invalid' as const, message: 'Failed to fetch OpenAPI file' } };
|
||||
}
|
||||
// If the error is not an OpenAPIParseError or DataFetcherError,
|
||||
// we assume it's an unknown error and return a generic error.
|
||||
console.error('Unknown error while fetching OpenAPI file:', error);
|
||||
return { error: { code: 'invalid' as const, message: 'Unknown error' } };
|
||||
}
|
||||
};
|
||||
|
||||
@@ -78,7 +100,7 @@ async function fetchFilesystemUncached(
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to fetch OpenAPI file: ${response.status} ${response.statusText}`);
|
||||
throw new DataFetcherError('Failed to fetch OpenAPI file', response.status);
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { getLogger } from '@/lib/logger';
|
||||
|
||||
export interface TraceSpan {
|
||||
setAttribute: (label: string, value: boolean | string | number) => void;
|
||||
}
|
||||
@@ -38,8 +40,8 @@ export async function trace<T>(
|
||||
} finally {
|
||||
if (process.env.SILENT !== 'true' && process.env.NODE_ENV !== 'development') {
|
||||
const end = now();
|
||||
// biome-ignore lint/suspicious/noConsole: we want to log performance data
|
||||
console.log(
|
||||
const logger = getLogger().subLogger(operation);
|
||||
logger.log(
|
||||
`trace ${completeName} ${traceError ? `failed with ${traceError.message}` : 'succeeded'} in ${end - start}ms`,
|
||||
attributes
|
||||
);
|
||||
|
||||
@@ -1,148 +1,17 @@
|
||||
import type { GitBookSiteContext } from '@/lib/context';
|
||||
import { throwIfDataError } from '@/lib/data';
|
||||
import { resolvePagePathDocumentOrGroup } from '@/lib/pages';
|
||||
import { getIndexablePages } from '@/lib/sitemap';
|
||||
import { getMarkdownForPagesTree } from '@/routes/llms';
|
||||
import { type RevisionPageDocument, type RevisionPageGroup, RevisionPageType } from '@gitbook/api';
|
||||
import type { Root } from 'mdast';
|
||||
import { toMarkdown } from 'mdast-util-to-markdown';
|
||||
import remarkParse from 'remark-parse';
|
||||
import { unified } from 'unified';
|
||||
import { getMarkdownForPage } from '@/lib/markdownPage';
|
||||
|
||||
/**
|
||||
* Generate a markdown version of a page.
|
||||
* Handles both regular document pages and group pages (pages with child pages).
|
||||
* Serve a markdown version of a page.
|
||||
* Returns a 404 if the page is not found.
|
||||
*/
|
||||
export async function servePageMarkdown(context: GitBookSiteContext, pagePath: string) {
|
||||
const pageLookup = resolvePagePathDocumentOrGroup(context.revision.pages, pagePath);
|
||||
const result = await throwIfDataError(getMarkdownForPage(context, pagePath));
|
||||
|
||||
if (!pageLookup) {
|
||||
return new Response(`Page "${pagePath}" not found`, { status: 404 });
|
||||
}
|
||||
|
||||
const { page } = pageLookup;
|
||||
|
||||
// Only handle documents and groups
|
||||
if (page.type !== RevisionPageType.Document && page.type !== RevisionPageType.Group) {
|
||||
return new Response(`Page "${pagePath}" is not a document or group`, { status: 404 });
|
||||
}
|
||||
|
||||
// Handle group pages
|
||||
if (page.type === RevisionPageType.Group) {
|
||||
return servePageGroup(context, page);
|
||||
}
|
||||
|
||||
const markdown = await throwIfDataError(
|
||||
context.dataFetcher.getRevisionPageMarkdown({
|
||||
spaceId: context.space.id,
|
||||
revisionId: context.revisionId,
|
||||
pageId: page.id,
|
||||
})
|
||||
);
|
||||
|
||||
// Handle empty document pages which have children
|
||||
if (isEmptyMarkdownPage(markdown) && page.pages.length > 0) {
|
||||
return servePageGroup(context, page);
|
||||
}
|
||||
|
||||
return new Response(markdown, {
|
||||
return new Response(result, {
|
||||
headers: {
|
||||
'Content-Type': 'text/markdown; charset=utf-8',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if a page is empty.
|
||||
* A page is empty if it has no content or only a title.
|
||||
*/
|
||||
function isEmptyMarkdownPage(markdown: string): boolean {
|
||||
// Remove frontmatter
|
||||
const stripped = markdown
|
||||
.trim()
|
||||
.replace(/^---\n[\s\S]*?\n---\n?/g, '')
|
||||
.trim();
|
||||
|
||||
// Fast path: try to quickly detect obvious matches
|
||||
if (/^[ \t]*# .+$/m.test(stripped)) {
|
||||
// If there's a single heading line or empty lines, and no other content
|
||||
return (
|
||||
/^#{1,6} .+\s*$/.test(stripped) &&
|
||||
!/\n\S+/g.test(stripped.split('\n').slice(1).join('\n'))
|
||||
);
|
||||
}
|
||||
|
||||
// Fallback: parse with remark for safety
|
||||
const tree = unified().use(remarkParse).parse(stripped) as Root;
|
||||
|
||||
let seenHeading = false;
|
||||
|
||||
for (const node of tree.children) {
|
||||
if (node.type === 'heading') {
|
||||
if (seenHeading) {
|
||||
return false;
|
||||
}
|
||||
seenHeading = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Allow empty whitespace-only text nodes (e.g., extra newlines)
|
||||
if (
|
||||
node.type === 'paragraph' &&
|
||||
node.children.length === 1 &&
|
||||
node.children[0].type === 'text' &&
|
||||
!node.children[0].value.trim()
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Anything else is disallowed
|
||||
return false;
|
||||
}
|
||||
|
||||
return seenHeading;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate markdown for a group page by creating a page listing.
|
||||
* Creates a markdown document with the page title as heading and a list of child pages.
|
||||
*/
|
||||
async function servePageGroup(
|
||||
context: GitBookSiteContext,
|
||||
page: RevisionPageDocument | RevisionPageGroup
|
||||
) {
|
||||
const siteSpaceUrl = context.space.urls.published;
|
||||
if (!siteSpaceUrl) {
|
||||
return new Response(`Page "${page.title}" is not published`, { status: 404 });
|
||||
}
|
||||
|
||||
const indexablePages = getIndexablePages(page.pages);
|
||||
|
||||
// Create a markdown tree with the page title as heading and a list of child pages
|
||||
const markdownTree: Root = {
|
||||
type: 'root',
|
||||
children: [
|
||||
{
|
||||
type: 'heading',
|
||||
depth: 1,
|
||||
children: [{ type: 'text', value: page.title }],
|
||||
},
|
||||
...(await getMarkdownForPagesTree(indexablePages, {
|
||||
siteSpaceUrl,
|
||||
linker: context.linker,
|
||||
withMarkdownPages: true,
|
||||
})),
|
||||
],
|
||||
};
|
||||
|
||||
return new Response(
|
||||
toMarkdown(markdownTree, {
|
||||
bullet: '-',
|
||||
}),
|
||||
{
|
||||
headers: {
|
||||
'Content-Type': 'text/markdown; charset=utf-8',
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -375,20 +375,36 @@ const config: Config = {
|
||||
},
|
||||
},
|
||||
pathLoading: {
|
||||
'0%,10%': {
|
||||
strokeDasharray: '100 100',
|
||||
strokeDashoffset: '0',
|
||||
opacity: '1',
|
||||
},
|
||||
'50%': {
|
||||
strokeDasharray: '100 100',
|
||||
strokeDashoffset: '-100',
|
||||
opacity: '0',
|
||||
},
|
||||
'51%': {
|
||||
strokeDasharray: '0 100',
|
||||
strokeDashoffset: '0',
|
||||
opacity: '0',
|
||||
},
|
||||
'90%,100%': {
|
||||
strokeDasharray: '100 100',
|
||||
strokeDashoffset: '0',
|
||||
opacity: '1',
|
||||
},
|
||||
},
|
||||
pathEnter: {
|
||||
'0%': {
|
||||
strokeDasharray: '0 100',
|
||||
strokeDashoffset: '0',
|
||||
opacity: '0',
|
||||
},
|
||||
'40%, 60%': {
|
||||
strokeDasharray: '100 100',
|
||||
strokeDashoffset: '0',
|
||||
opacity: '1',
|
||||
},
|
||||
'100%': {
|
||||
strokeDasharray: '100 100',
|
||||
strokeDashoffset: '-100',
|
||||
opacity: '0',
|
||||
strokeDashoffset: '0',
|
||||
},
|
||||
},
|
||||
stroke: {
|
||||
@@ -408,6 +424,14 @@ const config: Config = {
|
||||
opacity: '0',
|
||||
},
|
||||
},
|
||||
bob: {
|
||||
'0%, 100%': {
|
||||
transform: 'translateY(0)',
|
||||
},
|
||||
'50%': {
|
||||
transform: 'translateY(-10%)',
|
||||
},
|
||||
},
|
||||
enterFromRight: {
|
||||
from: { opacity: '0', transform: 'translateX(50%)', display: 'none' },
|
||||
to: { opacity: '1', transform: 'translateX(0)', display: 'block' },
|
||||
@@ -450,6 +474,7 @@ const config: Config = {
|
||||
},
|
||||
opacity: opacity(),
|
||||
screens: {
|
||||
xs: '480px',
|
||||
sm: '640px',
|
||||
md: '768px',
|
||||
lg: '1024px',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { ErrorObject } from '@scalar/openapi-parser';
|
||||
|
||||
type OpenAPIParseErrorCode =
|
||||
export type OpenAPIParseErrorCode =
|
||||
| 'invalid'
|
||||
| 'parse-v2-in-v3'
|
||||
| 'v2-conversion'
|
||||
|
||||
Reference in New Issue
Block a user