Compare commits

..

3 Commits

Author SHA1 Message Date
Peter White 9d300985bc Merge remote-tracking branch 'origin/main' into peter/updates-pagination 2026-11-26 09:18:38 +00:00
Peter White 9f2701c616 changeset 2026-11-26 09:18:38 +00:00
Peter White 0173636ced Paginate long Updates pages at 20 entries per page 2026-11-26 09:18:38 +00:00
61 changed files with 1652 additions and 115 deletions
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Paginate published Updates pages with more than 50 entries into 20-entry pages.
@@ -0,0 +1,54 @@
import type { Metadata, Viewport } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getDynamicSiteContext, getPagePathFromParams } from '@/app/utils';
import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
} from '@/components/SitePage';
import { parseUpdatesPageParam } from '@/lib/updates-url';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params);
return (
<SitePage
context={context}
pageParams={{ pathname }}
staticRoute={false}
updatesPage={updatesPage}
/>
);
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
const { context } = await getDynamicSiteContext(await props.params);
return generateSitePageViewport(context);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getDynamicSiteContext(params);
const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({
context,
pageParams: { pathname },
updatesPage,
});
}
@@ -0,0 +1,41 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getPagePathFromParams } from '@/app/utils';
import { EmbeddableDocsPage, generateEmbeddableDocsPageMetadata } from '@/components/Embeddable';
import { getEmbeddableDynamicContext } from '@/lib/embeddable';
import { parseUpdatesPageParam } from '@/lib/updates-url';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableDynamicContext(params);
const pathname = getPagePathFromParams(params);
return (
<EmbeddableDocsPage
context={context}
pageParams={{ pathname }}
staticRoute={false}
updatesPage={updatesPage}
/>
);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableDynamicContext(params);
const pathname = getPagePathFromParams(params);
return generateEmbeddableDocsPageMetadata({ context, pageParams: { pathname }, updatesPage });
}
@@ -0,0 +1,56 @@
import type { Metadata, Viewport } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@/app/utils';
import {
SitePage,
generateSitePageMetadata,
generateSitePageViewport,
} from '@/components/SitePage';
import { parseUpdatesPageParam } from '@/lib/updates-url';
export const dynamic = 'force-static';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params);
return (
<SitePage
context={context}
pageParams={{ pathname }}
staticRoute
updatesPage={updatesPage}
/>
);
}
export async function generateViewport(props: PageProps): Promise<Viewport> {
const { context } = await getStaticSiteContext(await props.params);
return generateSitePageViewport(context);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getStaticSiteContext(params);
const pathname = getPagePathFromParams(params);
return generateSitePageMetadata({
context,
pageParams: { pathname },
updatesPage,
});
}
@@ -0,0 +1,43 @@
import type { Metadata } from 'next';
import { notFound } from 'next/navigation';
import { type RouteParams, getPagePathFromParams } from '@/app/utils';
import { EmbeddableDocsPage, generateEmbeddableDocsPageMetadata } from '@/components/Embeddable';
import { getEmbeddableStaticContext } from '@/lib/embeddable';
import { parseUpdatesPageParam } from '@/lib/updates-url';
export const dynamic = 'force-static';
type PageProps = {
params: Promise<RouteParams & { page: string }>;
};
export default async function Page(props: PageProps) {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableStaticContext(params);
const pathname = getPagePathFromParams(params);
return (
<EmbeddableDocsPage
context={context}
pageParams={{ pathname }}
staticRoute
updatesPage={updatesPage}
/>
);
}
export async function generateMetadata(props: PageProps): Promise<Metadata> {
const params = await props.params;
const updatesPage = parseUpdatesPageParam(params.page);
if (updatesPage === null) {
notFound();
}
const { context } = await getEmbeddableStaticContext(params);
const pathname = getPagePathFromParams(params);
return generateEmbeddableDocsPageMetadata({ context, pageParams: { pathname }, updatesPage });
}
@@ -0,0 +1,384 @@
'use client';
import { useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import { useHash, scrollToHash } from '../hooks';
import { CONTENT_STYLE_REDUCED, MAIN_CONTENT_ID } from '../layout';
import { Button, SkeletonUpdate, SuspenseLoadedHint } from '../primitives';
import { UpdatesFilterContext, applyTagFilterAttribute, areTagsEqual } from './UpdatesFilter';
import { UpdatesFilterScript } from './UpdatesFilterScript';
import {
type FilteredUpdatesPageResult,
getFilteredUpdatesPage,
resolveUpdatesAnchor,
} from './UpdatesServerActions';
import { tString, useLanguage } from '@/intl/client';
import {
UPDATES_FILTER_KEY_ATTR,
UPDATES_FILTER_SEARCH_PARAM,
type UpdatesPageRange,
getUpdatesPageRange,
normalizeUpdatesFilterTags,
updatesFilterStyleKey,
} from '@/lib/updates';
import {
UPDATES_PAGE_SEARCH_PARAM,
parseUpdatesPageParam,
setUpdatesPageParam,
} from '@/lib/updates-url';
const PENDING_FILTER_ATTR = 'data-updates-pending-filter';
export const HIDE_PENDING_UPDATES = '[html[data-updates-pending-filter]_&]:hidden';
type FilteredPage = Extract<FilteredUpdatesPageResult, { status: 'ok' }>;
type UpdatesView =
| { status: 'unfiltered'; pagination: UpdatesPageRange }
| { status: 'loading'; pagination: UpdatesPageRange | null }
| { status: 'error'; pagination: null }
| ({ status: 'filtered' } & Omit<FilteredPage, 'status'>);
type UpdatesSelection = { tags: string[]; page: number };
const PaginatedUpdatesContext = React.createContext<{
view: UpdatesView;
goToPage: (page: number) => void;
retry: () => void;
} | null>(null);
export function PaginatedUpdatesProvider(props: {
pageId: string;
revisionId: string;
isEmbeddable: boolean;
tagSlugs: string[];
initialPagination: UpdatesPageRange;
children: React.ReactNode;
}) {
const { pageId, revisionId, isEmbeddable, tagSlugs, initialPagination, children } = props;
const router = useRouter();
const searchParams = useSearchParams();
const hash = useHash();
const availableTags = React.useMemo(() => new Set(tagSlugs), [tagSlugs]);
const styleKey = updatesFilterStyleKey(tagSlugs);
const [selectedTags, setSelectedTags] = React.useState<string[]>([]);
const [view, setView] = React.useState<UpdatesView>({
status: 'unfiltered',
pagination: initialPagination,
});
const selection = React.useRef<UpdatesSelection>({ tags: [], page: initialPagination.page });
const hasNewerRevision = React.useRef(false);
const requestId = React.useRef(0);
React.useLayoutEffect(() => {
document.documentElement.setAttribute(UPDATES_FILTER_KEY_ATTR, styleKey);
return () => {
requestId.current++;
document.documentElement.removeAttribute(UPDATES_FILTER_KEY_ATTR);
document.documentElement.removeAttribute(PENDING_FILTER_ATTR);
applyTagFilterAttribute([]);
};
}, [styleKey]);
const syncLocation = React.useCallback(
(force = false) => {
const url = new URL(window.location.href);
const { tags, page } = getUpdatesSelection(url, availableTags);
const previous = selection.current;
const sameTags = areTagsEqual(tags, previous.tags);
if (!force && sameTags && page === previous.page) {
return;
}
const id = ++requestId.current;
selection.current = { tags, page };
setSelectedTags(tags);
applyTagFilterAttribute(tags);
if (!tags.length) {
if (page !== initialPagination.page) {
setView({ status: 'loading', pagination: null });
router.replace(relativeURL(url));
return;
}
if (hasNewerRevision.current) {
setView({ status: 'loading', pagination: null });
window.location.replace(relativeURL(url));
return;
}
setView({ status: 'unfiltered', pagination: initialPagination });
return;
}
setView((current) => {
let pagination = null;
if (sameTags && current.pagination) {
pagination = getUpdatesPageRange(page, current.pagination.totalItems);
}
return { status: 'loading', pagination };
});
async function load() {
let result: FilteredUpdatesPageResult = { status: 'error' };
try {
result = await getFilteredUpdatesPage({ pageId, tags, page, isEmbeddable });
} catch {
// Network or aborted action leaves the filter selected so the reader can retry.
}
const currentURL = new URL(window.location.href);
const selected = getUpdatesSelection(currentURL, availableTags);
if (
id !== requestId.current ||
currentURL.pathname !== url.pathname ||
selected.page !== page ||
!areTagsEqual(selected.tags, tags)
) {
return;
}
if (result.status === 'error') {
setView({ status: 'error', pagination: null });
return;
}
if (result.revisionId !== revisionId) {
hasNewerRevision.current = true;
}
if (result.status === 'unfiltered') {
const fallback = currentURL;
fallback.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
setUpdatesPageParam(fallback.searchParams, initialPagination.page);
window.history.replaceState(null, '', relativeURL(fallback));
selection.current = { tags: [], page: initialPagination.page };
setSelectedTags([]);
applyTagFilterAttribute([]);
if (hasNewerRevision.current) {
setView({ status: 'loading', pagination: null });
window.location.replace(relativeURL(fallback));
return;
}
setView({ status: 'unfiltered', pagination: initialPagination });
return;
}
if (result.pagination.isClamped) {
const clamped = currentURL;
setUpdatesPageParam(clamped.searchParams, result.pagination.page);
window.history.replaceState(null, '', relativeURL(clamped));
selection.current = { tags, page: result.pagination.page };
}
setView({
status: 'filtered',
revisionId: result.revisionId,
content: result.content,
sections: result.sections,
pagination: result.pagination,
});
}
void load();
},
[availableTags, pageId, revisionId, initialPagination, isEmbeddable, router]
);
React.useLayoutEffect(() => {
syncLocation();
}, [searchParams, syncLocation]);
React.useEffect(() => {
const onPopState = () => syncLocation();
window.addEventListener('popstate', onPopState);
return () => {
window.removeEventListener('popstate', onPopState);
};
}, [syncLocation]);
React.useLayoutEffect(() => {
if (view.status !== 'loading') {
document.documentElement.removeAttribute(PENDING_FILTER_ATTR);
}
}, [view]);
React.useEffect(() => {
if (
view.status === 'loading' ||
view.status === 'error' ||
(view.status === 'unfiltered' && selection.current.tags.length > 0)
) {
return;
}
let active = true;
async function resolveHash() {
const url = new URL(window.location.href);
const anchorHash = url.hash;
if (!anchorHash || scrollToHash(anchorHash.slice(1))) {
return;
}
let anchor: string;
try {
anchor = decodeURIComponent(anchorHash.slice(1));
} catch {
return;
}
const id = requestId.current;
const { tags } = selection.current;
try {
const result = await resolveUpdatesAnchor({ pageId, anchor, tags, isEmbeddable });
if (
!active ||
!result.found ||
id !== requestId.current ||
url.href !== window.location.href
) {
return;
}
setUpdatesPageParam(url.searchParams, result.page);
if (result.clearTags) {
url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
}
if (url.href !== window.location.href) {
router.replace(relativeURL(url));
}
} catch {
// An unresolved hash should leave the visitor on the current page.
}
}
void resolveHash();
window.addEventListener('hashchange', resolveHash);
return () => {
active = false;
window.removeEventListener('hashchange', resolveHash);
};
}, [hash, isEmbeddable, pageId, router, view]);
function navigate(tags: string[], page: number, history: 'push' | 'replace') {
const url = new URL(window.location.href);
url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM);
for (const tag of tags) {
url.searchParams.append(UPDATES_FILTER_SEARCH_PARAM, tag);
}
setUpdatesPageParam(url.searchParams, page);
url.hash = '';
if (tags.length === 0 && (page !== initialPagination.page || hasNewerRevision.current)) {
requestId.current++;
selection.current = { tags, page };
setSelectedTags(tags);
applyTagFilterAttribute(tags);
setView({ status: 'loading', pagination: null });
if (hasNewerRevision.current) {
window.location.replace(relativeURL(url));
} else {
router.replace(relativeURL(url));
}
return;
}
if (history === 'push') {
window.history.pushState(null, '', relativeURL(url));
} else {
window.history.replaceState(null, '', relativeURL(url));
}
syncLocation();
const main = document.getElementById(MAIN_CONTENT_ID);
if (main) {
main.scrollIntoView({ block: 'start', behavior: 'instant' });
main.focus({ preventScroll: true });
}
}
function toggleTag(tag: string) {
const { tags } = selection.current;
if (tags.includes(tag)) {
navigate(
tags.filter((selected) => selected !== tag),
1,
'replace'
);
return;
}
navigate(normalizeUpdatesFilterTags([...tags, tag], availableTags), 1, 'replace');
}
return (
<UpdatesFilterContext.Provider
value={{
selectedTags,
selectedTagSet: new Set(selectedTags),
toggleTag,
clearTags: () => navigate([], 1, 'replace'),
}}
>
<PaginatedUpdatesContext.Provider
value={{
view,
goToPage: (page) => navigate(selection.current.tags, page, 'push'),
retry: () => syncLocation(true),
}}
>
{tagSlugs.length > 0 && (
<UpdatesFilterScript
tagSlugs={tagSlugs}
filterAttribute={PENDING_FILTER_ATTR}
/>
)}
{children}
</PaginatedUpdatesContext.Provider>
</UpdatesFilterContext.Provider>
);
}
export function usePaginatedUpdates() {
return React.useContext(PaginatedUpdatesContext);
}
export function PaginatedUpdatesBody(props: { children: React.ReactNode }) {
const updates = usePaginatedUpdates();
const language = useLanguage();
if (updates?.view.status === 'loading') {
return <SkeletonUpdate className={CONTENT_STYLE_REDUCED} />;
}
if (updates?.view.status === 'error') {
return (
<div
role="alert"
className={`${CONTENT_STYLE_REDUCED} flex items-center justify-between gap-4 rounded-lg border border-tint-subtle p-4 text-sm text-tint`}
>
<span>{tString(language, 'unexpected_error')}</span>
<Button
variant="secondary"
size="small"
label={tString(language, 'unexpected_error_retry')}
onClick={updates.retry}
/>
</div>
);
}
if (updates?.view.status === 'filtered') {
return (
<div className="contents" data-content-ref-root="">
<SuspenseLoadedHint />
{updates.view.content}
</div>
);
}
return <div className={`contents ${HIDE_PENDING_UPDATES}`}>{props.children}</div>;
}
function getUpdatesSelection(url: URL, availableTags: ReadonlySet<string>): UpdatesSelection {
return {
tags: normalizeUpdatesFilterTags(
url.searchParams.getAll(UPDATES_FILTER_SEARCH_PARAM),
availableTags
),
page: parseUpdatesPageParam(url.searchParams.get(UPDATES_PAGE_SEARCH_PARAM)) ?? 1,
};
}
function relativeURL(url: URL): string {
return `${url.pathname}${url.search}${url.hash}`;
}
@@ -36,7 +36,7 @@ const emptyUpdatesFilterContext: UpdatesFilterContextValue = {
clearTags: () => {},
};
const UpdatesFilterContext = React.createContext<UpdatesFilterContextValue | null>(null);
export const UpdatesFilterContext = React.createContext<UpdatesFilterContextValue | null>(null);
export function UpdatesFilterProvider(props: { tagSlugs: string[]; children: React.ReactNode }) {
const { tagSlugs, children } = props;
@@ -249,12 +249,12 @@ function TagChip(props: { tag: RevisionTag; onToggle: (tag: string) => void }) {
);
}
function areTagsEqual(left: string[], right: string[]): boolean {
export function areTagsEqual(left: string[], right: string[]): boolean {
return left.length === right.length && left.every((tag, index) => tag === right[index]);
}
/** Mirrors the active filter onto `<html>`, matching what the pre-paint script does on first load. */
function applyTagFilterAttribute(tags: string[]) {
export function applyTagFilterAttribute(tags: string[]) {
if (typeof document === 'undefined') {
return;
}
@@ -58,12 +58,12 @@ export function applyUpdatesFilterScript(
* Inline script that applies the URL's `?tag=` filter to `<html>` before first paint. Rendered only
* on pages with filterable updates (see SitePage), not globally.
*/
export function UpdatesFilterScript(props: { tagSlugs: string[] }) {
const { tagSlugs } = props;
export function UpdatesFilterScript(props: { tagSlugs: string[]; filterAttribute?: string }) {
const { tagSlugs, filterAttribute = UPDATES_TAG_FILTER_ATTR } = props;
const inserted = useRef(false);
const scriptArgs = serializeUpdatesFilterScriptArgs([
UPDATES_FILTER_SEARCH_PARAM,
UPDATES_TAG_FILTER_ATTR,
filterAttribute,
UPDATES_TAG_FILTER_CAP,
tagSlugs,
UPDATES_FILTER_KEY_ATTR,
@@ -0,0 +1,90 @@
'use client';
import { useSearchParams } from 'next/navigation';
import { Icon } from '@gitbook/icons';
import { CONTENT_STYLE_REDUCED } from '../layout';
import { Button } from '../primitives';
import { HIDE_PENDING_UPDATES, usePaginatedUpdates } from './PaginatedUpdates';
import { tString } from '@/intl/translate';
import type { TranslationLanguage } from '@/intl/translations';
import { tcls } from '@/lib/tailwind';
import {
UPDATES_FILTER_SEARCH_PARAM,
UPDATES_MAX_PAGE,
setUpdatesPageParam,
} from '@/lib/updates-url';
export function UpdatesPagination(props: { language: TranslationLanguage; baseHref: string }) {
const { language, baseHref } = props;
const updates = usePaginatedUpdates();
const searchParams = useSearchParams();
if (!updates?.view.pagination || updates.view.pagination.totalPages <= 1) {
return null;
}
const { view, goToPage } = updates;
const { page, totalPages, totalItems, start, end } = updates.view.pagination;
const number = new Intl.NumberFormat(language.locale);
const previousLabel = tString(language, 'previous_page');
const nextLabel = tString(language, 'next_page');
function buttonProps(targetPage: number, rel: 'prev' | 'next') {
if (view.status !== 'unfiltered') {
return { onClick: () => goToPage(targetPage) };
}
const params = new URLSearchParams(searchParams?.toString());
params.delete(UPDATES_FILTER_SEARCH_PARAM);
setUpdatesPageParam(params, targetPage);
const query = params.toString();
let href = baseHref;
if (query) {
href += `?${query}`;
}
return { href, rel };
}
return (
<div
className={tcls(
CONTENT_STYLE_REDUCED,
'mt-8 flex items-center justify-between gap-2 border-t border-tint-subtle pt-4',
view.status === 'unfiltered' && HIDE_PENDING_UPDATES
)}
>
<div aria-live="polite" className="text-sm text-tint">
{tString(
language,
'updates_pagination_range',
number.format(start),
number.format(end),
number.format(totalItems)
)}
</div>
<nav
aria-label={tString(language, 'updates_pagination_navigation')}
className="flex justify-end gap-2"
>
{page > 1 && (
<Button
variant="blank"
size="small"
icon="chevron-left"
label={previousLabel}
{...buttonProps(page - 1, 'prev')}
/>
)}
{page < totalPages && page < UPDATES_MAX_PAGE && (
<Button
variant="blank"
size="small"
trailing={<Icon icon="chevron-right" className="size-3" />}
label={nextLabel}
{...buttonProps(page + 1, 'next')}
/>
)}
</nav>
</div>
);
}
@@ -0,0 +1,144 @@
'use server';
import type * as React from 'react';
import { IconsProvider } from '@gitbook/icons';
import { PageBodyDocument } from '../PageBody/PageBodyDocument';
import { getPageDocument } from '@/lib/data';
import { getDocumentSections } from '@/lib/document-sections';
import {
getContentInlineIconSourceRequests,
getCustomizationIconStyle,
getInlineIconSources,
} from '@/lib/icons/inline';
import { getLogger } from '@/lib/logger';
import { resolvePageId } from '@/lib/pages';
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
import {
findUpdateAnchorPage,
getDocumentFilterableTags,
normalizeUpdatesFilterTags,
paginateUpdatesDocument,
} from '@/lib/updates';
import { UPDATES_MAX_PAGE } from '@/lib/updates-url';
type UpdatesPageAction = {
pageId: string;
tags: string[];
isEmbeddable: boolean;
};
export type FilteredUpdatesPageResult =
| {
status: 'ok';
revisionId: string;
content: React.ReactNode;
sections: Awaited<ReturnType<typeof getDocumentSections>>;
pagination: NonNullable<ReturnType<typeof paginateUpdatesDocument>['pagination']>;
}
| {
status: 'unfiltered';
revisionId: string;
}
| {
status: 'error';
};
export async function getFilteredUpdatesPage(
options: UpdatesPageAction & { page: number }
): Promise<FilteredUpdatesPageResult> {
const logger = getLogger().subLogger('updatesPagination');
if (!Number.isInteger(options.page) || options.page < 1 || options.page > UPDATES_MAX_PAGE) {
logger.warn('Invalid filtered updates page number');
return { status: 'error' };
}
try {
const { context, page, document } = await getUpdatesPageDocument(options);
const availableTags = new Set(
getDocumentFilterableTags(document, context.revision).map((tag) => tag.slug)
);
const tags = normalizeUpdatesFilterTags(options.tags, availableTags);
if (!tags.length) {
logger.info('No selected tags on the current revision', { pageId: page.id });
return { status: 'unfiltered', revisionId: context.revisionId };
}
const result = paginateUpdatesDocument(document, context.revision, {
page: options.page,
tags,
});
if (!result.pagination) {
logger.info('Current revision no longer needs updates pagination', { pageId: page.id });
return { status: 'unfiltered', revisionId: context.revisionId };
}
const [sections, iconSources] = await Promise.all([
getDocumentSections(context, result.document),
getInlineIconSources(
getContentInlineIconSourceRequests({
iconStyle: getCustomizationIconStyle(context.customization),
document: result.document,
})
),
]);
logger.info('Rendered filtered updates page', {
siteId: context.site.id,
pageId: page.id,
page: result.pagination.page,
totalItems: result.pagination.totalItems,
totalPages: result.pagination.totalPages,
});
return {
status: 'ok',
revisionId: context.revisionId,
content: (
<IconsProvider iconSources={iconSources}>
<PageBodyDocument context={context} page={page} document={result.document} />
</IconsProvider>
),
sections,
pagination: result.pagination,
};
} catch {
logger.warn('Could not render filtered updates page');
return { status: 'error' };
}
}
export async function resolveUpdatesAnchor(options: UpdatesPageAction & { anchor: string }) {
const logger = getLogger().subLogger('updatesPagination');
try {
const { context, page, document } = await getUpdatesPageDocument(options);
const result = findUpdateAnchorPage(document, context.revision, options);
logger.info('Resolved updates anchor', {
siteId: context.site.id,
pageId: page.id,
found: result.found,
page: result.found && result.page,
});
if (result.found && result.page <= UPDATES_MAX_PAGE) {
return result;
}
} catch {
logger.warn('Could not resolve updates anchor');
}
return { found: false as const };
}
async function getUpdatesPageDocument({ pageId, isEmbeddable }: UpdatesPageAction) {
const context = await fetchServerActionSiteContext(
await getServerActionBaseContext({ isEmbeddable })
);
const target = resolvePageId(context.revision.pages, pageId);
if (!target) {
throw new Error('Updates page not found');
}
const { page } = target;
const document = await getPageDocument(context, page);
if (!document) {
throw new Error('Updates document not found');
}
return { context: { ...context, page }, page, document };
}
@@ -1,7 +1,9 @@
import type { Metadata } from 'next';
import { SiteInsightsDisplayContext } from '@gitbook/api';
import { IconsProvider } from '@gitbook/icons';
import { PaginatedUpdatesProvider } from '../DocumentView/PaginatedUpdates';
import { HeaderMobileMenu } from '../Header/HeaderMobileMenu';
import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown';
import { PageBody } from '../PageBody';
@@ -33,6 +35,7 @@ export const dynamic = 'force-static';
type EmbeddableDocsPageProps = {
context: GitBookSiteContext;
pageParams: PagePathParams;
updatesPage?: number;
};
/**
@@ -41,11 +44,51 @@ type EmbeddableDocsPageProps = {
export async function EmbeddableDocsPage(
props: EmbeddableDocsPageProps & { staticRoute: boolean }
) {
const { context, pageParams } = props;
const { page, document, ancestors, withPageFeedback } = await getSitePageData({
context,
pageParams,
});
const { context } = props;
const {
page,
document,
ancestors,
withPageFeedback,
contentHasUpdates,
pagination,
pageHref,
filterableTags,
iconSources,
} = await getSitePageData(props);
let updatesBaseHref: string | undefined;
if (pagination) {
updatesBaseHref = pageHref;
}
let pageBody = (
<PageBody
context={context}
page={page}
ancestors={ancestors}
document={document}
withPageFeedback={withPageFeedback}
insightsDisplayContext={SiteInsightsDisplayContext.Embed}
staticRoute={props.staticRoute}
contentHasUpdates={contentHasUpdates}
updatesBaseHref={updatesBaseHref}
/>
);
if (pagination) {
pageBody = (
<IconsProvider iconSources={iconSources}>
<PaginatedUpdatesProvider
key={`${context.space.id}/${context.revisionId}/${page.id}/${pagination.page}`}
pageId={page.id}
revisionId={context.revisionId}
isEmbeddable
tagSlugs={filterableTags.map((tag) => tag.slug)}
initialPagination={pagination}
>
{pageBody}
</PaginatedUpdatesProvider>
</IconsProvider>
);
}
const variants = categorizeVariants(context);
@@ -147,15 +190,7 @@ export async function EmbeddableDocsPage(
) : null
}
/>
<PageBody
context={context}
page={page}
ancestors={ancestors}
document={document}
withPageFeedback={withPageFeedback}
insightsDisplayContext={SiteInsightsDisplayContext.Embed}
staticRoute={props.staticRoute}
/>
{pageBody}
</ScrollContainer>
</EmbeddableFrameBody>
</EmbeddableFrameMain>
@@ -15,7 +15,7 @@ import { PageFeedbackForm } from '../PageFeedback';
import { SideSheet } from '../primitives/SideSheet';
import { ThemeToggler } from '../ThemeToggler';
import { PageAsideCloseButton } from './PageAsideButton';
import { ScrollSectionsList } from './ScrollSectionsList';
import { PaginatedScrollSectionsList, ScrollSectionsList } from './ScrollSectionsList';
import { ScrollToTopButton } from './ScrollToTopButton';
import { getSpaceLanguage, t, tString } from '@/intl/server';
import type { GitBookSiteContext } from '@/lib/context';
@@ -29,6 +29,7 @@ export async function PageAside(props: {
page: RevisionPageDocument;
document: JSONDocument | null;
filterableTags: RevisionTag[];
withUpdatesPagination: boolean;
context: GitBookSiteContext;
withHeaderOffset: { sectionsHeader: boolean; topHeader: boolean };
withFullPageCover: boolean;
@@ -142,7 +143,11 @@ export async function PageAside(props: {
<div className="flex shrink flex-col overflow-hidden">
{document ? (
<React.Suspense fallback={null}>
<PageAsideSections document={document} context={context} />
<PageAsideSections
document={document}
context={context}
withUpdatesPagination={props.withUpdatesPagination}
/>
</React.Suspense>
) : null}
<PageAsideActions page={page} withPageFeedback={withPageFeedback} />
@@ -157,11 +162,19 @@ export async function PageAside(props: {
);
}
async function PageAsideSections(props: { document: JSONDocument; context: GitBookSiteContext }) {
async function PageAsideSections(props: {
document: JSONDocument;
context: GitBookSiteContext;
withUpdatesPagination: boolean;
}) {
const { document, context } = props;
const sections = await getDocumentSections(context, document);
if (props.withUpdatesPagination) {
return <PaginatedScrollSectionsList sections={sections} />;
}
return sections.length > 1 ? (
<div data-gb-page-outline className="overflow-y-auto">
<ScrollSectionsList sections={sections} />
@@ -4,6 +4,10 @@ import React from 'react';
import { OpenAPIMethodBadge } from '@gitbook/react-openapi';
import { HEADER_HEIGHT_DESKTOP } from '../layout';
import {
HIDE_PENDING_UPDATES,
usePaginatedUpdates,
} from '@/components/DocumentView/PaginatedUpdates';
import { useUpdatesFilter } from '@/components/DocumentView/UpdatesFilter';
import { useScrollActiveId } from '@/components/hooks';
import { useBodyLoaded } from '@/components/primitives';
@@ -21,6 +25,34 @@ const SECTION_INTERSECTING_THRESHOLD = 0.9;
*/
const ACTIVE_ITEM_OFFSET = 100;
export function PaginatedScrollSectionsList(props: { sections: DocumentSection[] }) {
const updates = usePaginatedUpdates();
const view = updates?.view;
if (view?.status === 'loading' || view?.status === 'error') {
return null;
}
let sections = props.sections;
if (view?.status === 'filtered') {
sections = view.sections;
}
if (sections.length <= 1) {
return null;
}
return (
<div
data-gb-page-outline
className={tcls(
'overflow-y-auto',
view?.status === 'unfiltered' && HIDE_PENDING_UPDATES
)}
>
<ScrollSectionsList sections={sections} />
</div>
);
}
export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }) {
const { selectedTagSet } = useUpdatesFilter();
const ids = React.useMemo(
@@ -4,7 +4,9 @@ import {
SiteInsightsDisplayContext,
} from '@gitbook/api';
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
import { DocumentViewSkeleton } from '../DocumentView';
import { PaginatedUpdatesBody } from '../DocumentView/PaginatedUpdates';
import { UpdatesPagination } from '../DocumentView/UpdatesPagination';
import { CurrentPageProvider } from '../hooks/useCurrentPage';
import { TrackPageViewEvent } from '../Insights';
import { CONTENT_STYLE } from '../layout';
@@ -12,6 +14,7 @@ import { PageFeedbackForm } from '../PageFeedback';
import { DateRelative, SuspenseLoadedHint } from '../primitives';
import OptionalSuspense from './OptionalSuspense';
import { PageBodyBlankslate } from './PageBodyBlankslate';
import { PageBodyDocument } from './PageBodyDocument';
import { PageCover } from './PageCover';
import { PageFooterNavigation } from './PageFooterNavigation';
import { PageHeader } from './PageHeader';
@@ -20,19 +23,11 @@ import { MAIN_CONTENT_ID } from '@/components/layout';
import { getSpaceLanguage } from '@/intl/server';
import { t } from '@/intl/translate';
import type { GitBookSiteContext } from '@/lib/context';
import {
hasAPIBlock,
hasFullWidthBlock,
hasMoreThan,
hasTopLevelBlock,
isNodeEmpty,
} from '@/lib/document';
import { hasAPIBlock, hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
import type { AncestorRevisionPage } from '@/lib/pages';
import { tcls } from '@/lib/tailwind';
import { getPageRSSURL } from '@/routes/rss';
const LINK_PREVIEW_MAX_COUNT = 500;
export async function PageBody(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
@@ -41,6 +36,8 @@ export async function PageBody(props: {
withPageFeedback: boolean;
insightsDisplayContext: SiteInsightsDisplayContext;
staticRoute: boolean;
contentHasUpdates: boolean;
updatesBaseHref?: string | undefined;
}) {
const {
page,
@@ -50,26 +47,14 @@ export async function PageBody(props: {
withPageFeedback,
insightsDisplayContext,
staticRoute,
contentHasUpdates,
updatesBaseHref,
} = props;
const { customization } = context;
// Update blocks can only be at the top level of the document, so we optimize the check.
const contentHasUpdates = document
? hasTopLevelBlock(document, (block) => block.type === 'updates')
: false;
// Comments can only be made on change request previews, so public pages skip their markers.
const withCommentAnchors = Boolean(context.changeRequest);
// Render link previews only if there are less than LINK_PREVIEW_MAX_COUNT links in the document.
const withLinkPreviews = document
? !hasMoreThan(
document,
(inline) => inline.object === 'inline' && inline.type === 'link',
LINK_PREVIEW_MAX_COUNT
)
: false;
// Determine if content should use wide layout (2-column or 1-column instead of 3-column)
// This happens when: (1) document has full-width blocks, OR (2) page layout is explicitly set to 'wide'
const wideContent = document ? hasFullWidthBlock(document) : false;
@@ -92,6 +77,29 @@ export async function PageBody(props: {
const pageHasToc = page.layout.tableOfContents && hasVisibleTOCItems;
let content = <PageBodyBlankslate page={page} context={context} />;
if (document && !isNodeEmpty(document)) {
content = (
<OptionalSuspense
staticRoute={staticRoute}
fallback={<DocumentViewSkeleton document={document} blockStyle="" />}
>
<SuspenseLoadedHint />
<div className="contents" data-content-ref-root="">
<PageBodyDocument document={document} context={context} page={page} />
</div>
</OptionalSuspense>
);
}
if (updatesBaseHref) {
content = (
<>
<PaginatedUpdatesBody>{content}</PaginatedUpdatesBody>
<UpdatesPagination language={language} baseHref={updatesBaseHref} />
</>
);
}
return (
<CurrentPageProvider page={{ spaceId: context.space.id, pageId: page.id }}>
{contentHasUpdates ? (
@@ -104,10 +112,11 @@ export async function PageBody(props: {
) : null}
<main
id={MAIN_CONTENT_ID}
tabIndex={-1}
// Comments on the whole page target anywhere in it that isn't a block.
{...(withCommentAnchors ? { 'data-comment-page': '' } : {})}
className={tcls(
'relative min-w-0 flex-1',
'relative min-w-0 flex-1 outline-none',
'break-anywhere', // Allow words to break if they are too long.
'py-8',
'layout-wide:no-sidebar:lg:max-xl:pb-20', // Add padding to prevent overlap of minimised trademark
@@ -138,32 +147,7 @@ export async function PageBody(props: {
hasAPIBlocks={hasAPIBlocks}
asEmbeddable={insightsDisplayContext === SiteInsightsDisplayContext.Embed}
/>
{document && !isNodeEmpty(document) ? (
<OptionalSuspense
staticRoute={staticRoute}
fallback={<DocumentViewSkeleton document={document} blockStyle="" />}
>
<SuspenseLoadedHint />
<div className="contents" data-content-ref-root="">
<DocumentView
document={document}
style="flex flex-col [&>*+*]:mt-5"
context={{
mode: 'default',
contentContext: {
...context,
page,
},
withLinkPreviews,
withCommentAnchors,
isPageBody: true,
}}
/>
</div>
</OptionalSuspense>
) : (
<PageBodyBlankslate page={page} context={context} />
)}
{content}
</div>
{page.layout.pagination && customization.pagination.enabled ? (
@@ -0,0 +1,34 @@
import type { JSONDocument, RevisionPageDocument } from '@gitbook/api';
import { DocumentView } from '../DocumentView';
import type { GitBookSiteContext } from '@/lib/context';
import { hasMoreThan } from '@/lib/document';
const LINK_PREVIEW_MAX_COUNT = 500;
export function PageBodyDocument(props: {
context: GitBookSiteContext;
page: RevisionPageDocument;
document: JSONDocument;
}) {
const { context, page, document } = props;
const withLinkPreviews = !hasMoreThan(
document,
(inline) => inline.object === 'inline' && inline.type === 'link',
LINK_PREVIEW_MAX_COUNT
);
return (
<DocumentView
document={document}
style="flex flex-col [&>*+*]:mt-5"
context={{
mode: 'default',
contentContext: { ...context, page },
withLinkPreviews,
withCommentAnchors: Boolean(context.changeRequest),
isPageBody: true,
}}
/>
);
}
@@ -6,6 +6,7 @@ import {
CustomizationHeaderPreset,
SiteInsightsDisplayContext,
type TranslationLanguage,
type RevisionTag,
} from '@gitbook/api';
import { IconsProvider } from '@gitbook/icons';
@@ -18,34 +19,43 @@ import {
} from './fetch';
import { PageClientLayout } from './PageClientLayout';
import { getPageFullTitle } from './title';
import { PaginatedUpdatesProvider } from '@/components/DocumentView/PaginatedUpdates';
import { UpdatesFilterProvider } from '@/components/DocumentView/UpdatesFilter';
import { UpdatesFilterScript } from '@/components/DocumentView/UpdatesFilterScript';
import { PageAside } from '@/components/PageAside';
import { PageBody, PageCover } from '@/components/PageBody';
import type { GitBookSiteContext } from '@/lib/context';
import { getDataOrNull, getPageDocument } from '@/lib/data';
import { hasTopLevelBlock } from '@/lib/document';
import {
getContentInlineIconSourceRequests,
getCustomizationIconStyle,
getInlineIconSources,
} from '@/lib/icons/inline';
import { getResizedImageURL } from '@/lib/images';
import { getLogger } from '@/lib/logger';
import { getPagePath } from '@/lib/pages';
import { resolveContentRef } from '@/lib/references';
import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { getSiteSpacePagePaths, resolveSiteSpaceCustomHomePage } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import {
countDocumentUpdates,
generateUpdatesFilterCSS,
getUpdatesPageRange,
paginateUpdatesDocument,
UPDATES_PAGINATION_THRESHOLD,
getDocumentFilterableTags,
updatesFilterStyleHref,
} from '@/lib/updates';
import { UPDATES_PAGE_SEARCH_PARAM } from '@/lib/updates-url';
export { getPageFullTitle } from './title';
export type SitePageProps = {
context: GitBookSiteContext;
pageParams: PagePathParams;
updatesPage?: number;
};
type AlternateLinkSpace = {
@@ -85,11 +95,18 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
withTopHeader,
pageMetaLinks,
iconSources,
filterableTags,
contentHasUpdates,
pagination,
pageHref,
} = await getSitePageData(props);
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
const filterableTags = document ? getDocumentFilterableTags(document, context.revision) : [];
const filterableTagSlugs = filterableTags.map((tag) => tag.slug);
const content = (
let updatesBaseHref: string | undefined;
if (pagination) {
updatesBaseHref = pageHref;
}
let content = (
<>
{/* Using `contents` makes the children of this div according to its parent — which keeps them in a single flex row with the TOC by default.
If there's a page cover, we use `flex flex-col` to lay out the PageCover above the PageBody + PageAside instead. */}
@@ -119,6 +136,7 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
page={page}
document={document}
filterableTags={filterableTags}
withUpdatesPagination={Boolean(pagination)}
withHeaderOffset={headerOffset}
withFullPageCover={withFullPageCover}
withPageFeedback={withPageFeedback}
@@ -132,6 +150,8 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
withPageFeedback={withPageFeedback}
insightsDisplayContext={SiteInsightsDisplayContext.Site}
staticRoute={props.staticRoute}
contentHasUpdates={contentHasUpdates}
updatesBaseHref={updatesBaseHref}
/>
</div>
<PageClientLayout pageMetaLinks={pageMetaLinks} />
@@ -139,18 +159,34 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
</>
);
if (pagination) {
content = (
<PaginatedUpdatesProvider
key={`${context.space.id}/${context.revisionId}/${page.id}/${pagination.page}`}
pageId={page.id}
revisionId={context.revisionId}
isEmbeddable={false}
tagSlugs={filterableTagSlugs}
initialPagination={pagination}
>
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
{content}
</PaginatedUpdatesProvider>
);
} else if (filterableTagSlugs.length > 0) {
content = (
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
<UpdatesFilterScript tagSlugs={filterableTagSlugs} />
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
{content}
</UpdatesFilterProvider>
);
}
return (
<IconsProvider iconSources={iconSources}>
<PageContextProvider pageId={page.id} spaceId={context.space.id} title={page.title}>
{filterableTagSlugs.length > 0 ? (
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
<UpdatesFilterScript tagSlugs={filterableTagSlugs} />
<UpdatesFilterStyle tagSlugs={filterableTagSlugs} />
{content}
</UpdatesFilterProvider>
) : (
content
)}
{content}
</PageContextProvider>
</IconsProvider>
);
@@ -204,7 +240,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
const { page, ancestors } = pageTarget;
const { customization, revision, linker, imageResizer } = context;
const canonical = (
let canonical = (
pageMetaLinks?.canonical
? new URL(
// If the canonical link is an absolute URL, use it as is.
@@ -216,6 +252,23 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
linker.toAbsoluteURL(linker.toPathForPage({ pages: revision.pages, page }))
).replace(/\/+$/, ''); // Trim trailing slashes in canonical URL to match the redirect behavior
let title = getPageFullTitle(context, page);
if (props.updatesPage) {
const document = await getPageDocument(context, page);
if (document) {
const count = countDocumentUpdates(document);
if (count > UPDATES_PAGINATION_THRESHOLD) {
const { page: pageNumber } = getUpdatesPageRange(props.updatesPage, count);
title = `${title} (Page ${pageNumber})`;
if (!pageMetaLinks?.canonical) {
const url = new URL(canonical);
url.searchParams.set(UPDATES_PAGE_SEARCH_PARAM, String(pageNumber));
canonical = url.toString();
}
}
}
}
const alternates = pageMetaLinks?.alternates.reduce<{
languages: Record<string, string>;
generic: {
@@ -239,7 +292,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
);
return {
title: getPageFullTitle(context, page),
title,
description: page.description ?? '',
keywords: page.keywords?.length ? page.keywords : undefined,
alternates: {
@@ -327,7 +380,44 @@ export async function getSitePageData(props: SitePageProps) {
const withSections = Boolean(visibleSections && visibleSections.list.length > 0);
const document = await getPageDocument(context, page);
const fullDocument = await getPageDocument(context, page);
const pageHref = context.linker.toPathForPagePath({ path: rawPathname });
let contentHasUpdates = false;
let filterableTags: RevisionTag[] = [];
let document = fullDocument;
let pagination = null;
if (fullDocument) {
contentHasUpdates = hasTopLevelBlock(fullDocument, (block) => block.type === 'updates');
filterableTags = getDocumentFilterableTags(fullDocument, context.revision);
({ document, pagination } = paginateUpdatesDocument(fullDocument, context.revision, {
page: props.updatesPage ?? 1,
}));
}
if (pagination || props.updatesPage) {
const logger = getLogger().subLogger('updatesPagination', {
labels: { siteId: context.site.id, pageId: page.id },
});
if (props.updatesPage && (!pagination || pagination.isClamped)) {
const targetPage = pagination?.page ?? 1;
logger.info('Redirected out-of-range updates page', {
requestedPage: props.updatesPage,
targetPage,
});
if (targetPage > 1) {
redirect(`${pageHref}?${UPDATES_PAGE_SEARCH_PARAM}=${targetPage}`);
}
redirect(pageHref);
}
if (pagination) {
logger.info('Rendered updates page', {
page: pagination.page,
totalItems: pagination.totalItems,
totalPages: pagination.totalPages,
});
}
}
const iconStyle = getCustomizationIconStyle(customization);
const iconSources = await getInlineIconSources(
getContentInlineIconSourceRequests({
@@ -347,6 +437,10 @@ export async function getSitePageData(props: SitePageProps) {
withTopHeader,
pageMetaLinks,
iconSources,
contentHasUpdates,
filterableTags,
pagination,
pageHref,
};
}
@@ -98,7 +98,10 @@ export const activeClasses = {
export const Button = React.forwardRef<
HTMLButtonElement | HTMLAnchorElement,
ButtonProps &
React.ButtonHTMLAttributes<HTMLButtonElement> & { target?: React.HTMLAttributeAnchorTarget }
React.ButtonHTMLAttributes<HTMLButtonElement> & {
target?: React.HTMLAttributeAnchorTarget;
rel?: string;
}
>(
(
{
@@ -164,6 +167,11 @@ export const Button = React.forwardRef<
}
}
let trailingElement = null;
if (trailing) {
trailingElement = <span className="button-trailing-icon ms-auto">{trailing}</span>;
}
const content = (
<>
{iconElement}
@@ -177,6 +185,7 @@ export const Button = React.forwardRef<
{children ?? label}
</span>
)}
{trailingElement}
</>
);
@@ -207,7 +216,6 @@ export const Button = React.forwardRef<
{...rest}
>
{content}
{trailing ? <span className="button-trailing-icon ms-auto">{trailing}</span> : null}
</button>
);
@@ -46,6 +46,8 @@ export const ar: TranslationLanguage = {
on_this_page: 'في هذه الصفحة',
next_page: 'التالي',
previous_page: 'السابق',
updates_pagination_navigation: 'التنقل بين الصفحات',
updates_pagination_range: '${1} - ${2} من أصل ${3} تحديثات',
toc_back_to_space: 'العودة إلى ${1}',
page_last_modified: 'آخر تحديث ${1}',
was_this_helpful: 'هل كان هذا مفيدا؟',
@@ -46,6 +46,8 @@ export const bg: TranslationLanguage = {
on_this_page: 'На тази страница',
next_page: 'Следваща',
previous_page: 'Предишна',
updates_pagination_navigation: 'Навигация между страниците',
updates_pagination_range: '${1} - ${2} от ${3} актуализации',
toc_back_to_space: 'Обратно към ${1}',
page_last_modified: 'Последна актуализация ${1}',
was_this_helpful: 'Беше ли полезно?',
@@ -46,6 +46,8 @@ export const cs: TranslationLanguage = {
on_this_page: 'Na této stránce',
next_page: 'Další',
previous_page: 'Předchozí',
updates_pagination_navigation: 'Navigace mezi stránkami',
updates_pagination_range: '${1} - ${2} z ${3} aktualizací',
toc_back_to_space: 'Zpět na ${1}',
page_last_modified: 'Poslední aktualizace ${1}',
was_this_helpful: 'Bylo to užitečné?',
@@ -46,6 +46,8 @@ export const da: TranslationLanguage = {
on_this_page: 'På denne side',
next_page: 'Næste',
previous_page: 'Forrige',
updates_pagination_navigation: 'Sidenavigation',
updates_pagination_range: '${1} - ${2} af ${3} opdateringer',
toc_back_to_space: 'Tilbage til ${1}',
page_last_modified: 'Sidst opdateret ${1}',
was_this_helpful: 'Var dette nyttigt?',
@@ -47,6 +47,8 @@ export const de: TranslationLanguage = {
on_this_page: 'Auf dieser Seite',
next_page: 'Nächste',
previous_page: 'Vorherige',
updates_pagination_navigation: 'Seitennavigation',
updates_pagination_range: '${1} - ${2} von ${3} Updates',
toc_back_to_space: 'Zurück zu ${1}',
page_last_modified: 'Zuletzt aktualisiert ${1}',
was_this_helpful: 'War das hilfreich?',
@@ -46,6 +46,8 @@ export const el: TranslationLanguage = {
on_this_page: 'Σε αυτήν τη σελίδα',
next_page: 'Επόμενη',
previous_page: 'Προηγούμενη',
updates_pagination_navigation: 'Πλοήγηση σελίδων',
updates_pagination_range: '${1} - ${2} από ${3} ενημερώσεις',
toc_back_to_space: 'Επιστροφή σε ${1}',
page_last_modified: 'Τελευταία ενημέρωση ${1}',
was_this_helpful: 'Ήταν χρήσιμο αυτό;',
@@ -44,6 +44,8 @@ export const en = {
on_this_page: 'On this page',
next_page: 'Next',
previous_page: 'Previous',
updates_pagination_navigation: 'Pagination Navigation',
updates_pagination_range: '${1} - ${2} of ${3} updates',
toc_back_to_space: 'Back to ${1}',
page_last_modified: 'Last updated ${1}',
was_this_helpful: 'Was this helpful?',
@@ -47,6 +47,8 @@ export const es: TranslationLanguage = {
on_this_page: 'En esta página',
next_page: 'Siguiente',
previous_page: 'Anterior',
updates_pagination_navigation: 'Navegación entre páginas',
updates_pagination_range: '${1} - ${2} de ${3} actualizaciones',
toc_back_to_space: 'Volver a ${1}',
page_last_modified: 'Última actualización ${1}',
was_this_helpful: '¿Te fue útil?',
@@ -46,6 +46,8 @@ export const et: TranslationLanguage = {
on_this_page: 'Sellel lehel',
next_page: 'Järgmine',
previous_page: 'Eelmine',
updates_pagination_navigation: 'Lehekülgede vahel liikumine',
updates_pagination_range: '${1} - ${2} / ${3} uuendust',
toc_back_to_space: 'Tagasi: ${1}',
page_last_modified: 'Viimati uuendatud ${1}',
was_this_helpful: 'Kas sellest oli abi?',
@@ -46,6 +46,8 @@ export const fi: TranslationLanguage = {
on_this_page: 'Tällä sivulla',
next_page: 'Seuraava',
previous_page: 'Edellinen',
updates_pagination_navigation: 'Sivujen selaus',
updates_pagination_range: '${1} - ${2} / ${3} päivitystä',
toc_back_to_space: 'Takaisin: ${1}',
page_last_modified: 'Päivitetty viimeksi ${1}',
was_this_helpful: 'Oliko tästä apua?',
@@ -46,6 +46,8 @@ export const fr: TranslationLanguage = {
on_this_page: 'Sur cette page',
next_page: 'Suivant',
previous_page: 'Précédent',
updates_pagination_navigation: 'Navigation entre les pages',
updates_pagination_range: '${1} - ${2} sur ${3} mises à jour',
toc_back_to_space: 'Retour à ${1}',
page_last_modified: 'Mis à jour ${1}',
was_this_helpful: 'Ce contenu vous a-t-il été utile ?',
@@ -46,6 +46,8 @@ export const he: TranslationLanguage = {
on_this_page: 'בדף הזה',
next_page: 'הבא',
previous_page: 'הקודם',
updates_pagination_navigation: 'ניווט בין עמודים',
updates_pagination_range: '${1} - ${2} מתוך ${3} עדכונים',
toc_back_to_space: 'חזרה אל ${1}',
page_last_modified: 'עודכן לאחרונה ${1}',
was_this_helpful: 'האם זה היה מועיל?',
@@ -46,6 +46,8 @@ export const hi: TranslationLanguage = {
on_this_page: 'इस पृष्ठ पर',
next_page: 'अगला',
previous_page: 'पिछला',
updates_pagination_navigation: 'पेज नेविगेशन',
updates_pagination_range: '${3} अपडेट में से ${1} - ${2}',
toc_back_to_space: '${1} पर वापस जाएँ',
page_last_modified: 'अंतिम अपडेट ${1}',
was_this_helpful: 'क्या यह उपयोगी था?',
@@ -46,6 +46,8 @@ export const hr: TranslationLanguage = {
on_this_page: 'Na ovoj stranici',
next_page: 'Sljedeća',
previous_page: 'Prethodna',
updates_pagination_navigation: 'Navigacija stranicama',
updates_pagination_range: '${1} - ${2} od ${3} ažuriranja',
toc_back_to_space: 'Natrag na ${1}',
page_last_modified: 'Zadnje ažurirano ${1}',
was_this_helpful: 'Je li ovo bilo korisno?',
@@ -46,6 +46,8 @@ export const hu: TranslationLanguage = {
on_this_page: 'Ezen az oldalon',
next_page: 'Következő',
previous_page: 'Előző',
updates_pagination_navigation: 'Lapozás',
updates_pagination_range: '${1} - ${2} / ${3} frissítés',
toc_back_to_space: 'Vissza ide: ${1}',
page_last_modified: 'Utoljára frissítve: ${1}',
was_this_helpful: 'Hasznos volt ez?',
@@ -46,6 +46,8 @@ export const id: TranslationLanguage = {
on_this_page: 'Di halaman ini',
next_page: 'Berikutnya',
previous_page: 'Sebelumnya',
updates_pagination_navigation: 'Navigasi halaman',
updates_pagination_range: '${1} - ${2} dari ${3} pembaruan',
toc_back_to_space: 'Kembali ke ${1}',
page_last_modified: 'Terakhir diperbarui ${1}',
was_this_helpful: 'Apakah ini membantu?',
@@ -47,6 +47,8 @@ export const it: TranslationLanguage = {
on_this_page: 'In questa pagina',
next_page: 'Successivo',
previous_page: 'Precedente',
updates_pagination_navigation: 'Navigazione tra le pagine',
updates_pagination_range: '${1} - ${2} di ${3} aggiornamenti',
toc_back_to_space: 'Torna a ${1}',
page_last_modified: 'Ultimo aggiornamento ${1}',
was_this_helpful: 'È stato utile?',
@@ -47,6 +47,8 @@ export const ja: TranslationLanguage = {
on_this_page: 'このページ内',
next_page: '次へ',
previous_page: '前へ',
updates_pagination_navigation: 'ページナビゲーション',
updates_pagination_range: '全${3}件の更新のうち${1}〜${2}件',
toc_back_to_space: '${1}に戻る',
page_last_modified: '最終更新 ${1}',
was_this_helpful: '役に立ちましたか?',
@@ -47,6 +47,8 @@ export const ko: TranslationLanguage = {
on_this_page: '이 페이지에서',
next_page: '다음',
previous_page: '이전',
updates_pagination_navigation: '페이지 탐색',
updates_pagination_range: '업데이트 ${3}개 중 ${1} - ${2}개',
toc_back_to_space: '${1}(으)로 돌아가기',
page_last_modified: '마지막 업데이트 ${1}',
was_this_helpful: '도움이 되었나요?',
@@ -46,6 +46,8 @@ export const lt: TranslationLanguage = {
on_this_page: 'Šiame puslapyje',
next_page: 'Kitas',
previous_page: 'Ankstesnis',
updates_pagination_navigation: 'Puslapių navigacija',
updates_pagination_range: '${1} - ${2} iš ${3} naujinimų',
toc_back_to_space: 'Atgal į ${1}',
page_last_modified: 'Paskutinį kartą atnaujinta ${1}',
was_this_helpful: 'Ar tai buvo naudinga?',
@@ -46,6 +46,8 @@ export const lv: TranslationLanguage = {
on_this_page: 'Šajā lapā',
next_page: 'Nākamā',
previous_page: 'Iepriekšējā',
updates_pagination_navigation: 'Lapu navigācija',
updates_pagination_range: '${1} - ${2} no ${3} atjauninājumiem',
toc_back_to_space: 'Atpakaļ uz ${1}',
page_last_modified: 'Pēdoreiz atjaunināts ${1}',
was_this_helpful: 'Vai tas bija noderīgi?',
@@ -46,6 +46,8 @@ export const ms: TranslationLanguage = {
on_this_page: 'Pada halaman ini',
next_page: 'Seterusnya',
previous_page: 'Sebelumnya',
updates_pagination_navigation: 'Navigasi halaman',
updates_pagination_range: '${1} - ${2} daripada ${3} kemas kini',
toc_back_to_space: 'Kembali ke ${1}',
page_last_modified: 'Terakhir dikemas kini ${1}',
was_this_helpful: 'Adakah ini membantu?',
@@ -47,6 +47,8 @@ export const nl: TranslationLanguage = {
on_this_page: 'Op deze pagina',
next_page: 'Volgende',
previous_page: 'Vorige',
updates_pagination_navigation: 'Paginanavigatie',
updates_pagination_range: '${1} - ${2} van ${3} updates',
toc_back_to_space: 'Terug naar ${1}',
page_last_modified: 'Laatst bijgewerkt ${1}',
was_this_helpful: 'Was dit nuttig?',
@@ -47,6 +47,8 @@ export const no: TranslationLanguage = {
on_this_page: 'På denne siden',
next_page: 'Neste',
previous_page: 'Forrige',
updates_pagination_navigation: 'Sidenavigasjon',
updates_pagination_range: '${1} - ${2} av ${3} oppdateringer',
toc_back_to_space: 'Tilbake til ${1}',
page_last_modified: 'Sist oppdatert ${1}',
was_this_helpful: 'Var dette nyttig?',
@@ -46,6 +46,8 @@ export const pl: TranslationLanguage = {
on_this_page: 'Na tej stronie',
next_page: 'Dalej',
previous_page: 'Wstecz',
updates_pagination_navigation: 'Nawigacja między stronami',
updates_pagination_range: '${1} - ${2} z ${3} aktualizacji',
toc_back_to_space: 'Powrót do ${1}',
page_last_modified: 'Ostatnia aktualizacja ${1}',
was_this_helpful: 'Czy to było pomocne?',
@@ -47,6 +47,8 @@ export const pt_br: TranslationLanguage = {
on_this_page: 'Nesta página',
next_page: 'Próximo',
previous_page: 'Anterior',
updates_pagination_navigation: 'Navegação entre páginas',
updates_pagination_range: '${1} - ${2} de ${3} atualizações',
toc_back_to_space: 'Voltar para ${1}',
page_last_modified: 'Atualizado ${1}',
was_this_helpful: 'Isto foi útil?',
@@ -46,6 +46,8 @@ export const pt: TranslationLanguage = {
on_this_page: 'Nesta página',
next_page: 'Seguinte',
previous_page: 'Anterior',
updates_pagination_navigation: 'Navegação entre páginas',
updates_pagination_range: '${1} - ${2} de ${3} atualizações',
toc_back_to_space: 'Voltar para ${1}',
page_last_modified: 'Última atualização ${1}',
was_this_helpful: 'Isto foi útil?',
@@ -46,6 +46,8 @@ export const ro: TranslationLanguage = {
on_this_page: 'Pe această pagină',
next_page: 'Următoarea',
previous_page: 'Anterioara',
updates_pagination_navigation: 'Navigare între pagini',
updates_pagination_range: '${1} - ${2} din ${3} actualizări',
toc_back_to_space: 'Înapoi la ${1}',
page_last_modified: 'Ultima actualizare ${1}',
was_this_helpful: 'A fost util?',
@@ -47,6 +47,8 @@ export const ru: TranslationLanguage = {
on_this_page: 'На этой странице',
next_page: 'Следующая',
previous_page: 'Предыдущая',
updates_pagination_navigation: 'Навигация по страницам',
updates_pagination_range: '${1} - ${2} из ${3} обновлений',
toc_back_to_space: 'Назад к ${1}',
page_last_modified: 'Последнее обновление ${1}',
was_this_helpful: 'Это было полезно?',
@@ -46,6 +46,8 @@ export const sk: TranslationLanguage = {
on_this_page: 'Na tejto stránke',
next_page: 'Ďalej',
previous_page: 'Predchádzajúca',
updates_pagination_navigation: 'Navigácia medzi stránkami',
updates_pagination_range: '${1} - ${2} z ${3} aktualizácií',
toc_back_to_space: 'Späť na ${1}',
page_last_modified: 'Naposledy aktualizované ${1}',
was_this_helpful: 'Bolo to užitočné?',
@@ -46,6 +46,8 @@ export const sl: TranslationLanguage = {
on_this_page: 'Na tej strani',
next_page: 'Naslednja',
previous_page: 'Prejšnja',
updates_pagination_navigation: 'Krmarjenje med stranmi',
updates_pagination_range: '${1} - ${2} od ${3} posodobitev',
toc_back_to_space: 'Nazaj na ${1}',
page_last_modified: 'Nazadnje posodobljeno ${1}',
was_this_helpful: 'Je bilo to koristno?',
@@ -46,6 +46,8 @@ export const sv: TranslationLanguage = {
on_this_page: 'På den här sidan',
next_page: 'Nästa',
previous_page: 'Föregående',
updates_pagination_navigation: 'Sidnavigering',
updates_pagination_range: '${1} - ${2} av ${3} uppdateringar',
toc_back_to_space: 'Tillbaka till ${1}',
page_last_modified: 'Senast uppdaterad ${1}',
was_this_helpful: 'Var detta till hjälp?',
@@ -45,6 +45,8 @@ export const th: TranslationLanguage = {
on_this_page: 'ในหน้านี้',
next_page: 'ถัดไป',
previous_page: 'ก่อนหน้า',
updates_pagination_navigation: 'การนำทางระหว่างหน้า',
updates_pagination_range: '${1} - ${2} จากการอัปเดต ${3} รายการ',
toc_back_to_space: 'กลับไปที่ ${1}',
page_last_modified: 'อัปเดตล่าสุด ${1}',
was_this_helpful: 'สิ่งนี้มีประโยชน์หรือไม่?',
@@ -46,6 +46,8 @@ export const tr: TranslationLanguage = {
on_this_page: 'Bu sayfada',
next_page: 'Sonraki',
previous_page: 'Önceki',
updates_pagination_navigation: 'Sayfa gezinme',
updates_pagination_range: '${3} güncellemeden ${1} - ${2}',
toc_back_to_space: 'Şuraya dön: ${1}',
page_last_modified: 'Son güncelleme ${1}',
was_this_helpful: 'Bu yararlı oldu mu?',
@@ -46,6 +46,8 @@ export const uk: TranslationLanguage = {
on_this_page: 'На цій сторінці',
next_page: 'Наступна',
previous_page: 'Попередня',
updates_pagination_navigation: 'Навігація сторінками',
updates_pagination_range: '${1} - ${2} з ${3} оновлень',
toc_back_to_space: 'Назад до ${1}',
page_last_modified: 'Останнє оновлення ${1}',
was_this_helpful: 'Це було корисно?',
@@ -46,6 +46,8 @@ export const vi: TranslationLanguage = {
on_this_page: 'Trên trang này',
next_page: 'Tiếp theo',
previous_page: 'Trước',
updates_pagination_navigation: 'Điều hướng trang',
updates_pagination_range: '${1} - ${2} trong số ${3} bản cập nhật',
toc_back_to_space: 'Quay lại ${1}',
page_last_modified: 'Cập nhật lần cuối ${1}',
was_this_helpful: 'Nội dung này có hữu ích không?',
@@ -45,6 +45,8 @@ export const yue: TranslationLanguage = {
on_this_page: '本頁內容',
next_page: '下一頁',
previous_page: '上一頁',
updates_pagination_navigation: '分頁導覽',
updates_pagination_range: '第 ${1} 至 ${2} 項更新,共 ${3} 項',
toc_back_to_space: '返去${1}',
page_last_modified: '最後更新 ${1}',
was_this_helpful: '呢個有冇幫助?',
@@ -45,6 +45,8 @@ export const zh_tw: TranslationLanguage = {
on_this_page: '本頁內容',
next_page: '下一頁',
previous_page: '上一頁',
updates_pagination_navigation: '分頁導覽',
updates_pagination_range: '第 ${1} 至 ${2} 項更新,共 ${3} 項',
toc_back_to_space: '返回${1}',
page_last_modified: '最後更新於 ${1}',
was_this_helpful: '這有幫助嗎?',
@@ -46,6 +46,8 @@ export const zh: TranslationLanguage = {
on_this_page: '在本页',
next_page: '下一页',
previous_page: '上一页',
updates_pagination_navigation: '分页导航',
updates_pagination_range: '第 ${1} 至 ${2} 条更新,共 ${3} 条',
toc_back_to_space: '返回${1}',
page_last_modified: '最后更新于 ${1}',
was_this_helpful: '这有帮助吗?',
+21
View File
@@ -0,0 +1,21 @@
/** URL search param carrying the active tag filter, e.g. `?tag=changelog`. */
export const UPDATES_FILTER_SEARCH_PARAM = 'tag';
export const UPDATES_MAX_PAGE = 500;
export const UPDATES_PAGE_SEARCH_PARAM = 'page';
export function parseUpdatesPageParam(raw: string | null | undefined): number | null {
const page = Number(raw);
if (!Number.isInteger(page) || page < 2 || page > UPDATES_MAX_PAGE || String(page) !== raw) {
return null;
}
return page;
}
export function setUpdatesPageParam(params: URLSearchParams, page: number) {
if (page > 1) {
params.set(UPDATES_PAGE_SEARCH_PARAM, String(page));
} else {
params.delete(UPDATES_PAGE_SEARCH_PARAM);
}
}
+206 -19
View File
@@ -10,6 +10,10 @@ import {
import { getRevisionTags, resolveBlockTags, resolveTag } from './tags';
import {
UPDATES_TAG_FILTER_CAP,
countDocumentUpdates,
findUpdateAnchorPage,
paginateUpdatesDocument,
parseUpdatesPageParam,
getDocumentFilterableTags,
normalizeUpdatesFilterTags,
} from './updates';
@@ -92,29 +96,212 @@ describe('normalizeUpdatesFilterTags', () => {
});
});
function createUpdatesDocument(entryTags: string[][]): JSONDocument {
return {
object: 'document',
data: { schemaVersion: 2 },
describe('updates pagination', () => {
it('keeps a 50-entry document intact and paginates 51 entries across two blocks', () => {
const short = createUpdatesDocument(Array.from({ length: 50 }, () => []));
expect(paginateUpdatesDocument(short, undefined, { page: 2 })).toEqual({
document: short,
pagination: null,
});
expect(paginateUpdatesDocument(short, undefined, { page: 2 }).document).toBe(short);
const long = createUpdatesDocument(
Array.from({ length: 51 }, () => []),
25
);
expect(countDocumentUpdates(long)).toBe(51);
for (const [page, start, end, blockTypes] of [
[1, 1, 20, ['updates', 'paragraph']],
[2, 21, 40, ['updates', 'paragraph', 'updates']],
[3, 41, 51, ['paragraph', 'updates']],
] as const) {
const result = paginateUpdatesDocument(long, undefined, { page });
expect(result.pagination).toEqual({
page,
totalPages: 3,
totalItems: 51,
pageSize: 20,
start,
end,
isClamped: false,
});
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: end - start + 1 }, (_, i) => `update-${start + i}`)
);
expect(result.document.nodes.map((block) => block.type)).toEqual([...blockTypes]);
}
});
it('keeps the first and seventh slices of a 260-entry changelog to 20 entries each', () => {
const document = createUpdatesDocument(
Array.from({ length: 260 }, () => []),
135
);
for (const [page, start] of [
[1, 1],
[7, 121],
] as const) {
const result = paginateUpdatesDocument(document, undefined, { page });
expect(result.pagination).toMatchObject({
page,
totalPages: 13,
start,
end: start + 19,
});
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: 20 }, (_, i) => `update-${start + i}`)
);
}
});
it('filters by any selected tag before calculating page bounds and clamps to the last match', () => {
const revision = {
tags: [createTag('odd', 'Odd'), createTag('even', 'Even')],
} as unknown as Revision;
const document = createUpdatesDocument(
Array.from({ length: 61 }, (_, index) => {
if (index % 3 === 0) {
return ['odd'];
}
if (index % 3 === 1) {
return ['even'];
}
return [];
}),
30
);
const result = paginateUpdatesDocument(document, revision, {
page: 9,
tags: [' odd ', 'even', 'unknown'],
});
expect(result.pagination).toMatchObject({
page: 3,
totalPages: 3,
totalItems: 41,
start: 41,
end: 41,
isClamped: true,
});
expect(getUpdateIds(result.document)).toEqual(['update-61']);
expect(countDocumentUpdates(document)).toBe(61);
});
it('finds a nested anchor on the filtered page or clears a filter that excludes it', () => {
const revision = { tags: [createTag('fixes', 'Fixes')] } as unknown as Revision;
const document = createUpdatesDocument(
Array.from({ length: 61 }, (_, index) => {
if (index % 2 === 0) {
return ['fixes'];
}
return [];
}),
26
);
expect(
findUpdateAnchorPage(document, revision, { anchor: 'update-43', tags: ['fixes'] })
).toEqual({ found: true, page: 2, clearTags: false });
expect(
findUpdateAnchorPage(document, revision, { anchor: 'update-44', tags: ['fixes'] })
).toEqual({ found: true, page: 3, clearTags: true });
expect(
findUpdateAnchorPage(document, revision, { anchor: 'missing', tags: ['fixes'] })
).toEqual({ found: false });
const tabUpdate = document.nodes[0];
if (tabUpdate?.type === 'updates' && tabUpdate.nodes[20]?.type === 'update') {
tabUpdate.nodes[20].nodes.push({
object: 'block',
type: 'tabs',
key: 'tabs-block',
data: {},
isVoid: false,
nodes: [
{
object: 'block',
type: 'tabs-item',
key: 'legacy-tab-key',
data: { title: 'Tab' },
isVoid: false,
nodes: [],
},
],
});
}
expect(findUpdateAnchorPage(document, revision, { anchor: 'legacy-tab-key' })).toEqual({
found: true,
page: 2,
clearTags: false,
});
});
});
describe('parseUpdatesPageParam', () => {
it.each([null, undefined, '1', '0', '-1', 'abc', '501', '2.5', '2e1', '02', ' 2', '2\n'])(
'rejects %s',
(param) => {
expect(parseUpdatesPageParam(param)).toBeNull();
}
);
it.each([2, 500])('accepts %s', (page) => {
expect(parseUpdatesPageParam(String(page))).toBe(page);
});
});
function getUpdateIds(document: JSONDocument) {
return document.nodes.flatMap((block) => {
if (block.type !== 'updates') {
return [];
}
return block.nodes.map((entry) => {
const heading = entry.nodes[0];
if (heading?.type === 'heading-1') {
return heading.meta?.id;
}
});
});
}
function createUpdatesDocument(entryTags: string[][], splitAt?: number): JSONDocument {
const entries = entryTags.map((tags, index) => ({
object: 'block' as const,
type: 'update' as const,
data: {
date: '2026-05-01',
tags: tags.map((tag) => ({ kind: 'tag' as const, tag })),
},
isVoid: false as const,
nodes: [
{
object: 'block',
type: 'updates',
data: { format: 'full' },
isVoid: false,
nodes: entryTags.map((tags, index) => ({
object: 'block',
type: 'update',
data: {
date: `2026-05-${String(index + 1).padStart(2, '0')}`,
tags: tags.map((tag) => ({ kind: 'tag', tag })),
},
isVoid: false,
nodes: [],
})),
object: 'block' as const,
type: 'heading-1' as const,
meta: { id: `update-${index + 1}` },
data: {},
isVoid: false as const,
nodes: [],
},
],
};
}));
const updates = (nodes: typeof entries) => ({
object: 'block' as const,
type: 'updates' as const,
data: { format: 'full' as const },
isVoid: false as const,
nodes,
});
const nodes: JSONDocument['nodes'] = [updates(entries)];
if (splitAt !== undefined) {
nodes.splice(
0,
1,
updates(entries.slice(0, splitAt)),
{ object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] },
updates(entries.slice(splitAt))
);
}
return { object: 'document', data: { schemaVersion: 2 }, nodes };
}
function createTag(slug: string, label: string): RevisionTag {
+160 -4
View File
@@ -1,10 +1,34 @@
import type { JSONDocument, Revision, RevisionTag } from '@gitbook/api';
import type {
DocumentBlock,
DocumentBlockUpdate,
DocumentInline,
JSONDocument,
Revision,
RevisionTag,
} from '@gitbook/api';
import { getBlocksByType } from './document';
import { getBlocksByType, hasMoreThan } from './document';
import { getRevisionTags, resolveBlockTags } from './tags';
/** URL search param carrying the active tag filter, e.g. `?tag=changelog`. */
export const UPDATES_FILTER_SEARCH_PARAM = 'tag';
export {
UPDATES_FILTER_SEARCH_PARAM,
UPDATES_MAX_PAGE,
UPDATES_PAGE_SEARCH_PARAM,
parseUpdatesPageParam,
} from './updates-url';
export const UPDATES_PAGINATION_THRESHOLD = 50;
export const UPDATES_PAGE_SIZE = 20;
export type UpdatesPageRange = {
page: number;
totalPages: number;
totalItems: number;
pageSize: number;
start: number;
end: number;
isClamped: boolean;
};
/** Attribute on `<html>` with the active filter's tag slugs, space-separated (e.g. `"a b"`). */
export const UPDATES_TAG_FILTER_ATTR = 'data-updates-tag-filter';
@@ -93,6 +117,138 @@ export function getDocumentFilterableTags(
return tags;
}
export function countDocumentUpdates(document: JSONDocument): number {
return getDocumentUpdates(document).length;
}
export function paginateUpdatesDocument(
document: JSONDocument,
revision: Revision | undefined,
{ page, tags }: { page: number; tags?: string[] }
): { document: JSONDocument; pagination: UpdatesPageRange | null } {
const updates = getDocumentUpdates(document);
if (updates.length <= UPDATES_PAGINATION_THRESHOLD) {
return { document, pagination: null };
}
const matching = filterUpdates(updates, document, revision, tags);
const pagination = getUpdatesPageRange(page, matching.length);
const slice = new Set(matching.slice(pagination.start - 1, pagination.end));
const nodes: JSONDocument['nodes'] = [];
for (const block of document.nodes) {
if (block.type !== 'updates') {
nodes.push(block);
continue;
}
const entries = block.nodes.filter((entry) => entry.type === 'update' && slice.has(entry));
if (entries.length > 0) {
nodes.push({ ...block, nodes: entries });
}
}
return { document: { ...document, nodes }, pagination };
}
export function getUpdatesPageRange(requestedPage: number, totalItems: number): UpdatesPageRange {
const totalPages = Math.max(1, Math.ceil(totalItems / UPDATES_PAGE_SIZE));
const page = Math.min(Math.max(1, requestedPage), totalPages);
let start = (page - 1) * UPDATES_PAGE_SIZE + 1;
if (totalItems === 0) {
start = 0;
}
return {
page,
totalPages,
totalItems,
pageSize: UPDATES_PAGE_SIZE,
start,
end: Math.min(page * UPDATES_PAGE_SIZE, totalItems),
isClamped: page !== requestedPage,
};
}
export function findUpdateAnchorPage(
document: JSONDocument,
revision: Revision | undefined,
{ anchor, tags }: { anchor: string; tags?: string[] }
): { found: true; page: number; clearTags: boolean } | { found: false } {
const updates = getDocumentUpdates(document);
const index = updates.findIndex((update) =>
hasMoreThan(update, (node) => matchesUpdateAnchor(node, anchor), 0)
);
const entry = updates[index];
if (!entry) {
return { found: false };
}
const filteredIndex = filterUpdates(updates, document, revision, tags).indexOf(entry);
if (filteredIndex >= 0) {
return {
found: true,
page: Math.floor(filteredIndex / UPDATES_PAGE_SIZE) + 1,
clearTags: false,
};
}
return { found: true, page: Math.floor(index / UPDATES_PAGE_SIZE) + 1, clearTags: true };
}
function matchesUpdateAnchor(node: DocumentBlock | DocumentInline, anchor: string): boolean {
if (node.object !== 'block') {
return false;
}
if ('meta' in node && node.meta && 'id' in node.meta && node.meta.id === anchor) {
return true;
}
if (node.type === 'tabs-item' && !node.meta?.id && node.key === anchor) {
return true;
}
return false;
}
function getDocumentUpdates(document: JSONDocument): DocumentBlockUpdate[] {
const updates: DocumentBlockUpdate[] = [];
for (const block of document.nodes) {
if (block.type !== 'updates') {
continue;
}
for (const entry of block.nodes) {
if (entry.type === 'update') {
updates.push(entry);
}
}
}
return updates;
}
function filterUpdates(
updates: DocumentBlockUpdate[],
document: JSONDocument,
revision: Revision | undefined,
tags: string[] | undefined
): DocumentBlockUpdate[] {
if (!tags?.length) {
return updates;
}
const availableTags = new Set(
getDocumentFilterableTags(document, revision).map((tag) => tag.slug)
);
const selectedTags = new Set(normalizeUpdatesFilterTags(tags, availableTags));
if (!selectedTags.size) {
return updates;
}
const revisionTags = getRevisionTags(revision);
return updates.filter((update) =>
resolveBlockTags(update.data.tags, revisionTags).some((tag) => selectedTags.has(tag.slug))
);
}
/**
* Escape a slug for interpolation into a CSS string literal (a quoted attribute-selector value).
*/
+60
View File
@@ -1,4 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
import { RequestCookiesAdapter } from 'next/dist/server/web/spec-extension/adapters/request-cookies';
import * as nextHeaders from 'next/headers';
import { NextRequest } from 'next/server';
import { middleware } from './middleware';
@@ -157,3 +159,61 @@ describe('direct site search middleware', () => {
expect(response.headers.get('server-timing')).toMatch(/^api;dur=\d+$/);
});
});
describe('Updates page middleware', () => {
it.each([
['/changelog', '', '/changelog', null],
['/changelog', '?page=2', '/changelog/2', null],
['/changelog', '?page=500&tag=fixes&tag=releases', '/changelog/500', 'noindex, follow'],
['/changelog', '?tag=fixes', '/changelog', 'noindex, follow'],
['/changelog', '?page=1', '/changelog', null],
['/changelog', '?page=0', '/changelog', null],
['/changelog', '?page=-1', '/changelog', null],
['/changelog', '?page=abc', '/changelog', null],
['/changelog', '?page=501', '/changelog', null],
['/changelog.md', '?page=2', '/~gitbook/markdown/changelog', null],
['/changelog/rss.xml', '?page=2', '/~gitbook/rss/changelog', null],
['/llms-full.txt', '?page=2', '/llms-full.txt', null],
['/sitemap.xml', '?page=2', '/sitemap.xml', null],
['/changelog', '?page=2&tag=fixes&ask=test', '/changelog/2', 'none'],
['/~gitbook/embed/page/changelog', '?page=2', '/~gitbook/embed/page/%2Fchangelog/2', null],
] as const)(
'rewrites %s%s without changing its query',
async (path, search, suffix, robots) => {
const url = new URL(`https://docs.example.com${path}${search}`);
fetchSpy.mockResolvedValueOnce(
Response.json({
site: 'site',
siteSpace: 'variant',
space: 'space',
organization: 'org',
apiToken: 'content-token',
pathname: path,
basePath: '',
siteBasePath: '',
canonicalUrl: url.origin + url.pathname,
complete: true,
})
);
const request = new NextRequest(url, { headers: { 'x-forwarded-host': url.host } });
const cookiesSpy = spyOn(nextHeaders, 'cookies').mockResolvedValue(
RequestCookiesAdapter.seal(request.cookies)
);
let response;
try {
response = await middleware(request);
} finally {
cookiesSpy.mockRestore();
}
expect(response.headers.get('x-gitbook-route-type')).toBe('static');
expect(response.headers.get('x-robots-tag')).toBe(robots);
const rewrite = response.headers.get('x-middleware-rewrite');
expect(rewrite).not.toBeNull();
const destination = new URL(rewrite!);
expect(destination.pathname).toEndWith(suffix);
expect(destination.search).toBe(search);
}
);
});
+20 -2
View File
@@ -70,6 +70,11 @@ import {
createRobotsTxtResponse,
isRobotsTxtRequest,
} from '@/lib/robots';
import {
UPDATES_FILTER_SEARCH_PARAM,
UPDATES_PAGE_SEARCH_PARAM,
parseUpdatesPageParam,
} from '@/lib/updates-url';
import {
type ResponseCookies,
getPathScopedCookieName,
@@ -746,6 +751,8 @@ async function serveSiteRequest(requestURL: URL, request: NextRequest, match: UR
response.headers.set('x-robots-tag', 'none');
} else if (hasRevisionSelector(siteURLData.basePath)) {
response.headers.set('x-robots-tag', REVISION_ROBOTS_TAG);
} else if (rewrittenURL.searchParams.has(UPDATES_FILTER_SEARCH_PARAM)) {
response.headers.set('x-robots-tag', 'noindex, follow');
}
// Allow cross-origin requests from the same parent domain as the site.
@@ -1114,7 +1121,7 @@ function encodePathInSiteContent(
const embedPage = pathname.match(EMBED_PAGE_PATH_REGEX);
if (embedPage) {
return {
pathname: `~gitbook/embed/page/${encodePagePath(embedPage[1])}`,
pathname: `~gitbook/embed/page/${encodeUpdatesPagePath(embedPage[1], request)}`,
};
}
@@ -1221,11 +1228,22 @@ function encodePathInSiteContent(
],
};
}
return { pathname: encodePagePath(pathname) };
return { pathname: encodeUpdatesPagePath(pathname, request) };
}
}
}
function encodeUpdatesPagePath(path: string | undefined, request: Request): string {
const pathname = encodePagePath(path);
const page = parseUpdatesPageParam(
new URL(request.url).searchParams.get(UPDATES_PAGE_SEARCH_PARAM)
);
if (page !== null) {
return `${pathname}/${page}`;
}
return pathname;
}
function encodePagePath(path: string | undefined): string {
return encodeURIComponent(path || '/');
}