Initial version

This commit is contained in:
Zeno Kapitein
2025-04-08 18:25:14 +02:00
parent 5a69692f54
commit 8547867c6d
11 changed files with 433 additions and 176 deletions
+1 -1
View File
@@ -24,7 +24,7 @@
},
"scripts": {
"generate": "rm -rf ./public && cp -r ../gitbook/public ./public",
"dev:v2": "env-cmd --silent -f ../../.env.local next --turbopack",
"dev:v2": "env-cmd --silent -f ../../.env.local next",
"build": "next build",
"build:v2": "next build",
"start": "next start",
+1
View File
@@ -1394,6 +1394,7 @@ async function* streamAIResponse(
input: params.input,
output: params.output,
model: params.model,
tools: params.tools,
});
for await (const event of res) {
@@ -189,5 +189,6 @@ export interface GitBookDataFetcher {
input: api.AIMessageInput[];
output: api.AIOutputFormat;
model: api.AIModel;
tools?: api.AIToolCapabilities;
}): AsyncGenerator<api.AIStreamResponse, void, unknown>;
}
@@ -0,0 +1,82 @@
'use client';
import { tcls } from '@/lib/tailwind';
import { Icon, type IconName } from '@gitbook/icons';
import { useEffect } from 'react';
import { useState } from 'react';
import { useVisitedPages } from '../Insights';
import { usePageContext } from '../PageContext';
import { streamPageJourneySuggestions } from './server-actions';
export function AIPageJourneySuggestions(props: { spaces: { id: string; title: string }[] }) {
const { spaces } = props;
const currentPage = usePageContext();
// const language = useLanguage();
const visitedPages = useVisitedPages((state) => state.pages);
const [journeys, setJourneys] = useState<({ label?: string; icon?: string } | undefined)[]>([]);
useEffect(() => {
let canceled = false;
(async () => {
const stream = await streamPageJourneySuggestions({
currentPage: {
id: currentPage.pageId,
title: currentPage.title,
},
currentSpace: {
id: currentPage.spaceId,
},
allSpaces: spaces,
visitedPages,
});
for await (const journeys of stream) {
if (canceled) return;
setJourneys(journeys);
}
})();
return () => {
canceled = true;
};
}, [currentPage.pageId, currentPage.spaceId, visitedPages, spaces]);
const shimmerBlocks = [
'[animation-delay:-.2s]',
'[animation-delay:-.4s]',
'[animation-delay:-.6s]',
'[animation-delay:-.8s]',
];
return (
<div className="grid w-72 grid-cols-2 gap-2 text-sm">
{shimmerBlocks.map((block, i) =>
journeys[i]?.icon ? (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: The index is the only identifier available, since we don't know the content of the block until it's loaded in.
key={i}
className="flex animate-fadeIn flex-col items-center justify-center gap-2 rounded border border-tint px-2 py-4 text-center [animation-delay:.2s] [animation-fill-mode:both]"
>
<Icon
icon={journeys[i].icon as IconName}
className="size-4 text-tint-subtle"
/>
{journeys[i].label}
</div>
) : (
<div
// biome-ignore lint/suspicious/noArrayIndexKey: The index is the only identifier available, since we don't know the content of the block until it's loaded in.
key={i}
className={tcls(
'h-24 animate-pulse rounded-md straight-corners:rounded-none border border-tint-subtle',
block
)}
/>
)
)}
</div>
);
}
@@ -0,0 +1,33 @@
import type { SiteStructure } from '@gitbook/api';
import type { GitBookSiteContext } from '@v2/lib/context';
import { AIPageJourneySuggestions } from './AIPageJourneySuggestions';
export function AdaptivePane(props: { context: GitBookSiteContext }) {
const { context } = props;
return (
<div>
<AIPageJourneySuggestions spaces={getSpaces(context.structure)} />
</div>
);
}
function getSpaces(structure: SiteStructure) {
if (structure.type === 'siteSpaces') {
return structure.structure.map((siteSpace) => ({
id: siteSpace.space.id,
title: siteSpace.space.title,
}));
}
const sections = structure.structure.flatMap((item) =>
item.object === 'site-section-group' ? item.sections : item
);
return sections.flatMap((section) =>
section.siteSpaces.map((siteSpace) => ({
id: siteSpace.space.id,
title: siteSpace.space.title,
}))
);
}
@@ -1,5 +1,10 @@
'use server';
import { type AIMessageInput, AIModel, type AIStreamResponse } from '@gitbook/api';
import {
type AIMessageInput,
AIModel,
type AIStreamResponse,
type AIToolCapabilities,
} from '@gitbook/api';
import type { GitBookBaseContext } from '@v2/lib/context';
import { EventIterator } from 'event-iterator';
import type { MaybePromise } from 'p-map';
@@ -47,11 +52,13 @@ export async function streamGenerateObject<T>(
schema,
messages,
model = AIModel.Fast,
tools = {},
}: {
schema: z.ZodSchema<T>;
messages: AIMessageInput[];
model?: AIModel;
previousResponseId?: string;
tools?: AIToolCapabilities;
}
) {
const rawStream = context.dataFetcher.streamAIResponse({
@@ -62,12 +69,13 @@ export async function streamGenerateObject<T>(
type: 'object',
schema: zodToJsonSchema(schema),
},
tools,
model,
});
let json = '';
return parseResponse<DeepPartial<T>>(rawStream, (event) => {
if (event.type === 'response_object') {
if (event.type === 'response_object' && event.jsonChunk) {
json += event.jsonChunk;
const parsed = partialJson.parse(json, partialJson.ALL);
@@ -1 +1,2 @@
export * from './streamLinkPageSummary';
export * from './streamPageJourneySuggestions';
@@ -0,0 +1,128 @@
'use server';
import { getV1BaseContext } from '@/lib/v1';
import { isV2 } from '@/lib/v2';
import { AIMessageRole } from '@gitbook/api';
import { getSiteURLDataFromMiddleware } from '@v2/lib/middleware';
import { getServerActionBaseContext } from '@v2/lib/server-actions';
import { z } from 'zod';
import { streamGenerateObject } from './api';
/**
* Get a summary of a page, in the context of another page
*/
export async function* streamPageJourneySuggestions({
currentPage,
currentSpace,
allSpaces,
visitedPages,
}: {
currentPage: {
id: string;
title: string;
};
currentSpace: {
id: string;
// title: string;
};
allSpaces: {
id: string;
title: string;
}[];
visitedPages?: Array<{ spaceId: string; pageId: string }>;
}) {
const baseContext = isV2() ? await getServerActionBaseContext() : await getV1BaseContext();
const siteURLData = await getSiteURLDataFromMiddleware();
const { stream } = await streamGenerateObject(
baseContext,
{
organizationId: siteURLData.organization,
siteId: siteURLData.site,
},
{
schema: z.object({
journeys: z
.array(
z.object({
label: z.string().describe('The label of the journey.'),
icon: z
.string()
.describe(
'The icon of the journey. Use an icon from FontAwesome, stripping the `fa-`. Examples: rocket-launch, tennis-ball, cat'
),
})
)
.describe('The possible journeys to take through the documentation.')
.max(4),
}),
tools: {
getPages: true,
getPageContent: true,
},
messages: [
{
role: AIMessageRole.Developer,
content:
"You are a knowledge navigator. Given the user's visited pages and the documentation's table of contents, suggest a named journey through the documentation. A journey is a list of pages that are related to each other. A journey's label starts with a verb and has a clear subject. Use sentence case (so only capitalize the first letter of the first word). Be concise and use short words to fit in the label. For example, use 'docs' instead of 'documentation'. Try to pick out specific journeys, not too generic.",
},
{
role: AIMessageRole.Developer,
content: `The user is in space "${currentSpace.title}"`,
},
{
role: AIMessageRole.Developer,
content: `Other spaces in the documentation are: ${allSpaces
.map(
(space) => `
- "${space.title}" (ID ${space.id})`
)
.join('\n')}
Feel free to create journeys across spaces.`,
},
{
role: AIMessageRole.Developer,
content: `The current page is: "${currentPage.title}" (ID ${currentPage.id}). You can use the getPageContent tool to get the content of any relevant links to include in the journey. Only follow links to pages.`,
attachments: [
{
type: 'page' as const,
spaceId: currentSpace.id,
pageId: currentPage.id,
},
],
},
...(visitedPages && visitedPages.length > 0
? [
{
role: AIMessageRole.Developer,
content: `The user's visited pages are: ${visitedPages.map((page) => page.pageId).join(', ')}. The content of the last 5 pages are included below.`,
attachments: visitedPages.slice(0, 5).map((page) => ({
type: 'page' as const,
spaceId: page.spaceId,
pageId: page.pageId,
})),
},
]
: []),
],
}
);
// const emitted = new Set<string>();
for await (const value of stream) {
const journeys = value.journeys;
if (!journeys) {
continue;
}
// for (const journey of journeys) {
// if (emitted.has(journey)) {
// continue;
// }
// emitted.add(journey);
// yield journey;
// }
yield journeys;
}
}
@@ -0,0 +1,105 @@
import { getSpaceLanguage, t } from '@/intl/server';
import { tcls } from '@/lib/tailwind';
import type { RevisionPageDocument, Space } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSiteContext } from '@v2/lib/context';
import React from 'react';
import { getPDFURLSearchParams } from '../PDF';
import { PageFeedbackForm } from '../PageFeedback';
export function PageActions(props: {
page: RevisionPageDocument;
context: GitBookSiteContext;
withPageFeedback: boolean;
}) {
const { page, withPageFeedback, context } = props;
const { customization, space } = context;
const language = getSpaceLanguage(customization);
const pdfHref = context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
);
return (
<div
className={tcls(
'flex',
'flex-col',
'gap-2',
'sidebar-list-default:px-3',
'page-api-block:xl:max-2xl:px-3',
'empty:hidden'
)}
>
{withPageFeedback ? (
<React.Suspense fallback={null}>
<PageFeedbackForm pageId={page.id} />
</React.Suspense>
) : null}
{/* {customization.git.showEditLink && space.gitSync?.url && page.git ? (
<div>
<a
href={urlJoin(space.gitSync.url, page.git.path)}
className={tcls(
'flex',
'flex-row',
'items-center',
'text-sm',
'hover:text-tint-strong',
'links-accent:hover:underline',
'links-accent:hover:underline-offset-4',
'links-accent:hover:decoration-[3px]',
'links-accent:hover:decoration-primary-subtle'
)}
>
<Icon
icon={
space.gitSync.installationProvider === 'gitlab'
? 'gitlab'
: 'github'
}
className={tcls('size-4', 'mr-1.5')}
/>
{t(language, 'edit_on_git', getGitSyncName(space))}
</a>
</div>
) : null} */}
{customization.pdf.enabled ? (
<div>
<a
href={pdfHref}
className={tcls(
'flex',
'flex-row',
'items-center',
'text-sm',
'hover:text-tint-strong',
'links-accent:hover:underline',
'links-accent:hover:underline-offset-4',
'links-accent:hover:decoration-[3px]',
'links-accent:hover:decoration-primary-subtle'
)}
>
<Icon icon="file-pdf" className={tcls('size-4', 'mr-1.5')} />
{t(language, 'pdf_download')}
</a>
</div>
) : null}
</div>
);
}
function getGitSyncName(space: Space): string {
if (space.gitSync?.installationProvider === 'github') {
return 'GitHub';
}
if (space.gitSync?.installationProvider === 'gitlab') {
return 'GitLab';
}
return 'Git';
}
@@ -3,22 +3,17 @@ import {
type RevisionPageDocument,
SiteAdsStatus,
SiteInsightsAdPlacement,
type Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSiteContext } from '@v2/lib/context';
import React from 'react';
import urlJoin from 'url-join';
import { getSpaceLanguage, t } from '@/intl/server';
import { getDocumentSections } from '@/lib/document-sections';
import { tcls } from '@/lib/tailwind';
import { AdaptivePane } from '../Adaptive/AdaptivePane';
import { Ad } from '../Ads';
import { getPDFURLSearchParams } from '../PDF';
import { PageFeedbackForm } from '../PageFeedback';
import { ThemeToggler } from '../ThemeToggler';
import { ScrollSectionsList } from './ScrollSectionsList';
import { PageActions } from './PageActions';
import { PageOutline } from './PageOutline';
/**
* Aside listing the headings in the document.
@@ -31,28 +26,20 @@ export function PageAside(props: {
withFullPageCover: boolean;
withPageFeedback: boolean;
}) {
const { page, document, withPageFeedback, context } = props;
const { page, document, withPageFeedback, withFullPageCover, withHeaderOffset, context } =
props;
const { customization, site, space } = context;
const language = getSpaceLanguage(customization);
const pdfHref = context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
);
customization.ai.adaptivePane = true;
return (
<aside
className={tcls(
'group/aside',
'hidden',
'xl:flex',
// 'page-no-toc:lg:flex',
'flex-col',
'basis-56',
// 'page-no-toc:basis-40',
// 'page-no-toc:xl:basis-56',
'grow-0',
'shrink-0',
'break-anywhere', // To prevent long words in headings from breaking the layout
@@ -60,6 +47,7 @@ export function PageAside(props: {
'text-tint',
'contrast-more:text-tint-strong',
'sticky',
// Without header
'lg:top-0',
'lg:max-h-screen',
@@ -91,141 +79,19 @@ export function PageAside(props: {
'page-api-block:p-2'
)}
>
{page.layout.outline ? (
<>
<div
className={tcls(
'hidden',
'page-api-block:xl:max-2xl:flex',
'text-xs',
'tracking-wide',
'font-semibold',
'uppercase',
'flex-row',
'items-center',
'gap-2'
)}
>
<Icon icon="block-quote" className={tcls('size-3')} />
{t(language, 'on_this_page')}
<Icon
icon="chevron-down"
className={tcls(
'size-3',
'opacity-6',
'ml-auto',
'page-api-block:xl:max-2xl:group-hover/aside:hidden'
)}
<div className='lg:top:0 sticky flex flex-col gap-6 overflow-y-auto overflow-x-visible border-none py-8 *:border-tint-subtle site-header-sections:lg:top-[6.75rem] site-header:lg:top-16 [&>*:not(:first-child)]:border-t [&>*:not(:first-child)]:pt-6'>
{customization.ai.adaptivePane ? <AdaptivePane context={context} /> : null}
{page.layout.outline ? (
<>
<PageOutline document={document} context={context} />
<PageActions
page={page}
context={context}
withPageFeedback={withPageFeedback}
/>
</div>
<div
className={tcls(
'overflow-y-auto',
'overflow-x-visible',
'flex',
'flex-col',
'shrink',
'pb-12',
'sticky',
'lg:top:0',
'site-header:lg:top-16',
'site-header-sections:lg:top-[6.75rem]',
'gap-6',
'pt-8',
'page-api-block:xl:max-2xl:py-0',
// Hide it for api page, until hovered
'page-api-block:xl:max-2xl:hidden',
'page-api-block:xl:max-2xl:group-hover/aside:flex'
)}
>
{document ? (
<React.Suspense fallback={null}>
<PageAsideSections document={document} context={context} />
</React.Suspense>
) : null}
<div
className={tcls(
'flex',
'flex-col',
'gap-3',
'sidebar-list-default:px-3',
'border-t',
'first:border-none',
'border-tint-subtle',
'py-4',
'first:pt-0',
'page-api-block:xl:max-2xl:px-3',
'empty:hidden'
)}
>
{withPageFeedback ? (
<React.Suspense fallback={null}>
<PageFeedbackForm pageId={page.id} className={tcls('mt-2')} />
</React.Suspense>
) : null}
{customization.git.showEditLink && space.gitSync?.url && page.git ? (
<div>
<a
href={urlJoin(space.gitSync.url, page.git.path)}
className={tcls(
'flex',
'flex-row',
'items-center',
'text-sm',
'hover:text-tint-strong',
'links-accent:hover:underline',
'links-accent:hover:underline-offset-4',
'links-accent:hover:decoration-[3px]',
'links-accent:hover:decoration-primary-subtle',
'py-2'
)}
>
<Icon
icon={
space.gitSync.installationProvider === 'gitlab'
? 'gitlab'
: 'github'
}
className={tcls('size-4', 'mr-1.5')}
/>
{t(language, 'edit_on_git', getGitSyncName(space))}
</a>
</div>
) : null}
{customization.pdf.enabled ? (
<div>
<a
href={pdfHref}
className={tcls(
'flex',
'flex-row',
'items-center',
'text-sm',
'hover:text-tint-strong',
'links-accent:hover:underline',
'links-accent:hover:underline-offset-4',
'links-accent:hover:decoration-[3px]',
'links-accent:hover:decoration-primary-subtle',
'py-2'
)}
>
<Icon
icon="file-pdf"
className={tcls('size-4', 'mr-1.5')}
/>
{t(language, 'pdf_download')}
</a>
</div>
) : null}
</div>
</div>
</>
) : null}
</>
) : null}
</div>
<div
className={tcls(
'sticky bottom-0 z-10 mt-auto flex flex-col bg-tint-base theme-gradient-tint:bg-gradient-tint theme-gradient:bg-gradient-primary theme-muted:bg-tint-subtle pb-4 page-api-block:xl:max-2xl:hidden page-api-block:xl:max-2xl:pb-0 page-api-block:xl:max-2xl:group-hover/aside:flex [html.sidebar-filled.theme-bold.tint_&]:bg-tint-subtle',
@@ -254,22 +120,3 @@ export function PageAside(props: {
</aside>
);
}
async function PageAsideSections(props: { document: JSONDocument; context: GitBookSiteContext }) {
const { document, context } = props;
const sections = await getDocumentSections(context, document);
return sections.length > 1 ? <ScrollSectionsList sections={sections} /> : null;
}
function getGitSyncName(space: Space): string {
if (space.gitSync?.installationProvider === 'github') {
return 'GitHub';
}
if (space.gitSync?.installationProvider === 'gitlab') {
return 'GitLab';
}
return 'Git';
}
@@ -0,0 +1,51 @@
import { getSpaceLanguage, t } from '@/intl/server';
import { getDocumentSections } from '@/lib/document-sections';
import { tcls } from '@/lib/tailwind';
import type { JSONDocument } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { GitBookSiteContext } from '@v2/lib/context';
import React from 'react';
import { ScrollSectionsList } from './ScrollSectionsList';
export function PageOutline(props: {
document: JSONDocument | null;
context: GitBookSiteContext;
}) {
const { document, context } = props;
const { customization } = context;
const language = getSpaceLanguage(customization);
return (
<div>
<div className="mb-1 flex flex-row items-center gap-2 font-semibold text-xs uppercase tracking-wide">
<Icon icon="block-quote" className={tcls('size-3')} />
{t(language, 'on_this_page')}
</div>
<div
className={tcls(
'flex',
'flex-col'
// 'page-api-block:xl:max-2xl:py-0',
// // Hide it for api page, until hovered
// 'page-api-block:xl:max-2xl:hidden',
// 'page-api-block:xl:max-2xl:group-hover/aside:flex'
)}
>
{document ? (
<React.Suspense fallback={null}>
<PageAsideSections document={document} context={context} />
</React.Suspense>
) : null}
</div>
</div>
);
}
async function PageAsideSections(props: { document: JSONDocument; context: GitBookSiteContext }) {
const { document, context } = props;
const sections = await getDocumentSections(context, document);
return sections.length > 1 ? <ScrollSectionsList sections={sections} /> : null;
}