From 023dda30c0a02e3e88a0a0531b90c96c6d9a0771 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sun, 29 Nov 2026 00:56:23 +1100 Subject: [PATCH] Reduce Reader library hydration and long article setup work --- apps/reader/scripts/audit-library-article.mjs | 11 + apps/reader/scripts/audit-mobile-library.mjs | 15 +- .../scripts/benchmark-library-article.mjs | 249 +++++++++++++----- apps/reader/src/LibraryWorkspace.tsx | 13 +- apps/reader/src/annotation-list-order.ts | 41 ++- .../src/connect-workspace-refresh.test.ts | 8 +- apps/reader/src/connect-workspace.ts | 34 ++- apps/reader/src/mdbase-library-views.test.ts | 11 +- apps/reader/src/mdbase-library-views.ts | 43 ++- apps/reader/src/source-library-loader.ts | 2 +- .../reader/test-fixtures/annotation-scale.tsx | 25 +- .../library-article-benchmark.tsx | 207 ++++++++++++++- docs/reader-performance.md | 9 +- .../connect/src/content-search-repository.ts | 24 +- packages/connect/src/mapping.ts | 6 +- .../connect/src/source-pagination.test.ts | 4 +- packages/connect/src/source-repository.ts | 11 +- .../renderer-html/src/html-document.test.ts | 16 ++ packages/renderer-html/src/html-document.ts | 25 +- .../renderer-html/src/html-runtime.test.ts | 6 +- packages/renderer-html/src/html-runtime.ts | 20 +- .../renderer-html/src/html-surface.test.ts | 2 + packages/renderer-html/src/html-surface.ts | 2 +- 23 files changed, 606 insertions(+), 178 deletions(-) diff --git a/apps/reader/scripts/audit-library-article.mjs b/apps/reader/scripts/audit-library-article.mjs index 8fcce169..4253c757 100644 --- a/apps/reader/scripts/audit-library-article.mjs +++ b/apps/reader/scripts/audit-library-article.mjs @@ -129,6 +129,17 @@ try { return times.sort((a, b) => a - b)[3]; }); console.log("10k grid scroll to mounted row, ms", scrollMedian); + await grid.locator('[aria-rowindex="2"]').focus(); + await grid.evaluate((element) => { + element.closest(".library-table-frame").scrollTop = 4800; + }); + await expect(grid.locator('[aria-rowindex="2"]')).toHaveCount(0); + const search = page.getByRole("textbox", { name: "Search this view" }); + await search.focus(); + await search.press("ArrowDown"); + await expect(grid.locator("[data-row-index]:focus")).toHaveCount(1); + await page.keyboard.press("Home"); + await expect(grid.locator('[aria-rowindex="2"]')).toBeFocused(); await page.addScriptTag({ path: createRequire(import.meta.url).resolve("axe-core/axe.min.js") }); for (const width of [360, 768, 1280]) { await page.setViewportSize({ width, height: 900 }); diff --git a/apps/reader/scripts/audit-mobile-library.mjs b/apps/reader/scripts/audit-mobile-library.mjs index a37fb271..296a1110 100644 --- a/apps/reader/scripts/audit-mobile-library.mjs +++ b/apps/reader/scripts/audit-mobile-library.mjs @@ -5,6 +5,8 @@ import { resolve } from "node:path"; import { chromium, expect } from "@playwright/test"; import { createServer } from "vite"; +import { chooseOption } from "./audit-select.mjs"; + const root = resolve(import.meta.dirname, ".."); const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js"); const server = await createServer({ @@ -36,6 +38,7 @@ const collection = [ { collectionId: "audit", id: "structural", + readingStatus: "finished", path: "sources/structural.md", title: "Structural learning", creators: ["Inez"], @@ -82,11 +85,21 @@ try { const search = page.getByRole("textbox", { name: "Search this view" }); await expect(grid).toHaveAttribute("aria-rowcount", "3", { timeout: 60000 }); await assertAxe(page, `${colorScheme} library`); + const filter = page.locator(".library-workspace-more > summary:visible"); + await filter.tap(); + const status = page.getByRole("combobox", { name: "Status", exact: true }); + await chooseOption(status, "finished"); + await expect(grid).toHaveAttribute("aria-rowcount", "2"); + await expect(grid.getByRole("row", { name: /^Structural learning/u })).toBeVisible(); + await chooseOption(status, "inbox"); + await expect(grid.getByRole("row", { name: /^Attention and memory/u })).toBeVisible(); + await chooseOption(status, "all"); + await page.keyboard.press("Escape"); + await expect(filter).toBeFocused(); await page.keyboard.press("/"); await expect(search).toBeFocused(); await search.fill("attention"); await expect(grid).toHaveAttribute("aria-rowcount", "2"); - const filter = page.locator(".library-workspace-more > summary:visible"); await filter.tap(); const options = page.locator(".reader-menu-panel:visible").filter({ hasText: "Clear filters" }); const tag = page.getByRole("textbox", { name: "Tag", exact: true }); diff --git a/apps/reader/scripts/benchmark-library-article.mjs b/apps/reader/scripts/benchmark-library-article.mjs index 2e8348e2..b9d72eaa 100644 --- a/apps/reader/scripts/benchmark-library-article.mjs +++ b/apps/reader/scripts/benchmark-library-article.mjs @@ -1,13 +1,45 @@ // Optional second server runs the same fixture on the baseline revision. +import { createHash } from "node:crypto"; + import { chromium, expect } from "@playwright/test"; const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311"; +const pairs = Number(process.env.READER_BENCH_PAIRS ?? 9); const origins = [process.env.READER_BASELINE_ORIGIN, origin].filter(Boolean); +if (!Number.isInteger(pairs) || pairs < 1) { + throw new Error("READER_BENCH_PAIRS must be a positive integer."); +} for (const url of origins) { if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(url)) { throw new Error("Performance measurements require a loopback origin."); } } +const article = `Long article

Study 00000

${Array.from( + { length: 3000 }, + (_, index) => + `${index % 10 === 0 ? `

Section ${index / 10}

` : ""}

Passage [${index}]. ${"Attention and retention. ".repeat(6)}

