Merge pull request #1688 from ZyPulse-zy/fix/pdf-resize-reading-position

fix(reading): preserve PDF reading position across resizes
This commit is contained in:
Bingxi Zhao
2026-10-04 14:19:54 +08:00
committed by GitHub
3 changed files with 547 additions and 2 deletions

View File

@@ -1,6 +1,13 @@
"use client";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { loadPdfjs, pdfjsWasmUrl, type PdfDocument } from "@/lib/pdfjs-loader";
@@ -91,6 +98,13 @@ export function PdfDocumentView({
message: string;
} | null>(null);
const [pageWidth, setPageWidth] = useState(0);
const committedWidthRef = useRef(0);
const resizeAnchorRef = useRef<{
doc: PdfDocument;
locator: string;
fraction: number;
viewportOffset: number;
} | null>(null);
const [visibleLocator, setVisibleLocator] = useState(1);
// Tagged with the jump's nonce for the same reason: a stale flash cannot
// outlive the request that produced it.
@@ -158,13 +172,61 @@ export function PdfDocumentView({
// -- width ---------------------------------------------------------------
useLayoutEffect(() => {
committedWidthRef.current = pageWidth;
const anchor = resizeAnchorRef.current;
resizeAnchorRef.current = null;
const root = scrollRef.current;
if (!root || !anchor || anchor.doc !== doc) return;
const page = root.querySelector<HTMLElement>(
`[data-reader-unit="${anchor.locator}"]`,
);
if (!page) return;
const rect = page.getBoundingClientRect();
// Restore after the new page heights commit, before paint or the visible
// locator effect can report the page at the old pixel scroll position.
root.scrollTop = Math.max(
0,
root.scrollTop +
rect.top -
root.getBoundingClientRect().top +
anchor.fraction * rect.height -
anchor.viewportOffset,
);
}, [doc, pageWidth]);
useEffect(() => {
const element = scrollRef.current;
if (!element) return;
const measure = () => {
// Leave room for the scrollbar gutter and the page's own margin.
const available = element.clientWidth - 48;
setPageWidth(Math.max(240, Math.min(1100, available)));
const nextWidth = Math.max(240, Math.min(1100, available));
if (nextWidth === committedWidthRef.current) {
// A resize can return to the committed width before React renders.
// Do not leave an unused anchor to override a later user scroll.
resizeAnchorRef.current = null;
} else if (doc && !resizeAnchorRef.current) {
const rootRect = element.getBoundingClientRect();
const pages =
element.querySelectorAll<HTMLElement>("[data-reader-unit]");
for (const page of pages) {
const rect = page.getBoundingClientRect();
if (rect.height <= 0 || rect.bottom <= rootRect.top) continue;
if (rect.top >= rootRect.bottom) break;
// The first visible page anchors the viewport's top edge. Keep the
// point in page coordinates, plus any padding/gap above that page.
// Coalesced notifications retain this anchor until the width commits.
resizeAnchorRef.current = {
doc,
locator: page.dataset.readerUnit!,
fraction: Math.max(0, (rootRect.top - rect.top) / rect.height),
viewportOffset: Math.max(0, rect.top - rootRect.top),
};
break;
}
}
setPageWidth(nextWidth);
};
measure();
const observer = new ResizeObserver(measure);

View File

@@ -0,0 +1,221 @@
import { expect, test, type Locator } from "@playwright/test";
import { jsPDF } from "jspdf";
const MATERIAL_ID = "dddddddddddddddd";
const WORKSPACE_ID = "pdf-resize-workspace";
const SESSION_ID = "pdf-resize-session";
const PAGE_COUNT = 160;
function pdfFixture(): Buffer {
const document = new jsPDF({ format: "a4" });
for (let locator = 1; locator <= PAGE_COUNT; locator += 1) {
if (locator > 1) document.addPage();
document.text(`Resize regression page ${locator}`, 20, 30);
}
return Buffer.from(document.output("arraybuffer"));
}
const pdfBytes = pdfFixture();
const material = {
material_id: MATERIAL_ID,
content_id: MATERIAL_ID,
filename: "resize-regression.pdf",
title: "PDF resize regression",
source_kind: "file",
source_url: "",
unit: "page",
unit_count: PAGE_COUNT,
mime: "application/pdf",
render_mode: "pdf",
has_raw_view: true,
status: "ready",
progress: 0,
cover_url: "",
error_code: "",
error_detail: "",
byte_size: pdfBytes.length,
size_bytes: pdfBytes.length,
char_count: 1000,
created_at: 1,
updated_at: 2,
last_opened_at: 2,
collections: [],
annotation_count: 0,
outline: [],
outline_text: "",
unit_refs: [],
};
test.beforeEach(async ({ page }) => {
await page.route("**/api/**", async (route) => {
const path = new URL(route.request().url()).pathname;
const json = (payload: unknown) => route.fulfill({ json: payload });
if (path === "/api/auth/status") {
return json({ enabled: false, authenticated: true });
}
if (path === "/api/settings/ui") return json({ language: "en" });
if (path === "/api/dashboard/suggestions") {
return json({ suggestions: [], stale: false });
}
if (path === "/api/settings/llm-options") {
return json({
active: { profile_id: "p", model_id: "m" },
options: [
{
profile_id: "p",
model_id: "m",
profile_name: "Profile",
model_name: "Model",
model: "model",
provider: "provider",
is_active_default: true,
},
],
});
}
if (path === "/api/partners" || path === "/api/partner-groups")
return json([]);
if (path === "/api/sessions") return json({ sessions: [] });
if (path === `/api/sessions/${SESSION_ID}`) {
return json({
id: SESSION_ID,
session_id: SESSION_ID,
title: material.title,
created_at: 1,
updated_at: 2,
status: "idle",
preferences: { capability: "immersive_reading" },
active_turns: [],
messages: [],
});
}
if (path === `/api/reading/workspaces/${WORKSPACE_ID}`) {
return json({
workspace: {
workspace_id: WORKSPACE_ID,
title: material.title,
description: "",
active_material_id: MATERIAL_ID,
created_at: 1,
updated_at: 2,
tabs: [
{
material,
tab_order: 0,
pinned: false,
opened: true,
added_at: 1,
},
],
},
sessions: [],
});
}
if (path === `/api/reading/workspaces/${WORKSPACE_ID}/sessions`) {
return json({ sessions: [] });
}
if (path === "/api/reading/supported-formats") {
return json({
extensions: [".pdf"],
max_bytes: 1024 * 1024,
raw_view_extensions: [".pdf"],
});
}
if (path === "/api/reading/extensions" || path.endsWith("/annotations"))
return json([]);
if (path === "/api/reading/materials") return json([material]);
if (path === `/api/reading/materials/${MATERIAL_ID}`) return json(material);
if (path === `/api/reading/materials/${MATERIAL_ID}/raw`) {
return route.fulfill({ contentType: "application/pdf", body: pdfBytes });
}
if (path.endsWith("/position"))
return json({ locator: 1, source_anchor: "" });
const unit = /\/units\/(\d+)$/.exec(path);
if (unit) {
return json({
locator: Number(unit[1]),
unit: "page",
text: `Resize regression page ${unit[1]}`,
});
}
return json({});
});
});
async function withinPage(root: Locator, locator: number): Promise<number> {
return root.evaluate((element, pageNumber) => {
const page = element.querySelector<HTMLElement>(
`[data-reader-unit="${pageNumber}"]`,
)!;
const pageRect = page.getBoundingClientRect();
return (
(element.getBoundingClientRect().top - pageRect.top) / pageRect.height
);
}, locator);
}
test("keeps the reading point when annotations toggle and the window resizes", async ({
page,
}) => {
await page.setViewportSize({ width: 1440, height: 900 });
await page.goto(`/learning/reading/${WORKSPACE_ID}/sessions/${SESSION_ID}`, {
waitUntil: "domcontentloaded",
});
const root = page
.locator(".dt-reader-scroll")
.filter({ has: page.locator('[data-reader-unit="99"]') });
await expect(root).toBeVisible();
await expect(root.locator('[data-reader-unit="1"] .textLayer')).toContainText(
"Resize regression page 1",
);
await page
.getByRole("button", { name: "Expand contents", exact: true })
.click();
await page.getByRole("tab", { name: "Annotations", exact: true }).click();
await root.evaluate((element) => {
const target = element.querySelector<HTMLElement>(
'[data-reader-unit="99"]',
)!;
const rect = target.getBoundingClientRect();
element.scrollTop +=
rect.top - element.getBoundingClientRect().top + rect.height * 0.3;
});
await expect(
root.locator('[data-reader-unit="99"] .textLayer'),
).toContainText("Resize regression page 99");
await expect.poll(() => withinPage(root, 99)).toBeCloseTo(0.3, 2);
for (const control of ["Close contents", "Expand contents"]) {
const beforeWidth = await root
.locator('[data-reader-unit="99"]')
.evaluate((element) => element.getBoundingClientRect().width);
await page.getByRole("button", { name: control, exact: true }).click();
await expect
.poll(() =>
root
.locator('[data-reader-unit="99"]')
.evaluate((element) => element.getBoundingClientRect().width),
)
.not.toBe(beforeWidth);
await expect.poll(() => withinPage(root, 99)).toBeCloseTo(0.3, 2);
}
for (const width of [1200, 1600, 1440]) {
const beforeWidth = await root
.locator('[data-reader-unit="99"]')
.evaluate((element) => element.getBoundingClientRect().width);
await page.setViewportSize({ width, height: 900 });
await expect
.poll(() =>
root
.locator('[data-reader-unit="99"]')
.evaluate((element) => element.getBoundingClientRect().width),
)
.not.toBe(beforeWidth);
await expect.poll(() => withinPage(root, 99)).toBeCloseTo(0.3, 2);
}
await expect(
root.locator('[data-reader-unit="99"] .textLayer'),
).toContainText("Resize regression page 99");
});

View File

@@ -0,0 +1,262 @@
import { act, fireEvent, render, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
PdfDocumentView,
type PdfDocumentViewProps,
} from "@/components/reading/PdfDocumentView";
const pdf = vi.hoisted(() => ({ ratios: new Map<number, number>() }));
// Keep both reader components real; only the PDF decoding/painting boundary is
// replaced. Page heights still come from PdfPage's measured aspect ratios.
vi.mock("@/lib/pdfjs-loader", () => ({
outputScale: () => 1,
pdfjsWasmUrl: () => "/pdfjs/wasm/",
loadPdfjs: async () => ({
getDocument: () => ({
destroy: async () => undefined,
promise: Promise.resolve({
getPage: async (locator: number) => ({
getViewport: ({ scale }: { scale: number }) => ({
width: 600 * scale,
height: 600 * (pdf.ratios.get(locator) ?? 1.414) * scale,
}),
render: () => ({
promise: Promise.resolve(),
cancel: () => undefined,
}),
getTextContent: async () => ({ items: [] }),
}),
}),
}),
TextLayer: class {
async render() {}
cancel() {}
},
}),
}));
vi.mock("react-i18next", () => {
const t = (key: string) => key;
return { useTranslation: () => ({ t }) };
});
const GAP = 16;
const ROOT_TOP = 80;
let containerWidth: number;
let viewportHeight: number;
let resizeCallbacks: Set<() => void>;
function pageTop(page: HTMLElement): number {
let top = GAP;
for (
let sibling = page.previousElementSibling;
sibling;
sibling = sibling.previousElementSibling
) {
top += Number.parseFloat((sibling as HTMLElement).style.height) + GAP;
}
return top;
}
function pageAt(root: HTMLElement, locator: number): HTMLElement {
const page = root.querySelector<HTMLElement>(
`[data-reader-unit="${locator}"]`,
);
if (!page) throw new Error(`Page ${locator} is missing`);
return page;
}
function positionWithin(root: HTMLElement, locator: number): number {
const page = pageAt(root, locator);
return (
(root.scrollTop - pageTop(page)) / Number.parseFloat(page.style.height)
);
}
async function resize(width: number): Promise<void> {
await act(async () => {
containerWidth = width;
for (const notify of resizeCallbacks) notify();
});
}
async function openReader(overrides: Partial<PdfDocumentViewProps> = {}) {
const onVisibleLocatorChange = vi.fn();
const props: PdfDocumentViewProps = {
materialId: "resize-pdf",
unitCount: 160,
annotations: [],
jump: null,
onSelection: vi.fn(),
onVisibleLocatorChange,
...overrides,
};
const view = render(<PdfDocumentView {...props} />);
const root = view.container.querySelector<HTMLElement>(".dt-reader-scroll")!;
let scrollTop = 0;
// jsdom supplies no layout. Model the browser's stacking and scroll clamp
// from the real page elements/styles, without stubbing either component.
Object.defineProperty(root, "scrollTop", {
configurable: true,
get: () => scrollTop,
set: (value: number) => {
const pages = root.querySelectorAll<HTMLElement>("[data-reader-unit]");
const last = pages[pages.length - 1];
const contentHeight = last
? pageTop(last) + Number.parseFloat(last.style.height) + GAP
: viewportHeight;
scrollTop = Math.max(0, Math.min(value, contentHeight - viewportHeight));
},
});
await waitFor(() => expect(pageAt(root, 1).style.width).toBe("600px"));
await act(async () => {});
return { ...view, root, props, onVisibleLocatorChange };
}
async function scrollTo(root: HTMLElement, locator: number, fraction = 0.3) {
const page = pageAt(root, locator);
root.scrollTop =
pageTop(page) + Number.parseFloat(page.style.height) * fraction;
await act(async () => {
fireEvent.scroll(root);
await new Promise<void>((resolve) =>
window.requestAnimationFrame(() => resolve()),
);
});
}
beforeEach(() => {
containerWidth = 648;
viewportHeight = 500;
resizeCallbacks = new Set();
pdf.ratios.clear();
vi.stubGlobal(
"ResizeObserver",
class {
constructor(private readonly callback: () => void) {}
observe() {
resizeCallbacks.add(this.callback);
}
disconnect() {
resizeCallbacks.delete(this.callback);
}
},
);
vi.spyOn(HTMLElement.prototype, "clientWidth", "get").mockImplementation(
function (this: HTMLElement) {
return this.classList.contains("dt-reader-scroll") ? containerWidth : 0;
},
);
vi.spyOn(HTMLElement.prototype, "getBoundingClientRect").mockImplementation(
function (this: HTMLElement) {
if (this.classList.contains("dt-reader-scroll")) {
return new DOMRect(120, ROOT_TOP, containerWidth, viewportHeight);
}
if (this.dataset.readerUnit) {
const root = this.closest<HTMLElement>(".dt-reader-scroll")!;
return new DOMRect(
144,
ROOT_TOP + pageTop(this) - root.scrollTop,
Number.parseFloat(this.style.width),
Number.parseFloat(this.style.height),
);
}
return new DOMRect();
},
);
});
afterEach(() => vi.unstubAllGlobals());
describe("PDF reading position during layout changes", () => {
it("keeps page 99 and its within-page position when the sidebar closes and reopens", async () => {
const { root, onVisibleLocatorChange } = await openReader();
await scrollTo(root, 99);
expect(onVisibleLocatorChange).toHaveBeenLastCalledWith(99);
onVisibleLocatorChange.mockClear();
await resize(1098);
expect(pageAt(root, 99).style.width).toBe("1050px");
expect(positionWithin(root, 99)).toBeCloseTo(0.3, 5);
await resize(648);
expect(positionWithin(root, 99)).toBeCloseTo(0.3, 5);
expect(
onVisibleLocatorChange.mock.calls.every(([locator]) => locator === 99),
).toBe(true);
});
it("uses the latest user scroll as the anchor during successive window resizes", async () => {
const { root } = await openReader();
await scrollTo(root, 99, 0.4);
for (const width of [848, 1048, 748, 548, 648]) {
await resize(width);
expect(positionWithin(root, 99)).toBeCloseTo(0.4, 5);
}
await scrollTo(root, 120, 0.25);
await resize(998);
expect(positionWithin(root, 120)).toBeCloseTo(0.25, 5);
});
it("preserves the anchor across coalesced resize notifications and a cancelled resize", async () => {
const { root } = await openReader();
await scrollTo(root, 99);
await act(async () => {
containerWidth = 1098;
for (const notify of resizeCallbacks) notify();
containerWidth = 848;
for (const notify of resizeCallbacks) notify();
});
expect(positionWithin(root, 99)).toBeCloseTo(0.3, 5);
await act(async () => {
containerWidth = 1098;
for (const notify of resizeCallbacks) notify();
containerWidth = 848;
for (const notify of resizeCallbacks) notify();
});
await scrollTo(root, 120, 0.2);
await resize(648);
expect(positionWithin(root, 120)).toBeCloseTo(0.2, 5);
});
it("preserves page-top padding and handles mixed measured page heights", async () => {
pdf.ratios.set(2, 0.75);
pdf.ratios.set(99, 1.8);
const { root } = await openReader();
expect(root.scrollTop).toBe(0);
await resize(1098);
expect(root.scrollTop).toBe(0);
await scrollTo(root, 99);
await waitFor(() => expect(pageAt(root, 99).style.height).toBe("1890px"));
await scrollTo(root, 99, 0.2);
await resize(648);
expect(positionWithin(root, 99)).toBeCloseTo(0.2, 5);
});
it("allows an explicit page jump after a resize and anchors subsequent resizes there", async () => {
const view = await openReader();
await scrollTo(view.root, 99);
await resize(1098);
view.rerender(
<PdfDocumentView {...view.props} jump={{ locator: 120, nonce: 1 }} />,
);
await waitFor(() =>
expect(pageAt(view.root, 120).getBoundingClientRect().top).toBe(
ROOT_TOP + GAP,
),
);
await resize(648);
expect(pageAt(view.root, 120).getBoundingClientRect().top).toBe(
ROOT_TOP + GAP,
);
});
it("clamps restoration at the document end", async () => {
const { root } = await openReader();
await scrollTo(root, 160, 0.6);
await resize(348);
const lastRect = pageAt(root, 160).getBoundingClientRect();
expect(lastRect.top).toBeLessThan(ROOT_TOP + viewportHeight);
expect(lastRect.bottom + GAP).toBeCloseTo(ROOT_TOP + viewportHeight, 5);
});
});