diff --git a/.changeset/updates-pagination.md b/.changeset/updates-pagination.md new file mode 100644 index 000000000..5adf350a5 --- /dev/null +++ b/.changeset/updates-pagination.md @@ -0,0 +1,5 @@ +--- +"gitbook": patch +--- + +Paginate published Updates pages with more than 50 entries into 20-entry pages. diff --git a/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/[page]/page.tsx b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/[page]/page.tsx new file mode 100644 index 000000000..304372fb3 --- /dev/null +++ b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/[page]/page.tsx @@ -0,0 +1,45 @@ +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; + +import { type RouteParams, getDynamicSiteContext, getPagePathFromParams } from '@/app/utils'; +import { SitePage, generateSitePageMetadata } from '@/components/SitePage'; +import { parseUpdatesPageParam } from '@/lib/updates-url'; + +type PageProps = { + params: Promise; +}; + +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 ( + + ); +} + +export async function generateMetadata(props: PageProps): Promise { + 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, + }); +} diff --git a/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/embed/page/[pagePath]/[page]/page.tsx b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/embed/page/[pagePath]/[page]/page.tsx new file mode 100644 index 000000000..9a6775d15 --- /dev/null +++ b/packages/gitbook/src/app/sites/dynamic/[mode]/[siteURL]/[siteData]/~gitbook/embed/page/[pagePath]/[page]/page.tsx @@ -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; +}; + +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 ( + + ); +} + +export async function generateMetadata(props: PageProps): Promise { + 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 }); +} diff --git a/packages/gitbook/src/app/sites/static/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/[page]/page.tsx b/packages/gitbook/src/app/sites/static/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/[page]/page.tsx new file mode 100644 index 000000000..1a4cb3150 --- /dev/null +++ b/packages/gitbook/src/app/sites/static/[mode]/[siteURL]/[siteData]/(content)/[pagePath]/[page]/page.tsx @@ -0,0 +1,47 @@ +import type { Metadata } from 'next'; +import { notFound } from 'next/navigation'; + +import { type RouteParams, getPagePathFromParams, getStaticSiteContext } from '@/app/utils'; +import { SitePage, generateSitePageMetadata } from '@/components/SitePage'; +import { parseUpdatesPageParam } from '@/lib/updates-url'; + +export const dynamic = 'force-static'; + +type PageProps = { + params: Promise; +}; + +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 ( + + ); +} + +export async function generateMetadata(props: PageProps): Promise { + 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, + }); +} diff --git a/packages/gitbook/src/app/sites/static/[mode]/[siteURL]/[siteData]/~gitbook/embed/page/[pagePath]/[page]/page.tsx b/packages/gitbook/src/app/sites/static/[mode]/[siteURL]/[siteData]/~gitbook/embed/page/[pagePath]/[page]/page.tsx new file mode 100644 index 000000000..49a05c9c6 --- /dev/null +++ b/packages/gitbook/src/app/sites/static/[mode]/[siteURL]/[siteData]/~gitbook/embed/page/[pagePath]/[page]/page.tsx @@ -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; +}; + +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 ( + + ); +} + +export async function generateMetadata(props: PageProps): Promise { + 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 }); +} diff --git a/packages/gitbook/src/components/DocumentView/PaginatedUpdates.tsx b/packages/gitbook/src/components/DocumentView/PaginatedUpdates.tsx new file mode 100644 index 000000000..40fe83c16 --- /dev/null +++ b/packages/gitbook/src/components/DocumentView/PaginatedUpdates.tsx @@ -0,0 +1,364 @@ +'use client'; + +import { useRouter, useSearchParams } from 'next/navigation'; +import React from 'react'; + +import { scrollToHash, useHash } from '../hooks'; +import { CONTENT_STYLE_REDUCED, MAIN_CONTENT_ID } from '../layout'; +import { Button, SkeletonUpdate, SuspenseLoadedHint } from '../primitives'; +import { UpdatesFilterContext, applyTagFilterAttribute } 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; +type FilterView = + | { status: 'loading'; tagsKey: string; pagination: UpdatesPageRange | null } + | { status: 'error'; pagination: null } + | ({ status: 'filtered'; tagsKey: string } & Omit); +type UpdatesView = { status: 'unfiltered'; pagination: UpdatesPageRange } | FilterView; + +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 searchParams = useSearchParams(); + const availableTags = React.useMemo(() => new Set(tagSlugs), [tagSlugs]); + const styleKey = updatesFilterStyleKey(tagSlugs); + const tagsKey = normalizeUpdatesFilterTags( + searchParams.getAll(UPDATES_FILTER_SEARCH_PARAM), + availableTags + ).join(' '); + const tags = React.useMemo(() => tagsKey.split(' ').filter(Boolean), [tagsKey]); + const page = parseUpdatesPageParam(searchParams.get(UPDATES_PAGE_SEARCH_PARAM)) ?? 1; + const { view, retry } = useFilteredUpdatesView({ + pageId, + revisionId, + isEmbeddable, + initialPagination, + tags, + page, + }); + + React.useLayoutEffect(() => { + document.documentElement.setAttribute(UPDATES_FILTER_KEY_ATTR, styleKey); + return () => { + document.documentElement.removeAttribute(UPDATES_FILTER_KEY_ATTR); + document.documentElement.removeAttribute(PENDING_FILTER_ATTR); + applyTagFilterAttribute([]); + }; + }, [styleKey]); + + React.useLayoutEffect(() => { + applyTagFilterAttribute(tags); + }, [tags]); + + React.useLayoutEffect(() => { + if (view.status !== 'loading') { + document.documentElement.removeAttribute(PENDING_FILTER_ATTR); + } + }, [view.status]); + + useResolveUpdatesAnchor({ pageId, isEmbeddable, tags, view }); + + function toggleTag(tag: string) { + let nextTags = normalizeUpdatesFilterTags([...tags, tag], availableTags); + if (tags.includes(tag)) { + nextTags = tags.filter((selected) => selected !== tag); + } + navigate(nextTags, 1, 'replace'); + } + + return ( + navigate([], 1, 'replace'), + }} + > + navigate(tags, nextPage, 'push'), + retry, + }} + > + {tagSlugs.length > 0 && ( + + )} + {children} + + + ); +} + +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 ; + } + if (updates?.view.status === 'error') { + return ( +
+ {tString(language, 'unexpected_error')} +
+ ); + } + if (updates?.view.status === 'filtered') { + return ( +
+ + {updates.view.content} +
+ ); + } + return
{props.children}
; +} + +/** Loads the filtered page for the selected tags and page, or falls back to the server-rendered one. */ +function useFilteredUpdatesView(options: { + pageId: string; + revisionId: string; + isEmbeddable: boolean; + initialPagination: UpdatesPageRange; + tags: string[]; + page: number; +}) { + const { pageId, revisionId, isEmbeddable, initialPagination, tags, page } = options; + const tagsKey = tags.join(' '); + const initialPage = initialPagination.page; + const router = useRouter(); + const [filterView, setFilterView] = React.useState(null); + const [retryCount, setRetryCount] = React.useState(0); + const hasNewerRevision = React.useRef(false); + const view = React.useMemo( + () => filterView ?? { status: 'unfiltered', pagination: initialPagination }, + [filterView, initialPagination] + ); + const isShowingPage = + filterView?.status === 'filtered' && + filterView.tagsKey === tagsKey && + filterView.pagination.page === page; + + React.useLayoutEffect(() => { + if (!tags.length) { + if (page === initialPage && !hasNewerRevision.current) { + setFilterView(null); + return; + } + setFilterView({ status: 'loading', tagsKey, pagination: null }); + const target = relativeURL(new URL(window.location.href)); + if (hasNewerRevision.current) { + // router.refresh() does not reconcile the [siteData] middleware rewrite. + window.location.replace(target); + } else { + router.replace(target); + } + return; + } + + // A clamped result rewrites the URL to the page it already shows. + if (isShowingPage) { + return; + } + + let cancelled = false; + setFilterView((current) => { + let pagination = null; + if (current?.status !== 'error' && current?.tagsKey === tagsKey && current.pagination) { + pagination = getUpdatesPageRange(page, current.pagination.totalItems); + } + return { status: 'loading', tagsKey, pagination }; + }); + + void getFilteredUpdatesPage({ pageId, tags, page, isEmbeddable }) + .catch((): FilteredUpdatesPageResult => ({ status: 'error' })) + .then((result) => { + if (cancelled) { + return; + } + if (result.status === 'error') { + setFilterView({ status: 'error', pagination: null }); + return; + } + if (result.revisionId !== revisionId) { + hasNewerRevision.current = true; + } + + const url = new URL(window.location.href); + if (result.status === 'unfiltered') { + url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM); + setUpdatesPageParam(url.searchParams, initialPage); + window.history.replaceState(null, '', relativeURL(url)); + return; + } + if (result.pagination.isClamped) { + setUpdatesPageParam(url.searchParams, result.pagination.page); + window.history.replaceState(null, '', relativeURL(url)); + } + setFilterView({ + status: 'filtered', + tagsKey, + revisionId: result.revisionId, + content: result.content, + sections: result.sections, + pagination: result.pagination, + }); + }); + + return () => { + cancelled = true; + }; + }, [ + tags, + tagsKey, + page, + retryCount, + isShowingPage, + initialPage, + pageId, + isEmbeddable, + revisionId, + router, + ]); + + return { view, retry: () => setRetryCount((count) => count + 1) }; +} + +/** Moves to the page holding an off-page `#anchor` once the current page has rendered. */ +function useResolveUpdatesAnchor(options: { + pageId: string; + isEmbeddable: boolean; + tags: string[]; + view: UpdatesView; +}) { + const { pageId, isEmbeddable, tags, view } = options; + const router = useRouter(); + const hash = useHash(); + + React.useEffect(() => { + if ( + view.status === 'loading' || + view.status === 'error' || + (view.status === 'unfiltered' && tags.length > 0) + ) { + return; + } + + let cancelled = false; + async function resolveHash() { + const url = new URL(window.location.href); + if (!url.hash || scrollToHash(url.hash.slice(1))) { + return; + } + + let anchor: string; + try { + anchor = decodeURIComponent(url.hash.slice(1)); + } catch { + return; + } + + try { + const result = await resolveUpdatesAnchor({ pageId, anchor, tags, isEmbeddable }); + if (cancelled || !result.found || 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 () => { + cancelled = true; + window.removeEventListener('hashchange', resolveHash); + }; + }, [hash, isEmbeddable, pageId, router, tags, view]); +} + +/** Writes the filter selection to the URL; the provider reacts through `useSearchParams()`. */ +function navigate(nextTags: string[], nextPage: number, history: 'push' | 'replace') { + const url = new URL(window.location.href); + url.searchParams.delete(UPDATES_FILTER_SEARCH_PARAM); + for (const tag of nextTags) { + url.searchParams.append(UPDATES_FILTER_SEARCH_PARAM, tag); + } + setUpdatesPageParam(url.searchParams, nextPage); + url.hash = ''; + if (history === 'push') { + window.history.pushState(null, '', relativeURL(url)); + } else { + window.history.replaceState(null, '', relativeURL(url)); + } + + const main = document.getElementById(MAIN_CONTENT_ID); + if (main) { + main.scrollIntoView({ block: 'start', behavior: 'instant' }); + // Keeps focus off document.body when the clicked pagination button unmounts. + main.focus({ preventScroll: true }); + } +} + +function relativeURL(url: URL): string { + return `${url.pathname}${url.search}${url.hash}`; +} diff --git a/packages/gitbook/src/components/DocumentView/UpdatesFilter.tsx b/packages/gitbook/src/components/DocumentView/UpdatesFilter.tsx index cf26933a3..1b3be706c 100644 --- a/packages/gitbook/src/components/DocumentView/UpdatesFilter.tsx +++ b/packages/gitbook/src/components/DocumentView/UpdatesFilter.tsx @@ -36,7 +36,7 @@ const emptyUpdatesFilterContext: UpdatesFilterContextValue = { clearTags: () => {}, }; -const UpdatesFilterContext = React.createContext(null); +export const UpdatesFilterContext = React.createContext(null); export function UpdatesFilterProvider(props: { tagSlugs: string[]; children: React.ReactNode }) { const { tagSlugs, children } = props; @@ -254,7 +254,7 @@ function areTagsEqual(left: string[], right: string[]): boolean { } /** Mirrors the active filter onto ``, matching what the pre-paint script does on first load. */ -function applyTagFilterAttribute(tags: string[]) { +export function applyTagFilterAttribute(tags: string[]) { if (typeof document === 'undefined') { return; } diff --git a/packages/gitbook/src/components/DocumentView/UpdatesFilterScript.tsx b/packages/gitbook/src/components/DocumentView/UpdatesFilterScript.tsx index 42bcfbd29..7297a0a73 100644 --- a/packages/gitbook/src/components/DocumentView/UpdatesFilterScript.tsx +++ b/packages/gitbook/src/components/DocumentView/UpdatesFilterScript.tsx @@ -58,12 +58,12 @@ export function applyUpdatesFilterScript( * Inline script that applies the URL's `?tag=` filter to `` 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, diff --git a/packages/gitbook/src/components/DocumentView/UpdatesPagination.tsx b/packages/gitbook/src/components/DocumentView/UpdatesPagination.tsx new file mode 100644 index 000000000..077dbdb06 --- /dev/null +++ b/packages/gitbook/src/components/DocumentView/UpdatesPagination.tsx @@ -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 ( +
+
+ {tString( + language, + 'updates_pagination_range', + number.format(start), + number.format(end), + number.format(totalItems) + )} +
+ +
+ ); +} diff --git a/packages/gitbook/src/components/DocumentView/UpdatesServerActions.tsx b/packages/gitbook/src/components/DocumentView/UpdatesServerActions.tsx new file mode 100644 index 000000000..2b867bba1 --- /dev/null +++ b/packages/gitbook/src/components/DocumentView/UpdatesServerActions.tsx @@ -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>; + pagination: NonNullable['pagination']>; + } + | { + status: 'unfiltered'; + revisionId: string; + } + | { + status: 'error'; + }; + +export async function getFilteredUpdatesPage( + options: UpdatesPageAction & { page: number } +): Promise { + 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: ( + + + + ), + 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 }; +} diff --git a/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx b/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx index d63e44128..f38c0a2dd 100644 --- a/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx +++ b/packages/gitbook/src/components/Embeddable/EmbeddableDocsPage.tsx @@ -2,6 +2,7 @@ import type { Metadata } from 'next'; import { SiteInsightsDisplayContext } from '@gitbook/api'; +import { PaginatedUpdatesProvider } from '../DocumentView/PaginatedUpdates'; import { HeaderMobileMenu } from '../Header/HeaderMobileMenu'; import { SpacesDropdown, TranslationsDropdown } from '../Header/SpacesDropdown'; import { PageBody } from '../PageBody'; @@ -33,6 +34,7 @@ export const dynamic = 'force-static'; type EmbeddableDocsPageProps = { context: GitBookSiteContext; pageParams: PagePathParams; + updatesPage?: number; }; /** @@ -41,11 +43,42 @@ 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, + pagination, + updatesBaseHref, + filterableTags, + } = await getSitePageData(props); + let pageBody = ( + + ); + if (pagination) { + pageBody = ( + tag.slug)} + initialPagination={pagination} + > + {pageBody} + + ); + } const variants = categorizeVariants(context); @@ -147,15 +180,7 @@ export async function EmbeddableDocsPage( ) : null } /> - + {pageBody} diff --git a/packages/gitbook/src/components/PageAside/PageAside.tsx b/packages/gitbook/src/components/PageAside/PageAside.tsx index df94de58e..82e00929d 100644 --- a/packages/gitbook/src/components/PageAside/PageAside.tsx +++ b/packages/gitbook/src/components/PageAside/PageAside.tsx @@ -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: {
{document ? ( - + ) : null} @@ -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 ; + } + return sections.length > 1 ? (
diff --git a/packages/gitbook/src/components/PageAside/ScrollSectionsList.tsx b/packages/gitbook/src/components/PageAside/ScrollSectionsList.tsx index df93b7286..22f97b17a 100644 --- a/packages/gitbook/src/components/PageAside/ScrollSectionsList.tsx +++ b/packages/gitbook/src/components/PageAside/ScrollSectionsList.tsx @@ -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 ( +
+ +
+ ); +} + export function ScrollSectionsList({ sections }: { sections: DocumentSection[] }) { const { selectedTagSet } = useUpdatesFilter(); const ids = React.useMemo( diff --git a/packages/gitbook/src/components/PageBody/PageBody.tsx b/packages/gitbook/src/components/PageBody/PageBody.tsx index 639c8336f..f49eb87ca 100644 --- a/packages/gitbook/src/components/PageBody/PageBody.tsx +++ b/packages/gitbook/src/components/PageBody/PageBody.tsx @@ -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, hasTopLevelBlock, 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,7 @@ export async function PageBody(props: { withPageFeedback: boolean; insightsDisplayContext: SiteInsightsDisplayContext; staticRoute: boolean; + updatesBaseHref?: string | undefined; }) { const { page, @@ -50,6 +46,7 @@ export async function PageBody(props: { withPageFeedback, insightsDisplayContext, staticRoute, + updatesBaseHref, } = props; const { customization } = context; @@ -61,15 +58,6 @@ export async function PageBody(props: { // 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 +80,29 @@ export async function PageBody(props: { const pageHasToc = page.layout.tableOfContents && hasVisibleTOCItems; + let content = ; + if (document && !isNodeEmpty(document)) { + content = ( + } + > + +
+ +
+
+ ); + } + if (updatesBaseHref) { + content = ( + <> + {content} + + + ); + } + return ( {contentHasUpdates ? ( @@ -104,10 +115,11 @@ export async function PageBody(props: { ) : null}
- {document && !isNodeEmpty(document) ? ( - } - > - -
- -
-
- ) : ( - - )} + {content}
{page.layout.pagination && customization.pagination.enabled ? ( diff --git a/packages/gitbook/src/components/PageBody/PageBodyDocument.tsx b/packages/gitbook/src/components/PageBody/PageBodyDocument.tsx new file mode 100644 index 000000000..92fea901d --- /dev/null +++ b/packages/gitbook/src/components/PageBody/PageBodyDocument.tsx @@ -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 ( + + ); +} diff --git a/packages/gitbook/src/components/SitePage/SitePage.tsx b/packages/gitbook/src/components/SitePage/SitePage.tsx index 7d8b9e321..b7a80870b 100644 --- a/packages/gitbook/src/components/SitePage/SitePage.tsx +++ b/packages/gitbook/src/components/SitePage/SitePage.tsx @@ -6,6 +6,7 @@ import { CustomizationHeaderPreset, SiteInsightsDisplayContext, type TranslationLanguage, + type RevisionTag, } from '@gitbook/api'; import { IconsProvider } from '@gitbook/icons'; @@ -18,6 +19,7 @@ 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'; @@ -30,22 +32,29 @@ import { 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 +94,13 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean }) withTopHeader, pageMetaLinks, iconSources, + filterableTags, + pagination, + updatesBaseHref, } = 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 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 +130,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 +144,7 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean }) withPageFeedback={withPageFeedback} insightsDisplayContext={SiteInsightsDisplayContext.Site} staticRoute={props.staticRoute} + updatesBaseHref={updatesBaseHref} />
@@ -139,18 +152,34 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean }) ); + if (pagination) { + content = ( + + + {content} + + ); + } else if (filterableTagSlugs.length > 0) { + content = ( + + + + {content} + + ); + } + return ( - {filterableTagSlugs.length > 0 ? ( - - - - {content} - - ) : ( - content - )} + {content} ); @@ -204,7 +233,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise 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; generic: { @@ -239,7 +285,7 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise 0); - const document = await getPageDocument(context, page); + const fullDocument = await getPageDocument(context, page); + const pageHref = context.linker.toPathForPagePath({ path: rawPathname }); + let filterableTags: RevisionTag[] = []; + let document = fullDocument; + let pagination = null; + if (fullDocument) { + 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({ @@ -336,6 +417,11 @@ export async function getSitePageData(props: SitePageProps) { }) ); + let updatesBaseHref: string | undefined; + if (pagination) { + updatesBaseHref = pageHref; + } + return { context, page, @@ -347,6 +433,9 @@ export async function getSitePageData(props: SitePageProps) { withTopHeader, pageMetaLinks, iconSources, + filterableTags, + pagination, + updatesBaseHref, }; } diff --git a/packages/gitbook/src/components/primitives/Button.tsx b/packages/gitbook/src/components/primitives/Button.tsx index 9907a4c7b..368bbc473 100644 --- a/packages/gitbook/src/components/primitives/Button.tsx +++ b/packages/gitbook/src/components/primitives/Button.tsx @@ -98,7 +98,10 @@ export const activeClasses = { export const Button = React.forwardRef< HTMLButtonElement | HTMLAnchorElement, ButtonProps & - React.ButtonHTMLAttributes & { target?: React.HTMLAttributeAnchorTarget } + React.ButtonHTMLAttributes & { + target?: React.HTMLAttributeAnchorTarget; + rel?: string; + } >( ( { @@ -164,6 +167,11 @@ export const Button = React.forwardRef< } } + let trailingElement = null; + if (trailing) { + trailingElement = {trailing}; + } + const content = ( <> {iconElement} @@ -177,6 +185,7 @@ export const Button = React.forwardRef< {children ?? label} )} + {trailingElement} ); @@ -207,7 +216,6 @@ export const Button = React.forwardRef< {...rest} > {content} - {trailing ? {trailing} : null} ); diff --git a/packages/gitbook/src/intl/translations/ar.ts b/packages/gitbook/src/intl/translations/ar.ts index b11d8c946..b64150320 100644 --- a/packages/gitbook/src/intl/translations/ar.ts +++ b/packages/gitbook/src/intl/translations/ar.ts @@ -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: 'هل كان هذا مفيدا؟', diff --git a/packages/gitbook/src/intl/translations/bg.ts b/packages/gitbook/src/intl/translations/bg.ts index 72c0b9f4a..0053a0a12 100644 --- a/packages/gitbook/src/intl/translations/bg.ts +++ b/packages/gitbook/src/intl/translations/bg.ts @@ -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: 'Беше ли полезно?', diff --git a/packages/gitbook/src/intl/translations/cs.ts b/packages/gitbook/src/intl/translations/cs.ts index c9b81d1a8..48b247232 100644 --- a/packages/gitbook/src/intl/translations/cs.ts +++ b/packages/gitbook/src/intl/translations/cs.ts @@ -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é?', diff --git a/packages/gitbook/src/intl/translations/da.ts b/packages/gitbook/src/intl/translations/da.ts index 675a496c2..07b6f8f86 100644 --- a/packages/gitbook/src/intl/translations/da.ts +++ b/packages/gitbook/src/intl/translations/da.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/de.ts b/packages/gitbook/src/intl/translations/de.ts index 186e76b11..12e544b52 100644 --- a/packages/gitbook/src/intl/translations/de.ts +++ b/packages/gitbook/src/intl/translations/de.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/el.ts b/packages/gitbook/src/intl/translations/el.ts index d37aba98c..012909551 100644 --- a/packages/gitbook/src/intl/translations/el.ts +++ b/packages/gitbook/src/intl/translations/el.ts @@ -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: 'Ήταν χρήσιμο αυτό;', diff --git a/packages/gitbook/src/intl/translations/en.ts b/packages/gitbook/src/intl/translations/en.ts index f70120051..767f71787 100644 --- a/packages/gitbook/src/intl/translations/en.ts +++ b/packages/gitbook/src/intl/translations/en.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/es.ts b/packages/gitbook/src/intl/translations/es.ts index bce94e954..28922a932 100644 --- a/packages/gitbook/src/intl/translations/es.ts +++ b/packages/gitbook/src/intl/translations/es.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/et.ts b/packages/gitbook/src/intl/translations/et.ts index db7f29486..d1a0c79b3 100644 --- a/packages/gitbook/src/intl/translations/et.ts +++ b/packages/gitbook/src/intl/translations/et.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/fi.ts b/packages/gitbook/src/intl/translations/fi.ts index 4be671615..bf3a05407 100644 --- a/packages/gitbook/src/intl/translations/fi.ts +++ b/packages/gitbook/src/intl/translations/fi.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/fr.ts b/packages/gitbook/src/intl/translations/fr.ts index 1afd9c494..ee60cc06d 100644 --- a/packages/gitbook/src/intl/translations/fr.ts +++ b/packages/gitbook/src/intl/translations/fr.ts @@ -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 ?', diff --git a/packages/gitbook/src/intl/translations/he.ts b/packages/gitbook/src/intl/translations/he.ts index 71fbe59b1..ccebe593d 100644 --- a/packages/gitbook/src/intl/translations/he.ts +++ b/packages/gitbook/src/intl/translations/he.ts @@ -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: 'האם זה היה מועיל?', diff --git a/packages/gitbook/src/intl/translations/hi.ts b/packages/gitbook/src/intl/translations/hi.ts index dfc59d976..a7aa514d1 100644 --- a/packages/gitbook/src/intl/translations/hi.ts +++ b/packages/gitbook/src/intl/translations/hi.ts @@ -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: 'क्या यह उपयोगी था?', diff --git a/packages/gitbook/src/intl/translations/hr.ts b/packages/gitbook/src/intl/translations/hr.ts index 70de9dbc1..c02b8ed7b 100644 --- a/packages/gitbook/src/intl/translations/hr.ts +++ b/packages/gitbook/src/intl/translations/hr.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/hu.ts b/packages/gitbook/src/intl/translations/hu.ts index 6be311b76..ea30e6195 100644 --- a/packages/gitbook/src/intl/translations/hu.ts +++ b/packages/gitbook/src/intl/translations/hu.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/id.ts b/packages/gitbook/src/intl/translations/id.ts index eb4ea32ec..b521879b4 100644 --- a/packages/gitbook/src/intl/translations/id.ts +++ b/packages/gitbook/src/intl/translations/id.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/it.ts b/packages/gitbook/src/intl/translations/it.ts index 44273aa2d..450132a27 100644 --- a/packages/gitbook/src/intl/translations/it.ts +++ b/packages/gitbook/src/intl/translations/it.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/ja.ts b/packages/gitbook/src/intl/translations/ja.ts index f78fe4fc3..91cf0a84e 100644 --- a/packages/gitbook/src/intl/translations/ja.ts +++ b/packages/gitbook/src/intl/translations/ja.ts @@ -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: '役に立ちましたか?', diff --git a/packages/gitbook/src/intl/translations/ko.ts b/packages/gitbook/src/intl/translations/ko.ts index a4190c9c4..f62348af5 100644 --- a/packages/gitbook/src/intl/translations/ko.ts +++ b/packages/gitbook/src/intl/translations/ko.ts @@ -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: '도움이 되었나요?', diff --git a/packages/gitbook/src/intl/translations/lt.ts b/packages/gitbook/src/intl/translations/lt.ts index a7926c0de..067be8d60 100644 --- a/packages/gitbook/src/intl/translations/lt.ts +++ b/packages/gitbook/src/intl/translations/lt.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/lv.ts b/packages/gitbook/src/intl/translations/lv.ts index 094f403b8..6e917fa39 100644 --- a/packages/gitbook/src/intl/translations/lv.ts +++ b/packages/gitbook/src/intl/translations/lv.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/ms.ts b/packages/gitbook/src/intl/translations/ms.ts index 96298b625..e8292f978 100644 --- a/packages/gitbook/src/intl/translations/ms.ts +++ b/packages/gitbook/src/intl/translations/ms.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/nl.ts b/packages/gitbook/src/intl/translations/nl.ts index 272c36481..528d9a5e5 100644 --- a/packages/gitbook/src/intl/translations/nl.ts +++ b/packages/gitbook/src/intl/translations/nl.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/no.ts b/packages/gitbook/src/intl/translations/no.ts index 2be89c300..e5abae35e 100644 --- a/packages/gitbook/src/intl/translations/no.ts +++ b/packages/gitbook/src/intl/translations/no.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/pl.ts b/packages/gitbook/src/intl/translations/pl.ts index d011a8447..4eed583a5 100644 --- a/packages/gitbook/src/intl/translations/pl.ts +++ b/packages/gitbook/src/intl/translations/pl.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/pt-br.ts b/packages/gitbook/src/intl/translations/pt-br.ts index 57e40cbd0..205b0d23c 100644 --- a/packages/gitbook/src/intl/translations/pt-br.ts +++ b/packages/gitbook/src/intl/translations/pt-br.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/pt.ts b/packages/gitbook/src/intl/translations/pt.ts index 3d4a9097b..85c1bfafe 100644 --- a/packages/gitbook/src/intl/translations/pt.ts +++ b/packages/gitbook/src/intl/translations/pt.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/ro.ts b/packages/gitbook/src/intl/translations/ro.ts index 54cd5f9a6..98a685296 100644 --- a/packages/gitbook/src/intl/translations/ro.ts +++ b/packages/gitbook/src/intl/translations/ro.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/ru.ts b/packages/gitbook/src/intl/translations/ru.ts index 459a8d9a5..2ab3565e7 100644 --- a/packages/gitbook/src/intl/translations/ru.ts +++ b/packages/gitbook/src/intl/translations/ru.ts @@ -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: 'Это было полезно?', diff --git a/packages/gitbook/src/intl/translations/sk.ts b/packages/gitbook/src/intl/translations/sk.ts index 4232e910c..30fbf4227 100644 --- a/packages/gitbook/src/intl/translations/sk.ts +++ b/packages/gitbook/src/intl/translations/sk.ts @@ -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é?', diff --git a/packages/gitbook/src/intl/translations/sl.ts b/packages/gitbook/src/intl/translations/sl.ts index 50d855373..3bd71e2fe 100644 --- a/packages/gitbook/src/intl/translations/sl.ts +++ b/packages/gitbook/src/intl/translations/sl.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/sv.ts b/packages/gitbook/src/intl/translations/sv.ts index 12752b119..deef2de40 100644 --- a/packages/gitbook/src/intl/translations/sv.ts +++ b/packages/gitbook/src/intl/translations/sv.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/th.ts b/packages/gitbook/src/intl/translations/th.ts index 407a36e70..877263ee5 100644 --- a/packages/gitbook/src/intl/translations/th.ts +++ b/packages/gitbook/src/intl/translations/th.ts @@ -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: 'สิ่งนี้มีประโยชน์หรือไม่?', diff --git a/packages/gitbook/src/intl/translations/tr.ts b/packages/gitbook/src/intl/translations/tr.ts index fddae97bd..f00c988fe 100644 --- a/packages/gitbook/src/intl/translations/tr.ts +++ b/packages/gitbook/src/intl/translations/tr.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/uk.ts b/packages/gitbook/src/intl/translations/uk.ts index 92c23080b..871b344a5 100644 --- a/packages/gitbook/src/intl/translations/uk.ts +++ b/packages/gitbook/src/intl/translations/uk.ts @@ -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: 'Це було корисно?', diff --git a/packages/gitbook/src/intl/translations/vi.ts b/packages/gitbook/src/intl/translations/vi.ts index b48d2d5a9..47d6eee7c 100644 --- a/packages/gitbook/src/intl/translations/vi.ts +++ b/packages/gitbook/src/intl/translations/vi.ts @@ -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?', diff --git a/packages/gitbook/src/intl/translations/yue.ts b/packages/gitbook/src/intl/translations/yue.ts index 92a2b438b..66dac168f 100644 --- a/packages/gitbook/src/intl/translations/yue.ts +++ b/packages/gitbook/src/intl/translations/yue.ts @@ -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: '呢個有冇幫助?', diff --git a/packages/gitbook/src/intl/translations/zh-tw.ts b/packages/gitbook/src/intl/translations/zh-tw.ts index a24ece021..4883aaff0 100644 --- a/packages/gitbook/src/intl/translations/zh-tw.ts +++ b/packages/gitbook/src/intl/translations/zh-tw.ts @@ -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: '這有幫助嗎?', diff --git a/packages/gitbook/src/intl/translations/zh.ts b/packages/gitbook/src/intl/translations/zh.ts index 563165528..20170db02 100644 --- a/packages/gitbook/src/intl/translations/zh.ts +++ b/packages/gitbook/src/intl/translations/zh.ts @@ -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: '这有帮助吗?', diff --git a/packages/gitbook/src/lib/updates-url.ts b/packages/gitbook/src/lib/updates-url.ts new file mode 100644 index 000000000..0f0810c4e --- /dev/null +++ b/packages/gitbook/src/lib/updates-url.ts @@ -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); + } +} diff --git a/packages/gitbook/src/lib/updates.test.ts b/packages/gitbook/src/lib/updates.test.ts index 244d4fde0..2a82072c7 100644 --- a/packages/gitbook/src/lib/updates.test.ts +++ b/packages/gitbook/src/lib/updates.test.ts @@ -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 { diff --git a/packages/gitbook/src/lib/updates.ts b/packages/gitbook/src/lib/updates.ts index fb148d613..41b734140 100644 --- a/packages/gitbook/src/lib/updates.ts +++ b/packages/gitbook/src/lib/updates.ts @@ -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 `` 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). */ diff --git a/packages/gitbook/src/middleware.test.ts b/packages/gitbook/src/middleware.test.ts index 190a39004..307bc0428 100644 --- a/packages/gitbook/src/middleware.test.ts +++ b/packages/gitbook/src/middleware.test.ts @@ -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); + } + ); +}); diff --git a/packages/gitbook/src/middleware.ts b/packages/gitbook/src/middleware.ts index bc124caae..b7e074f6f 100644 --- a/packages/gitbook/src/middleware.ts +++ b/packages/gitbook/src/middleware.ts @@ -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 || '/'); }