Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PdfViewer.browser.test.tsx

111 lines5.0 KB

1import { expect, it, vi } from "vite-plus/test";
2import { render } from "../../../test/render";
3import "~/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.
8vi.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​
15import 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.
19function 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" });
50​
51it("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});