Compare commits

...

3 Commits

Author SHA1 Message Date
Steeve Pastorelli 46fb745c4c changeset 2026-11-18 22:17:10 +01:00
Steeve Pastorelli 50afd7f1b8 Move the Git metadata tests to the page actions 2026-11-18 22:17:09 +01:00
Steeve Pastorelli f39580fddc Make the page actions menu load its own data 2026-11-18 22:17:09 +01:00
8 changed files with 280 additions and 211 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
@@ -0,0 +1,31 @@
import type { RevisionPageDocument } from '@gitbook/api';
import { PageActionsDropdown } from './PageActionsDropdown';
import { getPageActionsURLs } from './pageActionsURLs';
import type { GitBookSiteContext } from '@/lib/context';
/**
* Menu of the page actions. It loads what it shows from the context and the page alone, so it can be
* rendered and cached apart from the page body.
*/
export async function PageActionsMenu(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
}) {
const { context, page } = props;
const { linker, revision } = context;
return (
<PageActionsDropdown
siteTitle={context.site.title}
urls={await getPageActionsURLs(context, page)}
actions={context.customization.pageActions}
page={{
id: page.id,
title: page.title,
path: page.path,
href: linker.toPathForPage({ pages: revision.pages, page }),
}}
/>
);
}
@@ -0,0 +1,101 @@
import { describe, expect, it, mock } from 'bun:test';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { getPageGitMetadata } = await import('./pageActionsData');
const page = {
id: 'page-1',
title: 'Introduction',
kind: 'sheet',
type: 'document',
path: 'readme',
slug: 'readme',
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('getPageGitMetadata', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result).toEqual(git);
});
it('does not fetch Git metadata already on the page', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await getPageGitMetadata(context, { ...page, git });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await getPageGitMetadata(context, page);
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result).toBeUndefined();
});
});
@@ -0,0 +1,63 @@
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
const CONFIGURABLE_PAGE_ACTIONS = [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
CustomizationPageActionType.Git,
];
/**
* Whether a given built-in page action is enabled.
*/
export function isPageActionEnabled(
customization: GitBookSiteContext['customization'],
type: CustomizationPageActionType
): boolean {
const { pageActions } = customization;
if (pageActions.items) {
return pageActions.items.includes(type);
}
return false;
}
/**
* Whether any of the configured page actions is enabled. The RSS feed is not part of them: it is
* only offered on pages with an updates block.
*/
export function hasConfiguredPageActions(customization: GitBookSiteContext['customization']) {
return CONFIGURABLE_PAGE_ACTIONS.some((type) => isPageActionEnabled(customization, type));
}
/**
* Get the Git metadata of a page for the Edit on Git action, or nothing when that action is not shown.
*/
export async function getPageGitMetadata(
context: GitBookSiteContext,
page: RevisionPageDocument
): Promise<RevisionPageDocument['git']> {
if (
!context.space.gitSync?.url ||
!isPageActionEnabled(context.customization, CustomizationPageActionType.Git)
) {
return undefined;
}
if (page.git) {
return page.git;
}
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
return pageWithMetadata?.type === 'document' ? pageWithMetadata.git : undefined;
}
@@ -0,0 +1,66 @@
import urlJoin from 'url-join';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import { getPDFURLSearchParams } from '../PDF';
import { getPageGitMetadata, isPageActionEnabled } from './pageActionsData';
import type { PageActionsDropdownURLs } from './PageActionsDropdown';
import type { GitBookSiteContext } from '@/lib/context';
import { getPageDocument } from '@/lib/data';
import { hasTopLevelBlock } from '@/lib/document';
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
import { getPageRSSURL } from '@/routes/rss';
/**
* Return the URLs for the page actions. The page's Git path and RSS feed are loaded here, so the
* page actions depend on the context and the page alone.
*/
export async function getPageActionsURLs(
context: GitBookSiteContext,
page: RevisionPageDocument
): Promise<PageActionsDropdownURLs> {
const [document, git] = await Promise.all([
getPageDocument(context, page),
getPageGitMetadata(context, page),
]);
// Update blocks can only be at the top level of the document, so we optimize the check.
const withRSSFeed = document
? hasTopLevelBlock(document, (block) => block.type === 'updates')
: false;
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
const { gitSync } = context.space;
return {
html: context.linker.toAbsoluteURL(pagePath),
// For the markdown URL, we use the page.path to ensure it works for the default page.
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
editOnGit:
gitSync?.url && git
? {
provider: gitSync.installationProvider,
url: urlJoin(gitSync.url, git.path),
}
: undefined,
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
? context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
)
: undefined,
mcp: getPageActionsMCPURL(context),
};
}
/**
* Return the MCP URL to be used in the page actions dropdown.
*/
function getPageActionsMCPURL(context: GitBookSiteContext) {
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
}
@@ -1,24 +1,19 @@
import assertNever from 'assert-never';
import urlJoin from 'url-join';
import {
CustomizationPageActionType,
type RevisionPage,
type RevisionPageDocument,
type SiteSection,
type SiteSectionGroup,
import type {
RevisionPage,
RevisionPageDocument,
SiteSection,
SiteSectionGroup,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { SpacesDropdownMenuItems, type VariantSpace } from '../Header/SpacesDropdownMenuItem';
import { CONTENT_STYLE, CONTENT_STYLE_REDUCED } from '../layout';
import {
PageActionsDropdown,
type PageActionsDropdownURLs,
} from '../PageActions/PageActionsDropdown';
import { hasConfiguredPageActions } from '../PageActions/pageActionsData';
import { PageActionsMenu } from '../PageActions/PageActionsMenu';
import { PageAsideToggleButton } from '../PageAside/PageAsideButton';
import { PageIcon } from '../PageIcon';
import { getPDFURLSearchParams } from '../PDF';
import {
findBestTargetURL,
getTargetURLForSiteSpace,
@@ -27,11 +22,9 @@ import { categorizeVariants } from '../SpaceLayout/categorizeVariants';
import { BreadcrumbItemDropdown, type BreadcrumbSibling } from './BreadcrumbItemDropdown';
import { PageTags } from './PageTags';
import type { GitBookSiteContext, SiteStructureNode } from '@/lib/context';
import { hasAdaptiveMcpEndpoint } from '@/lib/mcp/endpoints';
import { type AncestorRevisionPage, resolveFirstDocument } from '@/lib/pages';
import { getLocalizedTitle } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import { getPageRSSURL } from '@/routes/rss';
export async function PageHeader(props: {
context: GitBookSiteContext;
@@ -146,15 +139,8 @@ export async function PageHeader(props: {
// Show page actions if *any* of the configured actions are enabled, or if the RSS feed is
// available. RSS is contextual (only on update/blog index pages) and is not part of the
// configured `items` list, so it is checked separately.
const hasConfiguredPageActions = [
CustomizationPageActionType.Assistant,
CustomizationPageActionType.ExternalAi,
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Mcp,
CustomizationPageActionType.Pdf,
CustomizationPageActionType.Git,
].some((type) => isPageActionEnabled(context.customization, type));
const hasPageActions = pageActionsEnabled && (hasConfiguredPageActions || withRSSFeed);
const hasPageActions =
pageActionsEnabled && (hasConfiguredPageActions(context.customization) || withRSSFeed);
if (!page.layout.title && !page.layout.description && !hasPageActions) {
return null;
@@ -181,19 +167,7 @@ export async function PageHeader(props: {
]
)}
>
{hasPageActions ? (
<PageActionsDropdown
siteTitle={context.site.title}
urls={getPageActionsURLs({ context, page, withRSSFeed })}
actions={context.customization.pageActions}
page={{
id: page.id,
title: page.title,
path: page.path,
href: linker.toPathForPage({ pages: revision.pages, page }),
}}
/>
) : null}
{hasPageActions ? <PageActionsMenu context={context} page={page} /> : null}
<PageAsideToggleButton />
</div>
);
@@ -520,67 +494,3 @@ function BreadcrumbSeparator() {
/>
);
}
/**
* Return the URLs for the page actions.
*/
function getPageActionsURLs({
context,
page,
withRSSFeed,
}: {
context: GitBookSiteContext;
page: RevisionPageDocument;
withRSSFeed: boolean;
}): PageActionsDropdownURLs {
const pagePath = context.linker.toPathForPage({ pages: context.revision.pages, page });
return {
html: context.linker.toAbsoluteURL(pagePath),
// For the markdown URL, we use the page.path to ensure it works for the default page.
markdown: `${context.linker.toAbsoluteURL(context.linker.toPathInSpace(page.path))}.md`,
rss: withRSSFeed ? getPageRSSURL(context, page) : undefined,
editOnGit:
isPageActionEnabled(context.customization, CustomizationPageActionType.Git) &&
context.space.gitSync?.url &&
page.git
? {
provider: context.space?.gitSync?.installationProvider,
url: urlJoin(context.space.gitSync.url, page.git.path),
}
: undefined,
pdf: isPageActionEnabled(context.customization, CustomizationPageActionType.Pdf)
? context.linker.toPathInSpace(
`~gitbook/pdf?${getPDFURLSearchParams({
page: page.id,
only: true,
limit: 100,
}).toString()}`
)
: undefined,
mcp: getPageActionsMCPURL(context),
};
}
/**
* Whether a given built-in page action is enabled.
*/
function isPageActionEnabled(
customization: GitBookSiteContext['customization'],
type: CustomizationPageActionType
): boolean {
const { pageActions } = customization;
if (pageActions.items) {
return pageActions.items.includes(type);
}
return false;
}
/**
* Return the MCP URL to be used in the page actions dropdown.
*/
function getPageActionsMCPURL(context: GitBookSiteContext) {
const useAuthenticatedEndpoint = hasAdaptiveMcpEndpoint(context) && context.isLoggedInVisitor;
const endpoint = useAuthenticatedEndpoint ? '~gitbook/mcp/auth' : '~gitbook/mcp';
return context.linker.toAbsoluteURL(context.linker.toPathInSite(endpoint));
}
@@ -1,17 +1,13 @@
import { describe, expect, it, mock } from 'bun:test';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const {
fetchPageData,
getLowercasePathnameRedirect,
resolveMissingPagePath,
resolveSitePageFromURL,
} = await import('./fetch');
const { getLowercasePathnameRedirect, resolveMissingPagePath, resolveSitePageFromURL } =
await import('./fetch');
const { normalizeURL } = await import('@/lib/data/urls');
const { createLinker } = await import('@/lib/links');
@@ -25,81 +21,6 @@ const page = {
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revision: { pages: [page] },
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('fetchPageData', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result.pageTarget?.page.git).toEqual(git);
expect(result.context.page?.git).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
});
describe('resolveMissingPagePath', () => {
function createRedirectContext(options: {
siteRedirect?: { source?: string; target: string; permanent?: boolean };
@@ -1,7 +1,6 @@
import { permanentRedirect, redirect } from 'next/navigation';
import {
CustomizationPageActionType,
type RevisionPageDocument,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
@@ -30,34 +29,7 @@ export type PageParams = PagePathParams | PageIdParams;
* Optimized to fetch in parallel as much as possible.
*/
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
let pageTarget = await resolvePage(context, params);
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
if (
pageTarget &&
!pageTarget.page.git &&
context.space.gitSync?.url &&
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
) {
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: pageTarget.page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
pageTarget = {
...pageTarget,
page: {
...pageTarget.page,
git: pageWithMetadata.git,
},
};
}
}
const pageTarget = await resolvePage(context, params);
return {
context: {