Compare commits

...

3 Commits

Author SHA1 Message Date
Peter White 49aa9bfdcf Keep open-tab updates pagination handling unchanged 2026-11-26 21:23:42 +00:00
Peter White c22c1214b7 changeset 2026-11-26 21:17:32 +00:00
Peter White d4109363d3 Tighten updates pagination eligibility to single top-level updates blocks 2026-11-26 21:16:49 +00:00
4 changed files with 285 additions and 118 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Restrict updates pagination to single top-level Updates blocks.
@@ -39,11 +39,10 @@ import { isPageIndexable, isSiteIndexable } from '@/lib/seo';
import { getSiteSpacePagePaths, resolveSiteSpaceCustomHomePage } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
import {
countDocumentUpdates,
generateUpdatesFilterCSS,
getUpdatesPageRange,
getUpdatesPaginationEligibility,
paginateUpdatesDocument,
UPDATES_PAGINATION_THRESHOLD,
getDocumentFilterableTags,
updatesFilterStyleHref,
} from '@/lib/updates';
@@ -249,9 +248,12 @@ export async function generateSitePageMetadata(props: SitePageProps): Promise<Me
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);
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status === 'eligible') {
const { page: pageNumber } = getUpdatesPageRange(
props.updatesPage,
eligibility.updates.length
);
title = `${title} (Page ${pageNumber})`;
if (!pageMetaLinks?.canonical) {
const url = new URL(canonical);
@@ -378,17 +380,29 @@ export async function getSitePageData(props: SitePageProps) {
let filterableTags: RevisionTag[] = [];
let document = fullDocument;
let pagination = null;
let eligibility = null;
if (fullDocument) {
filterableTags = getDocumentFilterableTags(fullDocument, context.revision);
({ document, pagination } = paginateUpdatesDocument(fullDocument, context.revision, {
page: props.updatesPage ?? 1,
}));
({ document, pagination, eligibility } = paginateUpdatesDocument(
fullDocument,
context.revision,
{
page: props.updatesPage ?? 1,
}
));
}
if (pagination || props.updatesPage) {
if (eligibility?.status === 'skipped' || pagination || props.updatesPage) {
const logger = getLogger().subLogger('updatesPagination', {
labels: { siteId: context.site.id, pageId: page.id },
});
if (eligibility?.status === 'skipped') {
logger.info('Skipped updates pagination', {
reason: eligibility.reason,
totalUpdates: eligibility.totalUpdates,
updatesBlocks: eligibility.updatesBlocks,
});
}
if (props.updatesPage && (!pagination || pagination.isClamped)) {
const targetPage = pagination?.page ?? 1;
logger.info('Redirected out-of-range updates page', {
+162 -81
View File
@@ -1,6 +1,10 @@
import { describe, expect, it } from 'bun:test';
import {
type DocumentBlockHeading,
type DocumentBlockParagraph,
type DocumentBlockUpdate,
type DocumentBlockUpdates,
DocumentTextColor,
type JSONDocument,
type Revision,
@@ -10,8 +14,9 @@ import {
import { getRevisionTags, resolveBlockTags, resolveTag } from './tags';
import {
UPDATES_TAG_FILTER_CAP,
countDocumentUpdates,
type UpdatesPaginationEligibility,
findUpdateAnchorPage,
getUpdatesPaginationEligibility,
paginateUpdatesDocument,
parseUpdatesPageParam,
getDocumentFilterableTags,
@@ -97,63 +102,119 @@ describe('normalizeUpdatesFilterTags', () => {
});
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
);
it('paginates a single top-level updates block and keeps the surrounding blocks', () => {
const document = createDocument([
createHeading('intro'),
createParagraph(),
createUpdatesBlock(createUpdateEntries(260)),
createParagraph(),
]);
for (const [page, start] of [
[1, 1],
[7, 121],
] as const) {
const result = paginateUpdatesDocument(document, undefined, { page });
expect(result.pagination).toMatchObject({
expect(result.pagination).toEqual({
page,
totalPages: 13,
totalItems: 260,
pageSize: 20,
start,
end: start + 19,
isClamped: false,
});
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: 20 }, (_, i) => `update-${start + i}`)
);
expect(result.document.nodes.map((block) => block.type)).toEqual([
'heading-1',
'paragraph',
'updates',
'paragraph',
]);
}
});
it('keeps 50 entries intact and paginates 51', () => {
const short = createDocument([createUpdatesBlock(createUpdateEntries(50))]);
expect(getUpdatesPaginationEligibility(short)).toEqual({ status: 'below-threshold' });
const shortResult = paginateUpdatesDocument(short, undefined, { page: 2 });
expect(shortResult.pagination).toBeNull();
expect(shortResult.document).toBe(short);
const long = createDocument([createUpdatesBlock(createUpdateEntries(51))]);
const eligibility = getUpdatesPaginationEligibility(long);
expect(eligibility.status).toBe('eligible');
if (eligibility.status === 'eligible') {
expect(eligibility.updates).toHaveLength(51);
}
const result = paginateUpdatesDocument(long, undefined, { page: 3 });
expect(result.pagination).toMatchObject({ page: 3, totalPages: 3, start: 41, end: 51 });
expect(getUpdateIds(result.document)).toEqual(
Array.from({ length: 11 }, (_, i) => `update-${41 + i}`)
);
});
it.each([
[25, 26],
[60, 10],
])('does not paginate two top-level updates blocks of %i and %i entries', (first, second) => {
const entries = createUpdateEntries(first + second);
const document = createDocument([
createUpdatesBlock(entries.slice(0, first)),
createParagraph(),
createUpdatesBlock(entries.slice(first)),
]);
expectNotPaginated(document, {
status: 'skipped',
reason: 'multiple-updates-blocks',
totalUpdates: first + second,
updatesBlocks: 2,
});
});
it('does not paginate when another updates block is nested inside a container', () => {
const entries = createUpdateEntries(62);
const document = createDocument([
createUpdatesBlock(entries.slice(0, 60)),
wrapInIf(createUpdatesBlock(entries.slice(60))),
]);
expectNotPaginated(document, {
status: 'skipped',
reason: 'nested-updates-block',
totalUpdates: 62,
updatesBlocks: 2,
});
});
it('does not paginate an updates block that is only nested', () => {
const document = createDocument([wrapInIf(createUpdatesBlock(createUpdateEntries(60)))]);
expectNotPaginated(document, { status: 'below-threshold' });
});
it('does not paginate an updates block with non-update entries', () => {
const entries = createUpdateEntries(60);
const document = createDocument([
createUpdatesBlock([
...entries.slice(0, 30),
{
object: 'block',
type: 'if',
data: { expression: 'visitor.claims.beta' },
isVoid: false,
nodes: entries.slice(30, 32),
},
...entries.slice(32),
]),
]);
expectNotPaginated(document, {
status: 'skipped',
reason: 'non-update-entries',
totalUpdates: 59,
updatesBlocks: 1,
});
});
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')],
@@ -167,8 +228,7 @@ describe('updates pagination', () => {
return ['even'];
}
return [];
}),
30
})
);
const result = paginateUpdatesDocument(document, revision, {
@@ -184,7 +244,6 @@ describe('updates pagination', () => {
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', () => {
@@ -195,8 +254,7 @@ describe('updates pagination', () => {
return ['fixes'];
}
return [];
}),
26
})
);
expect(
findUpdateAnchorPage(document, revision, { anchor: 'update-43', tags: ['fixes'] })
@@ -263,45 +321,68 @@ function getUpdateIds(document: JSONDocument) {
});
}
function createUpdatesDocument(entryTags: string[][], splitAt?: number): JSONDocument {
const entries = entryTags.map((tags, index) => ({
object: 'block' as const,
type: 'update' as const,
function expectNotPaginated(document: JSONDocument, eligibility: UpdatesPaginationEligibility) {
expect(getUpdatesPaginationEligibility(document)).toEqual(eligibility);
const result = paginateUpdatesDocument(document, undefined, { page: 2 });
expect(result).toEqual({
document,
pagination: null,
eligibility,
});
expect(result.document).toBe(document);
expect(findUpdateAnchorPage(document, undefined, { anchor: 'update-1' })).toEqual({
found: false,
});
}
function createUpdatesDocument(entryTags: string[][]): JSONDocument {
return createDocument([createUpdatesBlock(createUpdateEntries(entryTags.length, entryTags))]);
}
function createDocument(nodes: JSONDocument['nodes']): JSONDocument {
return { object: 'document', data: { schemaVersion: 2 }, nodes };
}
function createUpdateEntries(count: number, entryTags: string[][] = []): DocumentBlockUpdate[] {
return Array.from({ length: count }, (_, index) => ({
object: 'block',
type: 'update',
data: {
date: '2026-05-01',
tags: tags.map((tag) => ({ kind: 'tag' as const, tag })),
tags: (entryTags[index] ?? []).map((tag) => ({ kind: 'tag', tag })),
},
isVoid: false as const,
nodes: [
{
object: 'block' as const,
type: 'heading-1' as const,
meta: { id: `update-${index + 1}` },
data: {},
isVoid: false as const,
nodes: [],
},
],
isVoid: false,
nodes: [createHeading(`update-${index + 1}`)],
}));
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 createUpdatesBlock(nodes: DocumentBlockUpdates['nodes']): DocumentBlockUpdates {
return { object: 'block', type: 'updates', data: { format: 'full' }, isVoid: false, nodes };
}
function wrapInIf(block: DocumentBlockUpdates): JSONDocument['nodes'][number] {
return {
object: 'block',
type: 'if',
data: { expression: 'visitor.claims.beta' },
isVoid: false,
nodes: [block],
};
}
function createHeading(id: string): DocumentBlockHeading {
return {
object: 'block',
type: 'heading-1',
meta: { id },
data: {},
isVoid: false,
nodes: [],
};
}
function createParagraph(): DocumentBlockParagraph {
return { object: 'block', type: 'paragraph', data: {}, isVoid: false, nodes: [] };
}
function createTag(slug: string, label: string): RevisionTag {
+95 -28
View File
@@ -1,6 +1,7 @@
import type {
DocumentBlock,
DocumentBlockUpdate,
DocumentBlockUpdates,
DocumentInline,
JSONDocument,
Revision,
@@ -30,6 +31,21 @@ export type UpdatesPageRange = {
isClamped: boolean;
};
export type UpdatesPaginationSkipReason =
| 'multiple-updates-blocks'
| 'nested-updates-block'
| 'non-update-entries';
export type UpdatesPaginationEligibility =
| { status: 'eligible'; block: DocumentBlockUpdates; updates: DocumentBlockUpdate[] }
| { status: 'below-threshold' }
| {
status: 'skipped';
reason: UpdatesPaginationSkipReason;
totalUpdates: number;
updatesBlocks: number;
};
/** 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';
@@ -117,38 +133,100 @@ export function getDocumentFilterableTags(
return tags;
}
export function countDocumentUpdates(document: JSONDocument): number {
return getDocumentUpdates(document).length;
/**
* Pagination only slices a document with a single top-level `updates` block made of more than
* `UPDATES_PAGINATION_THRESHOLD` direct `update` entries.
*/
export function getUpdatesPaginationEligibility(
document: JSONDocument
): UpdatesPaginationEligibility {
let topLevelBlock: DocumentBlockUpdates | undefined;
let topLevelBlockCount = 0;
let totalUpdates = 0;
for (const block of document.nodes) {
if (block.type !== 'updates') {
continue;
}
topLevelBlock ??= block;
topLevelBlockCount++;
totalUpdates += block.nodes.length;
}
if (!topLevelBlock || totalUpdates <= UPDATES_PAGINATION_THRESHOLD) {
return { status: 'below-threshold' };
}
if (topLevelBlockCount > 1) {
return {
status: 'skipped',
reason: 'multiple-updates-blocks',
totalUpdates,
updatesBlocks: topLevelBlockCount,
};
}
const updates: DocumentBlockUpdate[] = [];
for (const entry of topLevelBlock.nodes) {
if (entry.type !== 'update') {
return {
status: 'skipped',
reason: 'non-update-entries',
totalUpdates,
updatesBlocks: 1,
};
}
updates.push(entry);
}
const allUpdatesBlocks = getBlocksByType(document, 'updates');
if (allUpdatesBlocks.length > 1) {
let allUpdatesCount = 0;
for (const updatesBlock of allUpdatesBlocks) {
allUpdatesCount += updatesBlock.nodes.length;
}
return {
status: 'skipped',
reason: 'nested-updates-block',
totalUpdates: allUpdatesCount,
updatesBlocks: allUpdatesBlocks.length,
};
}
return { status: 'eligible', block: topLevelBlock, updates };
}
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 };
): {
document: JSONDocument;
pagination: UpdatesPageRange | null;
eligibility: UpdatesPaginationEligibility;
} {
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status !== 'eligible') {
return { document, pagination: null, eligibility };
}
const matching = filterUpdates(updates, document, revision, tags);
const matching = filterUpdates(eligibility.updates, document, revision, tags);
const pagination = getUpdatesPageRange(page, matching.length);
const slice = new Set(matching.slice(pagination.start - 1, pagination.end));
const entries = matching.slice(pagination.start - 1, pagination.end);
const nodes: JSONDocument['nodes'] = [];
for (const block of document.nodes) {
if (block.type !== 'updates') {
if (block !== eligibility.block) {
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 };
return { document: { ...document, nodes }, pagination, eligibility };
}
export function getUpdatesPageRange(requestedPage: number, totalItems: number): UpdatesPageRange {
@@ -175,7 +253,12 @@ export function findUpdateAnchorPage(
revision: Revision | undefined,
{ anchor, tags }: { anchor: string; tags?: string[] }
): { found: true; page: number; clearTags: boolean } | { found: false } {
const updates = getDocumentUpdates(document);
const eligibility = getUpdatesPaginationEligibility(document);
if (eligibility.status !== 'eligible') {
return { found: false };
}
const { updates } = eligibility;
const index = updates.findIndex((update) =>
hasMoreThan(update, (node) => matchesUpdateAnchor(node, anchor), 0)
);
@@ -209,22 +292,6 @@ function matchesUpdateAnchor(node: DocumentBlock | DocumentInline, anchor: strin
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,