Skip to content

Commit 4c1ada4

Browse files
committed
fix(web): preserve PDF scroll and zoom across autoreloads
1 parent 884c699 commit 4c1ada4

3 files changed

Lines changed: 123 additions & 30 deletions

File tree

‎apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx‎

Lines changed: 66 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2337,6 +2337,7 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre
23372337
function planningPdf(
23382338
titles = ["Quarterly outlook", "Delivery milestones", "Budget and risks"],
23392339
firstHeight = 140,
2340+
pageHeight = 792,
23402341
) {
23412342
const objects = [
23422343
"<< /Type /Catalog /Pages 2 0 R >>",
@@ -2346,7 +2347,7 @@ function planningPdf(
23462347
for (const [index, title] of titles.entries()) {
23472348
const text = `/GS1 gs BT /F1 24 Tf 30 ${index === 0 ? 70 : 700} Td ${index === 0 ? "(Quarter) Tj /F2 24 Tf (ly outlook) Tj" : `(${title}) Tj`} ET`;
23482349
objects.push(
2349-
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? firstHeight : 792}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 ${font} 0 R /F2 ${font + 1} 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,
2350+
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? firstHeight : pageHeight}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 ${font} 0 R /F2 ${font + 1} 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,
23502351
`<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
23512352
);
23522353
}
@@ -2366,7 +2367,7 @@ function planningPdf(
23662367
return new Blob([source], { type: "application/pdf" });
23672368
}
23682369

2369-
it("keeps the workspace PDF page after reloads and clamps it when the document gets shorter", async () => {
2370+
it("keeps workspace PDF scroll and zoom after reloads and clamps them when the document shrinks", async () => {
23702371
assetUrlState.mockReset();
23712372
const { WorkspaceBrowserPreview } = await import("./FilePreviewPanel");
23722373
using _native = vi.spyOn(navigator, "pdfViewerEnabled", "get").mockReturnValue(false);
@@ -2376,13 +2377,18 @@ it("keeps the workspace PDF page after reloads and clamps it when the document g
23762377
planningPdf(["Quarterly outlook", "Delivery milestones", "Updated budget"], 500),
23772378
);
23782379
const shorter = URL.createObjectURL(planningPdf(["Quarterly outlook", "Updated milestones"]));
2380+
const shrunk = URL.createObjectURL(
2381+
planningPdf(["Quarterly outlook", "Small page", "Budget and risks"], 500, 200),
2382+
);
23792383
const single = URL.createObjectURL(planningPdf(["Quarterly outlook"]));
23802384
return {
23812385
original,
23822386
updated,
23832387
shorter,
2388+
shrunk,
23842389
single,
2385-
[Symbol.dispose]: () => [original, updated, shorter, single].forEach(URL.revokeObjectURL),
2390+
[Symbol.dispose]: () =>
2391+
[original, updated, shorter, shrunk, single].forEach(URL.revokeObjectURL),
23862392
};
23872393
})();
23882394
const preview = (src: string, mutation: string, path = "/repo/planning.pdf") => {
@@ -2413,12 +2419,53 @@ it("keeps the workspace PDF page after reloads and clamps it when the document g
24132419
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
24142420
await screen.getByRole("button", { name: "Next page", exact: true }).click();
24152421
await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2422+
for (let index = 0; index < 4; index++) {
2423+
await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
2424+
}
2425+
const region = () => screen.container.querySelector<HTMLElement>('[role="region"]')!;
2426+
const canvas = (page: number) =>
2427+
region().querySelector<HTMLCanvasElement>(`canvas[aria-label="Page ${page}"]`)!;
2428+
const offset = (page: number) =>
2429+
region().getBoundingClientRect().top - canvas(page).getBoundingClientRect().top;
2430+
const scrollTo = (options: ScrollToOptions) =>
2431+
act(async () => {
2432+
const node = region();
2433+
const scrolled = new Promise<void>((resolve) =>
2434+
node.addEventListener("scroll", () => resolve(), { once: true }),
2435+
);
2436+
node.scrollTo(options);
2437+
await scrolled;
2438+
});
2439+
const zoom = screen.container.textContent!.match(/\d+%/)![0];
2440+
const top = region().scrollTop;
2441+
await scrollTo({ top: top + 100, left: 80 });
2442+
await vi.waitFor(() => {
2443+
expect(region().scrollTop).toBeCloseTo(top + 100, 0);
2444+
expect(region().scrollLeft).toBe(80);
2445+
});
2446+
const savedOffset = offset(3);
24162447
await screen.rerender(preview(urls.updated, "two"));
24172448
await vi.waitFor(() => {
24182449
expect(screen.container.textContent).toContain("3 / 3 pages");
24192450
expect(screen.container.querySelector('[role="region"]')?.textContent).toContain(
24202451
"Updated budget",
24212452
);
2453+
expect(screen.container.textContent).toContain(zoom);
2454+
expect(region().scrollLeft).toBe(80);
2455+
expect(offset(3)).toBeCloseTo(savedOffset, 0);
2456+
});
2457+
await screen.getByRole("button", { name: "Previous page", exact: true }).click();
2458+
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
2459+
const secondPageTop = region().scrollTop;
2460+
await scrollTo({ top: secondPageTop + 600 });
2461+
await vi.waitFor(() => expect(region().scrollTop).toBeCloseTo(secondPageTop + 600, 0));
2462+
await screen.rerender(preview(urls.shrunk, "smaller-page"));
2463+
await vi.waitFor(() => {
2464+
expect(screen.container.textContent).toContain("2 / 3 pages");
2465+
expect(screen.container.textContent).toContain(zoom);
2466+
expect(region().scrollLeft).toBe(80);
2467+
expect(offset(2)).toBeGreaterThan(0);
2468+
expect(offset(2)).toBeLessThan(canvas(2).getBoundingClientRect().height);
24222469
});
24232470
await screen.rerender(preview(urls.shorter, "three"));
24242471
await vi.waitFor(() => {
@@ -2431,10 +2478,25 @@ it("keeps the workspace PDF page after reloads and clamps it when the document g
24312478
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 1 pages"));
24322479
await screen.rerender(preview(urls.original, "five"));
24332480
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
2481+
await screen.getByRole("button", { name: "Fit width", exact: true }).click();
2482+
await screen.rerender(preview(urls.original, "six"));
2483+
await vi.waitFor(() => {
2484+
expect(screen.container.textContent).toContain("Fit width");
2485+
expect(region().scrollLeft).toBe(0);
2486+
});
2487+
await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
2488+
const firstPageZoom = screen.container.textContent!.match(/\d+%/)![0];
2489+
await screen.rerender(preview(urls.original, "seven"));
2490+
await vi.waitFor(() => expect(screen.container.textContent).toContain(firstPageZoom));
24342491
await screen.getByRole("button", { name: "Next page", exact: true }).click();
24352492
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
24362493
await screen.rerender(preview(urls.original, "one", "/repo/another.pdf"));
2437-
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
2494+
await vi.waitFor(() => {
2495+
expect(screen.container.textContent).toContain("1 / 3 pages");
2496+
expect(screen.container.textContent).toContain("Fit width");
2497+
expect(region().scrollTop).toBe(0);
2498+
expect(region().scrollLeft).toBe(0);
2499+
});
24382500
});
24392501

24402502
it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {

‎apps/web/src/components/files/BrowserDocumentFrame.tsx‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
} from "react";
3434
import { isElectron } from "~/env";
3535
import { FileSurfaceLoading } from "./fileSurfaceChrome";
36+
import type { PdfViewState } from "./PdfViewer";
3637

3738
import { useOpenLink } from "~/browser/useOpenLink";
3839
import { ExpandedImageDialog } from "~/components/chat/ExpandedImageDialog";
@@ -75,17 +76,17 @@ const PdfViewer = lazy(() => import("./PdfViewer"));
7576

7677
/**
7778
* documentKey includes the file's revision and remounts the viewer when it changes.
78-
* A stable documentId keeps this component mounted to track the current page number across reloads.
79+
* A stable documentId keeps this component mounted to track the page, scroll, and zoom across reloads.
7980
*/
8081
function PdfDocument(props: { src: string; title: string; documentKey: string }) {
81-
const [page, setPage] = useState(0);
82+
const [view, setView] = useState<PdfViewState>({ page: 0, offset: 0, zoom: null, left: 0 });
8283
return (
8384
<PdfDocumentRevision
8485
key={props.documentKey}
8586
src={props.src}
8687
title={props.title}
87-
initialPage={page}
88-
onPageChange={setPage}
88+
initialView={view}
89+
onViewChange={setView}
8990
/>
9091
);
9192
}
@@ -97,8 +98,8 @@ function PdfDocument(props: { src: string; title: string; documentKey: string })
9798
function PdfDocumentRevision(props: {
9899
src: string;
99100
title: string;
100-
initialPage: number;
101-
onPageChange: (page: number) => void;
101+
initialView: PdfViewState;
102+
onViewChange: (view: PdfViewState) => void;
102103
}) {
103104
const [src] = useState(props.src);
104105
// The Electron shell does not enable PDF plugins. WebKit embeds on iOS
@@ -120,8 +121,8 @@ function PdfDocumentRevision(props: {
120121
<PdfViewer
121122
src={src}
122123
title={props.title}
123-
initialPage={props.initialPage}
124-
onPageChange={props.onPageChange}
124+
initialView={props.initialView}
125+
onViewChange={props.onViewChange}
125126
/>
126127
</Suspense>
127128
);
@@ -139,7 +140,7 @@ export function BrowserDocumentFrame(props: {
139140
readonly threadRef?: ScopedThreadRef | undefined;
140141
/** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
141142
readonly documentKey?: string | undefined;
142-
/** Resource identity without its revision, so PDF reloads can retain the page. */
143+
/** Resource identity without its revision, so PDF reloads can retain the reading position. */
143144
readonly documentId?: string | undefined;
144145
}) {
145146
const key = props.documentKey ?? props.src;

‎apps/web/src/components/files/PdfViewer.tsx‎

Lines changed: 47 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,13 @@ import "./pdfViewer.css";
1818
const MAX_PAGES = 2000;
1919
const MAX_FIND_TEXT = 4 * 1024 * 1024;
2020

21+
export type PdfViewState = {
22+
page: number;
23+
offset: number;
24+
zoom: number | null;
25+
left: number;
26+
};
27+
2128
function PdfPage(props: {
2229
document: PDFDocumentProxy;
2330
index: number;
@@ -119,14 +126,17 @@ function PdfPage(props: {
119126
export default function PdfViewer(props: {
120127
src: string;
121128
title: string;
122-
initialPage?: number;
123-
onPageChange?: (page: number) => void;
129+
initialView?: PdfViewState;
130+
onViewChange?: (view: PdfViewState) => void;
124131
}) {
132+
const [initialView] = useState<PdfViewState>(
133+
() => props.initialView ?? { page: 0, offset: 0, zoom: null, left: 0 },
134+
);
125135
const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
126136
const [error, setError] = useState<string | null>(null);
127137
const [revision, setRevision] = useState(0);
128138
const [ratios, setRatios] = useState<number[]>([]);
129-
const [zoom, setZoom] = useState<number | null>(null);
139+
const [zoom, setZoom] = useState(initialView.zoom);
130140
const [pageWidth, setPageWidth] = useState(612);
131141
const [viewport, setViewport] = useState({ width: 600, height: 800 });
132142
const [scrollTop, setScrollTop] = useState(0);
@@ -138,7 +148,7 @@ export default function PdfViewer(props: {
138148
const scroll = useRef<HTMLDivElement>(null);
139149
const find = useRef<HTMLInputElement>(null);
140150
const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
141-
const [initialPage] = useState(props.initialPage ?? 0);
151+
const initialPage = initialView.page;
142152
// oxlint-disable-next-line t3code/react-effect-budget -- Own the PDF fetch, load timeout, and pdf.js document task across source changes, retries, and unmounts.
143153
useEffect(() => {
144154
const controller = new AbortController();
@@ -163,7 +173,7 @@ export default function PdfViewer(props: {
163173
throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");
164174
const first = (await document.getPage(1)).getViewport({ scale: 1 });
165175
const sizes = await Promise.all(
166-
Array.from({ length: Math.min(initialPage, document.numPages) }, async (_, index) => {
176+
Array.from({ length: Math.min(initialPage + 1, document.numPages) }, async (_, index) => {
167177
const size = (await document.getPage(index + 1)).getViewport({ scale: 1 });
168178
return size.height / size.width;
169179
}),
@@ -228,14 +238,30 @@ export default function PdfViewer(props: {
228238
const jumpToPage = useEffectEvent((index: number) => {
229239
scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
230240
});
231-
const { onPageChange } = props;
232-
// oxlint-disable-next-line t3code/react-effect-budget -- Restore the saved PDF page after the loaded document's page layout commits.
233-
useLayoutEffect(() => {
234-
if (!pdf) return;
241+
const saveView = (node: HTMLDivElement) => {
242+
const page = pageAtOffset(node.scrollTop);
243+
props.onViewChange?.({
244+
page,
245+
offset: Math.max(0, node.scrollTop - (offsets[page]! - 16)),
246+
zoom,
247+
left: node.scrollLeft,
248+
});
249+
};
250+
const restoreView = useEffectEvent(() => {
251+
const node = scroll.current;
252+
if (!pdf || !node) return;
235253
const page = Math.min(initialPage, pdf.numPages - 1);
236-
jumpToPage(page);
237-
onPageChange?.(page);
238-
}, [pdf, initialPage, onPageChange]);
254+
node.scrollTo({
255+
top:
256+
offsets[page]! - 16 + Math.min(initialView.offset, Math.max(0, width * ratios[page]! - 1)),
257+
left: initialView.left,
258+
});
259+
saveView(node);
260+
});
261+
// oxlint-disable-next-line t3code/react-effect-budget -- Restore the saved PDF scroll position after the loaded document's page layout commits.
262+
useLayoutEffect(() => {
263+
if (pdf) restoreView();
264+
}, [pdf]);
239265
const showPage = (index: number) => {
240266
scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
241267
};
@@ -251,10 +277,14 @@ export default function PdfViewer(props: {
251277
useLayoutEffect(() => {
252278
const anchor = zoomAnchor.current;
253279
zoomAnchor.current = null;
254-
if (!anchor || anchor.width === width) return;
255-
scroll.current?.scrollTo({
256-
top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
257-
});
280+
const node = scroll.current;
281+
if (!anchor || !node) return;
282+
if (anchor.width !== width) {
283+
node.scrollTo({
284+
top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
285+
});
286+
}
287+
saveView(node);
258288
});
259289
// oxlint-disable-next-line t3code/react-effect-budget -- Scroll to the first asynchronous search result after its measured page offsets have committed.
260290
useLayoutEffect(() => {
@@ -401,7 +431,7 @@ export default function PdfViewer(props: {
401431
onScroll={(event) => {
402432
const top = event.currentTarget.scrollTop;
403433
setScrollTop(top);
404-
props.onPageChange?.(pageAtOffset(top));
434+
saveView(event.currentTarget);
405435
}}
406436
onKeyDown={(event) => {
407437
if ((event.ctrlKey || event.metaKey) && event.key === "f") {

0 commit comments

Comments
 (0)