Skip to content

Commit 0a6c5ee

Browse files
committed
fix(web): preserve PDF page across autoreloads
1 parent 3f94487 commit 0a6c5ee

4 files changed

Lines changed: 157 additions & 22 deletions

File tree

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

Lines changed: 76 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2334,19 +2334,19 @@ it("toggles a Mermaid attachment between diagram and source through the lazy pre
23342334
expect(screen.container.querySelector('[role="alert"]')).toBeNull();
23352335
});
23362336

2337-
it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {
2337+
function planningPdf(
2338+
titles = ["Quarterly outlook", "Delivery milestones", "Budget and risks"],
2339+
firstHeight = 140,
2340+
) {
23382341
const objects = [
23392342
"<< /Type /Catalog /Pages 2 0 R >>",
2340-
"<< /Type /Pages /Count 3 /Kids [3 0 R 5 0 R 7 0 R] >>",
2343+
`<< /Type /Pages /Count ${titles.length} /Kids [${titles.map((_, index) => `${3 + index * 2} 0 R`).join(" ")}] >>`,
23412344
];
2342-
for (const [index, title] of [
2343-
"Quarterly outlook",
2344-
"Delivery milestones",
2345-
"Budget and risks",
2346-
].entries()) {
2345+
const font = 3 + titles.length * 2;
2346+
for (const [index, title] of titles.entries()) {
23472347
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`;
23482348
objects.push(
2349-
`<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 ${index === 0 ? 140 : 792}] /Rotate ${index === 2 ? 90 : 0} /Resources << /Font << /F1 9 0 R /F2 10 0 R >> /ExtGState << /GS1 << /TR << /FunctionType 2 /Domain [0 1] /C0 [0] /C1 [1] /N 2 >> >> >> >> /Contents ${4 + index * 2} 0 R >>`,
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 >>`,
23502350
`<< /Length ${text.length} >>\nstream\n${text}\nendstream`,
23512351
);
23522352
}
@@ -2359,11 +2359,76 @@ it("navigates, searches, zooms, and selects mixed-height PDF pages", async () =>
23592359
source += `${index + 1} 0 obj\n${object}\nendobj\n`;
23602360
}
23612361
const xref = source.length;
2362-
source += `xref\n0 11\n0000000000 65535 f \n${offsets
2362+
source += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n${offsets
23632363
.slice(1)
23642364
.map((offset) => `${String(offset).padStart(10, "0")} 00000 n \n`)
2365-
.join("")}trailer\n<< /Size 11 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
2366-
const file = new Blob([source], { type: "application/pdf" });
2365+
.join("")}trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF`;
2366+
return new Blob([source], { type: "application/pdf" });
2367+
}
2368+
2369+
it("keeps the PDF page after reloads and clamps it when the document gets shorter", async () => {
2370+
const { BrowserDocumentFrame } = await import("./BrowserDocumentFrame");
2371+
using _native = vi.spyOn(navigator, "pdfViewerEnabled", "get").mockReturnValue(false);
2372+
using urls = (() => {
2373+
const original = URL.createObjectURL(planningPdf());
2374+
const updated = URL.createObjectURL(
2375+
planningPdf(["Quarterly outlook", "Delivery milestones", "Updated budget"], 500),
2376+
);
2377+
const shorter = URL.createObjectURL(planningPdf(["Quarterly outlook", "Updated milestones"]));
2378+
const single = URL.createObjectURL(planningPdf(["Quarterly outlook"]));
2379+
return {
2380+
original,
2381+
updated,
2382+
shorter,
2383+
single,
2384+
[Symbol.dispose]: () => [original, updated, shorter, single].forEach(URL.revokeObjectURL),
2385+
};
2386+
})();
2387+
const preview = (src: string, revision: string, documentId = "planning") => (
2388+
<div style={{ display: "flex", height: 600, width: 320 }}>
2389+
<BrowserDocumentFrame
2390+
src={src}
2391+
title="Planning PDF"
2392+
pdf
2393+
documentKey={revision}
2394+
documentId={documentId}
2395+
/>
2396+
</div>
2397+
);
2398+
await using screen = await render(preview(urls.original, "one"));
2399+
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"), {
2400+
timeout: 15_000,
2401+
});
2402+
await screen.getByRole("button", { name: "Next page", exact: true }).click();
2403+
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
2404+
await screen.getByRole("button", { name: "Next page", exact: true }).click();
2405+
await vi.waitFor(() => expect(screen.container.textContent).toContain("3 / 3 pages"));
2406+
await screen.rerender(preview(urls.updated, "two"));
2407+
await vi.waitFor(() => {
2408+
expect(screen.container.textContent).toContain("3 / 3 pages");
2409+
expect(screen.container.querySelector('[role="region"]')?.textContent).toContain(
2410+
"Updated budget",
2411+
);
2412+
});
2413+
await screen.rerender(preview(urls.shorter, "three"));
2414+
await vi.waitFor(() => {
2415+
expect(screen.container.textContent).toContain("2 / 2 pages");
2416+
expect(screen.container.querySelector('[role="region"]')?.textContent).toContain(
2417+
"Updated milestones",
2418+
);
2419+
});
2420+
await screen.rerender(preview(urls.single, "four"));
2421+
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 1 pages"));
2422+
await screen.rerender(preview(urls.original, "five"));
2423+
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
2424+
await screen.getByRole("button", { name: "Next page", exact: true }).click();
2425+
await vi.waitFor(() => expect(screen.container.textContent).toContain("2 / 3 pages"));
2426+
await screen.rerender(preview(urls.original, "one", "another-document"));
2427+
await vi.waitFor(() => expect(screen.container.textContent).toContain("1 / 3 pages"));
2428+
});
2429+
2430+
it("navigates, searches, zooms, and selects mixed-height PDF pages", async () => {
2431+
const file = planningPdf();
23672432
const { default: PdfViewer } = await import("./PdfViewer");
23682433
const url = URL.createObjectURL(file);
23692434
try {

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

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,33 @@ export const isPdfPreviewFile = (path: string): boolean =>
7373

7474
const PdfViewer = lazy(() => import("./PdfViewer"));
7575

76-
function PdfDocument(props: { src: string; title: string }) {
76+
/**
77+
* 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+
*/
80+
function PdfDocument(props: { src: string; title: string; documentKey: string }) {
81+
const [page, setPage] = useState(0);
82+
return (
83+
<PdfDocumentRevision
84+
key={props.documentKey}
85+
src={props.src}
86+
title={props.title}
87+
initialPage={page}
88+
onPageChange={setPage}
89+
/>
90+
);
91+
}
92+
93+
/**
94+
* File URLs expire and are refreshed even when the PDF hasn't changed.
95+
* Keep the initial URL so those refreshes don't reload the viewer.
96+
*/
97+
function PdfDocumentRevision(props: {
98+
src: string;
99+
title: string;
100+
initialPage: number;
101+
onPageChange: (page: number) => void;
102+
}) {
77103
const [src] = useState(props.src);
78104
// The Electron shell does not enable PDF plugins. WebKit embeds on iOS
79105
// expose only the first page, even when pdfViewerEnabled reports support.
@@ -91,7 +117,12 @@ function PdfDocument(props: { src: string; title: string }) {
91117
/>
92118
) : (
93119
<Suspense fallback={<FileSurfaceLoading />}>
94-
<PdfViewer src={src} title={props.title} />
120+
<PdfViewer
121+
src={src}
122+
title={props.title}
123+
initialPage={props.initialPage}
124+
onPageChange={props.onPageChange}
125+
/>
95126
</Suspense>
96127
);
97128
}
@@ -108,10 +139,17 @@ export function BrowserDocumentFrame(props: {
108139
readonly threadRef?: ScopedThreadRef | undefined;
109140
/** Stable resource identity and revision; defaults to src for callers that reload on URL changes. */
110141
readonly documentKey?: string | undefined;
142+
/** Resource identity without its revision, so PDF reloads can retain the page. */
143+
readonly documentId?: string | undefined;
111144
}) {
112145
const key = props.documentKey ?? props.src;
113146
return props.pdf ? (
114-
<PdfDocument key={key} src={props.src} title={props.title} />
147+
<PdfDocument
148+
key={props.documentId ?? key}
149+
documentKey={key}
150+
src={props.src}
151+
title={props.title}
152+
/>
115153
) : props.htmlRender ? (
116154
<HtmlRenderDocument
117155
key={key}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,7 @@ function WorkspaceBrowserPreview(props: {
257257
<BrowserDocumentFrame
258258
src={`${assetUrl.url}${revisionSuffix}`}
259259
documentKey={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}:${props.workspaceMutationId}`}
260+
documentId={`${props.environmentId}:${resource._tag}:${props.threadRef.threadId}:${props.absolutePath}`}
260261
title={props.title}
261262
pdf={isPdfPreviewFile(props.absolutePath)}
262263
/>

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

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,12 @@ function PdfPage(props: {
116116
);
117117
}
118118

119-
export default function PdfViewer(props: { src: string; title: string }) {
119+
export default function PdfViewer(props: {
120+
src: string;
121+
title: string;
122+
initialPage?: number;
123+
onPageChange?: (page: number) => void;
124+
}) {
120125
const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
121126
const [error, setError] = useState<string | null>(null);
122127
const [revision, setRevision] = useState(0);
@@ -133,6 +138,7 @@ export default function PdfViewer(props: { src: string; title: string }) {
133138
const scroll = useRef<HTMLDivElement>(null);
134139
const find = useRef<HTMLInputElement>(null);
135140
const zoomAnchor = useRef<{ page: number; offset: number; width: number } | null>(null);
141+
const [initialPage] = useState(props.initialPage ?? 0);
136142
// 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.
137143
useEffect(() => {
138144
const controller = new AbortController();
@@ -156,9 +162,20 @@ export default function PdfViewer(props: { src: string; title: string }) {
156162
if (document.numPages > MAX_PAGES)
157163
throw new Error("Preview limited to 2,000 pages. Save this PDF to read it in full.");
158164
const first = (await document.getPage(1)).getViewport({ scale: 1 });
165+
const sizes = await Promise.all(
166+
Array.from({ length: Math.min(initialPage, document.numPages) }, async (_, index) => {
167+
const size = (await document.getPage(index + 1)).getViewport({ scale: 1 });
168+
return size.height / size.width;
169+
}),
170+
);
159171
if (controller.signal.aborted) return;
160172
setPageWidth(first.width);
161-
setRatios(Array.from({ length: document.numPages }, () => first.height / first.width));
173+
setRatios(
174+
Array.from(
175+
{ length: document.numPages },
176+
(_, index) => sizes[index] ?? first.height / first.width,
177+
),
178+
);
162179
setPdf(document);
163180
})
164181
.catch((cause: unknown) => {
@@ -172,7 +189,7 @@ export default function PdfViewer(props: { src: string; title: string }) {
172189
clearTimeout(timeout);
173190
void task?.destroy();
174191
};
175-
}, [props.src, revision]);
192+
}, [props.src, revision, initialPage]);
176193
// oxlint-disable-next-line t3code/react-effect-budget -- Measure the PDF viewport before paint and observe resizes for fit-width sizing and visible-page selection.
177194
useLayoutEffect(() => {
178195
const node = scroll.current;
@@ -189,10 +206,12 @@ export default function PdfViewer(props: { src: string; title: string }) {
189206
for (const ratio of ratios) result.push(result[result.length - 1]! + width * ratio + 16);
190207
return result;
191208
})();
192-
const current = Math.max(
193-
0,
194-
ratios.findIndex((_, index) => offsets[index + 1]! > scrollTop + 17),
195-
);
209+
const pageAtOffset = (top: number) =>
210+
Math.max(
211+
0,
212+
ratios.findIndex((_, index) => offsets[index + 1]! > top + 17),
213+
);
214+
const current = pageAtOffset(scrollTop);
196215
const visible = ratios.flatMap((ratio, index) =>
197216
offsets[index + 1]! >= scrollTop - viewport.height &&
198217
offsets[index]! <= scrollTop + viewport.height * 2
@@ -209,6 +228,14 @@ export default function PdfViewer(props: { src: string; title: string }) {
209228
const jumpToPage = useEffectEvent((index: number) => {
210229
scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
211230
});
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;
235+
const page = Math.min(initialPage, pdf.numPages - 1);
236+
jumpToPage(page);
237+
onPageChange?.(page);
238+
}, [pdf, initialPage, onPageChange]);
212239
const showPage = (index: number) => {
213240
scroll.current?.scrollTo({ top: Math.max(0, (offsets[index] ?? 16) - 16) });
214241
};
@@ -371,7 +398,11 @@ export default function PdfViewer(props: { src: string; title: string }) {
371398
aria-label={props.title}
372399
tabIndex={0}
373400
className="relative min-h-0 min-w-0 w-full flex-1 overflow-auto bg-muted/40"
374-
onScroll={(event) => setScrollTop(event.currentTarget.scrollTop)}
401+
onScroll={(event) => {
402+
const top = event.currentTarget.scrollTop;
403+
setScrollTop(top);
404+
props.onPageChange?.(pageAtOffset(top));
405+
}}
375406
onKeyDown={(event) => {
376407
if ((event.ctrlKey || event.metaKey) && event.key === "f") {
377408
event.preventDefault();

0 commit comments

Comments
 (0)