From c2dcc5d7f007d0a09d3df1d68ceca7eb2de9efe3 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sat, 28 Nov 2026 20:20:30 +1100 Subject: [PATCH] Speed up Reader search, imports, and reading progress --- .github/workflows/ci.yml | 2 + apps/reader/package.json | 2 + apps/reader/scripts/audit-mobile-library.mjs | 172 ++++++++++++++ .../scripts/benchmark-import-progress.mjs | 77 +++++++ .../reader/scripts/reader-audit-documents.mjs | 10 +- apps/reader/src/LibraryWorkspace.tsx | 13 +- apps/reader/src/ReaderWorkspaceView.tsx | 8 +- apps/reader/src/mdbase-library-views.ts | 129 ++++++----- apps/reader/src/reader-shell.css | 9 +- apps/reader/src/source-parts-reading.test.tsx | 37 +++ apps/reader/src/use-library-filter.ts | 59 +++++ apps/reader/src/use-reading-resume.ts | 19 +- .../test-fixtures/library-scale.test.tsx | 47 +++- .../test-fixtures/performance-fixture.tsx | 212 ++++++++++++++++++ docs/reader-performance.md | 69 ++++++ packages/connect/src/annotation-source.ts | 48 +++- .../src/content-search-repository.test.ts | 32 +++ .../connect/src/content-search-repository.ts | 17 +- packages/platform/src/platform.test.ts | 8 + packages/platform/src/reader-services.ts | 8 +- .../renderer-epub/src/epub-safe-fetch.test.ts | 4 +- packages/renderer-epub/src/epub-safe-fetch.ts | 24 +- packages/renderer-html/src/html-document.ts | 36 +-- 23 files changed, 925 insertions(+), 117 deletions(-) create mode 100644 apps/reader/scripts/audit-mobile-library.mjs create mode 100644 apps/reader/scripts/benchmark-import-progress.mjs create mode 100644 apps/reader/src/use-library-filter.ts create mode 100644 apps/reader/test-fixtures/performance-fixture.tsx diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7c7191fb..77730680 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -61,6 +61,8 @@ jobs: run: pnpm --filter @mdbase-reader/app test:pdf-touch - name: Verify library keyboard navigation and restored article highlights run: pnpm --filter @mdbase-reader/app test:library-article + - name: Verify mobile library filters and article accessibility + run: pnpm --filter @mdbase-reader/app test:mobile-library - name: Verify imported SVG rendering in the HTML sandbox run: pnpm --filter @mdbase-reader/app test:html-svg - name: Verify private feedback with sample data and intercepted delivery diff --git a/apps/reader/package.json b/apps/reader/package.json index ae3c0196..fc17aebe 100644 --- a/apps/reader/package.json +++ b/apps/reader/package.json @@ -19,7 +19,9 @@ "preview": "vite preview --host 127.0.0.1", "test": "pnpm manifest && pnpm manifest:verify && node --test scripts/*.test.mjs && vitest run src capture --maxWorkers=2 --testTimeout=15000", "bench:library": "vitest run test-fixtures/library-scale.test.tsx", + "bench:import-progress": "node scripts/benchmark-import-progress.mjs", "test:browser": "node scripts/audit-reader.mjs", + "test:mobile-library": "node scripts/audit-mobile-library.mjs", "test:library-article": "node scripts/audit-library-article.mjs", "test:html-svg": "node scripts/audit-html-svg.mjs", "test:feedback": "node scripts/feedback-browser-test.mjs", diff --git a/apps/reader/scripts/audit-mobile-library.mjs b/apps/reader/scripts/audit-mobile-library.mjs new file mode 100644 index 00000000..a37fb271 --- /dev/null +++ b/apps/reader/scripts/audit-mobile-library.mjs @@ -0,0 +1,172 @@ +import { createHash } from "node:crypto"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; + +import { chromium, expect } from "@playwright/test"; +import { createServer } from "vite"; + +const root = resolve(import.meta.dirname, ".."); +const axePath = createRequire(import.meta.url).resolve("axe-core/axe.min.js"); +const server = await createServer({ + root, + server: { host: "127.0.0.1", port: 0, strictPort: true }, +}); +const article = `Attention and memory

Attention and memory

Methods

${"

The authors compared two reading methods.

".repeat(1200)}
`; +const collection = [ + { + collectionId: "audit", + id: "attention", + path: "sources/attention.md", + title: "Attention and memory", + creators: ["Ada"], + tags: ["research"], + documents: [ + { + fileId: "article", + file: "[[article.html]]", + revision: `sha256:${createHash("sha256").update(article).digest("hex")}`, + mediaType: "text/html", + role: "primary", + }, + ], + frontmatter: {}, + body: "", + recordRevision: "rev-1", + }, + { + collectionId: "audit", + id: "structural", + path: "sources/structural.md", + title: "Structural learning", + creators: ["Inez"], + tags: ["learning"], + documents: [], + frontmatter: {}, + body: "", + recordRevision: "rev-2", + }, +]; + +let browser; +try { + await server.listen(); + const origin = `http://127.0.0.1:${server.httpServer.address().port}`; + browser = await chromium.launch(); + for (const colorScheme of ["light", "dark"]) { + const context = await browser.newContext({ + viewport: { width: 360, height: 740 }, + isMobile: true, + hasTouch: true, + colorScheme, + reducedMotion: "reduce", + }); + const page = await context.newPage(); + await page.route("**/*", (route) => + new URL(route.request().url()).origin === origin ? route.continue() : route.abort(), + ); + await page.route(origin + "/__reader-audit/**", (route) => { + const path = new URL(route.request().url()).pathname.slice("/__reader-audit/".length); + if (path === "library") return route.fulfill({ json: collection }); + if (path === "document/article") + return route.fulfill({ body: article, contentType: "text/html" }); + if (path.startsWith("source/")) { + const source = collection.find(({ id }) => id === path.slice("source/".length)); + if (source) return route.fulfill({ json: source }); + } + if (path === "search" || path.startsWith("annotations/")) return route.fulfill({ json: [] }); + return route.fulfill({ status: 404 }); + }); + const fixtureUrl = origin + "/test-fixtures/audit-reader.html?unrelated=keep"; + await page.goto(fixtureUrl); + const grid = page.getByRole("treegrid", { name: "Sources" }); + const search = page.getByRole("textbox", { name: "Search this view" }); + await expect(grid).toHaveAttribute("aria-rowcount", "3", { timeout: 60000 }); + await assertAxe(page, `${colorScheme} library`); + 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 }); + await tag.fill("research"); + await expect(grid).toHaveAttribute("aria-rowcount", "2"); + const bounds = await options.boundingBox(); + expect(bounds?.x).toBeGreaterThanOrEqual(0); + expect(bounds.x + bounds.width).toBeLessThanOrEqual(360); + await assertAxe(page, `${colorScheme} open filters`); + await page.keyboard.press("Escape"); + await expect(filter).toBeFocused(); + await expect.poll(() => new URL(page.url()).hash).toContain("reader-filter="); + expect(new URL(page.url()).searchParams.get("unrelated")).toBe("keep"); + const filteredUrl = page.url(); + await page.reload(); + await expect(search).toHaveValue("attention"); + await filter.tap(); + await expect(tag).toHaveValue("research"); + await page.keyboard.press("Escape"); + await page.keyboard.press("/"); + await search.press("Escape"); + await expect(search).toHaveValue(""); + await expect(grid).toHaveAttribute("aria-rowcount", "2"); + await search.press("ArrowDown"); + const row = grid.getByRole("row", { name: /^Attention and memory/u }); + await expect(row).toBeFocused(); + await page.evaluate((hash) => { + globalThis.location.hash = hash; + }, new URL(filteredUrl).hash); + await expect(search).toHaveValue("attention"); + await page.evaluate(() => { + globalThis.location.hash = ""; + }); + await expect(grid).toHaveAttribute("aria-rowcount", "3"); + await page.goBack(); + await expect(search).toHaveValue("attention"); + await row.getByRole("link").tap(); + const frame = page.locator("iframe.html-viewer:visible"); + await expect(frame).toBeVisible(); + await expect( + frame.contentFrame().getByRole("heading", { name: "Attention and memory" }), + ).toBeVisible(); + const document = frame.contentFrame().locator("html"); + await expect(document).toHaveAttribute("data-reader-scheme", colorScheme); + await frame.contentFrame().locator("h1").tap(); + await page.keyboard.press("PageDown"); + await expect.poll(() => document.evaluate((root) => root.scrollTop)).toBeGreaterThan(0); + const sourceViews = page.getByRole("navigation", { name: "Source views" }); + await expect(sourceViews).toBeVisible(); + for (const button of await sourceViews.getByRole("button").all()) { + const bounds = await button.boundingBox(); + expect(bounds?.height).toBeGreaterThanOrEqual(44); + expect(bounds?.width).toBeGreaterThanOrEqual(44); + } + expect( + await page.evaluate(() => ({ + viewport: globalThis.innerWidth, + document: globalThis.document.documentElement.scrollWidth, + dark: globalThis.matchMedia("(prefers-color-scheme: dark)").matches, + })), + ).toEqual({ viewport: 360, document: 360, dark: colorScheme === "dark" }); + await assertAxe(page, `${colorScheme} article`); + await context.close(); + } + console.log( + "360px touch Chromium: filters, URL restoration, keyboard and article controls passed in light and dark", + ); +} finally { + await browser?.close(); + await server.close(); +} + +async function assertAxe(page, label) { + await page.addScriptTag({ path: axePath }); + const violations = await page.evaluate(async () => { + const results = await globalThis.axe.run(globalThis.document, { resultTypes: ["violations"] }); + return results.violations.map(({ id, nodes }) => ({ + id, + targets: nodes.map(({ target, failureSummary }) => ({ target, failureSummary })), + })); + }); + expect(violations, label).toEqual([]); +} diff --git a/apps/reader/scripts/benchmark-import-progress.mjs b/apps/reader/scripts/benchmark-import-progress.mjs new file mode 100644 index 00000000..591953bf --- /dev/null +++ b/apps/reader/scripts/benchmark-import-progress.mjs @@ -0,0 +1,77 @@ +import { resolve } from "node:path"; + +import { chromium, expect } from "@playwright/test"; +import { createServer } from "vite"; + +import { auditEpub, auditPdf } from "./reader-audit-documents.mjs"; + +const root = resolve(import.meta.dirname, ".."); +const server = await createServer({ + root, + server: { host: "127.0.0.1", port: 0, strictPort: true }, +}); +let browser; +try { + await server.listen(); + const origin = `http://127.0.0.1:${server.httpServer.address().port}`; + browser = await chromium.launch(); + const page = await browser.newPage({ reducedMotion: "reduce" }); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.route(`${origin}/__performance`, async (route) => + route.fulfill({ + contentType: "text/html", + body: await server.transformIndexHtml( + "/__performance", + "Reader performance fixture", + ), + }), + ); + await page.goto(`${origin}/__performance`); + const chapter = Array.from( + { length: 1200 }, + (_, i) => + `

${"Research notes and patient attention. ".repeat(12)}

`, + ).join(""); + const importFiles = new Map([ + ["article.html", Buffer.from(`${chapter}`)], + [ + "book.epub", + await auditEpub( + `${chapter}`, + ), + ], + ["papers.pdf", auditPdf(1000, 40)], + ]); + const files = []; + for (const [name, body] of importFiles) { + const url = `${origin}/__performance/${name}`; + await page.route(url, (route) => route.fulfill({ body })); + files.push({ name, url }); + } + const moduleUrl = `/@fs${root}/test-fixtures/performance-fixture.tsx`; + const imports = await page.evaluate( + async ({ moduleUrl, files }) => { + const { runImportFixture } = await import(moduleUrl); + return runImportFixture(files); + }, + { moduleUrl, files }, + ); + await page.context().setOffline(true); + const progress = await page.evaluate(async (moduleUrl) => { + const { runProgressFixture } = await import(moduleUrl); + if (globalThis.navigator.onLine) throw new Error("Progress fixture must run offline"); + return runProgressFixture(); + }, moduleUrl); + console.log( + "Chromium input bytes", + Object.fromEntries([...importFiles].map(([name, file]) => [name, file.length])), + ); + console.log("Chromium import", imports); + console.log("Chromium offline progress", progress); + expect(errors).toEqual([]); + console.log("Chromium", browser.version()); +} finally { + await browser?.close(); + await server.close(); +} diff --git a/apps/reader/scripts/reader-audit-documents.mjs b/apps/reader/scripts/reader-audit-documents.mjs index 9146facd..153e14fa 100644 --- a/apps/reader/scripts/reader-audit-documents.mjs +++ b/apps/reader/scripts/reader-audit-documents.mjs @@ -1,16 +1,16 @@ import { ZipWriter, Uint8ArrayWriter, TextReader } from "@zip.js/zip.js"; -export function auditPdf() { +export function auditPdf(pageCount = 8, lines = 1) { const objects = [ "<< /Type /Catalog /Pages 2 0 R >>", "", "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", ]; const pages = []; - for (let page = 1; page <= 8; page += 1) { + for (let page = 1; page <= pageCount; page += 1) { const id = objects.length + 1; pages.push(`${id} 0 R`); - const text = `BT /F1 18 Tf 60 700 Td ([test] PDF reading fixture - Page ${page}) Tj 0 -35 Td (Patient attention and durable research notes.) Tj ET`; + const text = `BT /F1 18 Tf 60 700 Td ([test] PDF reading fixture - Page ${page}) Tj 0 -35 Td (Patient attention and durable research notes.) Tj${" 0 -15 Td (Patient attention and durable research notes.) Tj".repeat(lines - 1)} ET`; objects.push( `<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources << /Font << /F1 3 0 R >> >> /Contents ${id + 1} 0 R >>`, ); @@ -31,7 +31,7 @@ export function auditPdf() { return Buffer.from(pdf); } -export async function auditEpub() { +export async function auditEpub(chapter) { const writer = new ZipWriter(new Uint8ArrayWriter(), { useWebWorkers: false, level: 0 }); const entries = { mimetype: "application/epub+zip", @@ -41,7 +41,7 @@ export async function auditEpub() { 'test-reader-epub[test] EPUB reading fixtureen2026-09-01T00:00:00Z', "OEBPS/nav.xhtml": 'Contents', - "OEBPS/chapter.xhtml": `Reading

[test] EPUB reading fixture

${Array.from({ length: 30 }, (_, index) => `

Patient attention and durable research notes. This is disposable test paragraph ${index + 1}.

`).join("")}`, + "OEBPS/chapter.xhtml": `Reading

[test] EPUB reading fixture

${chapter ?? Array.from({ length: 30 }, (_, index) => `

Patient attention and durable research notes. This is disposable test paragraph ${index + 1}.

`).join("")}`, }; for (const [path, content] of Object.entries(entries)) { await writer.add(path, new TextReader(content)); diff --git a/apps/reader/src/LibraryWorkspace.tsx b/apps/reader/src/LibraryWorkspace.tsx index d0b022bd..fc5eddff 100644 --- a/apps/reader/src/LibraryWorkspace.tsx +++ b/apps/reader/src/LibraryWorkspace.tsx @@ -48,6 +48,7 @@ import { Menu } from "./Menu.js"; import { OverlayPresence } from "./OverlayPresence.js"; import { ReaderNotice } from "./ReaderNotice.js"; import { useInspectedLibraryRow } from "./use-inspected-library-row.js"; +import { useLibraryFilter } from "./use-library-filter.js"; import { layoutOf, useLibraryLayoutDraft } from "./use-library-layout-draft.js"; import { useLibraryWrites } from "./use-library-writes.js"; import { useRovingControls } from "./use-roving-controls.js"; @@ -72,6 +73,7 @@ export function LibraryWorkspace({ gateway, controller, focused, + syncFilterUrl = false, onOpenView, onOpenSource, onOpenBeside, @@ -101,6 +103,7 @@ export function LibraryWorkspace({ readonly gateway: ReaderWorkspaceGateway; readonly controller: MdbaseLibraryViewsController; readonly focused: boolean; + readonly syncFilterUrl?: boolean; readonly onOpenView: (view: MdbaseLibraryView) => void; readonly onOpenSource: (sourceId: SourceId) => void; readonly onOpenBeside: (sourceId: SourceId) => void; @@ -112,7 +115,7 @@ export function LibraryWorkspace({ const trailingControls = useRovingControls(); const collectionKey = allSources[0]?.collectionId ?? "library"; const [layout, setLayout] = useLibraryLayoutDraft(collectionKey, view); - const [filter, setFilter] = useState(view.configuration.filter); + const [filter, setFilter] = useLibraryFilter(view.configuration.filter, syncFilterUrl); const configuration = useMemo( () => ({ ...layout, filter }), [layout, filter], @@ -431,12 +434,16 @@ export function LibraryWorkspace({ ) : null} - {filterCount ? {filterCount} : null} + {filterCount ? ( + + {filterCount} + + ) : null} } > diff --git a/apps/reader/src/ReaderWorkspaceView.tsx b/apps/reader/src/ReaderWorkspaceView.tsx index 2ca89efa..2e779b7f 100644 --- a/apps/reader/src/ReaderWorkspaceView.tsx +++ b/apps/reader/src/ReaderWorkspaceView.tsx @@ -19,6 +19,7 @@ import { inspectorSourceForTab } from "./inspector-source.js"; import { InspectorPane, preloadInspectorTools } from "./InspectorPane.js"; import { LibraryNavigator } from "./LibraryNavigator.js"; import { LibraryWorkspace } from "./LibraryWorkspace.js"; +import { defaultLibraryView } from "./mdbase-library-views.js"; import { mobileSourceBar } from "./mobile-source-bar.js"; import { OverlayPresence } from "./OverlayPresence.js"; import { followedPane, notesView } from "./panel-workspace-state.js"; @@ -147,6 +148,9 @@ export function ReaderWorkspaceView({ const shellRef = useRef(null); useShellChrome(shellRef, model, mobile); const annotationCounts = useLibraryAnnotationCounts(model); + const urlLibraryTab = sourceWorkspace.layout.panes + .flatMap(({ tabs }) => tabs) + .find((tab) => tab.kind === "library" && tab.libraryViewId === defaultLibraryView.key); const notices = useShellNotices( model.deploymentUpdateAvailable, model.gateway.createFollowThrough, @@ -322,9 +326,10 @@ export function ReaderWorkspaceView({ }} renderLibrary={(workspaceTab, focused) => { const libraryView = model.libraryViews.view(workspaceTab.libraryViewId); + const syncFilterUrl = workspaceTab.id === urlLibraryTab?.id; return ( sourceWorkspace.openView(id, view)} controller={model.libraryViews} focused={focused} + syncFilterUrl={syncFilterUrl} // A tab's own view switcher changes that tab, even one pinned to its view. onOpenView={(next) => dock.showLibraryView(workspaceTab.id, next.key, next.name)} onOpenSource={(id) => sourceWorkspace.open(id)} diff --git a/apps/reader/src/mdbase-library-views.ts b/apps/reader/src/mdbase-library-views.ts index 23028928..6da4d87f 100644 --- a/apps/reader/src/mdbase-library-views.ts +++ b/apps/reader/src/mdbase-library-views.ts @@ -130,19 +130,23 @@ export function libraryViewConfiguration(presentation: unknown): LibraryViewConf ? options["sortField"] : defaultLibraryViewConfiguration.sortField; const sortDirection = options["sortDirection"] === "asc" ? "asc" : "desc"; - const filter = objectValue(options["filter"]); return { columns: columns.length > 0 ? columns : defaultLibraryViewConfiguration.columns, columnWidths: parseColumnWidths(options["columnWidths"]), sortField, sortDirection, - filter: { - query: typeof filter["query"] === "string" ? filter["query"] : "", - status: isStatus(filter["status"]) ? filter["status"] : "all", - format: isFormat(filter["format"]) ? filter["format"] : "all", - tag: typeof filter["tag"] === "string" ? filter["tag"] : "", - conditions: parseConditions(filter["conditions"]), - }, + filter: parseLibraryViewFilter(options["filter"]), + }; +} + +export function parseLibraryViewFilter(value: unknown): LibraryViewFilter { + const filter = objectValue(value); + return { + query: typeof filter["query"] === "string" ? filter["query"] : "", + status: isStatus(filter["status"]) ? filter["status"] : "all", + format: isFormat(filter["format"]) ? filter["format"] : "all", + tag: typeof filter["tag"] === "string" ? filter["tag"] : "", + conditions: parseConditions(filter["conditions"]), }; } @@ -232,20 +236,48 @@ export function applyLibraryViewConfiguration( ) { return false; } - return ( - !query || - [ - source.title, - ...source.creators, - ...source.tags.map(String), - source.partOf ? parentTitle(source.partOf) : undefined, - ] - .join(" ") - .toLocaleLowerCase() - .includes(query) - ); + return !query || metadataSearchText(source, parentTitle).includes(query); }); - return filtered.sort((left, right) => compareSources(left, right, configuration)); + const { sortField, sortDirection } = configuration; + const direction = sortDirection === "asc" ? 1 : -1; + const key = propertyKey(sortField); + if (key !== null) { + // Dotted paths and formatted property values are independent of the comparison pair. + return filtered + .map((source) => ({ source, value: propertySortValue(propertyValue(source, key)) })) + .sort((left, right) => direction * compareSortValues(left.value, right.value)) + .map(({ source }) => source); + } + return filtered.sort( + (left, right) => + direction * compareSortValues(sortValue(left, sortField), sortValue(right, sortField)), + ); +} + +// 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(); + +function metadataSearchText( + source: SourceSummary, + parentTitle: (id: SourceSummary["id"]) => string | undefined, +): string { + const cached = searchTextBySource.get(source); + if (cached !== undefined) { + return cached; + } + const text = [ + source.title, + ...source.creators, + ...source.tags, + source.partOf ? parentTitle(source.partOf) : undefined, + ] + .join(" ") + .toLocaleLowerCase(); + if (!source.partOf) { + searchTextBySource.set(source, text); + } + return text; } /** A source's format; `note` means no file is attached, `file` an unrecognised one. */ @@ -332,38 +364,29 @@ function columnSelection(column: LibraryColumn): string { } } -function compareSources( - left: SourceSummary, - right: SourceSummary, - configuration: LibraryViewConfiguration, -): number { - const key = propertyKey(configuration.sortField); - const value = (source: SourceSummary): string | number => { - if (key !== null) { - return propertySortValue(propertyValue(source, key)); - } - switch (configuration.sortField) { - case "title": - return source.title; - case "creator": - return source.creators[0] ?? ""; - case "published": - return Number(source.published ?? 0); - case "status": - return source.readingStatus ?? "inbox"; - case "saved": - return source.id; - case "opened": - return source.reading?.lastOpenedAt ?? ""; - default: - return ""; - } - }; - const a = value(left); - const b = value(right); - const comparison = - typeof a === "number" && typeof b === "number" ? a - b : String(a).localeCompare(String(b)); - return configuration.sortDirection === "asc" ? comparison : -comparison; +function sortValue(source: SourceSummary, field: LibrarySortField): string | number { + switch (field) { + case "title": + return source.title; + case "creator": + return source.creators[0] ?? ""; + case "published": + return Number(source.published ?? 0); + case "status": + return source.readingStatus ?? "inbox"; + case "saved": + return source.id; + case "opened": + return source.reading?.lastOpenedAt ?? ""; + default: + return ""; + } +} + +function compareSortValues(a: string | number, b: string | number): number { + return typeof a === "number" && typeof b === "number" + ? a - b + : String(a).localeCompare(String(b)); } function viewIdentifier(name: string): string { diff --git a/apps/reader/src/reader-shell.css b/apps/reader/src/reader-shell.css index 99021a65..aca23d59 100644 --- a/apps/reader/src/reader-shell.css +++ b/apps/reader/src/reader-shell.css @@ -3164,7 +3164,14 @@ display: flex; align-items: center; gap: 6px; - color: var(--action); + border: 0; + border-radius: var(--ui-radius); + color: var(--ink); + background: transparent; +} + +.reader-menu-panel .library-condition-add:hover { + background: var(--hover); } .library-condition-add svg { diff --git a/apps/reader/src/source-parts-reading.test.tsx b/apps/reader/src/source-parts-reading.test.tsx index 9ddc9a68..745fcdb4 100644 --- a/apps/reader/src/source-parts-reading.test.tsx +++ b/apps/reader/src/source-parts-reading.test.tsx @@ -228,6 +228,43 @@ it("leaves a reader outside the chapter where they are when the source record re expect(surface.currentLocation()).toEqual({ kind: "pdf", pageIndex: 22 }); }); +it("flushes a pending chapter position when leaving without resaving a settled position", async () => { + const { chapter } = await anthology(); + const surface = pdf(chapter); + const save = vi.fn().mockResolvedValue(undefined); + function Harness(): null { + useReadingResume({ source: chapter, surface, save }); + return null; + } + const open = async (): Promise => { + await act(async () => { + root.render(); + await vi.advanceTimersByTimeAsync(0); + }); + }; + await open(); + await act(async () => { + await surface.goTo({ kind: "pdf", pageIndex: 13 }); + await vi.advanceTimersByTimeAsync(1200); + root.render(null); + }); + expect(save).toHaveBeenCalledTimes(1); + + await open(); + await act(async () => { + await surface.goTo({ kind: "pdf", pageIndex: 14 }); + await surface.goTo({ kind: "pdf", pageIndex: 15 }); + root.render(null); + }); + expect(save).toHaveBeenCalledTimes(2); + expect(save).toHaveBeenLastCalledWith( + chapter.id, + surface.document.document, + { kind: "pdf", pageIndex: 15 }, + 0.5, + ); +}); + it("restores a position saved elsewhere while the surface was inactive, instead of overwriting it", async () => { const { chapter } = await anthology(); const surface = pdf(chapter); diff --git a/apps/reader/src/use-library-filter.ts b/apps/reader/src/use-library-filter.ts new file mode 100644 index 00000000..fb073006 --- /dev/null +++ b/apps/reader/src/use-library-filter.ts @@ -0,0 +1,59 @@ +import { useEffect, useState, type Dispatch, type SetStateAction } from "react"; + +import { parseLibraryViewFilter, type LibraryViewFilter } from "./mdbase-library-views.js"; + +const filterPrefix = "#reader-filter="; + +function readFilter(hash: string, fallback: LibraryViewFilter): LibraryViewFilter { + if (!hash.startsWith(filterPrefix)) { + return fallback; + } + try { + return parseLibraryViewFilter(JSON.parse(decodeURIComponent(hash.slice(filterPrefix.length)))); + } catch { + return fallback; + } +} + +/** The primary All sources tab can restore a filter from a link or reload. */ +export function useLibraryFilter( + defaults: LibraryViewFilter, + syncUrl: boolean, +): readonly [LibraryViewFilter, Dispatch>] { + const [filter, setFilter] = useState(() => + syncUrl ? readFilter(window.location.hash, defaults) : defaults, + ); + useEffect(() => { + if (!syncUrl) { + return; + } + const restore = (): void => setFilter(readFilter(window.location.hash, defaults)); + window.addEventListener("popstate", restore); + window.addEventListener("hashchange", restore); + return () => { + window.removeEventListener("popstate", restore); + window.removeEventListener("hashchange", restore); + }; + }, [defaults, syncUrl]); + + useEffect(() => { + if (!syncUrl) { + return; + } + const url = new URL(window.location.href); + if (url.hash && !url.hash.startsWith(filterPrefix)) { + return; + } + const serialized = JSON.stringify(filter); + const hash = + serialized === JSON.stringify(defaults) + ? "" + : `${filterPrefix}${encodeURIComponent(serialized)}`; + if (url.hash !== hash) { + // Search can include private note text. HTTP requests omit the fragment. + url.hash = hash; + window.history.replaceState(window.history.state, "", url); + } + }, [defaults, filter, syncUrl]); + return [filter, setFilter]; +} diff --git a/apps/reader/src/use-reading-resume.ts b/apps/reader/src/use-reading-resume.ts index 10ba2a17..90f0a69b 100644 --- a/apps/reader/src/use-reading-resume.ts +++ b/apps/reader/src/use-reading-resume.ts @@ -72,7 +72,7 @@ export function useReadingResume(input: { let unsubscribe: (() => void) | undefined; let timer: ReturnType | undefined; let latest: ReaderLocator | null = null; - let progress: number | null | undefined; + let measureProgress: ((locator: ReaderLocator) => number | null) | undefined; const saveForSource = saveRef.current; const persist = ( locator: ReaderLocator, @@ -102,6 +102,13 @@ export function useReadingResume(input: { } }); }; + const flush = (report = true): void => { + if (latest) { + const locator = latest; + latest = null; + persist(locator, measureProgress?.(locator), report); + } + }; void (async () => { const range = await resolveSourceReadingRange(current, surface); if (!isActive() || (range && !range.valid)) { @@ -112,11 +119,13 @@ export function useReadingResume(input: { return; } setState({ status: "idle" }); + measureProgress = range?.valid + ? (locator) => range.measure(locator)?.progress ?? null + : undefined; const update = (locator: ReaderLocator): void => { latest = locator; - progress = range?.valid ? (range.measure(locator)?.progress ?? null) : undefined; clearTimeout(timer); - timer = setTimeout(() => persist(locator, progress), 1_200); + timer = setTimeout(flush, 1_200); }; unsubscribe = surface.locations.subscribe(update); const initial = surface.currentLocation(); @@ -140,9 +149,7 @@ export function useReadingResume(input: { // resuming from our own write would pull a reader browsing outside a chapter to its start. unsubscribe?.(); clearTimeout(timer); - if (latest) { - persist(latest, progress, false); - } + flush(false); }; }, [contextKey, sourceId, surface]); diff --git a/apps/reader/test-fixtures/library-scale.test.tsx b/apps/reader/test-fixtures/library-scale.test.tsx index 9ee205ad..35b1c319 100644 --- a/apps/reader/test-fixtures/library-scale.test.tsx +++ b/apps/reader/test-fixtures/library-scale.test.tsx @@ -20,7 +20,7 @@ const collection = collectionId("benchmark"); const collapsed = new Set(); /** Local CPU only. Already-decoded pages, no network, SDK I/O, React commit or paint. */ -for (const count of [2000, 10_000]) { +for (const count of [5000, 10_000]) { it(`profiles a library of ${String(count)} sources`, async () => { const sources: SourceSummary[] = Array.from({ length: count }, (_, index) => ({ collectionId: collection, @@ -29,6 +29,7 @@ for (const count of [2000, 10_000]) { title: `Paper ${String((index * 7919) % count)}`, creators: ["Research group"], tags: [index % 10 === 0 ? "history" : "science"], + readingStatus: index % 3 === 0 ? "reading" : "inbox", properties: { score: index % 100, tags: [index % 10 === 0 ? "history" : "science"] }, documents: [], })); @@ -89,34 +90,60 @@ for (const count of [2000, 10_000]) { await median("tag suggestions", () => { expect(fieldValueSuggestions(sources, "tags")).toEqual(["science", "history"]); }); + await median("tag/status filtering and custom-field sort", () => { + const results = applyLibraryViewConfiguration(sources, { + ...view, + filter: { ...view.filter, tag: "history", status: "reading" }, + sortField: "property:score", + sortDirection: "desc", + }); + expect(results).toHaveLength(Math.ceil(count / 30)); + expect(results[0]?.properties?.["score"]).toBe(90); + }); // Each heavily annotated source contributes 200 matching notes spread across pages. const notes = annotations.map((annotation, index) => ({ path: `annotations/${annotation.id}.md`, types: ["reader-annotation"], - effective: { source: `[[source-${String(index % (count / 200))}]]` }, + effective: { source: `[[sources/${String(index % (count / 200))}]]` }, body: `Selected passage ${String(index)} ${"annotation context ".repeat(40)}`, })); + const records = [ + ...notes, + ...sources.slice(0, count / 200).map((source) => ({ + path: source.path, + types: ["reader-source"], + effective: { id: source.id }, + body: `Selected passage in a source note about ${source.title}`, + })), + ]; + let resolvedLinks = 0; const search = new ConnectContentSearchRepository({ async *pages() { - for (let offset = 0; offset < notes.length; offset += 128) { + for (let offset = 0; offset < records.length; offset += 128) { yield await Promise.resolve({ complete: true, - records: notes.slice(offset, offset + 128), + records: records.slice(offset, offset + 128), }); } }, - // Legacy bare-ID links, with no record at the link target in this fixture. - resolveLinks: (_from: string, links: string[]) => - Promise.resolve({ + resolveLinks: (_from: string, links: string[]) => { + resolvedLinks += links.length; + return Promise.resolve({ complete: true, - resolutions: links.map(() => ({ kind: "not_found" })), - }), + resolutions: links.map((link) => ({ kind: "record", path: `${link.slice(2, -2)}.md` })), + }); + }, + find: ({ path }: { path: string }) => + Promise.resolve({ effective: { id: `source-${path.slice(8, -3)}` } }), } as unknown as MdbaseClient); - await median("annotation search results", async () => { + await median("source-note and annotation search results", async () => { + resolvedLinks = 0; const results = await search.search(collection, "passage"); expect(results).toHaveLength(count / 200); expect(results.every((match) => match.passages?.length === 3)).toBe(true); + expect(results.every((match) => match.kinds.join() === "annotation,source-note")).toBe(true); }); + stdout.write(`links passed to SDK: ${String(resolvedLinks)}\n`); await median("collection highlight headings", () => { const headings = annotationGroupHeadings(annotations, undefined, sources, true); expect(headings.at(-1)?.source?.summary).toBe(sources.at(-1)); diff --git a/apps/reader/test-fixtures/performance-fixture.tsx b/apps/reader/test-fixtures/performance-fixture.tsx new file mode 100644 index 00000000..59d869e9 --- /dev/null +++ b/apps/reader/test-fixtures/performance-fixture.tsx @@ -0,0 +1,212 @@ +import { collectionId, fileRevision, importSourceFile, recordRevision } from "@mdbase-reader/core"; +import { + BrowserStorage, + createReaderRuntimeServices, + MemoryStorage, +} from "@mdbase-reader/platform"; +import { EpubArchive, sanitizePublicationMarkup } from "@mdbase-reader/renderer-epub"; +import { + HtmlDocumentRuntime, + HtmlReadingSurface, + prepareHtmlDocument, +} from "@mdbase-reader/renderer-html"; +import { flushSync } from "react-dom"; +import { createRoot } from "react-dom/client"; + +import { readDocumentFileDetails } from "../src/document-details.js"; +import { beginExplicitReadingNavigation } from "../src/reading-navigation-priority.js"; +import { useReadingResume } from "../src/use-reading-resume.js"; + +import type { DocumentDescriptor, Source } from "@mdbase-reader/core"; + +const runtime = createReaderRuntimeServices(new MemoryStorage()); +const collection = collectionId("performance"); +const href = "long-article.html"; +const documentTarget: DocumentDescriptor = { + file: "[[long-article.html]]", + revision: fileRevision("sha256:abcdef"), + mediaType: "text/html", + role: "primary", + range: { kind: "fragment", start: "#p0", end: "#p1199" }, +}; +const articleBody = Array.from( + { length: 1200 }, + (_, index) => + `

${"Long article text about attention and retention. ".repeat(12)}

`, +).join(""); +const article = `Long article${articleBody}`; +export async function runImportFixture( + files: readonly { name: string; url: string }[], +): Promise>> { + const metrics: Record = {}; + for (const { name, url } of files) { + const bytes = new Uint8Array(await (await fetch(url)).arrayBuffer()); + metrics[`plan and hash ${name}`] = await median(() => planImport(name, bytes)); + metrics[`read import metadata ${name}`] = await median(async () => { + const { metadata } = await readDocumentFileDetails({ name, bytes }); + if (name.endsWith(".epub") && metadata.language !== "en") { + throw new Error("EPUB metadata did not survive."); + } + }); + if (name.endsWith(".epub")) { + const blob = new Blob([bytes]); + let chapter = ""; + metrics["open EPUB, read and sanitize chapter"] = await median(async () => { + const archive = await EpubArchive.open(blob); + try { + chapter = await archive.readText("OEBPS/chapter.xhtml"); + sanitizeChapter(chapter); + } finally { + await archive.close(); + } + }); + metrics["sanitize EPUB chapter"] = await median(() => sanitizeChapter(chapter)); + } + } + metrics["sanitize 1200-paragraph HTML"] = await median(() => { + const cleaned = prepareHtmlDocument(article); + if (!cleaned.includes('id="p1199"') || !cleaned.includes("Content-Security-Policy")) { + throw new Error("HTML sanitization changed the fixture contract."); + } + }); + return metrics; +} + +function sanitizeChapter(chapter: string): void { + const cleaned = sanitizePublicationMarkup(chapter, "application/xhtml+xml"); + if (cleaned.includes("onclick=") || !cleaned.includes('id="p1199"')) { + throw new Error("EPUB sanitization changed the fixture contract."); + } +} + +async function planImport(name: string, bytes: Uint8Array): Promise { + const source = await importSourceFile( + { + ...runtime, + imports: { + findExactDuplicate: () => Promise.resolve(null), + commitFile: (plan) => { + if (plan.representations[0]?.bytes !== bytes) { + throw new Error("The import did not preserve the supplied bytes."); + } + return Promise.resolve({ + collectionId: plan.collectionId, + id: plan.sourceId, + path: plan.recordPath, + title: plan.title, + creators: [], + tags: [], + documents: [], + body: "", + frontmatter: {}, + recordRevision: recordRevision("bench"), + }); + }, + }, + }, + { name, bytes, collectionId: collection }, + ); + if (!source.title) { + throw new Error("The import did not produce a source."); + } +} + +export async function runProgressFixture(): Promise>> { + const frame = document.createElement("iframe"); + frame.title = "Reading progress benchmark"; + const loaded = new Promise((done) => { + frame.addEventListener("load", () => done(), { once: true }); + }); + frame.srcdoc = prepareHtmlDocument(article); + document.body.append(frame); + await loaded; + const articleRuntime = new HtmlDocumentRuntime(frame, href); + const surface = new HtmlReadingSurface( + { document: documentTarget, mediaType: "text/html", url: href }, + articleRuntime, + ); + const host = document.createElement("div"); + document.body.append(host); + const source: Source = { + collectionId: collection, + id: runtime.ids.source(), + path: "sources/long-article.md", + title: "Long article", + creators: [], + tags: [], + documents: [documentTarget], + body: "", + frontmatter: {}, + recordRevision: recordRevision("bench"), + }; + const key = "reader-audit-progress"; + const storage = new BrowserStorage(); + const metrics: Record = {}; + let saves = 0; + function Resume(): null { + useReadingResume({ + source, + surface, + save: (_id, _file, position, progress) => { + saves += 1; + return storage.set(key, JSON.stringify({ position, progress })); + }, + }); + return null; + } + try { + await beginExplicitReadingNavigation(surface); + const times: number[] = []; + for (let sample = 0; sample < 8; sample += 1) { + await storage.remove(key); + saves = 0; + const root = createRoot(host); + flushSync(() => root.render()); + await new Promise(requestAnimationFrame); + const started = performance.now(); + for (let index = 1; index <= 1000; index += 1) { + surface.locations.emit({ kind: "html", href, progression: index / 2000 }); + } + if (sample > 0) { + times.push(performance.now() - started); + } + if (sample === 0) { + await new Promise((done) => setTimeout(done, 1300)); + if (saves !== 1) { + throw new Error("Progress did not persist after scrolling settled."); + } + } + flushSync(() => root.unmount()); + await new Promise(requestAnimationFrame); + const saved = await new BrowserStorage().get(key); + if (!saved?.includes('"progression":0.5') || !saved.includes('"progress":null')) { + throw new Error("The latest locator and chapter progress did not persist."); + } + if (sample === 0) { + metrics["writes for one settled burst followed by unmount"] = saves; + } + } + metrics["dispatch 1000 chapter position updates"] = middle(times); + return metrics; + } finally { + await surface.destroy(); + frame.remove(); + host.remove(); + await storage.remove(key); + } +} + +async function median(run: () => void | Promise): Promise { + await run(); + const times: number[] = []; + for (let sample = 0; sample < 7; sample += 1) { + const started = performance.now(); + await run(); + times.push(performance.now() - started); + } + return middle(times); +} + +function middle(times: number[]): number { + return Number(times.sort((left, right) => left - right)[3]?.toFixed(2)); +} diff --git a/docs/reader-performance.md b/docs/reader-performance.md index 69a20ab1..9a2d1307 100644 --- a/docs/reader-performance.md +++ b/docs/reader-performance.md @@ -134,3 +134,72 @@ After installing workspace dependencies and Playwright Chromium, run `node apps/reader/scripts/audit-library-article.mjs` for the browser fixture. It starts and closes its own loopback server. To compare an earlier commit, copy the two benchmark files into a worktree at that commit and run the same commands. + +## Search, imports and reading progress (2026-11-28) + +The comparison starts at `d739e84f`, which includes #352 and #354. Each timing is +the median of seven samples after one warm-up. Vitest ran with Node 22.22.0 on the +shared build VM. Chromium 156.0.8078.4 ran on the local workstation against fixtures. + +| Vitest operation | 5,000 before | 5,000 after | 10,000 before | 10,000 after | +| ------------------------------------- | -----------: | ----------: | ------------: | -----------: | +| Three title, author and tag queries | 6.86 ms | 4.05 ms | 15.29 ms | 9.04 ms | +| Tag and status filter and custom sort | 0.78 ms | 0.42 ms | 0.94 ms | 0.38 ms | +| Tag suggestions | 0.53 ms | 0.53 ms | 0.26 ms | 0.23 ms | +| Source-note and annotation results | 4.74 ms | 4.01 ms | 6.72 ms | 5.76 ms | +| Link occurrences sent to the SDK | 5,000 | 25 | 10,000 | 50 | + +The mixed search returns 200 annotations and a source note per owner. Results +retain both kinds and the first three passages per owner. Link resolution is +shared by folder and exact link text for the current paged search. The CPU fixture +uses preselected SDK pages and excludes the authority's evaluator and transport. +Tag suggestions sample 2,000 sources. The warmed metadata query benefits from +caching each unchanged summary, with chapter titles resolved against the current +parent collection. + +Chromium results take the median of three runs per revision, alternating +baseline and candidate on the same workstation. The metadata rows provide +context for the import path and varied with workstation load. + +| Chromium operation | Before | After | +| ---------------------------------------- | -------: | ------: | +| Plan and hash HTML (568 KB) | 1.0 ms | 0.6 ms | +| Plan and hash EPUB (1.17 MB) | 2.0 ms | 1.4 ms | +| Plan and hash PDF (2.70 MB) | 5.4 ms | 3.4 ms | +| Read HTML import metadata | 3.2 ms | 3.6 ms | +| Read EPUB import metadata | 12.3 ms | 11.6 ms | +| Read PDF import metadata | 22.6 ms | 21.0 ms | +| Sanitize HTML | 11.4 ms | 7.1 ms | +| Open EPUB, read and sanitize the chapter | 63.2 ms | 54.3 ms | +| Sanitize the loaded EPUB chapter | 47.7 ms | 33.3 ms | +| Dispatch 1,000 chapter position updates | 624.2 ms | 1.3 ms | +| Writes after a settled burst and leaving | 2 | 1 | + +The fixtures cover HTML and XHTML documents with 1,200 paragraphs, the latter +with a 600 KB inline data payload, and a 1,000-page PDF. Import planning includes +format detection and Web Crypto hashing against an in-memory repository. The +metadata and sanitizer rows run the corresponding Reader and renderer code in +Chromium. File transfer and hosted storage are outside these measurements. + +Progress dispatch sends 1,000 locator events to the real HTML surface and +Reader's resume hook with the browser offline. The write port uses real browser +storage in the fixture. It checks the last locator after the idle save and after +leaving with a pending update. Dispatch timing excludes the 1.2-second debounce, +and the storage test covers the Reader hook through its write boundary. + +The 360 px touch fixture checks the library, open filter menu and HTML reader +with axe-core in both colour schemes. It also checks URL reload and browser Back, +slash search, Escape and ArrowDown focus, and PageDown within the article. The +first All sources tab owns the URL fragment. Search text stays out of HTTP +requests, and unrelated query parameters survive filter edits. + +```sh +rpnpm --filter @mdbase-reader/app run bench:library +pnpm --filter @mdbase-reader/app run bench:import-progress +pnpm --filter @mdbase-reader/app run test:mobile-library +``` + +For a baseline, copy the benchmark scripts and their fixtures into a checkout +of the baseline commit and run the same entry points there. For Chromium, run +`node apps/reader/scripts/benchmark-import-progress.mjs` if the baseline predates +the package script. diff --git a/packages/connect/src/annotation-source.ts b/packages/connect/src/annotation-source.ts index 8c36a131..8efcb410 100644 --- a/packages/connect/src/annotation-source.ts +++ b/packages/connect/src/annotation-source.ts @@ -8,6 +8,8 @@ import { import type { MdbaseClient, RecordView } from "@mdbase-dev/sdk"; +export type AnnotationLinkTargets = Map>; + /** * mdbase resolves an annotation's `source` link, so Reader never guesses a link's target from its * text: a link can name a path or a shortened filename, and mdbase alone knows which record it @@ -61,8 +63,9 @@ export async function resolveAnnotationSources( annotations: readonly { readonly path: string; readonly reference: unknown }[], options: ReaderRequestOptions = {}, ids = new Map(), + linksByFolder: AnnotationLinkTargets = new Map(), ): Promise> { - const targets = await sourceLinkTargets(client, annotations, options); + const targets = await sourceLinkTargets(client, annotations, options, linksByFolder); await readSourceIds(client, [...new Set(targets.values())], ids, options); return new Map( annotations.map(({ path, reference }) => { @@ -78,29 +81,50 @@ async function sourceLinkTargets( client: MdbaseClient, annotations: readonly { readonly path: string; readonly reference: unknown }[], options: ReaderRequestOptions, + linksByFolder: AnnotationLinkTargets, ): Promise> { - // A link resolves against its note's folder alone (spec 08), so one request serves a folder. - const folders = new Map(); + // A link resolves against its note's folder alone (spec 08). Ask once per distinct + // occurrence, including across pages when the caller supplies a search-scoped cache. + const folders = new Map }>(); + const targets = new Map(); for (const { path, reference } of annotations) { const link = linkOccurrence(reference); if (!link) { continue; } const folder = path.slice(0, Math.max(0, path.lastIndexOf("/"))); - const group = folders.get(folder) ?? { from: path, paths: [], links: [] }; - group.paths.push(path); - group.links.push(link); + const known = linksByFolder.get(folder); + if (known?.has(link)) { + const target = known.get(link); + if (target) { + targets.set(path, target); + } + continue; + } + const group = folders.get(folder) ?? { from: path, pathsByLink: new Map() }; + const paths = group.pathsByLink.get(link); + if (paths) { + paths.push(path); + } else { + group.pathsByLink.set(link, [path]); + } folders.set(folder, group); } - const targets = new Map(); - for (const { from, paths, links } of folders.values()) { + for (const [folder, { from, pathsByLink }] of folders) { + const links = [...pathsByLink.keys()]; const resolved = await resolveLinksFrom(client, from, links, options); - for (const [index, path] of paths.entries()) { - const target = resolved[index]; - if (target?.kind === "record" && target.path) { - targets.set(path, target.path); + const known = linksByFolder.get(folder) ?? new Map(); + for (const [index, [link, paths]] of [...pathsByLink].entries()) { + const resolution = resolved[index]; + const target = resolution?.kind === "record" ? resolution.path : undefined; + known.set(link, target); + if (target) { + for (const path of paths) { + targets.set(path, target); + } } } + linksByFolder.set(folder, known); } return targets; } diff --git a/packages/connect/src/content-search-repository.test.ts b/packages/connect/src/content-search-repository.test.ts index f37193a8..e88c3c01 100644 --- a/packages/connect/src/content-search-repository.test.ts +++ b/packages/connect/src/content-search-repository.test.ts @@ -100,6 +100,38 @@ describe("ConnectContentSearchRepository", () => { records.slice(0, 3).map((record) => record.path), ); expect(find).toHaveBeenCalledTimes(1); + expect(links.resolveLinks).toHaveBeenCalledExactlyOnceWith( + records[0]?.path, + ["[[My paper|Study]]"], + {}, + ); + }); + + it("resolves identical links independently by folder and on each search", async () => { + const first = testRecord({ path: "one/Owner.md", effective: { id: "first" } }); + const second = testRecord({ path: "two/Owner.md", effective: { id: "second" } }); + const note = (path: string): RecordView => + testRecord({ + path, + effective: { type: "reader-annotation", source: "[[Owner]]" }, + body: "Matched passage", + }); + let moved = false; + const links = linkIndex([first, second], (_link, from) => + !moved && from.startsWith("one/") ? first.path : second.path, + ); + const repository = new ConnectContentSearchRepository( + mockSdk({ + ...links, + find: ({ path }: { path: string }) => Promise.resolve(path === first.path ? first : second), + pages: () => queryStream([page([note("one/a.md"), note("two/a.md")])]), + }), + ); + const search = async (): Promise => + (await repository.search(collectionId("reading"), "matched")).map(({ sourceId }) => sourceId); + expect(await search()).toEqual(["first", "second"]); + moved = true; + expect(await search()).toEqual(["second"]); }); it("includes bounded passage context without losing record destinations", async () => { diff --git a/packages/connect/src/content-search-repository.ts b/packages/connect/src/content-search-repository.ts index b54c4078..f8692747 100644 --- a/packages/connect/src/content-search-repository.ts +++ b/packages/connect/src/content-search-repository.ts @@ -7,7 +7,11 @@ import { type SourceTextSearchMatch, } from "@mdbase-reader/core"; -import { annotationSourceValue, resolveAnnotationSources } from "./annotation-source.js"; +import { + annotationSourceValue, + resolveAnnotationSources, + type AnnotationLinkTargets, +} from "./annotation-source.js"; import { completeReaderPages } from "./repository-client.js"; import type { MdbaseClient, Query, RecordView } from "@mdbase-dev/sdk"; @@ -32,6 +36,7 @@ export class ConnectContentSearchRepository implements ContentSearchRepository { } const matches = new Map(); const sourceIds = new Map(); + const linksByFolder: AnnotationLinkTargets = new Map(); for await (const outcome of completeReaderPages(this.client, searchInput(normalized), { ...options, include: { effective: true, body: true }, @@ -41,7 +46,15 @@ export class ConnectContentSearchRepository implements ContentSearchRepository { path: record.path, reference: annotationSourceValue(record), })); - const owners = await resolveAnnotationSources(this.client, references, options, sourceIds); + options.signal?.throwIfAborted(); + const owners = await resolveAnnotationSources( + this.client, + references, + options, + sourceIds, + linksByFolder, + ); + options.signal?.throwIfAborted(); for (const record of records) { const match = recordMatch(record, owners); if (!match) { diff --git a/packages/platform/src/platform.test.ts b/packages/platform/src/platform.test.ts index 14d3ea04..ea91ceb6 100644 --- a/packages/platform/src/platform.test.ts +++ b/packages/platform/src/platform.test.ts @@ -91,6 +91,14 @@ describe("StorageCreateJournal", () => { }); describe("createReaderRuntimeServices", () => { + it("hashes only the supplied bytes of an offset view", async () => { + const { hasher } = createReaderRuntimeServices(new MemoryStorage()); + const view = new Uint8Array([0, 97, 98, 99, 0]).subarray(1, 4); + await expect(hasher.sha256(view)).resolves.toBe( + "sha256:ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", + ); + }); + it("creates UUID mutation identities accepted by resumable file transfers", () => { const services = createReaderRuntimeServices(new MemoryStorage()); diff --git a/packages/platform/src/reader-services.ts b/packages/platform/src/reader-services.ts index 0c7c8341..3f6861c9 100644 --- a/packages/platform/src/reader-services.ts +++ b/packages/platform/src/reader-services.ts @@ -154,7 +154,13 @@ export function createReaderRuntimeServices(storage: KeyValueStorage): { clock: { now: () => dateTime(new Date().toISOString()) }, hasher: { async sha256(bytes) { - const buffer = await crypto.subtle.digest("SHA-256", bytes.slice().buffer); + // Web Crypto snapshots the passed view, including its offset and length. Copy only + // SharedArrayBuffer-backed inputs, which Web Crypto does not accept. + const input = + bytes.buffer instanceof ArrayBuffer + ? new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength) + : new Uint8Array(bytes); + const buffer = await crypto.subtle.digest("SHA-256", input); const digest = Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0"), ).join(""); diff --git a/packages/renderer-epub/src/epub-safe-fetch.test.ts b/packages/renderer-epub/src/epub-safe-fetch.test.ts index be7f5fcf..70ee4034 100644 --- a/packages/renderer-epub/src/epub-safe-fetch.test.ts +++ b/packages/renderer-epub/src/epub-safe-fetch.test.ts @@ -11,8 +11,9 @@ describe("sanitizePublicationMarkup", () => {

Readable text

- unsafe + unsafe + unsafe
`, "text/html", ); @@ -26,6 +27,7 @@ describe("sanitizePublicationMarkup", () => { expect(document.body.hasAttribute("onload")).toBe(false); expect(document.querySelector("a")?.hasAttribute("href")).toBe(false); expect(document.querySelector("a")?.hasAttribute("ping")).toBe(false); + expect(document.querySelector("#active-data")?.hasAttribute("href")).toBe(false); expect(document.querySelector("img")?.getAttribute("src")).toBe("data:image/png;base64,"); expect(document.querySelector("img")?.hasAttribute("onerror")).toBe(false); }); diff --git a/packages/renderer-epub/src/epub-safe-fetch.ts b/packages/renderer-epub/src/epub-safe-fetch.ts index 502c8eff..2217d31a 100644 --- a/packages/renderer-epub/src/epub-safe-fetch.ts +++ b/packages/renderer-epub/src/epub-safe-fetch.ts @@ -6,6 +6,13 @@ import type { FetchImplementation } from "@readium/shared"; const ACTIVE_ELEMENTS = "script, iframe, frame, frameset, object, embed, form, base"; const URL_ATTRIBUTES = ["href", "src", "xlink:href", "poster", "data", "action", "formaction"]; +const ACTIVE_URL_PREFIXES = [ + "javascript:", + "vbscript:", + "data:text/html", + "data:application/xhtml+xml", +]; +const MAX_ACTIVE_URL_PREFIX_LENGTH = Math.max(...ACTIVE_URL_PREFIXES.map(({ length }) => length)); export const safePublicationFetch: FetchImplementation = async (input, init) => { const response = await fetch(input, init); @@ -55,6 +62,9 @@ function sanitizePublicationDocument(markup: string, mediaType: string): Documen } function sanitizeElement(element: Element): void { + if (!element.hasAttributes()) { + return; + } for (const attribute of [...element.attributes]) { const name = attribute.name.toLowerCase(); if (name.startsWith("on") || ["srcdoc", "ping"].includes(name)) { @@ -71,18 +81,18 @@ function sanitizeElement(element: Element): void { function unsafeActiveUrl(value: string): boolean { let compact = ""; - for (let index = 0; index < value.length; index += 1) { + // Only the scheme and media type can match. A data URL can contain megabytes after them. + for ( + let index = 0; + index < value.length && compact.length < MAX_ACTIVE_URL_PREFIX_LENGTH; + index += 1 + ) { if (value.charCodeAt(index) > 32) { compact += value.charAt(index); } } compact = compact.toLowerCase(); - return ( - compact.startsWith("javascript:") || - compact.startsWith("vbscript:") || - compact.startsWith("data:text/html") || - compact.startsWith("data:application/xhtml+xml") - ); + return ACTIVE_URL_PREFIXES.some((prefix) => compact.startsWith(prefix)); } function parserMediaType(mediaType: string): DOMParserSupportedType { diff --git a/packages/renderer-html/src/html-document.ts b/packages/renderer-html/src/html-document.ts index 82b1480b..01bf9578 100644 --- a/packages/renderer-html/src/html-document.ts +++ b/packages/renderer-html/src/html-document.ts @@ -30,7 +30,7 @@ const unwrappedElements = ["form", "button"] as const; */ export const outsideArticleRevealedAttribute = "data-reader-revealed"; -const urlAttributes = ["href", "src", "poster", "action", "formaction", "xlink:href"] as const; +const urlAttributes = new Set(["href", "src", "poster", "action", "formaction", "xlink:href"]); /** The article's text: page text kept outside the article is left out. */ export function htmlDocumentText(document: Document): string { @@ -91,25 +91,31 @@ export function prepareHtmlDocument(source: string): string { } function sanitizeAttributes(element: Element): void { - for (const attribute of [...element.attributes]) { - const name = attribute.name.toLocaleLowerCase(); + for (const attribute of element.getAttributeNames()) { + const name = attribute.toLocaleLowerCase(); if (name.startsWith("on") || name === "srcdoc" || name === "srcset" || name === "style") { - element.removeAttribute(attribute.name); + element.removeAttribute(attribute); + } else if (urlAttributes.has(attribute)) { + sanitizeResource(element, attribute); } } - for (const name of urlAttributes) { - const value = element.getAttribute(name)?.trim(); - if (name === "src" && element.localName === "img" && value) { - const svg = sanitizedSvgImage(value); - if (svg) { - element.setAttribute(name, svg); - continue; - } - } - if (value && !safeResource(name, value)) { - element.removeAttribute(name); +} + +function sanitizeResource(element: Element, name: string): void { + const value = element.getAttribute(name)?.trim(); + if (!value) { + return; + } + if (name === "src" && element.localName === "img") { + const svg = sanitizedSvgImage(value); + if (svg) { + element.setAttribute(name, svg); + return; } } + if (!safeResource(name, value)) { + element.removeAttribute(name); + } } function safeResource(attribute: string, value: string): boolean {