The best way to control Claude Code, Codex and more from any computer or phone
perf(web): PDF Find jumps to the first match in long PDFs 3.1x faster (median) (#33956)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Andrei committed
Nov 13, 2026 at 05:50 UTC
a03f7185f2aa59466f44cfe113d1807c9733290c
2 files changed
+81
-11
apps/web/src/components/files/PdfViewer.browser.test.tsx
+71
-7
@@ -12,24 +12,56 @@ vi.mock(import("pdfjs-dist/build/pdf.worker.min.mjs?url"), async () => {
12
};
13
});
14
15
+// Holds one page's Find text until the test opens it, so a scan can be observed mid-flight.
16
+const findGate = vi.hoisted(() => ({ page: 0, open: () => {}, opened: Promise.resolve() }));
17
+function setup(page: number) {
18
+ findGate.page = page;
19
+ findGate.opened = new Promise((resolve) => (findGate.open = resolve));
20
+}
21
+vi.mock(import("./pdfDocument"), async (importOriginal) => {
22
+ const actual = await importOriginal();
23
+ return {
24
+ ...actual,
25
+ openPdf: (bytes) => {
26
+ const task = actual.openPdf(bytes);
27
+ const promise = task.promise.then((document) => {
28
+ const getPage = document.getPage.bind(document);
29
+ document.getPage = async (number) => {
30
+ const page = await getPage(number);
31
+ const getTextContent = page.getTextContent.bind(page);
32
+ page.getTextContent = async (params) => {
33
+ if (number === findGate.page) await findGate.opened;
34
+ return getTextContent(params);
35
+ };
36
+ return page;
37
+ };
38
+ return document;
39
+ });
40
+ return Object.defineProperty(task, "promise", { value: promise });
41
+ },
42
+ };
43
+});
44
+
45
import PdfViewer from "./PdfViewer";
46
47
// Page 1 is a short banner whose title is drawn in two runs with a font change, so pdf.js
48
// splits it into two text spans. Page 2 is a letter page rotated a quarter turn.
19
-function twoPagePdf() {
20
- const pages = [
49
+function testPdf(
50
+ pages = [
51
{
52
box: "0 0 612 140",
53
rotate: 0,
54
text: "BT /F1 24 Tf 30 70 Td (Quarter) Tj /F2 24 Tf (ly outlook) Tj ET",
55
},
56
{ box: "0 0 612 792", rotate: 90, text: "BT /F1 24 Tf 30 700 Td (Budget and risks) Tj ET" },
27
- ];
57
+ ],
58
+) {
59
+ const fonts = 3 + pages.length * 2;
60
const objects = [
61
"<< /Type /Catalog /Pages 2 0 R >>",
30
- "<< /Type /Pages /Count 2 /Kids [3 0 R 5 0 R] >>",
62
+ `<< /Type /Pages /Count ${pages.length} /Kids [${pages.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] >>`,
63
...pages.flatMap(({ box, rotate, text }, index) => [
32
- `<< /Type /Page /Parent 2 0 R /MediaBox [${box}] /Rotate ${rotate} /Resources << /Font << /F1 7 0 R /F2 8 0 R >> >> /Contents ${4 + index * 2} 0 R >>`,
64
+ `<< /Type /Page /Parent 2 0 R /MediaBox [${box}] /Rotate ${rotate} /Resources << /Font << /F1 ${fonts} 0 R /F2 ${fonts + 1} 0 R >> >> /Contents ${4 + index * 2} 0 R >>`,
65
`<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
66
]),
67
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
@@ -49,7 +81,7 @@ function twoPagePdf() {
81
}
82
83
it("fits the width, then finds split and rotated text and jumps to its page", async () => {
52
- const url = URL.createObjectURL(twoPagePdf());
84
+ const url = URL.createObjectURL(testPdf());
85
try {
86
const container = document.createElement("div");
87
container.style.cssText = "display:flex;width:500px;height:600px";
@@ -110,8 +142,40 @@ it("fits the width, then finds split and rotated text and jumps to its page", as
142
}
143
});
144
145
+it("jumps to the first hit while still counting and keeps later manual navigation", async () => {
146
+ setup(4);
147
+ const page = (text: string) => ({
148
+ box: "0 0 612 792",
149
+ rotate: 0,
150
+ text: `BT /F1 24 Tf 30 700 Td (${text}) Tj ET`,
151
+ });
152
+ const url = URL.createObjectURL(
153
+ testPdf([page("Intro"), page("Needle one"), page("Needle two"), page("Closing")]),
154
+ );
155
+ try {
156
+ await using screen = await render(
157
+ <div className="flex h-[300px] w-[320px]">
158
+ <PdfViewer src={url} title="Searched PDF" />
159
+ </div>,
160
+ );
161
+ await expect.element(screen.getByText("1 / 4 pages")).toBeVisible();
162
+ await screen.getByRole("searchbox", { name: "Find in PDF" }).fill("needle");
163
+ await expect.element(screen.getByText("2 / 4 pages")).toBeVisible();
164
+ await expect.element(screen.getByRole("status")).toHaveTextContent("Searching…");
165
+
166
+ await screen.getByRole("button", { name: "Next page", exact: true }).click();
167
+ await expect.element(screen.getByText("3 / 4 pages")).toBeVisible();
168
+ findGate.open();
169
+ await expect.element(screen.getByRole("status")).toHaveTextContent("1/2");
170
+ await expect.element(screen.getByText("3 / 4 pages")).toBeVisible();
171
+ } finally {
172
+ findGate.open();
173
+ URL.revokeObjectURL(url);
174
+ }
175
+});
176
+
177
it("restores page, within-page offset and zoom after a remount", async () => {
114
- const url = URL.createObjectURL(twoPagePdf());
178
+ const url = URL.createObjectURL(testPdf());
179
const viewer = (mount: number, positionKey: string) => (
180
<div className="flex h-[300px] w-[320px]">
181
<PdfViewer key={mount} src={url} title="Restored PDF" positionKey={positionKey} />
apps/web/src/components/files/PdfViewer.tsx
+10
-4
@@ -289,10 +289,11 @@ export default function PdfViewer(props: {
289
}
290
saveView(node, anchor !== null);
291
});
292
+ const firstMatch = matches[0];
293
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
294
useLayoutEffect(() => {
294
- if (matches.length) jumpToPage(matches[0]!);
295
- }, [matches]);
295
+ if (firstMatch !== undefined) jumpToPage(firstMatch);
296
+ }, [firstMatch]);
297
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Debounce pdf.js text extraction and cancel obsolete searches when the query or document changes.
298
useEffect(() => {
299
if (!pdf || !query.trim()) {
@@ -311,18 +312,23 @@ export default function PdfViewer(props: {
312
const sizes: number[] = [];
313
let size = 0;
314
for (let index = 0; index < pdf.numPages; index++) {
314
- if (cancelled) return;
315
const page = await pdf.getPage(index + 1);
316
const pageSize = page.getViewport({ scale: 1 });
317
sizes.push(pageSize.height / pageSize.width);
318
const content = await page.getTextContent();
319
+ if (cancelled) return;
320
const text = pdfPageText(content.items);
321
size += text.length;
322
if (size > MAX_FIND_TEXT)
323
throw new Error(
324
"This PDF has too much text to search. Save it to search in another app.",
325
);
325
- if (pdfFindIncludes(text, query)) found.push(index);
326
+ if (!pdfFindIncludes(text, query)) continue;
327
+ found.push(index);
328
+ if (found.length > 1) continue;
329
+ // Pages up to the first hit are measured, so its jump lands before the scan finishes.
330
+ setRatios((old) => [...sizes, ...old.slice(sizes.length)]);
331
+ setMatches([index]);
332
}
333
if (cancelled) return;
334
setRatios(sizes);