Merge PR #2648: perf(web): optimize PDF page rendering

This commit is contained in:
Bingxi Zhao (Frank)
2026-11-14 23:01:19 +08:00
3 changed files with 484 additions and 67 deletions

View File

@@ -1,6 +1,6 @@
"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import { type CSSProperties, useEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { loadPdfjs, outputScale, type PdfDocument } from "@/lib/pdfjs-loader";
import type { AnnotationItem } from "@/lib/reading-api";
@@ -28,6 +28,27 @@ export interface PdfPageProps {
onAnnotationClick?: (annotation: AnnotationItem) => void;
}
/** Debounce before the single final repaint once a resize settles. */
const FINAL_REPAINT_DELAY_MS = 150;
/** Set on the text layer root by React rather than pdf.js. */
const REACT_OWNED_TEXT_STYLES = new Set(["--total-scale-factor", "pointer-events"]);
function copyPdfjsRootMetadata(source: HTMLElement, target: HTMLElement) {
for (let index = 0; index < source.style.length; index += 1) {
const name = source.style.item(index);
if (!name || REACT_OWNED_TEXT_STYLES.has(name)) continue;
target.style.setProperty(
name,
source.style.getPropertyValue(name),
source.style.getPropertyPriority(name),
);
}
for (const attribute of source.attributes) {
if (!attribute.name.startsWith("data-")) continue;
target.setAttribute(attribute.name, attribute.value);
}
}
/**
* One rendered PDF page: canvas, selectable text layer, annotation overlay.
*
@@ -61,122 +82,153 @@ export function PdfPage({
const textLayerRef = useRef<HTMLDivElement | null>(null);
// Whether this page was ever drawn, so only those are handed back.
const renderedRef = useRef(false);
const paintedWidthRef = useRef<number | null>(null);
const [ratio, setRatio] = useState<number | null>(null);
const [failed, setFailed] = useState(false);
const [baseWidth, setBaseWidth] = useState(0);
const [canvasFailed, setCanvasFailed] = useState(false);
const [textFailed, setTextFailed] = useState(false);
const height = Math.round(width * (ratio ?? fallbackRatio));
const textScale = baseWidth > 0 ? width / baseWidth : 1;
useEffect(() => {
if (!active || width <= 0) return;
let cancelled = false;
let renderTask: { cancel: () => void } | null = null;
let textLayer: { cancel: () => void } | null = null;
let cancelSchedule: (() => void) | null = null;
(async () => {
try {
const pdfjs = await loadPdfjs();
const page = await doc.getPage(locator);
renderedRef.current = true;
if (cancelled) return;
const base = page.getViewport({ scale: 1 });
if (base.width > 0) {
setRatio(base.height / base.width);
setBaseWidth(base.width);
}
const scale = width / base.width;
const viewport = page.getViewport({ scale });
// Canvas and text layer are rendered CONCURRENTLY and independently.
// The text layer needs only the viewport and the page's text content —
// it has no dependency on the bitmap being finished — so chaining it
// behind the canvas render promise only made selection and quote
// highlighting hostage to that promise settling. Some embedded browsers
// paint the page but never settle it, which produced a document that
// looked perfect and could not be selected at all.
const paintCanvas = async () => {
const canvas = canvasRef.current;
if (!canvas) return;
const dpr = outputScale();
canvas.width = Math.floor(viewport.width * dpr);
canvas.height = Math.floor(viewport.height * dpr);
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
// `canvas` only, never alongside `canvasContext`: pdf.js documents the
// context parameter as backwards-compatibility requiring
// `canvas: null`, and passing both is an unsupported combination.
renderTask = page.render({
canvas,
viewport,
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
});
await (renderTask as unknown as { promise: Promise<void> }).promise;
try {
const base = page.getViewport({ scale: 1 });
const viewport = page.getViewport({ scale: width / base.width });
canvas.width = Math.floor(viewport.width * dpr);
canvas.height = Math.floor(viewport.height * dpr);
canvas.style.width = `${Math.floor(viewport.width)}px`;
canvas.style.height = `${Math.floor(viewport.height)}px`;
// `canvas` only, never alongside `canvasContext`: pdf.js documents the
// context parameter as backwards-compatibility requiring
// `canvas: null`, and passing both is an unsupported combination.
renderTask = page.render({
canvas,
viewport,
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : undefined,
});
await (renderTask as unknown as { promise: Promise<void> }).promise;
if (cancelled) return;
paintedWidthRef.current = width;
setCanvasFailed(false);
} catch (error) {
// pdf.js throws RenderingCancelledException on a cancelled task —
// that is the normal path when scrolling, not a failure to report.
const name = (error as { name?: string } | null)?.name ?? "";
if (!cancelled && name !== "RenderingCancelledException") {
setCanvasFailed(true);
}
}
};
const buildTextLayer = async () => {
const textContent = await page.getTextContent();
// Re-checked after the await: two runs of this effect (a resize
// mid-render) would otherwise both reach `render()` on the same
// container and the loser would wipe the winner's spans.
if (cancelled) return;
const container = textLayerRef.current;
if (!container) return;
container.replaceChildren();
// pdf.js positions the spans with `--total-scale-factor`; without it
// every run collapses to the same tiny size and selection is useless.
container.style.setProperty("--total-scale-factor", String(scale));
const layer = new pdfjs.TextLayer({
textContentSource: textContent,
container,
viewport,
});
textLayer = layer as unknown as { cancel: () => void };
await layer.render();
};
// allSettled: a canvas failure must not cost the page its text layer,
// and vice versa. Failures are reported below only if BOTH sides failed,
// since either one alone still leaves a usable page.
const outcomes = await Promise.allSettled([
paintCanvas(),
buildTextLayer(),
]);
if (cancelled) return;
const fatal = outcomes.every(
(outcome) =>
outcome.status === "rejected" &&
(outcome.reason as { name?: string } | null)?.name !==
"RenderingCancelledException",
);
setFailed(fatal);
if (paintedWidthRef.current == null) {
void paintCanvas();
} else if (paintedWidthRef.current !== width) {
// Resize: keep the CSS-scaled bitmap until the width settles, then
// repaint once at the final size.
const handle = window.setTimeout(
() => void paintCanvas(),
FINAL_REPAINT_DELAY_MS,
);
cancelSchedule = () => window.clearTimeout(handle);
}
} catch (error) {
// pdf.js throws RenderingCancelledException on a cancelled task — that
// is the normal path when scrolling, not a failure to report.
const name = (error as { name?: string } | null)?.name ?? "";
if (!cancelled && name !== "RenderingCancelledException") {
setFailed(true);
setCanvasFailed(true);
setTextFailed(true);
}
}
})();
return () => {
cancelled = true;
cancelSchedule?.();
try {
renderTask?.cancel();
} catch {
// Already settled.
}
};
}, [active, doc, locator, width]);
// Build the text layer once per active period, independently of bitmap
// completion. Resizing changes only --total-scale-factor.
useEffect(() => {
const container = textLayerRef.current;
if (!active || !container) return;
let cancelled = false;
let textLayer: { cancel: () => void } | null = null;
container.replaceChildren();
const buildTextLayer = async () => {
try {
const [pdfjs, page] = await Promise.all([loadPdfjs(), doc.getPage(locator)]);
renderedRef.current = true;
if (cancelled) return;
const textContent = await page.getTextContent();
if (cancelled) return;
const staged = document.createElement("div");
staged.className = "textLayer";
staged.style.setProperty("--total-scale-factor", "1");
const layer = new pdfjs.TextLayer({
textContentSource: textContent,
container: staged,
viewport: page.getViewport({ scale: 1 }),
});
textLayer = layer;
await layer.render();
if (cancelled) return;
copyPdfjsRootMetadata(staged, container);
container.replaceChildren(...staged.childNodes);
setTextFailed(false);
} catch (error) {
const name = (error as { name?: string } | null)?.name ?? "";
if (!cancelled && name !== "AbortException") setTextFailed(true);
}
};
void buildTextLayer();
return () => {
cancelled = true;
try {
textLayer?.cancel();
} catch {
// Already settled.
}
};
}, [doc, locator, width, active]);
}, [active, doc, locator]);
// Free the canvas bitmap when the page scrolls far away. Without this a
// 600-page document accumulates every page it ever showed.
useEffect(() => {
if (active) return;
paintedWidthRef.current = null;
const canvas = canvasRef.current;
if (canvas) {
canvas.width = 0;
@@ -196,6 +248,7 @@ export function PdfPage({
useEffect(
() => () => {
paintedWidthRef.current = null;
if (renderedRef.current) releasePage(doc, locator);
},
[doc, locator],
@@ -218,7 +271,12 @@ export function PdfPage({
className="textLayer"
// The text layer is the selection surface; annotations sit above it but
// must not swallow drags, so only this layer takes pointer events.
style={{ pointerEvents: "auto" }}
style={
{
pointerEvents: "auto",
"--total-scale-factor": String(textScale),
} as CSSProperties
}
/>
<AnnotationLayer
annotations={pageAnnotations}
@@ -231,7 +289,7 @@ export function PdfPage({
<span className="font-mono text-[11px] text-black/25">{locator}</span>
</div>
)}
{failed && (
{canvasFailed && textFailed && (
<div className="absolute inset-0 flex items-center justify-center bg-white/90 px-6 text-center">
<span className="text-[12px] text-[var(--muted-foreground)]">
{t("This page could not be rendered.")}

View File

@@ -18,6 +18,7 @@ vi.mock("@/lib/pdfjs-loader", () => ({
destroy: async () => undefined,
promise: Promise.resolve({
getPage: async (locator: number) => ({
cleanup: () => undefined,
getViewport: ({ scale }: { scale: number }) => ({
width: 600 * scale,
height: 600 * (pdf.ratios.get(locator) ?? 1.414) * scale,

View File

@@ -0,0 +1,358 @@
import { act, render, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PdfPage } from "@/components/reading/PdfPage";
import type { PdfDocument } from "@/lib/pdfjs-loader";
const pdf = vi.hoisted(() => ({
cleanupCalls: 0,
getPageCalls: 0,
getTextContentCalls: 0,
outputScale: 1,
renderCalls: 0,
renderGate: null as Promise<void> | null,
renderWidths: [] as number[],
textLayerGate: null as Promise<void> | null,
textLayerConstructions: 0,
textLayerRenders: 0,
}));
vi.mock("@/lib/pdfjs-loader", () => ({
outputScale: () => pdf.outputScale,
loadPdfjs: async () => ({
TextLayer: class {
private readonly container: HTMLElement;
constructor({ container }: { container: HTMLElement }) {
pdf.textLayerConstructions += 1;
this.container = container;
this.container.style.width = "600px";
this.container.style.height = "800px";
this.container.style.setProperty("--min-font-size", "1");
this.container.dataset.mainRotation = "0";
}
async render() {
pdf.textLayerRenders += 1;
await pdf.textLayerGate;
const span = document.createElement("span");
span.textContent = "retained text";
this.container.append(span);
}
cancel() {}
},
}),
}));
vi.mock("react-i18next", () => ({
useTranslation: () => ({ t: (key: string) => key }),
}));
const page = {
cleanup: () => {
pdf.cleanupCalls += 1;
},
getTextContent: async () => {
pdf.getTextContentCalls += 1;
return { items: [], styles: {} };
},
getViewport: ({ scale }: { scale: number }) => ({
height: 800 * scale,
rotation: 0,
scale,
width: 600 * scale,
}),
render: ({ viewport }: { viewport: { width: number } }) => {
pdf.renderCalls += 1;
pdf.renderWidths.push(viewport.width);
return {
cancel: () => undefined,
promise: pdf.renderGate ?? Promise.resolve(),
};
},
};
const doc = {
getPage: async () => {
pdf.getPageCalls += 1;
return page;
},
} as unknown as PdfDocument;
function deferred<T>() {
let resolve!: (value: T) => void;
let reject!: (reason?: unknown) => void;
const promise = new Promise<T>((resolvePromise, rejectPromise) => {
resolve = resolvePromise;
reject = rejectPromise;
});
return { promise, reject, resolve };
}
function element({
document = doc,
active = true,
retain = true,
width = 600,
}: {
document?: PdfDocument;
active?: boolean;
retain?: boolean;
width?: number;
} = {}) {
return (
<PdfPage
doc={document}
locator={1}
width={width}
fallbackRatio={4 / 3}
active={active}
retain={retain}
annotations={[]}
/>
);
}
async function flushEffects() {
await act(async () => {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
});
}
beforeEach(() => {
pdf.cleanupCalls = 0;
pdf.getPageCalls = 0;
pdf.getTextContentCalls = 0;
pdf.outputScale = 1;
pdf.renderCalls = 0;
pdf.renderGate = null;
pdf.renderWidths = [];
pdf.textLayerGate = null;
pdf.textLayerConstructions = 0;
pdf.textLayerRenders = 0;
});
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe("PdfPage rendering lifecycle", () => {
it("builds selectable text without waiting for the visible bitmap", async () => {
const renderGate = deferred<void>();
pdf.renderGate = renderGate.promise;
const view = render(element());
await waitFor(() => expect(pdf.renderCalls).toBe(1));
await waitFor(() => expect(pdf.getTextContentCalls).toBe(1));
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
await act(async () => {
renderGate.resolve();
await renderGate.promise;
});
});
it("renders the first bitmap at the final device scale", async () => {
pdf.outputScale = 2;
const view = render(element());
await waitFor(() => expect(pdf.renderCalls).toBe(1));
expect(view.container.querySelector("canvas")!.width).toBe(1200);
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
await flushEffects();
expect(pdf.renderCalls).toBe(1);
});
it("reuses one text layer and its nodes across width changes", async () => {
const view = render(element());
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
const originalSpan = view.container.querySelector(".textLayer span");
view.rerender(element({ width: 700 }));
view.rerender(element({ width: 800 }));
await flushEffects();
expect(view.container.querySelector(".textLayer span")).toBe(originalSpan);
expect(pdf.getTextContentCalls).toBe(1);
expect(pdf.textLayerConstructions).toBe(1);
expect(pdf.textLayerRenders).toBe(1);
});
it("drops inactive text nodes and rebuilds them when the page returns", async () => {
const view = render(element());
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
const originalSpan = view.container.querySelector(".textLayer span");
view.rerender(element({ active: false, retain: true }));
expect(view.container.querySelector(".textLayer span")).toBeNull();
view.rerender(element({ active: true, retain: true }));
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
expect(view.container.querySelector(".textLayer span")).not.toBe(originalSpan);
expect(pdf.getTextContentCalls).toBe(2);
});
it("does not acquire an untouched page only because it is retained", async () => {
render(element({ active: false, retain: true }));
await flushEffects();
expect(pdf.getPageCalls).toBe(0);
});
it("repaints once at the final width after resize settles", async () => {
const view = render(element());
await waitFor(() => expect(pdf.renderCalls).toBe(1));
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
vi.useFakeTimers();
view.rerender(element({ width: 700 }));
view.rerender(element({ width: 800 }));
await flushEffects();
expect(pdf.renderCalls).toBe(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(149);
});
expect(pdf.renderCalls).toBe(1);
await act(async () => {
await vi.advanceTimersByTimeAsync(1);
});
expect(pdf.renderCalls).toBe(2);
expect(pdf.renderWidths).toEqual([600, 800]);
});
it("releases the previous page and repaints when the document changes at the same width", async () => {
const firstCleanup = vi.fn();
const secondCleanup = vi.fn();
const firstPage = { ...page, cleanup: firstCleanup };
const secondPage = { ...page, cleanup: secondCleanup };
const firstDocument = {
getPage: async () => firstPage,
} as unknown as PdfDocument;
const secondDocument = {
getPage: async () => secondPage,
} as unknown as PdfDocument;
const view = render(element({ document: firstDocument }));
await waitFor(() => expect(pdf.renderCalls).toBe(1));
view.rerender(element({ document: secondDocument }));
await waitFor(() => expect(pdf.renderCalls).toBe(2));
expect(firstCleanup).toHaveBeenCalledTimes(1);
expect(secondCleanup).not.toHaveBeenCalled();
});
it("contains synchronous page setup failures inside the page error state", async () => {
const brokenPage = {
...page,
getViewport: () => {
throw new Error("broken viewport");
},
};
const brokenDocument = {
getPage: async () => brokenPage,
} as unknown as PdfDocument;
const view = render(element({ document: brokenDocument }));
await waitFor(() =>
expect(
view.getByText("This page could not be rendered."),
).toBeInTheDocument(),
);
});
it("keeps usable text when canvas task creation fails synchronously", async () => {
const brokenCanvasPage = {
...page,
render: () => {
throw new Error("broken canvas");
},
};
const brokenDocument = {
getPage: async () => brokenCanvasPage,
} as unknown as PdfDocument;
const view = render(element({ document: brokenDocument }));
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
expect(
view.queryByText("This page could not be rendered."),
).not.toBeInTheDocument();
});
it("publishes the visible bitmap without waiting for deferred text", async () => {
const textGate = deferred<void>();
pdf.textLayerGate = textGate.promise;
const view = render(element());
await waitFor(() => expect(pdf.renderCalls).toBe(1));
await waitFor(() => expect(pdf.textLayerRenders).toBe(1));
expect(view.container.querySelector(".textLayer span")).toBeNull();
textGate.resolve();
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
});
it("releases canvas, text nodes, and page resources outside retention", async () => {
const view = render(element());
await waitFor(() =>
expect(view.container.querySelector(".textLayer span")).not.toBeNull(),
);
const textLayer = view.container.querySelector<HTMLElement>(".textLayer")!;
expect(textLayer.style.width).toBe("600px");
expect(textLayer.dataset.mainRotation).toBe("0");
view.rerender(element({ active: false, retain: false }));
await waitFor(() => expect(pdf.cleanupCalls).toBe(1));
expect(textLayer.childNodes).toHaveLength(0);
const canvas = view.container.querySelector("canvas")!;
expect(canvas.width).toBe(0);
expect(canvas.height).toBe(0);
});
it("cancels an in-flight canvas render when the page turns off", async () => {
const renderGate = deferred<void>();
const cancel = vi.fn();
const slowPage = {
...page,
render: () => ({ cancel, promise: renderGate.promise }),
};
const slowDocument = {
getPage: async () => slowPage,
} as unknown as PdfDocument;
const view = render(element({ document: slowDocument }));
await waitFor(() =>
expect(view.container.querySelector("canvas")!.width).toBe(600),
);
view.rerender(
element({ document: slowDocument, active: false, retain: true }),
);
await waitFor(() => expect(cancel).toHaveBeenCalledTimes(1));
renderGate.resolve();
});
});