From 6ec8320dc7b5752cdc9543e7ab6e5737d4f286f1 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sun, 29 Nov 2026 00:14:23 +1100 Subject: [PATCH 1/2] Reduce library work and locate painted highlights without rescoring exact matches --- apps/reader/scripts/audit-library-article.mjs | 6 + .../scripts/benchmark-library-article.mjs | 146 +++++++++++------- apps/reader/src/ReaderWorkspaceView.tsx | 3 + apps/reader/src/library-columns.ts | 3 + apps/reader/src/mdbase-library-views.test.ts | 18 +++ apps/reader/src/mdbase-library-views.ts | 72 +++++---- .../library-article-benchmark.tsx | 125 ++++++++++----- .../connect/src/annotation-source-pages.ts | 2 +- packages/connect/src/annotation-source.ts | 21 +-- .../connect/src/content-search-repository.ts | 3 +- .../core/src/domain/text-quote-match.test.ts | 18 +++ packages/core/src/domain/text-quote-match.ts | 76 ++++++--- packages/reading-surface/src/text-quote.ts | 2 +- 13 files changed, 339 insertions(+), 156 deletions(-) diff --git a/apps/reader/scripts/audit-library-article.mjs b/apps/reader/scripts/audit-library-article.mjs index 1fb346d2..8fcce169 100644 --- a/apps/reader/scripts/audit-library-article.mjs +++ b/apps/reader/scripts/audit-library-article.mjs @@ -105,6 +105,12 @@ try { console.log("Library", size, width, "mounted rows", await rows.count()); } } + await page.keyboard.press("Control+k"); + const palette = page.getByRole("dialog", { name: "Reader commands" }); + await palette.getByRole("combobox").fill("Study 09999"); + await expect(palette.getByRole("option", { name: /Study 09999/u })).toBeVisible(); + await page.keyboard.press("Escape"); + await expect(palette).toBeHidden(); const scrollMedian = await grid.evaluate(async (el) => { const frame = el.closest(".library-table-frame"); const times = []; diff --git a/apps/reader/scripts/benchmark-library-article.mjs b/apps/reader/scripts/benchmark-library-article.mjs index ce364eb6..66d2e93e 100644 --- a/apps/reader/scripts/benchmark-library-article.mjs +++ b/apps/reader/scripts/benchmark-library-article.mjs @@ -1,9 +1,12 @@ -// Run locally with a warmed Vite server. Each row has one warm-up and nine samples. +// Optional second server runs the same fixture on the baseline revision. import { chromium, expect } from "@playwright/test"; const origin = process.env.READER_AUDIT_ORIGIN ?? "http://127.0.0.1:5311"; -if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+$/u.test(origin)) { - throw new Error("Performance measurements require a loopback origin."); +const origins = [process.env.READER_BASELINE_ORIGIN, origin].filter(Boolean); +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 articles = Array.from({ length: 10_000 }, (_, index) => ({ collectionId: "benchmark", @@ -20,7 +23,6 @@ const articles = Array.from({ length: 10_000 }, (_, index) => ({ recordRevision: "rev-1", })); const browser = await chromium.launch(); -const page = await browser.newPage({ viewport: { width: 1280, height: 900 } }); function summary(times) { const sorted = times.toSorted((a, b) => a - b); @@ -32,57 +34,95 @@ function summary(times) { } try { - const errors = []; - page.on("pageerror", (error) => errors.push(error.message)); - 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; - return route.fulfill({ json: path.endsWith("/library") ? articles : [] }); - }); - await page.addInitScript(() => { - globalThis.readerGridReady = new Promise((resolve) => { - const observer = new globalThis.MutationObserver(() => { - if (globalThis.document.querySelector('.library-table[aria-rowcount="10001"]')) { - observer.disconnect(); - resolve(performance.now()); - } + const reports = {}; + for (const count of [100, 10_000]) { + const sources = articles.slice(0, count); + 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 page.route("**/*", (route) => + new URL(route.request().url()).origin === url ? route.continue() : 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 : [] }); }); - observer.observe(globalThis.document, { attributes: true, childList: true, subtree: true }); - }); - }); - const startup = []; - const grid = page.locator(".library-table:visible"); - for (let i = 0; i < 10; i++) { - await page.goto(`${origin}/test-fixtures/audit-reader.html`, { waitUntil: "domcontentloaded" }); - const elapsed = await page.evaluate(() => globalThis.readerGridReady); - if (i) startup.push(elapsed); + 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.route("**/*", (route) => + new URL(route.request().url()).origin === url ? route.continue() : route.abort(), + ); + await fixture.goto(`${url}/test-fixtures/import-proof.html`); + lanes.push({ url, page, fixture, 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), + ); + 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 (const { url, page, times } of lanes) { + reports[`${count} @ ${url}`] = Object.fromEntries( + Object.entries(times).map(([k, v]) => [k, summary(v)]), + ); + await page.context().close(); + } } - await expect(grid).toHaveAttribute("aria-rowcount", "10001"); - expect(await grid.locator("[data-row-index]").count()).toBeLessThan(60); - const runs = await page.evaluate( - async ({ sources, moduleUrl }) => { - const { measureLibraryAndArticle } = await import(moduleUrl); - return measureLibraryAndArticle(sources); - }, - { sources: articles, moduleUrl: "/test-fixtures/library-article-benchmark.tsx" }, - ); - expect(errors).toEqual([]); - console.log( - JSON.stringify( - { - chromium: browser.version(), - milliseconds: Object.fromEntries( - [["startup to virtualized 10k grid", startup], ...Object.entries(runs)].map( - ([label, times]) => [label, summary(times)], - ), - ), - }, - null, - 2, - ), - ); + console.log(JSON.stringify({ chromium: browser.version(), milliseconds: reports }, null, 2)); } finally { await browser.close(); } diff --git a/apps/reader/src/ReaderWorkspaceView.tsx b/apps/reader/src/ReaderWorkspaceView.tsx index 2e779b7f..f4fd3c8a 100644 --- a/apps/reader/src/ReaderWorkspaceView.tsx +++ b/apps/reader/src/ReaderWorkspaceView.tsx @@ -675,6 +675,9 @@ function useCommandsForView( }, ): ReturnType { const createSourceParts = useSourcePartCreation(); + if (!model.commandsOpen) { + return []; + } return readerCommands({ libraryViews: model.libraryViews.views, sources: model.library.sources, diff --git a/apps/reader/src/library-columns.ts b/apps/reader/src/library-columns.ts index 724a3963..231f7a6f 100644 --- a/apps/reader/src/library-columns.ts +++ b/apps/reader/src/library-columns.ts @@ -131,6 +131,9 @@ export function propertyValue( if (selected && key in selected) { return selected[key]; } + if (!key.includes(".")) { + return source.properties?.[key]; + } let current: unknown = source.properties; for (const part of key.split(".")) { if (typeof current !== "object" || current === null || Array.isArray(current)) { diff --git a/apps/reader/src/mdbase-library-views.test.ts b/apps/reader/src/mdbase-library-views.test.ts index 342f8979..4933ec5c 100644 --- a/apps/reader/src/mdbase-library-views.test.ts +++ b/apps/reader/src/mdbase-library-views.test.ts @@ -78,6 +78,24 @@ describe("mdbase library views", () => { ]); }); + it("keeps title ties stable in both directions when filtering mixed-case tags", () => { + const rows = [ + source("b", "Same", "reading", ["Study"]), + source("c", "Last", "reading", ["study"]), + source("a", "Same", "reading", ["STUDY"]), + ]; + const base = defaultLibraryViewConfiguration; + 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"], + ); + } + expect(rows.map((row) => row.id)).toEqual(["b", "c", "a"]); + }); + it("round-trips Reader presentation options", () => { const configuration = libraryViewConfiguration({ type: "table", diff --git a/apps/reader/src/mdbase-library-views.ts b/apps/reader/src/mdbase-library-views.ts index 6da4d87f..cb87e92e 100644 --- a/apps/reader/src/mdbase-library-views.ts +++ b/apps/reader/src/mdbase-library-views.ts @@ -215,31 +215,53 @@ export function applyLibraryViewConfiguration( } const query = configuration.filter.query.trim().toLocaleLowerCase(); const tag = configuration.filter.tag.trim().toLocaleLowerCase(); - const filtered = sources.filter((source) => { - if ( - configuration.filter.status !== "all" && - (source.readingStatus ?? "inbox") !== configuration.filter.status - ) { - return false; - } - if ( - configuration.filter.format !== "all" && - sourceFormat(source) !== configuration.filter.format - ) { - return false; - } - if (tag && !source.tags.some((candidate) => candidate.toLocaleLowerCase() === tag)) { - return false; - } - if ( - !configuration.filter.conditions.every((condition) => matchesCondition(source, condition)) - ) { - return false; - } - return !query || metadataSearchText(source, parentTitle).includes(query); - }); - const { sortField, sortDirection } = configuration; + 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 matchingTags = new Map(); + function matchesTag(candidate: string): boolean { + const known = matchingTags.get(candidate); + if (known !== undefined) { + return known; + } + const matches = candidate.toLocaleLowerCase() === tag; + matchingTags.set(candidate, matches); + return matches; + } + const filtered = unfiltered + ? [...sources] + : sources.filter((source) => { + if ( + configuration.filter.status !== "all" && + (source.readingStatus ?? "inbox") !== configuration.filter.status + ) { + return false; + } + if ( + configuration.filter.format !== "all" && + sourceFormat(source) !== configuration.filter.format + ) { + return false; + } + if (tag && !source.tags.some(matchesTag)) { + return false; + } + if ( + !configuration.filter.conditions.every((condition) => matchesCondition(source, condition)) + ) { + return false; + } + return !query || metadataSearchText(source, parentTitle).includes(query); + }); + if (sortField === "title") { + return filtered.sort((a, b) => direction * a.title.localeCompare(b.title)); + } const key = propertyKey(sortField); if (key !== null) { // Dotted paths and formatted property values are independent of the comparison pair. @@ -366,8 +388,6 @@ function columnSelection(column: LibraryColumn): string { function sortValue(source: SourceSummary, field: LibrarySortField): string | number { switch (field) { - case "title": - return source.title; case "creator": return source.creators[0] ?? ""; case "published": diff --git a/apps/reader/test-fixtures/library-article-benchmark.tsx b/apps/reader/test-fixtures/library-article-benchmark.tsx index 1238af41..979bf477 100644 --- a/apps/reader/test-fixtures/library-article-benchmark.tsx +++ b/apps/reader/test-fixtures/library-article-benchmark.tsx @@ -1,5 +1,6 @@ import { ConnectContentSearchRepository } from "@mdbase-reader/connect"; import { collectionId, type Annotation, type SourceSummary } from "@mdbase-reader/core"; +import "@mdbase-reader/i18n"; import { HtmlDocumentRuntime, prepareHtmlDocument } from "@mdbase-reader/renderer-html"; import { fieldValueSuggestions } from "../src/library-conditions.js"; @@ -16,51 +17,77 @@ type HighlightWindow = Window & { export async function measureLibraryAndArticle( sources: readonly SourceSummary[], -): Promise>> { - const samples: Record = {}; - async function measure(name: string, operation: () => unknown): Promise { - const times = []; - for (let run = 0; run < 10; run++) { - const start = performance.now(); +): Promise>> { + const samples: Record = {}; + async function measure(name: string, operation: () => unknown, repeat = 1): Promise { + const start = performance.now(); + for (let run = 0; run < repeat; run++) { await operation(); - if (run) { - times.push(performance.now() - start); - } } - samples[name] = times; + samples[name] = (performance.now() - start) / repeat; } + const repeats = sources.length < 1000 ? 100 : 8; const defaults = defaultLibraryViewConfiguration; - await measure("sort 10k titles", () => { - const sorted = applyLibraryViewConfiguration(sources, defaults); - if (!sorted[0]?.title.endsWith("00000")) { - throw new Error("Wrong sort order"); - } - }); - await measure("filter 10k by metadata and tag", () => { - const matches = applyLibraryViewConfiguration(sources, { - ...defaults, - filter: { ...defaults.filter, query: "study", tag: "research" }, - }); - if (matches.length !== 5000) { - throw new Error("Wrong filter result"); - } - }); - await measure("tag suggestions from 10k library", () => { - if (!fieldValueSuggestions(sources, "tags").length) { - throw new Error("Missing tags"); - } - }); + await measure( + "sort fresh title snapshot", + () => { + const sorted = applyLibraryViewConfiguration([...sources], defaults); + if (sorted[0]?.title !== "Study 00000" || sorted.length !== sources.length) { + throw new Error("Wrong sort order"); + } + }, + repeats, + ); + // Opening All sources precedes typing into its filter. + applyLibraryViewConfiguration(sources, defaults); + await measure( + "filter title order by metadata and tag", + () => { + const matches = applyLibraryViewConfiguration(sources, { + ...defaults, + filter: { ...defaults.filter, query: "study", tag: "research" }, + }); + if (matches.length !== sources.length / 2 || matches[0]?.title !== "Study 00000") { + throw new Error("Wrong filter result"); + } + }, + repeats, + ); + await measure( + "rank tag suggestions", + () => { + const tags = fieldValueSuggestions(sources, "tags"); + if (tags[0] !== "reading" || tags[1] !== "research") { + throw new Error("Wrong tag counts"); + } + }, + repeats, + ); // Inject local query pages so this measures Reader's result processing only. - const records = sources.map(({ id }, index) => { + const ownerCount = sources.length / 10; + const annotations = sources.map(({ id }, index) => { return { path: `annotations/${id}.md`, - frontmatter: { id, type: "reader-annotation", source: `[[sources/${String(index % 1000)}]]` }, + frontmatter: { + id, + type: "reader-annotation", + source: `[[sources/${String(index % ownerCount)}]]`, + }, types: ["reader-annotation"], body: "> Paper mentions attention and retention.\n\nReader highlight comment.", }; }); + const records = [ + ...sources.slice(0, ownerCount).map(({ path, id }) => ({ + path, + frontmatter: { type: "reader-source", id }, + types: ["reader-source"], + body: "Source note about attention.", + })), + ...annotations, + ]; const client = { resolveLinks(_from: unknown, links: string[]) { return Promise.resolve({ @@ -82,12 +109,22 @@ export async function measureLibraryAndArticle( }, } as unknown as MdbaseClient; const search = new ConnectContentSearchRepository(client); - await measure("process 10k annotation search hits", async () => { - const results = await search.search(collectionId("benchmark"), "attention"); - if (results.length !== 1000) { - throw new Error(`Wrong search result: ${String(results.length)}`); - } - }); + await measure( + "group source-note and annotation search hits", + async () => { + const results = await search.search(collectionId("benchmark"), "attention"); + if ( + results.length !== ownerCount || + !results.every((hit) => hit.kinds.length === 2 && hit.passages?.length === 3) + ) { + throw new Error(`Wrong search result: ${String(results.length)}`); + } + }, + repeats, + ); + if (sources.length < 1000) { + return samples; + } const paragraphs = Array.from( { length: 3000 }, @@ -104,7 +141,10 @@ export async function measureLibraryAndArticle( const loaded = new Promise((done) => frame.addEventListener("load", done, { once: true })); frame.srcdoc = prepareHtmlDocument(article); await loaded; - if (!frame.contentDocument?.getElementById("p2999")?.getBoundingClientRect().height) { + if ( + frame.contentDocument?.querySelector("[onclick]") || + !frame.contentDocument?.getElementById("p2999")?.getBoundingClientRect().height + ) { throw new Error("Last paragraph is missing"); } }); @@ -134,7 +174,12 @@ export async function measureLibraryAndArticle( const css = (frame.contentWindow as HighlightWindow | null)?.CSS.highlights.get( "reader-annotation-yellow", ); - if (css?.size !== 600 || [...css].at(-1)?.startContainer.parentElement?.id !== "p2995") { + if ( + css?.size !== 600 || + [...css].some( + (range, i) => range.startContainer.parentElement?.id !== `p${String(i * 5)}`, + ) + ) { throw new Error("Highlights did not anchor to the expected passages"); } } finally { diff --git a/packages/connect/src/annotation-source-pages.ts b/packages/connect/src/annotation-source-pages.ts index 7215feb6..60f36805 100644 --- a/packages/connect/src/annotation-source-pages.ts +++ b/packages/connect/src/annotation-source-pages.ts @@ -23,7 +23,7 @@ export async function* annotationSourcePages( return; } // Source IDs by record path, shared by every page's link resolution. - const ids = new Map(); + const ids = new Map(); const signal = options.signal ? { signal: options.signal } : {}; for (const scope of annotationQueryScopes(options.paths)) { const selected = scope ? new Set(scope) : null; diff --git a/packages/connect/src/annotation-source.ts b/packages/connect/src/annotation-source.ts index 8efcb410..5fcdf277 100644 --- a/packages/connect/src/annotation-source.ts +++ b/packages/connect/src/annotation-source.ts @@ -62,18 +62,18 @@ export async function resolveAnnotationSources( client: MdbaseClient, annotations: readonly { readonly path: string; readonly reference: unknown }[], options: ReaderRequestOptions = {}, - ids = new Map(), + ids = new Map(), linksByFolder: AnnotationLinkTargets = new Map(), ): Promise> { const targets = await sourceLinkTargets(client, annotations, options, linksByFolder); await readSourceIds(client, [...new Set(targets.values())], ids, options); - return new Map( - annotations.map(({ path, reference }) => { - const target = targets.get(path); - const id = target ? ids.get(target) : undefined; - return [path, id ? sourceId(id) : legacySourceId(reference)]; - }), - ); + const owners = new Map(); + for (const { path, reference } of annotations) { + const target = targets.get(path); + const id = target ? ids.get(target) : undefined; + owners.set(path, id ?? legacySourceId(reference)); + } + return owners; } /** The record path each annotation's `source` link reaches, by annotation path. */ @@ -133,7 +133,7 @@ async function sourceLinkTargets( async function readSourceIds( client: MdbaseClient, paths: readonly string[], - ids: Map, + ids: Map, options: ReaderRequestOptions, ): Promise { const unknown = paths.filter((path) => !ids.has(path)); @@ -145,7 +145,8 @@ async function readSourceIds( ); for (const [index, path] of unknown.entries()) { const record = records[index]; - ids.set(path, record ? stringField((record.effective ?? record.frontmatter)["id"]) : undefined); + const id = record && stringField((record.effective ?? record.frontmatter)["id"]); + ids.set(path, id ? sourceId(id) : undefined); } } diff --git a/packages/connect/src/content-search-repository.ts b/packages/connect/src/content-search-repository.ts index f8692747..5f26bcac 100644 --- a/packages/connect/src/content-search-repository.ts +++ b/packages/connect/src/content-search-repository.ts @@ -1,6 +1,7 @@ import { sourceId, type CollectionId, + type SourceId, type ContentSearchRepository, type ReaderRequestOptions, type SourceTextMatchKind, @@ -35,7 +36,7 @@ export class ConnectContentSearchRepository implements ContentSearchRepository { return []; } const matches = new Map(); - const sourceIds = new Map(); + const sourceIds = new Map(); const linksByFolder: AnnotationLinkTargets = new Map(); for await (const outcome of completeReaderPages(this.client, searchInput(normalized), { ...options, diff --git a/packages/core/src/domain/text-quote-match.test.ts b/packages/core/src/domain/text-quote-match.test.ts index 2fc03462..3a2b9d60 100644 --- a/packages/core/src/domain/text-quote-match.test.ts +++ b/packages/core/src/domain/text-quote-match.test.ts @@ -79,6 +79,24 @@ describe("matchTextQuote", () => { expect(matched("Read 📖 patiently.", { exact: "📖 patiently" })).toBe("📖 patiently"); }); + it.each([ + ["a 📖\u00ad b 📖 b", { exact: "📖 b" }], + ["aaaaa", { exact: "aa", prefix: "a", suffix: "a" }], + ["first quote and second quote", { exact: "quote", prefix: "second " }], + ["first quote and second quote", { exact: "quote", prefix: "the second " }], + ["a distinctive inside phrase follows", { exact: "distinctive phrase follows" }], + ["missing", { exact: " " }], + ["missing", { exact: "absent" }], + ] as const)("paints the same range as the scored matcher in %s", (text, quote) => { + const match = matchTextQuote(text, quote); + const range = textQuoteMatcher(text, "range")(quote); + if (match) { + expect(range).toMatchObject({ start: match.start, end: match.end }); + } else { + expect(range).toBeNull(); + } + }); + it("locates many quotations in one prepared text", () => { const match = textQuoteMatcher("one two three"); expect([match({ exact: "one" })?.start, match({ exact: "three" })?.start]).toEqual([0, 8]); diff --git a/packages/core/src/domain/text-quote-match.ts b/packages/core/src/domain/text-quote-match.ts index 7822105f..c6e3289f 100644 --- a/packages/core/src/domain/text-quote-match.ts +++ b/packages/core/src/domain/text-quote-match.ts @@ -37,12 +37,12 @@ const maximumAnchorOccurrences = 50; const maximumComparisonCells = 4_000_000; /** Characters that differ between copies of a page without changing what it says. */ -const ignorable = /[\s\u00ad\u200b-\u200d\u2060\ufeff]/u; +const ignorable = /[\s\u00ad\u200b-\u200d\u2060\ufeff]+/gu; interface Normalized { readonly text: string; /** For each normalized character, its offset in the original text. */ - readonly offsets: readonly number[]; + readonly offsets: Uint32Array; } interface Candidate { @@ -76,35 +76,61 @@ export function resolveSearchQuote( return match && !match.ambiguous && !match.approximate ? match : null; } -/** Prepares `text` once for locating many quotations in it. */ -export function textQuoteMatcher(text: string): (quote: TextQuote) => TextQuoteMatch | null { +type QuoteRange = Pick; + +/** Prepares the text once. Range-only callers accept the first equally good placement. */ +export function textQuoteMatcher(text: string): (quote: TextQuote) => TextQuoteMatch | null; +export function textQuoteMatcher( + text: string, + mode: "range", +): (quote: TextQuote) => QuoteRange | null; +export function textQuoteMatcher( + text: string, + mode?: "range", +): (quote: TextQuote) => QuoteRange | null { const haystack = normalize(text); return (quote) => { - const needle = normalize(quote.exact).text; + const needle = quote.exact.replace(ignorable, ""); if (!needle) { return null; } - const best = bestMatch(haystack.text, needle, quote); - if (!best) { - return null; - } - const start = haystack.offsets[best.start]; - const last = haystack.offsets[best.end - 1]; - if (start === undefined || last === undefined) { - return null; + const prefix = (quote.prefix ?? "").replace(ignorable, ""); + const suffix = (quote.suffix ?? "").replace(ignorable, ""); + if (mode === "range") { + // Painting needs the first best range. A full context match already has the + // maximum possible score, even when a later occurrence ties. + const found = haystack.text.indexOf(prefix + needle + suffix); + if (found >= 0) { + const start = found + prefix.length; + return originalRange(haystack, start, start + needle.length); + } } - return { start, end: last + 1, ambiguous: best.ambiguous, approximate: best.errors > 0 }; + const best = bestMatch(haystack.text, needle, prefix, suffix); + const range = best && originalRange(haystack, best.start, best.end); + return ( + best && + range && { + ...range, + ambiguous: best.ambiguous, + approximate: best.errors > 0, + } + ); }; } +function originalRange(haystack: Normalized, start: number, end: number): QuoteRange | null { + const first = haystack.offsets[start]; + const last = haystack.offsets[end - 1]; + return first === undefined || last === undefined ? null : { start: first, end: last + 1 }; +} + function bestMatch( text: string, needle: string, - quote: TextQuote, + prefix: string, + suffix: string, ): (Candidate & { readonly ambiguous: boolean }) | null { const first = text.indexOf(needle); - const prefix = normalize(quote.prefix ?? "").text; - const suffix = normalize(quote.suffix ?? "").text; if (first === -1) { return choose(text, approximate(text, needle), prefix, suffix); } @@ -137,14 +163,16 @@ function bestMatch( } function normalize(value: string): Normalized { - let text = ""; - const offsets: number[] = []; - for (let index = 0; index < value.length; index++) { - const character = value.charAt(index); - if (!ignorable.test(character)) { - text += character; - offsets.push(index); + const text = value.replace(ignorable, ""); + const offsets = new Uint32Array(text.length); + // Both strings use UTF-16 offsets. Ignorable code units never occur in text. + let raw = 0; + for (let index = 0; index < text.length; index++) { + const code = text.charCodeAt(index); + while (value.charCodeAt(raw) !== code) { + raw++; } + offsets[index] = raw++; } return { text, offsets }; } diff --git a/packages/reading-surface/src/text-quote.ts b/packages/reading-surface/src/text-quote.ts index cf346aed..c2768904 100644 --- a/packages/reading-surface/src/text-quote.ts +++ b/packages/reading-surface/src/text-quote.ts @@ -13,7 +13,7 @@ export function locateTextQuote(root: Element, quote: TextQuote): Range | null { /** Reuse an index while a caller guarantees that the root's text has not changed. */ export function createTextQuoteLocator(root: Element): (quote: TextQuote) => Range | null { const index = textIndex(root); - const matchQuote = textQuoteMatcher(index.text); + const matchQuote = textQuoteMatcher(index.text, "range"); return (quote) => { const match = matchQuote(quote); return match ? rangeAt(root.ownerDocument, index.nodes, match.start, match.end) : null; From ca95a6871093df312c8889a0aac9ffc89834ee17 Mon Sep 17 00:00:00 2001 From: callumalpass Date: Sun, 29 Nov 2026 00:18:30 +1100 Subject: [PATCH 2/2] Keep Vite module requests out of the benchmark interception loop --- apps/reader/scripts/benchmark-library-article.mjs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/apps/reader/scripts/benchmark-library-article.mjs b/apps/reader/scripts/benchmark-library-article.mjs index 66d2e93e..2e8348e2 100644 --- a/apps/reader/scripts/benchmark-library-article.mjs +++ b/apps/reader/scripts/benchmark-library-article.mjs @@ -43,8 +43,9 @@ try { const page = await context.newPage(); const errors = []; page.on("pageerror", (error) => errors.push(error.message)); - await page.route("**/*", (route) => - new URL(route.request().url()).origin === url ? route.continue() : route.abort(), + 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"); @@ -80,9 +81,6 @@ try { // 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.route("**/*", (route) => - new URL(route.request().url()).origin === url ? route.continue() : route.abort(), - ); await fixture.goto(`${url}/test-fixtures/import-proof.html`); lanes.push({ url, page, fixture, errors, times: {} }); } @@ -94,6 +92,7 @@ try { 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(