`, +).join("")}
`; +const target = { + fileId: "article", + file: "[[article.html]]", + revision: `sha256:${createHash("sha256").update(article).digest("hex")}`, + mediaType: "text/html", + role: "primary", +}; +const highlights = Array.from({ length: 600 }, (_, index) => ({ + collectionId: "benchmark", + sourceId: "source-0", + id: `highlight-${index}`, + body: `> Passage [${index * 5}] + +Reader highlight comment.`, + annotationType: "highlight", + tags: [], + createdAt: "2026-01-01T00:00:00Z", + recordRevision: "rev-1", + document: target, + target: { quote: { exact: `Passage [${index * 5}]` } }, +})); const articles = Array.from({ length: 10_000 }, (_, index) => ({ collectionId: "benchmark", id: `source-${index}`, @@ -16,7 +48,8 @@ const articles = Array.from({ length: 10_000 }, (_, index) => ({ creators: [`Author ${index % 673}`], tags: [`tag-${index % 100}`, index % 2 ? "reading" : "research"], published: String(1900 + (index % 125)), - documents: [], + readingStatus: ["inbox", "reading", "finished"][index % 3], + documents: index === 0 ? [target] : [], properties: { tags: [`tag-${index % 100}`, index % 2 ? "reading" : "research"] }, frontmatter: {}, body: "", @@ -27,9 +60,9 @@ const browser = await chromium.launch(); function summary(times) { const sorted = times.toSorted((a, b) => a - b); return { - median: Number(sorted[Math.floor(sorted.length / 2)].toFixed(2)), - p95: Number(sorted[Math.ceil(sorted.length * 0.95) - 1].toFixed(2)), - samples: times.map((time) => Number(time.toFixed(2))), + median: Number(sorted[Math.floor(sorted.length / 2)].toFixed(3)), + p95: Number(sorted[Math.ceil(sorted.length * 0.95) - 1].toFixed(3)), + samples: times.map((time) => Number(time.toFixed(3))), }; } @@ -40,85 +73,169 @@ try { const lanes = []; for (const url of origins) { const context = await browser.newContext({ viewport: { width: 1280, height: 900 } }); - const page = await context.newPage(); const errors = []; - page.on("pageerror", (error) => errors.push(error.message)); await context.route( (request) => request.origin !== url, (route) => route.abort(), ); - await page.route(`${url}/__reader-audit/**`, (route) => { - const library = new URL(route.request().url()).pathname.endsWith("/library"); - return route.fulfill({ json: library ? sources : [] }); - }); - await page.addInitScript((count) => { - performance.setResourceTimingBufferSize(5000); - globalThis.readerGridReady = new Promise((resolve, reject) => { - const observer = new globalThis.MutationObserver(() => { - if (globalThis.document.querySelector(`.library-table[aria-rowcount="${count + 1}"]`)) { - observer.disconnect(); - const now = performance.now(); - const response = performance.getEntriesByName( - new URL("/__reader-audit/library", globalThis.location.href).href, - )[0]; - if (!response) { - reject(new Error("Missing library response timing")); - return; - } - resolve({ - "startup to virtualized grid": now, - "library response to grid": now - response.responseEnd, - }); - } - }); - observer.observe(globalThis.document, { - attributes: true, - childList: true, - subtree: true, - }); - }); - }, count); // Keep component timings independent of deferred React work following the first grid commit. const fixture = await context.newPage(); fixture.on("pageerror", (error) => errors.push(error.message)); await fixture.goto(`${url}/test-fixtures/import-proof.html`); - lanes.push({ url, page, fixture, errors, times: {} }); + const sidebarPage = await context.newPage(); + sidebarPage.on("pageerror", (error) => errors.push(error.message)); + lanes.push({ url, context, fixture, sidebarPage, errors, times: {} }); } - for (let pair = 0; pair < 10; pair++) { - for (const { url, page, fixture, errors, times } of pair % 2 ? lanes.toReversed() : lanes) { - await page.goto(`${url}/test-fixtures/audit-reader.html`, { - waitUntil: "domcontentloaded", - }); - await expect(page.locator(".library-table:visible")).toHaveAttribute( - "aria-rowcount", - String(count + 1), - { timeout: 60_000 }, - ); - const grid = await page.evaluate(() => globalThis.readerGridReady); - expect(await page.locator(".library-table:visible [data-row-index]").count()).toBeLessThan( - 60, - ); - const runs = await fixture.evaluate( - async ({ sources, moduleUrl }) => - (await import(moduleUrl)).measureLibraryAndArticle(sources), - { sources, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" }, - ); - expect(errors).toEqual([]); - if (pair > 0) { - for (const [label, ms] of Object.entries({ - ...grid, - ...runs, - })) { - (times[label] ??= []).push(ms); + for (let pair = 0; pair <= pairs; pair++) { + for (const { url, fixture, sidebarPage, errors, times } of pair % 2 + ? lanes.toReversed() + : lanes) { + console.error(`Benchmarking ${count} sources, pair ${pair || "warm-up"}, ${url}`); + const context = await browser.newContext({ viewport: { width: 1280, height: 900 } }); + try { + await context.route( + (request) => request.origin !== url, + (route) => route.abort(), + ); + const page = await context.newPage(); + page.on("pageerror", (error) => errors.push(error.message)); + await page.route(`${url}/__reader-audit/**`, (route) => { + const path = new URL(route.request().url()).pathname.slice("/__reader-audit/".length); + if (path === "library") return route.fulfill({ json: sources }); + if (path === "source/source-0") return route.fulfill({ json: sources[0] }); + if (path === "document/article") + return route.fulfill({ body: article, contentType: "text/html" }); + if (path === "annotations/source-0") return route.fulfill({ json: highlights }); + return route.fulfill({ json: [] }); + }); + await page.addInitScript((count) => { + performance.setResourceTimingBufferSize(5000); + globalThis.readerGridReady = new Promise((resolve, reject) => { + const observer = new globalThis.MutationObserver(() => { + if ( + globalThis.document.querySelector(`.library-table[aria-rowcount="${count + 1}"]`) + ) { + observer.disconnect(); + const now = performance.now(); + const response = performance.getEntriesByName( + new URL("/__reader-audit/library", globalThis.location.href).href, + )[0]; + if (!response) { + reject(new Error("Missing library response timing")); + return; + } + resolve({ + "startup to virtualized grid": now, + "library response to grid": now - response.responseEnd, + }); + } + }); + observer.observe(globalThis.document, { + attributes: true, + childList: true, + subtree: true, + }); + }); + }, count); + await page.goto(`${url}/test-fixtures/audit-reader.html`, { + waitUntil: "domcontentloaded", + }); + await expect(page.locator(".library-table:visible")).toHaveAttribute( + "aria-rowcount", + String(count + 1), + { timeout: 60_000 }, + ); + const grid = await page.evaluate(() => globalThis.readerGridReady); + expect( + await page.locator(".library-table:visible [data-row-index]").count(), + ).toBeLessThan(60); + const scroll = await page + .locator(".library-table:visible") + .evaluate(async (table, count) => { + const viewport = table.closest(".library-table-frame"); + const index = Math.floor(count * 0.7); + const start = performance.now(); + viewport.scrollTop = index * 48; + while (!table.querySelector(`[data-row-index="${index}"]`)) { + if (performance.now() - start > 5000) + throw new Error("Grid did not mount target row"); + await new Promise((done) => globalThis.requestAnimationFrame(done)); + } + const elapsed = performance.now() - start; + viewport.scrollTop = 0; + return elapsed; + }, count); + const open = await page + .locator('.library-table:visible a[href="#source=source-0"]') + .evaluate((link) => { + const start = performance.now(); + link.click(); + return new Promise((resolve, reject) => { + function wait() { + const frame = globalThis.document.querySelector("iframe.html-viewer"); + const paragraph = frame?.contentDocument?.getElementById("p2999"); + if (paragraph?.getBoundingClientRect().height) resolve(performance.now() - start); + else if (performance.now() - start > 10000) + reject(new Error("Article did not render")); + else globalThis.requestAnimationFrame(wait); + } + wait(); + }); + }); + await page.close(); + await sidebarPage.goto( + `${url}/test-fixtures/annotation-scale.html?count=600&format=html`, + { + waitUntil: "domcontentloaded", + }, + ); + const annotationPanel = sidebarPage.getByRole("button", { name: "Mount annotations" }); + const sidebar = await annotationPanel.evaluate((tab) => { + const start = performance.now(); + tab.click(); + return new Promise((resolve, reject) => { + function wait() { + const cards = [ + ...globalThis.document.querySelectorAll('[data-item-id][aria-setsize="600"]'), + ].filter( + (item) => + item.getBoundingClientRect().height > 0 && !item.closest("[hidden], [inert]"), + ); + if (cards.length > 0 && cards.length < 30) resolve(performance.now() - start); + else if (performance.now() - start > 10000) + reject(new Error("Annotation sidebar did not render a bounded window")); + else globalThis.requestAnimationFrame(wait); + } + wait(); + }); + }); + const runs = await fixture.evaluate( + async ({ sources, moduleUrl }) => + (await import(moduleUrl)).measureLibraryAndArticle(sources), + { sources, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" }, + ); + expect(errors).toEqual([]); + if (pair > 0) { + for (const [label, ms] of Object.entries({ + ...grid, + "virtualized scroll to target row": scroll, + "open article to first usable iframe": open, + "open annotation sidebar (600 highlights)": sidebar, + ...runs, + })) { + (times[label] ??= []).push(ms); + } } + } finally { + await context.close(); } } } - for (const { url, page, times } of lanes) { + for (const { url, context, times } of lanes) { reports[`${count} @ ${url}`] = Object.fromEntries( Object.entries(times).map(([k, v]) => [k, summary(v)]), ); - await page.context().close(); + await context.close(); } } console.log(JSON.stringify({ chromium: browser.version(), milliseconds: reports }, null, 2)); diff --git a/apps/reader/src/LibraryWorkspace.tsx b/apps/reader/src/LibraryWorkspace.tsx index fc5eddff..a3b8a4f6 100644 --- a/apps/reader/src/LibraryWorkspace.tsx +++ b/apps/reader/src/LibraryWorkspace.tsx @@ -401,11 +401,14 @@ export function LibraryWorkspace({ updateFilter({ query: "" }); } else if (event.key === "ArrowDown" || event.key === "Escape") { event.preventDefault(); - resultsAreaRef.current - ?.querySelector( - '.search-passage-list button, .library-table-row:not(.is-header)[tabindex="0"]', - ) - ?.focus(); + const results = resultsAreaRef.current; + // The roving tab stop can be outside the mounted window after scrolling. + const target = + results?.querySelector( + '.search-passage-list button, .library-table-row[data-row-index][tabindex="0"]', + ) ?? + results?.querySelector(".library-table-row[data-row-index]"); + target?.focus(); } }} /> diff --git a/apps/reader/src/annotation-list-order.ts b/apps/reader/src/annotation-list-order.ts index 3e35cfd5..42a79e2b 100644 --- a/apps/reader/src/annotation-list-order.ts +++ b/apps/reader/src/annotation-list-order.ts @@ -18,10 +18,11 @@ export function browseAnnotations( return searchAnnotationIndex(indexAnnotations(annotations, order), query, filter); } -/** Sort and normalize once per snapshot/order, not on each search keystroke. */ +/** Search text is normalized on demand and reused for subsequent queries. */ interface AnnotationSearchEntry { readonly annotation: Annotation; - readonly text: string; + readonly source: SourceSummary | undefined; + text?: string; } /** * `sources` is given when the list covers many sources: search then also matches a source's @@ -45,21 +46,7 @@ export function indexAnnotations( compareDocumentOrder(a, b) : compareDocumentOrder, ) - .map((annotation) => { - const source = sources?.get(annotation.sourceId); - return { - annotation, - text: [ - annotation.body, - annotation.target?.quote?.exact, - annotation.locator?.label, - ...annotation.tags, - ...(source ? [source.title, ...source.creators] : []), - ] - .join(" ") - .toLocaleLowerCase(), - }; - }); + .map((annotation) => ({ annotation, source: sources?.get(annotation.sourceId) })); } export function searchAnnotationIndex( @@ -70,16 +57,28 @@ export function searchAnnotationIndex( const search = query.trim().toLocaleLowerCase(); return index .filter( - ({ annotation, text }) => + (entry) => (filter === "all" || (filter === "comments" - ? Boolean(annotationBodyContent(annotation.body).note.trim()) - : annotation.annotationType === filter)) && - (!search || text.includes(search)), + ? Boolean(annotationBodyContent(entry.annotation.body).note.trim()) + : entry.annotation.annotationType === filter)) && + (!search || (entry.text ??= annotationSearchText(entry)).includes(search)), ) .map(({ annotation }) => annotation); } +function annotationSearchText({ annotation, source }: AnnotationSearchEntry): string { + return [ + annotation.body, + annotation.target?.quote?.exact, + annotation.locator?.label, + ...annotation.tags, + ...(source ? [source.title, ...source.creators] : []), + ] + .join(" ") + .toLocaleLowerCase(); +} + /** A palette colour to list, or "" for any colour. */ export type AnnotationColorFilter = "" | HighlightColorKey; diff --git a/apps/reader/src/connect-workspace-refresh.test.ts b/apps/reader/src/connect-workspace-refresh.test.ts index dbd9a438..3cc416f6 100644 --- a/apps/reader/src/connect-workspace-refresh.test.ts +++ b/apps/reader/src/connect-workspace-refresh.test.ts @@ -40,13 +40,17 @@ it("bypasses warm source caches for draft conflict checks and retains the fresh "Test", createReaderRuntimeServices(new MemoryStorage()), ); - await gateway.library(); + const library = await gateway.library(); + expect(await gateway.library()).toBe(library); expect(await gateway.source(source.id)).toBe(source); expect(await gateway.source(source.id)).toBe(source); expect(get).toHaveBeenCalledTimes(1); expect(await gateway.refreshSource(source.id)).toBe(updated); expect(await gateway.source(source.id)).toBe(updated); - expect((await gateway.library()).sources[0]).toBe(updated); + const refreshed = await gateway.library(); + expect(refreshed.sources[0]).toBe(updated); + expect(library.sources[0]).toBe(source); + expect(await gateway.library()).toBe(refreshed); expect(await gateway.refreshSource(source.id)).toBeNull(); expect(get).toHaveBeenCalledTimes(3); }); diff --git a/apps/reader/src/connect-workspace.ts b/apps/reader/src/connect-workspace.ts index 7dfc404f..d1282c0d 100644 --- a/apps/reader/src/connect-workspace.ts +++ b/apps/reader/src/connect-workspace.ts @@ -79,7 +79,7 @@ import type { const noop = (): void => undefined; export class ConnectWorkspaceGateway implements ReaderWorkspaceGateway { - #library: ReaderLibrarySnapshot["sources"] | null = null; + #library: ReaderLibrarySnapshot | null = null; /** Bumped when a change outside this workspace makes the cached library stale. */ #libraryGeneration = 0; readonly #libraryLoads = new SharedRequests< @@ -173,7 +173,7 @@ export class ConnectWorkspaceGateway implements ReaderWorkspaceGateway { async library(options: ReaderLibraryRequestOptions = {}): Promise { options.signal?.throwIfAborted(); if (this.#library) { - return completeLibrarySnapshot(this.collectionName, this.#library); + return this.#library; } const generation = this.#libraryGeneration; return this.#libraryLoads.get( @@ -190,7 +190,7 @@ export class ConnectWorkspaceGateway implements ReaderWorkspaceGateway { signal.throwIfAborted(); // A load that a later change overtook must not become the cached library. if (generation === this.#libraryGeneration) { - this.#library = snapshot.sources; + this.#library = snapshot; } return snapshot; }, @@ -492,10 +492,16 @@ export class ConnectWorkspaceGateway implements ReaderWorkspaceGateway { options: Parameters[2] = {}, ): Promise { const expectedCitation = loadedCitation(source); - const updated = await saveSourceCitation(this.sources, source, this.#library ?? [], citation, { - ...(expectedCitation !== undefined ? { expectedCitation } : {}), - ...options, - }); + const updated = await saveSourceCitation( + this.sources, + source, + this.#library?.sources ?? [], + citation, + { + ...(expectedCitation !== undefined ? { expectedCitation } : {}), + ...options, + }, + ); this.#replaceSource(updated); for (const listener of this.#citationListeners) { listener(); @@ -863,7 +869,10 @@ export class ConnectWorkspaceGateway implements ReaderWorkspaceGateway { await this.sources.delete(plan); this.#sourcesById.delete(plan.sourceId); if (this.#library) { - this.#library = this.#library.filter(({ id }) => id !== plan.sourceId); + this.#library = completeLibrarySnapshot( + this.collectionName, + this.#library.sources.filter(({ id }) => id !== plan.sourceId), + ); } this.#countsChanged(); } @@ -871,8 +880,13 @@ export class ConnectWorkspaceGateway implements ReaderWorkspaceGateway { #replaceSource(source: Source, prepend = false): void { this.#sourcesById.set(source.id, source); if (this.#library) { - const remaining = this.#library.filter(({ id }) => id !== source.id); - this.#library = prepend ? [source, ...remaining] : replaceInOrder(this.#library, source); + const { sources } = this.#library; + this.#library = completeLibrarySnapshot( + this.collectionName, + prepend + ? [source, ...sources.filter(({ id }) => id !== source.id)] + : replaceInOrder(sources, source), + ); } } } diff --git a/apps/reader/src/mdbase-library-views.test.ts b/apps/reader/src/mdbase-library-views.test.ts index 4933ec5c..4ece1e52 100644 --- a/apps/reader/src/mdbase-library-views.test.ts +++ b/apps/reader/src/mdbase-library-views.test.ts @@ -88,10 +88,13 @@ describe("mdbase library views", () => { const filter = { ...base.filter, query: "author", tag: "study" }; for (const sortDirection of ["asc", "desc"] as const) { const configuration = { ...base, sortDirection }; - const filtered = applyLibraryViewConfiguration(rows, { ...configuration, filter }); - expect(filtered.map((row) => row.id)).toEqual( - sortDirection === "asc" ? ["c", "b", "a"] : ["b", "a", "c"], - ); + const expected = sortDirection === "asc" ? ["c", "b", "a"] : ["b", "a", "c"]; + const cold = applyLibraryViewConfiguration(rows, { ...configuration, filter }); + expect(cold.map((row) => row.id)).toEqual(expected); + const ordered = applyLibraryViewConfiguration(rows, configuration); + expect(applyLibraryViewConfiguration(rows, configuration)).toBe(ordered); + const warmed = applyLibraryViewConfiguration(rows, { ...configuration, filter }); + expect(warmed.map((row) => row.id)).toEqual(expected); } expect(rows.map((row) => row.id)).toEqual(["b", "c", "a"]); }); diff --git a/apps/reader/src/mdbase-library-views.ts b/apps/reader/src/mdbase-library-views.ts index cb87e92e..33b5f53f 100644 --- a/apps/reader/src/mdbase-library-views.ts +++ b/apps/reader/src/mdbase-library-views.ts @@ -203,6 +203,12 @@ export function buildLibraryView(request: LibraryViewSaveRequest): JsonObject { }; } +// A warmed title order can serve subsequent filters over the same immutable snapshot. +const titleOrders = new WeakMap< + readonly SourceSummary[], + Partial> +>(); + export function applyLibraryViewConfiguration( sources: readonly SourceSummary[], configuration: LibraryViewConfiguration, @@ -218,12 +224,13 @@ export function applyLibraryViewConfiguration( const { sortField, sortDirection, filter } = configuration; const direction = sortDirection === "asc" ? 1 : -1; // Empty filters are the common library-open path. Sorting owns its input. - const unfiltered = - !query && - !tag && - filter.status === "all" && - filter.format === "all" && - filter.conditions.length === 0; + const unfiltered = hasNoFilters(filter, query, tag); + // Metadata queries often discard most rows. Walk their original snapshot order. + let orders = sortField === "title" && !query ? titleOrders.get(sources) : undefined; + const ordered = orders?.[sortDirection]; + if (unfiltered && ordered) { + return ordered; + } const matchingTags = new Map(); function matchesTag(candidate: string): boolean { const known = matchingTags.get(candidate); @@ -236,7 +243,7 @@ export function applyLibraryViewConfiguration( } const filtered = unfiltered ? [...sources] - : sources.filter((source) => { + : (ordered ?? sources).filter((source) => { if ( configuration.filter.status !== "all" && (source.readingStatus ?? "inbox") !== configuration.filter.status @@ -260,7 +267,17 @@ export function applyLibraryViewConfiguration( return !query || metadataSearchText(source, parentTitle).includes(query); }); if (sortField === "title") { - return filtered.sort((a, b) => direction * a.title.localeCompare(b.title)); + if (!ordered) { + filtered.sort((a, b) => direction * a.title.localeCompare(b.title)); + } + if (unfiltered) { + if (!orders) { + orders = {}; + titleOrders.set(sources, orders); + } + orders[sortDirection] = filtered; + } + return filtered; } const key = propertyKey(sortField); if (key !== null) { @@ -276,6 +293,16 @@ export function applyLibraryViewConfiguration( ); } +function hasNoFilters(filter: LibraryViewFilter, query: string, tag: string): boolean { + return ( + !query && + !tag && + filter.status === "all" && + filter.format === "all" && + filter.conditions.length === 0 + ); +} + // Summaries are replaced when edited. Chapter text also depends on the current parent, so // its search text is derived from the current library snapshot. const searchTextBySource = new WeakMap(); diff --git a/apps/reader/src/source-library-loader.ts b/apps/reader/src/source-library-loader.ts index a9923cce..0b84e791 100644 --- a/apps/reader/src/source-library-loader.ts +++ b/apps/reader/src/source-library-loader.ts @@ -143,7 +143,7 @@ function snapshot( ): ReaderLibrarySnapshot { return { collectionName, - sources: [...sources], + sources: complete ? sources : [...sources], connectionState: "connected", sourceIndex: { loaded: sources.length, diff --git a/apps/reader/test-fixtures/annotation-scale.tsx b/apps/reader/test-fixtures/annotation-scale.tsx index 150ae12d..76a1149b 100644 --- a/apps/reader/test-fixtures/annotation-scale.tsx +++ b/apps/reader/test-fixtures/annotation-scale.tsx @@ -10,6 +10,7 @@ import { sourceId, type Annotation, } from "@mdbase-reader/core"; +import { ReaderI18nProvider } from "@mdbase-reader/i18n/react"; import { Profiler, useState, type JSX } from "react"; import { createRoot } from "react-dom/client"; @@ -17,12 +18,12 @@ import "@mdbase-reader/ui/styles.css"; import "../src/reader.css"; import "../src/annotation-polish.css"; import "../src/reader-shell.css"; +import "../src/notes-panel.css"; import { AnnotationList } from "../src/AnnotationList.js"; -const count = Math.min( - 3000, - Math.max(1, Number(new URLSearchParams(location.search).get("count")) || 300), -); +const parameters = new URLSearchParams(location.search); +const html = parameters.get("format") === "html"; +const count = Math.min(3000, Math.max(1, Number(parameters.get("count")) || 300)); const annotations: Annotation[] = Array.from({ length: count }, (_, index) => ({ id: annotationId(`scale_${String(index).padStart(4, "0")}`), collectionId: collectionId("annotation-scale-fixture"), @@ -32,14 +33,16 @@ const annotations: Annotation[] = Array.from({ length: count }, (_, index) => ({ recordRevision: recordRevision("fixture-1"), document: { fileId: fileId("scale-document"), - file: "[[scale.pdf]]", + file: html ? "[[scale.html]]" : "[[scale.pdf]]", revision: fileRevision(`sha256:${"a".repeat(64)}`), }, - annotationType: index % 5 === 0 ? "bookmark" : "highlight", + annotationType: !html && index % 5 === 0 ? "bookmark" : "highlight", locator: { label: `p. ${String(index + 1)}` }, - target: { position: { kind: "pdf", pageIndex: index } }, + target: html + ? { quote: { exact: `Passage ${String(index)}` } } + : { position: { kind: "pdf", pageIndex: index } }, body: - index % 5 === 0 + !html && index % 5 === 0 ? "" : `> Passage ${String(index)}: ${"Patient attention makes careful research possible. ".repeat(1 + (index % 9))}\n\nComment ${String(index)}: ${"A useful connection to revisit. ".repeat(index % 4)}`, tags: [index % 2 ? "research" : "attention"], @@ -123,4 +126,8 @@ const root = document.getElementById("root"); if (!root) { throw new Error("Missing fixture root"); } -createRoot(root).render(); +createRoot(root).render( + + + , +); diff --git a/apps/reader/test-fixtures/library-article-benchmark.tsx b/apps/reader/test-fixtures/library-article-benchmark.tsx index 979bf477..ac66c32b 100644 --- a/apps/reader/test-fixtures/library-article-benchmark.tsx +++ b/apps/reader/test-fixtures/library-article-benchmark.tsx @@ -1,8 +1,25 @@ -import { ConnectContentSearchRepository } from "@mdbase-reader/connect"; -import { collectionId, type Annotation, type SourceSummary } from "@mdbase-reader/core"; +import { + ConnectAnnotationAssetRepository, + ConnectAnnotationRepository, + ConnectContentSearchRepository, + ConnectSourceImportRepository, + ConnectSourceRepository, +} from "@mdbase-reader/connect"; +import { + collectionId, + fileRevision, + type Annotation, + type SourceSummary, +} from "@mdbase-reader/core"; import "@mdbase-reader/i18n"; -import { HtmlDocumentRuntime, prepareHtmlDocument } from "@mdbase-reader/renderer-html"; +import { createReaderRuntimeServices, MemoryStorage } from "@mdbase-reader/platform"; +import { + HtmlDocumentRuntime, + HtmlReadingSurface, + prepareHtmlDocument, +} from "@mdbase-reader/renderer-html"; +import { ConnectWorkspaceGateway } from "../src/connect-workspace.js"; import { fieldValueSuggestions } from "../src/library-conditions.js"; import { applyLibraryViewConfiguration, @@ -27,6 +44,79 @@ export async function measureLibraryAndArticle( samples[name] = (performance.now() - start) / repeat; } + // Return contract projections as the SDK would after decoding a page. + const views = sources.map((source) => ({ + id: source.id, + path: source.path, + types: ["reader-source"], + frontmatter: { + id: source.id, + title: source.title, + authors: source.creators, + tags: source.tags, + }, + })); + const projections = views.map(({ id, frontmatter }) => ({ + id, + implementations: [{ typeName: "reader-source", fields: frontmatter }], + })); + let pageReads = 0; + const sdk = { + async queryContract( + _contract: unknown, + { pageSize, cursor }: { pageSize: number; cursor?: string }, + ) { + pageReads++; + const start = Number(cursor ?? 0); + const end = start + pageSize; + await new Promise((done) => setTimeout(done, 0)); + return { + page: { + records: views.slice(start, end), + cursor: end < sources.length ? String(end) : undefined, + totalCount: sources.length, + complete: true, + }, + records: projections.slice(start, end), + }; + }, + } as unknown as MdbaseClient; + const files = { upload: () => Promise.reject(new Error("Benchmark is read-only")) }; + const gateway = new ConnectWorkspaceGateway( + new ConnectSourceRepository(sdk), + new ConnectAnnotationRepository(sdk), + new ConnectAnnotationAssetRepository(files), + new ConnectSourceImportRepository(sdk, files), + collectionId("benchmark"), + "Benchmark", + createReaderRuntimeServices(new MemoryStorage()), + ); + await measure("cold paged workspace hydration", async () => { + const start = performance.now(); + const snapshot = await gateway.library({ + onProgress: () => { + samples["first workspace page"] ??= performance.now() - start; + }, + }); + if ( + snapshot.sources.length !== sources.length || + snapshot.sources.at(-1)?.id !== sources.at(-1)?.id + ) { + throw new Error("Incomplete workspace hydration"); + } + }); + const coldPageReads = pageReads; + await measure( + "warm workspace library read", + async () => { + const snapshot = await gateway.library(); + if (snapshot.sources.length !== sources.length || pageReads !== coldPageReads) { + throw new Error("Warm library read fetched another page"); + } + }, + 100, + ); + const repeats = sources.length < 1000 ? 100 : 8; const defaults = defaultLibraryViewConfiguration; await measure( @@ -54,6 +144,21 @@ export async function measureLibraryAndArticle( }, repeats, ); + await measure( + "switch three status buckets", + () => { + for (const status of ["inbox", "reading", "finished"] as const) { + const matches = applyLibraryViewConfiguration(sources, { + ...defaults, + filter: { ...defaults.filter, status }, + }); + if (matches.length === 0 || matches.some((source) => source.readingStatus !== status)) { + throw new Error("Wrong status bucket"); + } + } + }, + repeats, + ); await measure( "rank tag suggestions", () => { @@ -76,7 +181,7 @@ export async function measureLibraryAndArticle( source: `[[sources/${String(index % ownerCount)}]]`, }, types: ["reader-annotation"], - body: "> Paper mentions attention and retention.\n\nReader highlight comment.", + body: "> Paper mentions attention and retention.\n\nAnnotation-only highlight comment.", }; }); const records = [ @@ -84,7 +189,7 @@ export async function measureLibraryAndArticle( path, frontmatter: { type: "reader-source", id }, types: ["reader-source"], - body: "Source note about attention.", + body: "Source-only note about attention.", })), ...annotations, ]; @@ -99,10 +204,12 @@ export async function measureLibraryAndArticle( const owner = sources[Number(path.slice(8, -3))]; return Promise.resolve(owner && { frontmatter: { id: owner.id } }); }, - async *pages() { - for (let offset = 0; offset < records.length; offset += 128) { + async *pages({ where, limit = 500 }: { where: string; limit?: number }) { + const query = JSON.parse(where.slice("file.body.lower().contains(".length, -1)) as string; + const matched = records.filter(({ body }) => body.toLowerCase().includes(query)); + for (let offset = 0; offset < matched.length; offset += limit) { yield await Promise.resolve({ - records: records.slice(offset, offset + 128), + records: matched.slice(offset, offset + limit), complete: true, }); } @@ -122,14 +229,30 @@ export async function measureLibraryAndArticle( }, repeats, ); - if (sources.length < 1000) { - return samples; + + for (const [query, kind] of [ + ["source-only", "source-note"], + ["annotation-only", "annotation"], + ] as const) { + await measure( + `search ${kind} bodies`, + async () => { + const results = await search.search(collectionId("benchmark"), query); + if ( + results.length !== ownerCount || + !results.every((hit) => hit.kinds.length === 1 && hit.kinds[0] === kind) + ) { + throw new Error(`Wrong ${kind} search results`); + } + }, + repeats, + ); } const paragraphs = Array.from( { length: 3000 }, (_, index) => - `

Passage [${String(index)}] about reading. The study compares two methods. ${"Attention and retention. ".repeat(6)}

`, + `${index % 10 === 0 ? `

Section ${String(index / 10)}

` : ""}

Passage [${String(index)}] about reading. The study compares two methods. ${"Attention and retention. ".repeat(6)}

`, ); const article = `Long article
${paragraphs.join("")}
`; const frame = document.createElement("iframe"); @@ -137,9 +260,34 @@ export async function measureLibraryAndArticle( frame.width = "800"; frame.height = "640"; document.body.append(frame); - await measure("sanitize and lay out 3k HTML paragraphs", async () => { + let prepared = ""; + await measure( + "sanitize long HTML", + () => { + prepared = prepareHtmlDocument(article); + }, + 4, + ); + const svg = encodeURIComponent( + '', + ); + const withSvg = article.replace( + "", + `${``.repeat(64)}`, + ); + await measure( + "sanitize HTML with 64 repeated SVGs", + () => { + const sanitized = prepareHtmlDocument(withSvg); + if (sanitized.includes("bad()") || !sanitized.includes("data:image/svg+xml,")) { + throw new Error("SVG was not sanitized and retained"); + } + }, + 4, + ); + await measure("load and lay out long HTML iframe", async () => { const loaded = new Promise((done) => frame.addEventListener("load", done, { once: true })); - frame.srcdoc = prepareHtmlDocument(article); + frame.srcdoc = prepared; await loaded; if ( frame.contentDocument?.querySelector("[onclick]") || @@ -148,6 +296,39 @@ export async function measureLibraryAndArticle( throw new Error("Last paragraph is missing"); } }); + const tocRuntime = new HtmlDocumentRuntime(frame, "long.html"); + const surfaceDocument = { + document: { file: "long.html", revision: fileRevision(`sha256:${"a".repeat(64)}`) }, + mediaType: "text/html", + url: "about:blank", + }; + const surface = new HtmlReadingSurface(surfaceDocument, tocRuntime); + try { + await measure( + "extract long article TOC", + () => { + const contents = surface.capabilities.contents?.entries(); + if (contents?.length !== 300 || contents.at(-1)?.title !== "Section 299") { + throw new Error("Wrong table of contents"); + } + }, + 20, + ); + await measure( + "check long article TOC availability", + async () => { + const runtime = new HtmlDocumentRuntime(frame, "long.html"); + const candidate = new HtmlReadingSurface(surfaceDocument, runtime); + if (!candidate.capabilities.contents) { + throw new Error("Missing table of contents"); + } + await candidate.destroy(); + }, + 8, + ); + } finally { + await surface.destroy(); + } const unique = Array.from({ length: 600 }, (_, index) => ({ id: `u${String(index)}`, body: "", diff --git a/docs/reader-performance.md b/docs/reader-performance.md index 9a2d1307..fe2519ee 100644 --- a/docs/reader-performance.md +++ b/docs/reader-performance.md @@ -40,10 +40,11 @@ Reader stays an SDK consumer; it does not duplicate authorization or readiness c indexes perform the normal missing-source checks. - Source metadata precedes its annotation query. Global annotation counts wait for the complete source index; saved views defer while a requested/active source is loading. -- Sources use the existing SDK options `firstPageSize: 100`, `pageSize: 1000`. With the updated - authority this means 11 requests for 10,000 sources, not 100. Older authorities remain usable - but can retain their original small pages. Growing progress intervals bound cumulative - snapshot copying even with those authorities; the first rows stay immediate. +- Sources request up to 512 records per SDK contract cursor page. This takes 20 requests for + 10,000 compact source records on replicas that support larger pages. SDK compatibility + limits keep older replicas at 128, and the replica may return shorter pages to fit its + byte budget. Reader publishes the first available rows immediately. Later progress + publications grow with the index size, and completed reads reuse the workspace snapshot. - Navigation and library counts distinguish partial loading from an empty/complete collection. The coordinated SDK change runs live setup assessment and contract description concurrently. diff --git a/packages/connect/src/content-search-repository.ts b/packages/connect/src/content-search-repository.ts index 5f26bcac..ea731e03 100644 --- a/packages/connect/src/content-search-repository.ts +++ b/packages/connect/src/content-search-repository.ts @@ -43,18 +43,16 @@ export class ConnectContentSearchRepository implements ContentSearchRepository { include: { effective: true, body: true }, })) { const records = outcome.records; - const references = records.filter(isAnnotationRecord).map((record) => ({ - path: record.path, - reference: annotationSourceValue(record), - })); + const references: { path: string; reference: unknown }[] = []; + for (const record of records) { + if (isAnnotationRecord(record)) { + references.push({ path: record.path, reference: annotationSourceValue(record) }); + } + } options.signal?.throwIfAborted(); - const owners = await resolveAnnotationSources( - this.client, - references, - options, - sourceIds, - linksByFolder, - ); + const owners = references.length + ? await resolveAnnotationSources(this.client, references, options, sourceIds, linksByFolder) + : undefined; options.signal?.throwIfAborted(); for (const record of records) { const match = recordMatch(record, owners); @@ -96,7 +94,7 @@ function searchInput(query: string): Query { function recordMatch( record: RecordView, - owners: ReadonlyMap, + owners: ReadonlyMap | undefined, ): { readonly id: string; readonly kind: SourceTextMatchKind } | null { const frontmatter = record.effective ?? record.frontmatter; const declaredType = frontmatter["type"]; @@ -104,7 +102,7 @@ function recordMatch( const id = frontmatter["id"]; return typeof id === "string" && id ? { id, kind: "source-note" } : null; } - const id = owners.get(record.path); + const id = owners?.get(record.path); return id ? { id, kind: "annotation" } : null; } diff --git a/packages/connect/src/mapping.ts b/packages/connect/src/mapping.ts index 5c6eeb51..8022980f 100644 --- a/packages/connect/src/mapping.ts +++ b/packages/connect/src/mapping.ts @@ -217,10 +217,14 @@ export function sourceSummaryFromContract( collection: CollectionId, record: ContractQueryRecord, views: readonly RecordView[], + index?: number, ): SourceSummary { const implementation = record.implementations.length === 1 ? record.implementations[0] : undefined; - const view = views.find((candidate) => candidate.id === record.id); + // The SDK verifies positional binding between projections and backing records. + const aligned = index === undefined ? undefined : views[index]; + const view = + aligned?.id === record.id ? aligned : views.find((candidate) => candidate.id === record.id); if (!implementation || !view) { throw new Error("Reader cannot select a unique source contract implementation."); } diff --git a/packages/connect/src/source-pagination.test.ts b/packages/connect/src/source-pagination.test.ts index 107e3da6..00a81e74 100644 --- a/packages/connect/src/source-pagination.test.ts +++ b/packages/connect/src/source-pagination.test.ts @@ -43,8 +43,8 @@ describe("Connect source pagination", () => { expect(pages.map(({ items }) => items.map(({ id }) => id))).toEqual([["src_01"], ["src_02"]]); expect(queryContract.mock.calls).toEqual([ - [sourceContract, { pageSize: 128 }], - [sourceContract, { pageSize: 128, cursor: "opaque-next" }], + [sourceContract, { pageSize: 512 }], + [sourceContract, { pageSize: 512, cursor: "opaque-next" }], ]); }); }); diff --git a/packages/connect/src/source-repository.ts b/packages/connect/src/source-repository.ts index b515d3f9..df31d895 100644 --- a/packages/connect/src/source-repository.ts +++ b/packages/connect/src/source-repository.ts @@ -68,8 +68,8 @@ export class ConnectSourceRepository implements SourceRepository { ...(options.signal ? { signal: options.signal } : {}), }); requireCompleteQuery(result.page); - const records = result.records.map((record) => - sourceSummaryFromContract(query.collectionId, record, result.page.records), + const records = result.records.map((record, index) => + sourceSummaryFromContract(query.collectionId, record, result.page.records, index), ); const items = await resolveSourceSummaryParts( this.client, @@ -91,13 +91,16 @@ export class ConnectSourceRepository implements SourceRepository { let cursor: string | undefined; do { const result = await this.client.queryContract(sourceContract, { - pageSize: 128, + // The SDK keeps older replicas at 128 and the cursor binds the requested limit. + pageSize: 512, ...(cursor ? { cursor } : {}), ...(options.signal ? { signal: options.signal } : {}), }); requireCompleteQuery(result.page); const summaries = result.records - .map((record) => sourceSummaryFromContract(query.collectionId, record, result.page.records)) + .map((record, index) => + sourceSummaryFromContract(query.collectionId, record, result.page.records, index), + ) .filter( (source) => query.readingStatus === undefined || source.readingStatus === query.readingStatus, diff --git a/packages/renderer-html/src/html-document.test.ts b/packages/renderer-html/src/html-document.test.ts index e83a6640..d204cad0 100644 --- a/packages/renderer-html/src/html-document.test.ts +++ b/packages/renderer-html/src/html-document.test.ts @@ -17,6 +17,22 @@ describe("prepareHtmlDocument", () => { expect(rendered.querySelector("code")?.textContent).toBe("const example = 42;"); expect(rendered.body.textContent).toContain("Unicode: café 漢字 🐨"); }); + it("sanitizes repeated SVGs and preserves each image's alt text", () => { + const svg = encodeURIComponent( + '', + ); + const url = `data:image/svg+xml,${svg}`; + const rendered = new DOMParser().parseFromString( + prepareHtmlDocument(`FirstSecond`), + "text/html", + ); + const images = [...rendered.querySelectorAll("img")]; + expect(images.map((image) => image.alt)).toEqual(["First", "Second"]); + const urls = images.map((image) => image.getAttribute("src")); + expect(urls[0]).toMatch(/^data:image\/svg\+xml,/u); + expect(urls[1]).toBe(urls[0]); + expect(decodeURIComponent(urls[0] ?? "")).not.toContain("ignored()"); + }); it("removes executable and network-bearing content while retaining readable markup", () => { const prepared = prepareHtmlDocument(` diff --git a/packages/renderer-html/src/html-document.ts b/packages/renderer-html/src/html-document.ts index 01bf9578..896d3098 100644 --- a/packages/renderer-html/src/html-document.ts +++ b/packages/renderer-html/src/html-document.ts @@ -82,32 +82,43 @@ export function prepareHtmlDocument(source: string): string { element.replaceWith(...element.childNodes); } } + const svgImages = new Map(); for (const element of parsed.querySelectorAll("*")) { - sanitizeAttributes(element); + if (element.hasAttributes()) { + sanitizeAttributes(element, svgImages); + } } parsed.head.prepend(cspMeta(parsed)); parsed.head.append(readerStyle(parsed)); return `\n${parsed.documentElement.outerHTML}`; } -function sanitizeAttributes(element: Element): void { +function sanitizeAttributes(element: Element, svgImages: Map): void { for (const attribute of element.getAttributeNames()) { - const name = attribute.toLocaleLowerCase(); + const name = attribute.toLowerCase(); if (name.startsWith("on") || name === "srcdoc" || name === "srcset" || name === "style") { element.removeAttribute(attribute); } else if (urlAttributes.has(attribute)) { - sanitizeResource(element, attribute); + sanitizeResource(element, attribute, svgImages); } } } -function sanitizeResource(element: Element, name: string): void { +function sanitizeResource( + element: Element, + name: string, + svgImages: Map, +): void { const value = element.getAttribute(name)?.trim(); if (!value) { return; } - if (name === "src" && element.localName === "img") { - const svg = sanitizedSvgImage(value); + if (name === "src" && element.localName === "img" && /^data:image\/svg\+xml[;,]/iu.test(value)) { + let svg = svgImages.get(value); + if (svg === undefined) { + svg = sanitizedSvgImage(value); + svgImages.set(value, svg); + } if (svg) { element.setAttribute(name, svg); return; diff --git a/packages/renderer-html/src/html-runtime.test.ts b/packages/renderer-html/src/html-runtime.test.ts index 0a2a0766..9209b88d 100644 --- a/packages/renderer-html/src/html-runtime.test.ts +++ b/packages/renderer-html/src/html-runtime.test.ts @@ -102,8 +102,12 @@ describe("HtmlDocumentRuntime page text outside the article", () => { }); it("leaves hidden headings out of the contents", () => { - const { runtime: reader } = runtime(); + const { runtime: reader, document: frame } = runtime(); + expect(reader.hasContents()).toBe(true); expect(reader.contents().map((entry) => entry.title)).toEqual(["Essay", "Method"]); + frame.querySelector("article h2")?.remove(); + expect(reader.hasContents()).toBe(false); + expect(reader.goToContents("1")).toBe(false); reader.destroy(); }); }); diff --git a/packages/renderer-html/src/html-runtime.ts b/packages/renderer-html/src/html-runtime.ts index c454220f..8f3496f8 100644 --- a/packages/renderer-html/src/html-runtime.ts +++ b/packages/renderer-html/src/html-runtime.ts @@ -161,6 +161,10 @@ export class HtmlDocumentRuntime { })); } + public hasContents(): boolean { + return headingElements(this.#document, 2).length === 2; + } + public goToContents(id: string): boolean { const heading = headingElements(this.#document)[Number(id)]; if (!heading) { @@ -450,11 +454,17 @@ function parentElement(node: Node): Element | null { return node.nodeType === Node.ELEMENT_NODE ? (node as Element) : node.parentElement; } -function headingElements(document: Document): HTMLElement[] { - return [...document.body.querySelectorAll("h1, h2, h3")].filter( - (heading) => - heading.textContent.trim() !== "" && !heading.closest(`[${outsideArticleAttribute}]`), - ); +function headingElements(document: Document, limit = Infinity): HTMLElement[] { + const headings: HTMLElement[] = []; + for (const heading of document.body.querySelectorAll("h1, h2, h3")) { + if (heading.textContent.trim() && !heading.closest(`[${outsideArticleAttribute}]`)) { + headings.push(heading); + if (headings.length === limit) { + break; + } + } + } + return headings; } /** Converts a range inside the frame to the parent window's viewport. */ diff --git a/packages/renderer-html/src/html-surface.test.ts b/packages/renderer-html/src/html-surface.test.ts index 00221df6..77192bbb 100644 --- a/packages/renderer-html/src/html-surface.test.ts +++ b/packages/renderer-html/src/html-surface.test.ts @@ -23,6 +23,7 @@ describe("HtmlReadingSurface", () => { setActiveAnnotation: vi.fn(), goToAnnotation: () => true, clearSelection: vi.fn(), + hasContents: () => false, contents: () => [], goToContents: () => false, destroy: vi.fn(), @@ -68,6 +69,7 @@ describe("HtmlReadingSurface", () => { onSelectionCleared: () => vi.fn(), onMotion: () => vi.fn(), onAnnotationActivated: () => vi.fn(), + hasContents: () => contents.length > 1, contents: () => contents, goToContents: () => true, } as unknown as HtmlDocumentRuntime, diff --git a/packages/renderer-html/src/html-surface.ts b/packages/renderer-html/src/html-surface.ts index 4bdd4153..8753d215 100644 --- a/packages/renderer-html/src/html-surface.ts +++ b/packages/renderer-html/src/html-surface.ts @@ -78,7 +78,7 @@ export class HtmlReadingSurface implements ReadingSurface { }, }, // A page with fewer than two headings has no useful contents. - ...(runtime.contents().length > 1 + ...(runtime.hasContents() ? { contents: { entries: () => runtime.contents(),