The best way to control Claude Code, Codex and more from any computer or phone
test(web): PDF viewer behavior is covered by fast tests (#25699)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 26, 2026 at 17:01 UTC
08bd2ec09c29996a5b3015f4a4cc4a93541eed42
4 files changed
+325
-45
apps/web/src/components/files/PdfViewer.browser.test.tsx
new
+111
@@ -0,0 +1,111 @@
1
+import { expect, it, vi } from "vite-plus/test";
2
+import { render } from "../../../test/render";
3
+import "~/index.css";
4
+
5
+// Vite serves the worker module through its transform with an inline source map (6.8 MB for
6
+// a 1.3 MB file), which dominated this test under CPU contention. A blob of the raw file is the
7
+// same code without the dev-server cost.
8
+vi.mock(import("pdfjs-dist/build/pdf.worker.min.mjs?url"), async () => {
9
+ const { default: source } = await import("pdfjs-dist/build/pdf.worker.min.mjs?raw");
10
+ return {
11
+ default: URL.createObjectURL(new Blob([source], { type: "text/javascript" })),
12
+ };
13
+});
14
+
15
+import PdfViewer from "./PdfViewer";
16
+
17
+// Page 1 is a short banner whose title is drawn in two runs with a font change, so pdf.js
18
+// splits it into two text spans. Page 2 is a letter page rotated a quarter turn.
19
+function twoPagePdf() {
20
+ const pages = [
21
+ {
22
+ box: "0 0 612 140",
23
+ rotate: 0,
24
+ text: "BT /F1 24 Tf 30 70 Td (Quarter) Tj /F2 24 Tf (ly outlook) Tj ET",
25
+ },
26
+ { box: "0 0 612 792", rotate: 90, text: "BT /F1 24 Tf 30 700 Td (Budget and risks) Tj ET" },
27
+ ];
28
+ const objects = [
29
+ "<< /Type /Catalog /Pages 2 0 R >>",
30
+ "<< /Type /Pages /Count 2 /Kids [3 0 R 5 0 R] >>",
31
+ ...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 >>`,
33
+ `<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
34
+ ]),
35
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",
36
+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",
37
+ ];
38
+ let source = "%PDF-1.4\n";
39
+ const offsets: number[] = [];
40
+ for (const [index, object] of objects.entries()) {
41
+ offsets.push(source.length);
42
+ source += `${index + 1} 0 obj\n${object}\nendobj\n`;
43
+ }
44
+ const xref = source.length;
45
+ source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets
46
+ .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)
47
+ .join("")}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
48
+ return new Blob([source], { type: "application/pdf" });
49
+}
50
+
51
+it("fits the width, then finds split and rotated text and jumps to its page", async () => {
52
+ const url = URL.createObjectURL(twoPagePdf());
53
+ try {
54
+ const container = document.createElement("div");
55
+ container.style.cssText = "display:flex;width:500px;height:600px";
56
+ await using screen = await render(<PdfViewer src={url} title="Planning PDF" />, {
57
+ container,
58
+ });
59
+ // The milestone is pdf.js booting its worker and parsing the document, not a frame count.
60
+ await expect.element(screen.getByText("1 / 2 pages"), { timeout: 10_000 }).toBeVisible();
61
+ const region = screen.container.querySelector<HTMLElement>('[role="region"]')!;
62
+ // Fit width follows the measured viewport, which settles once the scrollbar appears.
63
+ await vi.waitFor(() => {
64
+ const canvas = region.querySelector('canvas[aria-label="Page 1"]')!;
65
+ expect(canvas.getBoundingClientRect().width).toBe(region.clientWidth - 32);
66
+ expect(region.scrollWidth).toBe(region.clientWidth);
67
+ });
68
+
69
+ const find = screen.getByRole("searchbox", { name: "Find in PDF" });
70
+ await find.fill("quarterly outlook");
71
+ await expect.element(screen.getByRole("status")).toHaveTextContent("1/1");
72
+ await vi.waitFor(() =>
73
+ expect(
74
+ Array.from(region.querySelectorAll(".pdf-find-match"), (span) => span.textContent),
75
+ ).toEqual(["Quarter", "ly outlook"]),
76
+ );
77
+
78
+ await find.fill("budget");
79
+ await expect.element(screen.getByText("2 / 2 pages")).toBeVisible();
80
+ await expect.element(screen.getByRole("status")).toHaveTextContent("1/1");
81
+ const rotated = await vi.waitFor(() => {
82
+ const span = Array.from(region.querySelectorAll("[data-pdf-text-layer] span")).find(
83
+ (node) => node.textContent === "Budget and risks",
84
+ );
85
+ expect(span).toBeDefined();
86
+ return span!;
87
+ });
88
+ // The rotated page's text runs top to bottom inside the page, so a selection lands on it.
89
+ const textBounds = rotated.getBoundingClientRect();
90
+ const pageBounds = rotated.closest("[data-pdf-text-layer]")!.getBoundingClientRect();
91
+ expect(textBounds.height).toBeGreaterThan(textBounds.width);
92
+ expect(textBounds.width).toBeGreaterThan(0);
93
+ expect(textBounds.left).toBeGreaterThanOrEqual(pageBounds.left - 1);
94
+ expect(textBounds.top).toBeGreaterThanOrEqual(pageBounds.top - 1);
95
+ expect(textBounds.right).toBeLessThanOrEqual(pageBounds.right + 1);
96
+ expect(textBounds.bottom).toBeLessThanOrEqual(pageBounds.bottom + 1);
97
+ expect(getComputedStyle(rotated).userSelect).toBe("text");
98
+ const range = document.createRange();
99
+ range.selectNodeContents(rotated);
100
+ const selection = window.getSelection()!;
101
+ selection.removeAllRanges();
102
+ selection.addRange(range);
103
+ expect(selection.toString()).toBe("Budget and risks");
104
+ selection.removeAllRanges();
105
+
106
+ await find.fill(" ");
107
+ await expect.element(screen.getByRole("status")).toHaveTextContent("0/0");
108
+ } finally {
109
+ URL.revokeObjectURL(url);
110
+ }
111
+});
apps/web/src/components/files/PdfViewer.tsx
+28
-45
@@ -13,6 +13,18 @@ import { observeResize } from "~/lib/observeResize";
13
import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";
14
import { readBoundedDocument } from "./readBoundedDocument";
15
import { openPdf } from "./pdfDocument";
16
+import {
17
+ currentPdfPage,
18
+ pdfFindMatchRuns,
19
+ pdfPageOffsets,
20
+ pdfPageScrollTop,
21
+ pdfPageText,
22
+ pdfPageWidth,
23
+ PDF_MAX_ZOOM,
24
+ PDF_MIN_ZOOM,
25
+ stepPdfZoom,
26
+ visiblePdfPages,
27
+} from "./pdfLayout";
28
import "./pdfViewer.css";
29
30
const MAX_PAGES = 2000;
@@ -83,25 +95,12 @@ function PdfPage(props: {
95
const node = text.current;
96
if (!node) return;
97
const mark = () => {
86
- const runs = Array.from(node.querySelectorAll('span[role="presentation"], br')).map(
87
- (element) => ({
88
- element,
89
- text: element.tagName === "BR" ? "\n" : (element.textContent ?? "").toLowerCase(),
90
- }),
98
+ const elements = Array.from(node.querySelectorAll('span[role="presentation"], br'));
99
+ const hits = pdfFindMatchRuns(
100
+ elements.map((element) => (element.tagName === "BR" ? "\n" : (element.textContent ?? ""))),
101
+ props.query,
102
);
92
- const text = runs.map((run) => run.text).join("");
93
- const query = props.query.toLowerCase();
94
- let match = query.trim() ? text.indexOf(query) : -1;
95
- let offset = 0;
96
- for (const run of runs) {
97
- while (match !== -1 && match + query.length <= offset)
98
- match = text.indexOf(query, match + query.length);
99
- run.element.classList.toggle(
100
- "pdf-find-match",
101
- match !== -1 && match < offset + run.text.length,
102
- );
103
- offset += run.text.length;
104
- }
103
+ elements.forEach((element, index) => element.classList.toggle("pdf-find-match", hits[index]));
104
};
105
mark();
106
const observer = new MutationObserver(mark);
@@ -181,24 +180,10 @@ export default function PdfViewer(props: { src: string; title: string }) {
180
update();
181
return observeResize(node, update);
182
}, []);
184
- const fitWidth = Math.max(1, viewport.width - 32);
185
- const scale = zoom ?? fitWidth / pageWidth;
186
- const width = zoom === null ? fitWidth : pageWidth * zoom;
187
- const offsets = (() => {
188
- const result = [16];
189
- for (const ratio of ratios) result.push(result[result.length - 1]! + width * ratio + 16);
190
- return result;
191
- })();
192
- const current = Math.max(
193
- 0,
194
- ratios.findIndex((_, index) => offsets[index + 1]! > scrollTop + 17),
195
- );
196
- const visible = ratios.flatMap((ratio, index) =>
197
- offsets[index + 1]! >= scrollTop - viewport.height &&
198
- offsets[index]! <= scrollTop + viewport.height * 2
199
- ? [{ index, ratio }]
200
- : [],
201
- );
183
+ const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom);
184
+ const offsets = pdfPageOffsets(ratios, width);
185
+ const current = currentPdfPage(offsets, ratios.length, scrollTop);
186
+ const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height);
187
// Stable callbacks let page canvases survive scroll and find updates.
188
const [onSize] = useState(
189
() => (index: number, ratio: number) =>
@@ -207,10 +192,10 @@ export default function PdfViewer(props: { src: string; title: string }) {
192
),
193
);
194
const jumpToPage = useEffectEvent((index: number) => {
210
- scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
195
+ scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
196
});
197
const showPage = (index: number) => {
213
- scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
198
+ scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
199
};
200
const changeZoom = (value: number | null) => {
201
zoomAnchor.current = {
@@ -256,9 +241,7 @@ export default function PdfViewer(props: { src: string; title: string }) {
241
const pageSize = page.getViewport({ scale: 1 });
242
sizes.push(pageSize.height / pageSize.width);
243
const content = await page.getTextContent();
259
- const text = content.items
260
- .map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))
261
- .join("");
244
+ const text = pdfPageText(content.items);
245
size += text.length;
246
if (size > MAX_FIND_TEXT)
247
throw new Error(
@@ -305,8 +288,8 @@ export default function PdfViewer(props: { src: string; title: string }) {
288
</FileSurfaceAction>
289
<FileSurfaceAction
290
label="Zoom out"
308
- disabled={scale <= 0.25}
309
- onPress={() => changeZoom(Math.max(0.25, scale - 0.25))}
291
+ disabled={scale <= PDF_MIN_ZOOM}
292
+ onPress={() => changeZoom(stepPdfZoom(scale, -1))}
293
>
294
<MinusIcon className="size-3.5" />
295
</FileSurfaceAction>
@@ -315,8 +298,8 @@ export default function PdfViewer(props: { src: string; title: string }) {
298
</span>
299
<FileSurfaceAction
300
label="Zoom in"
318
- disabled={scale >= 3}
319
- onPress={() => changeZoom(Math.min(3, scale + 0.25))}
301
+ disabled={scale >= PDF_MAX_ZOOM}
302
+ onPress={() => changeZoom(stepPdfZoom(scale, 1))}
303
>
304
<PlusIcon className="size-3.5" />
305
</FileSurfaceAction>
apps/web/src/components/files/pdfLayout.test.ts
new
+113
@@ -0,0 +1,113 @@
1
+import { describe, expect, it } from "vite-plus/test";
2
+import {
3
+ currentPdfPage,
4
+ pdfFindMatchRuns,
5
+ pdfPageOffsets,
6
+ pdfPageScrollTop,
7
+ pdfPageText,
8
+ pdfPageWidth,
9
+ stepPdfZoom,
10
+ visiblePdfPages,
11
+} from "./pdfLayout";
12
+
13
+describe("pdfPageWidth", () => {
14
+ it("fits the page to the viewport minus its gutters until a zoom is chosen", () => {
15
+ expect(pdfPageWidth(500, 612, null)).toEqual({ width: 468, scale: 468 / 612 });
16
+ expect(pdfPageWidth(500, 612, 1.5)).toEqual({ width: 918, scale: 1.5 });
17
+ });
18
+
19
+ it("never collapses below one pixel in a tiny viewport", () => {
20
+ expect(pdfPageWidth(10, 612, null).width).toBe(1);
21
+ });
22
+});
23
+
24
+describe("stepPdfZoom", () => {
25
+ it("steps by a quarter and clamps to 25%..300%", () => {
26
+ expect(stepPdfZoom(1, 1)).toBe(1.25);
27
+ expect(stepPdfZoom(1, -1)).toBe(0.75);
28
+ expect(stepPdfZoom(2.9, 1)).toBe(3);
29
+ expect(stepPdfZoom(0.3, -1)).toBe(0.25);
30
+ });
31
+
32
+ it("starts from the fit-width scale when no zoom is set", () => {
33
+ const { scale } = pdfPageWidth(500, 612, null);
34
+ expect(stepPdfZoom(scale, 1)).toBeCloseTo(468 / 612 + 0.25);
35
+ });
36
+});
37
+
38
+describe("mixed-height page layout", () => {
39
+ // A short banner page, a letter page, then a page half as tall as it is wide.
40
+ const ratios = [140 / 612, 792 / 612, 306 / 612];
41
+ const width = 612;
42
+ const offsets = pdfPageOffsets(ratios, width);
43
+
44
+ it("stacks pages with a gap before, between, and after them", () => {
45
+ expect(offsets).toEqual([16, 172, 980, 1302]);
46
+ });
47
+
48
+ it("reports the page whose bottom is past the top gutter as current", () => {
49
+ expect(currentPdfPage(offsets, 3, 0)).toBe(0);
50
+ expect(currentPdfPage(offsets, 3, 154)).toBe(0);
51
+ expect(currentPdfPage(offsets, 3, 155)).toBe(1);
52
+ expect(currentPdfPage(offsets, 3, 962)).toBe(1);
53
+ expect(currentPdfPage(offsets, 3, 964)).toBe(2);
54
+ });
55
+
56
+ it("jumps to each page so that page becomes current", () => {
57
+ for (const index of [0, 1, 2])
58
+ expect(currentPdfPage(offsets, 3, pdfPageScrollTop(offsets, index))).toBe(index);
59
+ expect(pdfPageScrollTop(offsets, 7)).toBe(0);
60
+ });
61
+
62
+ it("mounts pages within a viewport above and two below", () => {
63
+ const indexes = (scrollTop: number, height: number) =>
64
+ visiblePdfPages(ratios, offsets, scrollTop, height).map((page) => page.index);
65
+ expect(indexes(0, 100)).toEqual([0, 1]);
66
+ expect(indexes(1100, 100)).toEqual([2]);
67
+ expect(indexes(1100, 900)).toEqual([1, 2]);
68
+ expect(visiblePdfPages(ratios, offsets, 0, 100)[0]).toEqual({ index: 0, ratio: ratios[0] });
69
+ });
70
+
71
+ it("scales offsets with the page width when zoomed", () => {
72
+ expect(pdfPageOffsets(ratios, width * 2)).toEqual([16, 312, 1912, 2540]);
73
+ });
74
+});
75
+
76
+describe("pdfPageText", () => {
77
+ it("joins text items, adds line ends, and skips marked content", () => {
78
+ expect(
79
+ pdfPageText([
80
+ { str: "Quarter", hasEOL: false },
81
+ { type: "beginMarkedContent" },
82
+ { str: "ly outlook", hasEOL: true },
83
+ { str: "Next", hasEOL: false },
84
+ ]),
85
+ ).toBe("Quarterly outlook\nNext");
86
+ });
87
+});
88
+
89
+describe("pdfFindMatchRuns", () => {
90
+ it("highlights every run a match spans when a word is split across spans", () => {
91
+ expect(pdfFindMatchRuns(["Quarter", "ly outlook", " for Q3"], "quarterly OUTLOOK")).toEqual([
92
+ true,
93
+ true,
94
+ false,
95
+ ]);
96
+ });
97
+
98
+ it("highlights each separate match", () => {
99
+ expect(pdfFindMatchRuns(["risk", " and ", "budget", " ", "Risk"], "risk")).toEqual([
100
+ true,
101
+ false,
102
+ false,
103
+ false,
104
+ true,
105
+ ]);
106
+ });
107
+
108
+ it("highlights nothing for a blank or missing query", () => {
109
+ expect(pdfFindMatchRuns(["a b", "c"], " ")).toEqual([false, false]);
110
+ expect(pdfFindMatchRuns(["a b", "c"], "")).toEqual([false, false]);
111
+ expect(pdfFindMatchRuns(["a b", "c"], "zzz")).toEqual([false, false]);
112
+ });
113
+});
apps/web/src/components/files/pdfLayout.ts
new
+73
@@ -0,0 +1,73 @@
1
+const PDF_PAGE_GAP = 16;
2
+export const PDF_MIN_ZOOM = 0.25;
3
+export const PDF_MAX_ZOOM = 3;
4
+const PDF_ZOOM_STEP = 0.25;
5
+
6
+export function pdfPageWidth(viewportWidth: number, pageWidth: number, zoom: number | null) {
7
+ const fitWidth = Math.max(1, viewportWidth - 2 * PDF_PAGE_GAP);
8
+ return {
9
+ scale: zoom ?? fitWidth / pageWidth,
10
+ width: zoom === null ? fitWidth : pageWidth * zoom,
11
+ };
12
+}
13
+
14
+export function stepPdfZoom(scale: number, direction: 1 | -1) {
15
+ return direction > 0
16
+ ? Math.min(PDF_MAX_ZOOM, scale + PDF_ZOOM_STEP)
17
+ : Math.max(PDF_MIN_ZOOM, scale - PDF_ZOOM_STEP);
18
+}
19
+
20
+/** Top offset of each page plus the end of the last one; ratios are height / width. */
21
+export function pdfPageOffsets(ratios: readonly number[], width: number) {
22
+ const result = [PDF_PAGE_GAP];
23
+ for (const ratio of ratios)
24
+ result.push(result[result.length - 1]! + width * ratio + PDF_PAGE_GAP);
25
+ return result;
26
+}
27
+
28
+export function currentPdfPage(offsets: readonly number[], pageCount: number, scrollTop: number) {
29
+ for (let index = 0; index < pageCount; index++)
30
+ if (offsets[index + 1]! > scrollTop + PDF_PAGE_GAP + 1) return index;
31
+ return 0;
32
+}
33
+
34
+/** Pages within one viewport above and two below the visible area stay mounted. */
35
+export function visiblePdfPages(
36
+ ratios: readonly number[],
37
+ offsets: readonly number[],
38
+ scrollTop: number,
39
+ viewportHeight: number,
40
+) {
41
+ return ratios.flatMap((ratio, index) =>
42
+ offsets[index + 1]! >= scrollTop - viewportHeight &&
43
+ offsets[index]! <= scrollTop + viewportHeight * 2
44
+ ? [{ index, ratio }]
45
+ : [],
46
+ );
47
+}
48
+
49
+export function pdfPageScrollTop(offsets: readonly number[], index: number) {
50
+ return Math.max(0, (offsets[index] ?? PDF_PAGE_GAP) - PDF_PAGE_GAP);
51
+}
52
+
53
+export function pdfPageText(
54
+ items: readonly ({ str: string; hasEOL: boolean } | { type: string })[],
55
+) {
56
+ return items.map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : "")).join("");
57
+}
58
+
59
+/** Which text runs hold part of a case-insensitive match, when pdf.js splits words across spans. */
60
+export function pdfFindMatchRuns(runs: readonly string[], query: string) {
61
+ const texts = runs.map((run) => run.toLowerCase());
62
+ const text = texts.join("");
63
+ const needle = query.toLowerCase();
64
+ let match = needle.trim() ? text.indexOf(needle) : -1;
65
+ let offset = 0;
66
+ return texts.map((run) => {
67
+ while (match !== -1 && match + needle.length <= offset)
68
+ match = text.indexOf(needle, match + needle.length);
69
+ const hit = match !== -1 && match < offset + run.length;
70
+ offset += run.length;
71
+ return hit;
72
+ });
73
+}