TypeScript
test(web): PDF viewer behavior is covered by fast tests (#25699)
Julius Marminge08bd2ec09c29
diff --git a/apps/web/src/components/files/PdfViewer.browser.test.tsx b/apps/web/src/components/files/PdfViewer.browser.test.tsxnew file mode 100644index 00000000000..95100d12d36--- /dev/null+++ b/apps/web/src/components/files/PdfViewer.browser.test.tsx@@ -0,0 +1,111 @@+import { expect, it, vi } from "vite-plus/test";+import { render } from "../../../test/render";+import "~/index.css";++// Vite serves the worker module through its transform with an inline source map (6.8 MB for+// a 1.3 MB file), which dominated this test under CPU contention. A blob of the raw file is the+// same code without the dev-server cost.+vi.mock(import("pdfjs-dist/build/pdf.worker.min.mjs?url"), async () => {+ const { default: source } = await import("pdfjs-dist/build/pdf.worker.min.mjs?raw");+ return {+ default: URL.createObjectURL(new Blob([source], { type: "text/javascript" })),+ };+});++import PdfViewer from "./PdfViewer";++// Page 1 is a short banner whose title is drawn in two runs with a font change, so pdf.js+// splits it into two text spans. Page 2 is a letter page rotated a quarter turn.+function twoPagePdf() {+ const pages = [+ {+ box: "0 0 612 140",+ rotate: 0,+ text: "BT /F1 24 Tf 30 70 Td (Quarter) Tj /F2 24 Tf (ly outlook) Tj ET",+ },+ { box: "0 0 612 792", rotate: 90, text: "BT /F1 24 Tf 30 700 Td (Budget and risks) Tj ET" },+ ];+ const objects = [+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Count 2 /Kids [3 0 R 5 0 R] >>",+ ...pages.flatMap(({ box, rotate, text }, index) => [+ `<< /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 >>`,+ `<< /Length ${text.length} >>\nstream\n${text}\nendstream`,+ ]),+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold >>",+ ];+ let source = "%PDF-1.4\n";+ const offsets: number[] = [];+ for (const [index, object] of objects.entries()) {+ offsets.push(source.length);+ source += `${index + 1} 0 obj\n${object}\nendobj\n`;+ }+ const xref = source.length;+ source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets+ .map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)+ .join("")}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;+ return new Blob([source], { type: "application/pdf" });+}++it("fits the width, then finds split and rotated text and jumps to its page", async () => {+ const url = URL.createObjectURL(twoPagePdf());+ try {+ const container = document.createElement("div");+ container.style.cssText = "display:flex;width:500px;height:600px";+ await using screen = await render(<PdfViewer src={url} title="Planning PDF" />, {+ container,+ });+ // The milestone is pdf.js booting its worker and parsing the document, not a frame count.+ await expect.element(screen.getByText("1 / 2 pages"), { timeout: 10_000 }).toBeVisible();+ const region = screen.container.querySelector<HTMLElement>('[role="region"]')!;+ // Fit width follows the measured viewport, which settles once the scrollbar appears.+ await vi.waitFor(() => {+ const canvas = region.querySelector('canvas[aria-label="Page 1"]')!;+ expect(canvas.getBoundingClientRect().width).toBe(region.clientWidth - 32);+ expect(region.scrollWidth).toBe(region.clientWidth);+ });++ const find = screen.getByRole("searchbox", { name: "Find in PDF" });+ await find.fill("quarterly outlook");+ await expect.element(screen.getByRole("status")).toHaveTextContent("1/1");+ await vi.waitFor(() =>+ expect(+ Array.from(region.querySelectorAll(".pdf-find-match"), (span) => span.textContent),+ ).toEqual(["Quarter", "ly outlook"]),+ );++ await find.fill("budget");+ await expect.element(screen.getByText("2 / 2 pages")).toBeVisible();+ await expect.element(screen.getByRole("status")).toHaveTextContent("1/1");+ const rotated = await vi.waitFor(() => {+ const span = Array.from(region.querySelectorAll("[data-pdf-text-layer] span")).find(+ (node) => node.textContent === "Budget and risks",+ );+ expect(span).toBeDefined();+ return span!;+ });+ // The rotated page's text runs top to bottom inside the page, so a selection lands on it.+ const textBounds = rotated.getBoundingClientRect();+ const pageBounds = rotated.closest("[data-pdf-text-layer]")!.getBoundingClientRect();+ expect(textBounds.height).toBeGreaterThan(textBounds.width);+ expect(textBounds.width).toBeGreaterThan(0);+ expect(textBounds.left).toBeGreaterThanOrEqual(pageBounds.left - 1);+ expect(textBounds.top).toBeGreaterThanOrEqual(pageBounds.top - 1);+ expect(textBounds.right).toBeLessThanOrEqual(pageBounds.right + 1);+ expect(textBounds.bottom).toBeLessThanOrEqual(pageBounds.bottom + 1);+ expect(getComputedStyle(rotated).userSelect).toBe("text");+ const range = document.createRange();+ range.selectNodeContents(rotated);+ const selection = window.getSelection()!;+ selection.removeAllRanges();+ selection.addRange(range);+ expect(selection.toString()).toBe("Budget and risks");+ selection.removeAllRanges();++ await find.fill(" ");+ await expect.element(screen.getByRole("status")).toHaveTextContent("0/0");+ } finally {+ URL.revokeObjectURL(url);+ }+});diff --git a/apps/web/src/components/files/PdfViewer.tsx b/apps/web/src/components/files/PdfViewer.tsxindex 70f005a532e..4a80112ddef 100644--- a/apps/web/src/components/files/PdfViewer.tsx+++ b/apps/web/src/components/files/PdfViewer.tsx@@ -13,6 +13,18 @@ import { observeResize } from "~/lib/observeResize";import { FileSurfaceAction, FileSurfaceFailure, FileSurfaceLoading } from "./fileSurfaceChrome";import { readBoundedDocument } from "./readBoundedDocument";import { openPdf } from "./pdfDocument";+import {+ currentPdfPage,+ pdfFindMatchRuns,+ pdfPageOffsets,+ pdfPageScrollTop,+ pdfPageText,+ pdfPageWidth,+ PDF_MAX_ZOOM,+ PDF_MIN_ZOOM,+ stepPdfZoom,+ visiblePdfPages,+} from "./pdfLayout";import "./pdfViewer.css";const MAX_PAGES = 2000;@@ -83,25 +95,12 @@ function PdfPage(props: {const node = text.current;if (!node) return;const mark = () => {- const runs = Array.from(node.querySelectorAll('span[role="presentation"], br')).map(- (element) => ({- element,- text: element.tagName === "BR" ? "\n" : (element.textContent ?? "").toLowerCase(),- }),+ const elements = Array.from(node.querySelectorAll('span[role="presentation"], br'));+ const hits = pdfFindMatchRuns(+ elements.map((element) => (element.tagName === "BR" ? "\n" : (element.textContent ?? ""))),+ props.query,);- const text = runs.map((run) => run.text).join("");- const query = props.query.toLowerCase();- let match = query.trim() ? text.indexOf(query) : -1;- let offset = 0;- for (const run of runs) {- while (match !== -1 && match + query.length <= offset)- match = text.indexOf(query, match + query.length);- run.element.classList.toggle(- "pdf-find-match",- match !== -1 && match < offset + run.text.length,- );- offset += run.text.length;- }+ elements.forEach((element, index) => element.classList.toggle("pdf-find-match", hits[index]));};mark();const observer = new MutationObserver(mark);@@ -181,24 +180,10 @@ export default function PdfViewer(props: { src: string; title: string }) {update();return observeResize(node, update);}, []);- const fitWidth = Math.max(1, viewport.width - 32);- const scale = zoom ?? fitWidth / pageWidth;- const width = zoom === null ? fitWidth : pageWidth * zoom;- const offsets = (() => {- const result = [16];- for (const ratio of ratios) result.push(result[result.length - 1]! + width * ratio + 16);- return result;- })();- const current = Math.max(- 0,- ratios.findIndex((_, index) => offsets[index + 1]! > scrollTop + 17),- );- const visible = ratios.flatMap((ratio, index) =>- offsets[index + 1]! >= scrollTop - viewport.height &&- offsets[index]! <= scrollTop + viewport.height * 2- ? [{ index, ratio }]- : [],- );+ const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom);+ const offsets = pdfPageOffsets(ratios, width);+ const current = currentPdfPage(offsets, ratios.length, scrollTop);+ const visible = visiblePdfPages(ratios, offsets, scrollTop, viewport.height);// Stable callbacks let page canvases survive scroll and find updates.const [onSize] = useState(() => (index: number, ratio: number) =>@@ -207,10 +192,10 @@ export default function PdfViewer(props: { src: string; title: string }) {),);const jumpToPage = useEffectEvent((index: number) => {- scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });+ scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });});const showPage = (index: number) => {- scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });+ scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });};const changeZoom = (value: number | null) => {zoomAnchor.current = {@@ -256,9 +241,7 @@ export default function PdfViewer(props: { src: string; title: string }) {const pageSize = page.getViewport({ scale: 1 });sizes.push(pageSize.height / pageSize.width);const content = await page.getTextContent();- const text = content.items- .map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : ""))- .join("");+ const text = pdfPageText(content.items);size += text.length;if (size > MAX_FIND_TEXT)throw new Error(@@ -305,8 +288,8 @@ export default function PdfViewer(props: { src: string; title: string }) {</FileSurfaceAction><FileSurfaceActionlabel="Zoom out"- disabled={scale <= 0.25}- onPress={() => changeZoom(Math.max(0.25, scale - 0.25))}+ disabled={scale <= PDF_MIN_ZOOM}+ onPress={() => changeZoom(stepPdfZoom(scale, -1))}><MinusIcon className="size-3.5" /></FileSurfaceAction>@@ -315,8 +298,8 @@ export default function PdfViewer(props: { src: string; title: string }) {</span><FileSurfaceActionlabel="Zoom in"- disabled={scale >= 3}- onPress={() => changeZoom(Math.min(3, scale + 0.25))}+ disabled={scale >= PDF_MAX_ZOOM}+ onPress={() => changeZoom(stepPdfZoom(scale, 1))}><PlusIcon className="size-3.5" /></FileSurfaceAction>diff --git a/apps/web/src/components/files/pdfLayout.test.ts b/apps/web/src/components/files/pdfLayout.test.tsnew file mode 100644index 00000000000..e0822a451e7--- /dev/null+++ b/apps/web/src/components/files/pdfLayout.test.ts@@ -0,0 +1,113 @@+import { describe, expect, it } from "vite-plus/test";+import {+ currentPdfPage,+ pdfFindMatchRuns,+ pdfPageOffsets,+ pdfPageScrollTop,+ pdfPageText,+ pdfPageWidth,+ stepPdfZoom,+ visiblePdfPages,+} from "./pdfLayout";++describe("pdfPageWidth", () => {+ it("fits the page to the viewport minus its gutters until a zoom is chosen", () => {+ expect(pdfPageWidth(500, 612, null)).toEqual({ width: 468, scale: 468 / 612 });+ expect(pdfPageWidth(500, 612, 1.5)).toEqual({ width: 918, scale: 1.5 });+ });++ it("never collapses below one pixel in a tiny viewport", () => {+ expect(pdfPageWidth(10, 612, null).width).toBe(1);+ });+});++describe("stepPdfZoom", () => {+ it("steps by a quarter and clamps to 25%..300%", () => {+ expect(stepPdfZoom(1, 1)).toBe(1.25);+ expect(stepPdfZoom(1, -1)).toBe(0.75);+ expect(stepPdfZoom(2.9, 1)).toBe(3);+ expect(stepPdfZoom(0.3, -1)).toBe(0.25);+ });++ it("starts from the fit-width scale when no zoom is set", () => {+ const { scale } = pdfPageWidth(500, 612, null);+ expect(stepPdfZoom(scale, 1)).toBeCloseTo(468 / 612 + 0.25);+ });+});++describe("mixed-height page layout", () => {+ // A short banner page, a letter page, then a page half as tall as it is wide.+ const ratios = [140 / 612, 792 / 612, 306 / 612];+ const width = 612;+ const offsets = pdfPageOffsets(ratios, width);++ it("stacks pages with a gap before, between, and after them", () => {+ expect(offsets).toEqual([16, 172, 980, 1302]);+ });++ it("reports the page whose bottom is past the top gutter as current", () => {+ expect(currentPdfPage(offsets, 3, 0)).toBe(0);+ expect(currentPdfPage(offsets, 3, 154)).toBe(0);+ expect(currentPdfPage(offsets, 3, 155)).toBe(1);+ expect(currentPdfPage(offsets, 3, 962)).toBe(1);+ expect(currentPdfPage(offsets, 3, 964)).toBe(2);+ });++ it("jumps to each page so that page becomes current", () => {+ for (const index of [0, 1, 2])+ expect(currentPdfPage(offsets, 3, pdfPageScrollTop(offsets, index))).toBe(index);+ expect(pdfPageScrollTop(offsets, 7)).toBe(0);+ });++ it("mounts pages within a viewport above and two below", () => {+ const indexes = (scrollTop: number, height: number) =>+ visiblePdfPages(ratios, offsets, scrollTop, height).map((page) => page.index);+ expect(indexes(0, 100)).toEqual([0, 1]);+ expect(indexes(1100, 100)).toEqual([2]);+ expect(indexes(1100, 900)).toEqual([1, 2]);+ expect(visiblePdfPages(ratios, offsets, 0, 100)[0]).toEqual({ index: 0, ratio: ratios[0] });+ });++ it("scales offsets with the page width when zoomed", () => {+ expect(pdfPageOffsets(ratios, width * 2)).toEqual([16, 312, 1912, 2540]);+ });+});++describe("pdfPageText", () => {+ it("joins text items, adds line ends, and skips marked content", () => {+ expect(+ pdfPageText([+ { str: "Quarter", hasEOL: false },+ { type: "beginMarkedContent" },+ { str: "ly outlook", hasEOL: true },+ { str: "Next", hasEOL: false },+ ]),+ ).toBe("Quarterly outlook\nNext");+ });+});++describe("pdfFindMatchRuns", () => {+ it("highlights every run a match spans when a word is split across spans", () => {+ expect(pdfFindMatchRuns(["Quarter", "ly outlook", " for Q3"], "quarterly OUTLOOK")).toEqual([+ true,+ true,+ false,+ ]);+ });++ it("highlights each separate match", () => {+ expect(pdfFindMatchRuns(["risk", " and ", "budget", " ", "Risk"], "risk")).toEqual([+ true,+ false,+ false,+ false,+ true,+ ]);+ });++ it("highlights nothing for a blank or missing query", () => {+ expect(pdfFindMatchRuns(["a b", "c"], " ")).toEqual([false, false]);+ expect(pdfFindMatchRuns(["a b", "c"], "")).toEqual([false, false]);+ expect(pdfFindMatchRuns(["a b", "c"], "zzz")).toEqual([false, false]);+ });+});diff --git a/apps/web/src/components/files/pdfLayout.ts b/apps/web/src/components/files/pdfLayout.tsnew file mode 100644index 00000000000..a539260f023--- /dev/null+++ b/apps/web/src/components/files/pdfLayout.ts@@ -0,0 +1,73 @@+const PDF_PAGE_GAP = 16;+export const PDF_MIN_ZOOM = 0.25;+export const PDF_MAX_ZOOM = 3;+const PDF_ZOOM_STEP = 0.25;++export function pdfPageWidth(viewportWidth: number, pageWidth: number, zoom: number | null) {+ const fitWidth = Math.max(1, viewportWidth - 2 * PDF_PAGE_GAP);+ return {+ scale: zoom ?? fitWidth / pageWidth,+ width: zoom === null ? fitWidth : pageWidth * zoom,+ };+}++export function stepPdfZoom(scale: number, direction: 1 | -1) {+ return direction > 0+ ? Math.min(PDF_MAX_ZOOM, scale + PDF_ZOOM_STEP)+ : Math.max(PDF_MIN_ZOOM, scale - PDF_ZOOM_STEP);+}++/** Top offset of each page plus the end of the last one; ratios are height / width. */+export function pdfPageOffsets(ratios: readonly number[], width: number) {+ const result = [PDF_PAGE_GAP];+ for (const ratio of ratios)+ result.push(result[result.length - 1]! + width * ratio + PDF_PAGE_GAP);+ return result;+}++export function currentPdfPage(offsets: readonly number[], pageCount: number, scrollTop: number) {+ for (let index = 0; index < pageCount; index++)+ if (offsets[index + 1]! > scrollTop + PDF_PAGE_GAP + 1) return index;+ return 0;+}++/** Pages within one viewport above and two below the visible area stay mounted. */+export function visiblePdfPages(+ ratios: readonly number[],+ offsets: readonly number[],+ scrollTop: number,+ viewportHeight: number,+) {+ return ratios.flatMap((ratio, index) =>+ offsets[index + 1]! >= scrollTop - viewportHeight &&+ offsets[index]! <= scrollTop + viewportHeight * 2+ ? [{ index, ratio }]+ : [],+ );+}++export function pdfPageScrollTop(offsets: readonly number[], index: number) {+ return Math.max(0, (offsets[index] ?? PDF_PAGE_GAP) - PDF_PAGE_GAP);+}++export function pdfPageText(+ items: readonly ({ str: string; hasEOL: boolean } | { type: string })[],+) {+ return items.map((item) => ("str" in item ? item.str + (item.hasEOL ? "\n" : "") : "")).join("");+}++/** Which text runs hold part of a case-insensitive match, when pdf.js splits words across spans. */+export function pdfFindMatchRuns(runs: readonly string[], query: string) {+ const texts = runs.map((run) => run.toLowerCase());+ const text = texts.join("");+ const needle = query.toLowerCase();+ let match = needle.trim() ? text.indexOf(needle) : -1;+ let offset = 0;+ return texts.map((run) => {+ while (match !== -1 && match + needle.length <= offset)+ match = text.indexOf(needle, match + needle.length);+ const hit = match !== -1 && match < offset + run.length;+ offset += run.length;+ return hit;+ });+}