Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions apps/web/src/components/files/PdfViewer.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ vi.mock(import("pdfjs-dist/build/pdf.worker.min.mjs?url"), async () => {

// Holds one page's Find text until the test opens it, so a scan can be observed mid-flight.
const findGate = vi.hoisted(() => ({ page: 0, open: () => {}, opened: Promise.resolve() }));
// Every page the viewer asks pdf.js for, in order.
const pageLoads = vi.hoisted((): number[] => []);
function setup(page: number) {
pageLoads.length = 0;
findGate.page = page;
findGate.opened = new Promise((resolve) => (findGate.open = resolve));
}
Expand All @@ -27,6 +30,7 @@ vi.mock(import("./pdfDocument"), async (importOriginal) => {
const promise = task.promise.then((document) => {
const getPage = document.getPage.bind(document);
document.getPage = async (number) => {
pageLoads.push(number);
const page = await getPage(number);
const getTextContent = page.getTextContent.bind(page);
page.getTextContent = async (params) => {
Expand Down Expand Up @@ -208,6 +212,37 @@ it("keeps the page in view, with its painted canvas, when the pane narrows", asy
}
});

it("paints a page that mounts during a resize only after the width settles", async () => {
setup(0);
const page = { box: "0 0 612 792", rotate: 0, text: "BT /F1 24 Tf 30 700 Td (Text) Tj ET" };
const url = URL.createObjectURL(testPdf(Array.from({ length: 6 }, () => page)));
try {
const container = document.createElement("div");
container.style.cssText = "display:flex;width:500px;height:600px";
await using screen = await render(<PdfViewer src={url} title="Dragged PDF" />, { container });
await expect.element(screen.getByText("1 / 6 pages"), { timeout: 10_000 }).toBeVisible();
const region = screen.container.querySelector<HTMLElement>('[role="region"]')!;
await vi.waitFor(() => expect(region.querySelector("canvas")!.width).toBeGreaterThan(300));
expect(region.querySelector('canvas[aria-label="Page 4"]')).toBeNull();

// Narrower pages bring page 4 into the mounted range in the same commit as the resize.
const resized = new Promise((resolve) => new ResizeObserver(resolve).observe(container));
container.style.width = "400px";
await resized;
const canvas = region.querySelector<HTMLCanvasElement>('canvas[aria-label="Page 4"]')!;
expect(canvas).not.toBeNull();
expect(pageLoads).not.toContain(4);

await vi.waitFor(() =>
expect(canvas.width).toBe(
Math.ceil((region.clientWidth - 32) * Math.min(2, window.devicePixelRatio)),
),
);
} finally {
URL.revokeObjectURL(url);
}
});

it("jumps to the first hit while still counting and keeps later manual navigation", async () => {
setup(4);
const page = (text: string) => ({
Expand Down
19 changes: 14 additions & 5 deletions apps/web/src/components/files/PdfViewer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,14 @@ function PdfPage(props: {
onError: (error: string) => void;
onPageLink: (index: number) => void;
onOpenLink: ((url: string, event: MouseEvent) => void) | undefined;
resizedAt: { readonly current: number };
}) {
const gt = useGT();
const [links, setLinks] = useState<readonly PdfLink[]>([]);
const canvas = useRef<HTMLCanvasElement>(null);
const text = useRef<HTMLDivElement>(null);
const painted = useRef<PDFDocumentProxy>(null);
const { document: pdf, index, width, onSize, onError } = props;
const { document: pdf, index, width, onSize, onError, resizedAt } = props;
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Render the PDF page canvas and text layer, cancelling tasks and releasing pdf.js page resources on cleanup.
useEffect(() => {
let cancelled = false;
Expand All @@ -90,8 +91,9 @@ function PdfPage(props: {
let loadedPage: Awaited<ReturnType<PDFDocumentProxy["getPage"]>> | undefined;
let timer: ReturnType<typeof setTimeout> | undefined;
void (async () => {
// A drag changes the width every frame. CSS scales the painted page until the width settles.
if (painted.current === pdf)
// A drag changes the width every frame. CSS scales the painted page until the width settles,
// and a page that mounts during the drag waits too.
if (painted.current === pdf || performance.now() - resizedAt.current < 150)
await new Promise((resolve) => (timer = setTimeout(resolve, 150)));
const page = await pdf.getPage(index + 1);
loadedPage = page;
Expand Down Expand Up @@ -169,7 +171,7 @@ function PdfPage(props: {
// Release operator lists when virtual pages leave the viewport.
void Promise.allSettled([paint?.promise]).then(() => loadedPage?.cleanup());
};
}, [pdf, index, width, onSize, onError]);
}, [pdf, index, width, onSize, onError, resizedAt]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Highlight pdf.js-owned text nodes and observe asynchronous text layer mutations for the current search query.
useEffect(() => {
const node = text.current;
Expand Down Expand Up @@ -273,6 +275,7 @@ export default function PdfViewer(props: {
const scroll = useRef<HTMLDivElement>(null);
const find = useRef<HTMLInputElement>(null);
const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
const resizedAt = useRef(-Infinity);
const initialPage = initialView.page;
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Own the PDF fetch, load timeout, and pdf.js document task across source changes, retries, and unmounts.
useEffect(() => {
Expand Down Expand Up @@ -335,7 +338,12 @@ export default function PdfViewer(props: {
if (!node) return;
const update = () => setViewport({ width: node.clientWidth, height: node.clientHeight });
update();
return observeResize(node, update);
let measured = node.clientWidth;
return observeResize(node, () => {
if (measured !== node.clientWidth) resizedAt.current = performance.now();
measured = node.clientWidth;
update();
});
}, []);
const { scale, width } = pdfPageWidth(viewport.width, pageWidth, zoom);
const offsets = pdfPageOffsets(ratios, width);
Expand Down Expand Up @@ -618,6 +626,7 @@ export default function PdfViewer(props: {
onError={setError}
onPageLink={showPage}
onOpenLink={props.onOpenLink}
resizedAt={resizedAt}
/>
</div>
))}
Expand Down
Loading