Skip to content

Commit f482dc5

Browse files
ashx-jclaudemaria-rcks
authored
fix(web): PDF previews keep their page across thread switches (#25496)
Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: maria-rcks <[email protected]>
1 parent e7c375d commit f482dc5

5 files changed

Lines changed: 115 additions & 15 deletions

File tree

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2468,6 +2468,7 @@ async function workspacePdfPreview() {
24682468
[original, updated, shorter, shrunk, single].forEach(URL.revokeObjectURL),
24692469
};
24702470
})();
2471+
const threadId = ThreadId.make(urls.original);
24712472
const preview = (src: string, mutation: string, path = "/repo/planning.pdf") => {
24722473
assetUrlState.mockReturnValue({
24732474
_tag: "Success",
@@ -2478,7 +2479,7 @@ async function workspacePdfPreview() {
24782479
<div className="flex h-[600px] w-[320px]">
24792480
<WorkspaceBrowserPreview
24802481
environmentId={EnvironmentId.make("test")}
2481-
threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }}
2482+
threadRef={{ environmentId: EnvironmentId.make("test"), threadId }}
24822483
draft={false}
24832484
absolutePath={path}
24842485
workspaceRoot="/repo"

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

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,15 @@ const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
5555

5656
const STALE_URL_MS = 5 * 60_000;
5757

58+
const blobKeys = new WeakMap<Blob, string>();
59+
let nextBlobKey = 0;
60+
61+
function blobKey(blob: Blob) {
62+
const key = blobKeys.get(blob) ?? `blob:${nextBlobKey++}`;
63+
blobKeys.set(blob, key);
64+
return key;
65+
}
66+
5867
export function ReadOnlySourcePreview(props: { name: string; text: string; wordWrap?: boolean }) {
5968
return (
6069
<Suspense fallback={<FileSurfaceLoading className="p-4" />}>
@@ -325,6 +334,17 @@ export function AttachmentFilePreview(props: {
325334
pdf={kind === "pdf"}
326335
htmlRender={props.htmlRender === true}
327336
threadRef={props.threadRef}
337+
// Each mount signs or creates a new URL, so the URL cannot identify the file across visits.
338+
// A draft keeps its Blob key after upload, so finishing the upload does not reload the PDF.
339+
documentKey={
340+
kind !== "pdf"
341+
? undefined
342+
: props.file
343+
? blobKey(props.file)
344+
: props.asset && "attachmentId" in props.asset
345+
? `${props.asset.environmentId}:${props.asset.attachmentId}`
346+
: undefined
347+
}
328348
/>
329349
) : kind === "audio" ? (
330350
<AudioPreview src={url} name={props.name} onError={() => setError("Unable to load audio.")} />

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ function PdfDocument(props: { src: string; title: string; documentKey: string })
8282
key={props.documentKey}
8383
src={props.src}
8484
title={props.title}
85+
positionKey={props.documentKey}
8586
initialView={view}
8687
onViewChange={setView}
8788
/>
@@ -92,6 +93,7 @@ function PdfDocument(props: { src: string; title: string; documentKey: string })
9293
function PdfDocumentRevision(props: {
9394
src: string;
9495
title: string;
96+
positionKey: string;
9597
initialView: PdfViewState;
9698
onViewChange: (view: PdfViewState) => void;
9799
}) {
@@ -115,6 +117,7 @@ function PdfDocumentRevision(props: {
115117
<PdfViewer
116118
src={src}
117119
title={props.title}
120+
positionKey={props.positionKey}
118121
initialView={props.initialView}
119122
onViewChange={props.onViewChange}
120123
/>

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

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,3 +109,54 @@ it("fits the width, then finds split and rotated text and jumps to its page", as
109109
URL.revokeObjectURL(url);
110110
}
111111
});
112+
113+
it("restores page, within-page offset and zoom after a remount", async () => {
114+
const url = URL.createObjectURL(twoPagePdf());
115+
const viewer = (mount: number, positionKey: string) => (
116+
<div className="flex h-[300px] w-[320px]">
117+
<PdfViewer key={mount} src={url} title="Restored PDF" positionKey={positionKey} />
118+
</div>
119+
);
120+
try {
121+
await using screen = await render(viewer(1, "restore:a"));
122+
await expect.element(screen.getByText("1 / 2 pages")).toBeVisible();
123+
await screen.getByRole("button", { name: "Zoom in", exact: true }).click();
124+
await screen.getByRole("button", { name: "Next page", exact: true }).click();
125+
await expect.element(screen.getByText("2 / 2 pages")).toBeVisible();
126+
const region = () => screen.getByRole("region", { name: "Restored PDF" }).element();
127+
const top = region().scrollTop + 40;
128+
const scrolled = new Promise((resolve) =>
129+
region().addEventListener("scroll", resolve, { once: true }),
130+
);
131+
region().scrollTop = top;
132+
await scrolled;
133+
await vi.waitFor(() => expect(region().scrollTop).toBeCloseTo(top, 0));
134+
const zoom = screen.container.textContent!.match(/\d+%/)![0];
135+
136+
await screen.rerender(viewer(2, "restore:a"));
137+
await expect.element(screen.getByText("2 / 2 pages")).toBeVisible();
138+
await vi.waitFor(() => expect(region().scrollTop).toBeCloseTo(top, 0));
139+
await vi.waitFor(() => expect(screen.container.textContent).toContain(zoom));
140+
141+
await screen.getByRole("button", { name: "Fit width", exact: true }).click();
142+
await vi.waitFor(() => {
143+
const canvas = region().querySelector("canvas")!;
144+
expect(canvas.getBoundingClientRect().width).toBe(region().clientWidth - 32);
145+
});
146+
const fitTop = region().scrollTop;
147+
await screen.rerender(viewer(3, "restore:a"));
148+
await expect.element(screen.getByText("2 / 2 pages")).toBeVisible();
149+
await vi.waitFor(() => {
150+
expect(region().querySelector("canvas")!.getBoundingClientRect().width).toBe(
151+
region().clientWidth - 32,
152+
);
153+
expect(region().scrollTop).toBeCloseTo(fitTop, 0);
154+
});
155+
156+
await screen.rerender(viewer(4, "restore:b"));
157+
await expect.element(screen.getByText("1 / 2 pages")).toBeVisible();
158+
await expect.element(screen.getByText("Fit width")).toBeVisible();
159+
} finally {
160+
URL.revokeObjectURL(url);
161+
}
162+
});

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

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ import "./pdfViewer.css";
3131
const MAX_PAGES = 2000;
3232
const MAX_FIND_TEXT = 4 * 1024 * 1024;
3333

34+
const MAX_POSITIONS = 50;
35+
type PdfPosition = PdfViewState & { width: number; ratios: readonly number[] };
36+
// Thread switches unmount the preview; retain only the most recent documents.
37+
const positions = new Map<string, PdfPosition>();
38+
3439
export type PdfViewState = {
3540
page: number;
3641
offset: number;
@@ -126,16 +131,20 @@ function PdfPage(props: {
126131
export default function PdfViewer(props: {
127132
src: string;
128133
title: string;
134+
positionKey?: string;
129135
initialView?: PdfViewState;
130136
onViewChange?: (view: PdfViewState) => void;
131137
}) {
138+
const [savedPosition] = useState(() =>
139+
props.positionKey === undefined ? undefined : positions.get(props.positionKey),
140+
);
132141
const [initialView] = useState<PdfViewState>(
133-
() => props.initialView ?? { page: 0, offset: 0, zoom: null, left: 0 },
142+
() => savedPosition ?? props.initialView ?? { page: 0, offset: 0, zoom: null, left: 0 },
134143
);
135144
const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
136145
const [error, setError] = useState<string | null>(null);
137146
const [revision, setRevision] = useState(0);
138-
const [ratios, setRatios] = useState<number[]>([]);
147+
const [ratios, setRatios] = useState<readonly number[]>([]);
139148
const [zoom, setZoom] = useState(initialView.zoom);
140149
const [pageWidth, setPageWidth] = useState(612);
141150
const [viewport, setViewport] = useState({ width: 600, height: 800 });
@@ -181,10 +190,12 @@ export default function PdfViewer(props: {
181190
if (controller.signal.aborted) return;
182191
setPageWidth(first.width);
183192
setRatios(
184-
Array.from(
185-
{ length: document.numPages },
186-
(_, index) => sizes[index] ?? first.height / first.width,
187-
),
193+
savedPosition?.ratios.length === document.numPages
194+
? savedPosition.ratios
195+
: Array.from(
196+
{ length: document.numPages },
197+
(_, index) => sizes[index] ?? first.height / first.width,
198+
),
188199
);
189200
setPdf(document);
190201
})
@@ -199,7 +210,7 @@ export default function PdfViewer(props: {
199210
clearTimeout(timeout);
200211
void task?.destroy();
201212
};
202-
}, [props.src, revision, initialPage]);
213+
}, [props.src, revision, initialPage, savedPosition]);
203214
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Measure the PDF viewport before paint and observe resizes for fit-width sizing and visible-page selection.
204215
useLayoutEffect(() => {
205216
const node = scroll.current;
@@ -222,24 +233,38 @@ export default function PdfViewer(props: {
222233
const jumpToPage = useEffectEvent((index: number) => {
223234
scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
224235
});
225-
const saveView = (node: HTMLDivElement) => {
236+
const saveView = (node: HTMLDivElement, notify = true) => {
226237
const page = currentPdfPage(offsets, ratios.length, node.scrollTop);
227-
props.onViewChange?.({
238+
if (!pdf) return;
239+
const view = {
228240
page,
229241
offset: Math.max(0, node.scrollTop - (offsets[page]! - 16)),
230242
zoom,
231243
left: node.scrollLeft,
232-
});
244+
};
245+
if (notify) props.onViewChange?.(view);
246+
if (props.positionKey !== undefined) {
247+
positions.delete(props.positionKey);
248+
positions.set(props.positionKey, { ...view, width, ratios });
249+
const oldest = positions.keys().next();
250+
if (positions.size > MAX_POSITIONS && !oldest.done) positions.delete(oldest.value);
251+
}
233252
};
234253
const restoreView = useEffectEvent(() => {
235254
const node = scroll.current;
236255
if (!pdf || !node) return;
237256
const page = Math.min(initialPage, pdf.numPages - 1);
238257
node.scrollTo({
239258
top:
240-
offsets[page]! - 16 + Math.min(initialView.offset, Math.max(0, width * ratios[page]! - 1)),
259+
offsets[page]! -
260+
16 +
261+
Math.min(
262+
initialView.offset * (savedPosition ? width / savedPosition.width : 1),
263+
Math.max(0, width * ratios[page]! - 1),
264+
),
241265
left: initialView.left,
242266
});
267+
setScrollTop(node.scrollTop);
243268
saveView(node);
244269
});
245270
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Restore the saved PDF scroll position after the loaded document's page layout commits.
@@ -262,13 +287,13 @@ export default function PdfViewer(props: {
262287
const anchor = zoomAnchor.current;
263288
zoomAnchor.current = null;
264289
const node = scroll.current;
265-
if (!anchor || !node) return;
266-
if (anchor.width !== width) {
290+
if (!node || !pdf) return;
291+
if (anchor && anchor.width !== width) {
267292
node.scrollTo({
268293
top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
269294
});
270295
}
271-
saveView(node);
296+
saveView(node, anchor !== null);
272297
});
273298
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
274299
useLayoutEffect(() => {

0 commit comments

Comments
 (0)