@devries-cameron20 / t3code Mirror · read-only / commits / f482dc5c57
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 08:15 UTC

fix(web): PDF previews keep their page across thread switches (#25496)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net>

ash committed Nov 1, 2026 at 21:58 UTC f482dc5c57479825420749d4e81fba5cf5ab8999
5 files changed +115 -15
apps/web/src/components/files/AttachmentFilePreview.browser.test.tsx
+2 -1
@@ -2468,6 +2468,7 @@ async function workspacePdfPreview() {
2468 [original, updated, shorter, shrunk, single].forEach(URL.revokeObjectURL),
2469 };
2470 })();
2471 + const threadId = ThreadId.make(urls.original);
2472 const preview = (src: string, mutation: string, path = "/repo/planning.pdf") => {
2473 assetUrlState.mockReturnValue({
2474 _tag: "Success",
@@ -2478,7 +2479,7 @@ async function workspacePdfPreview() {
2479 <div className="flex h-[600px] w-[320px]">
2480 <WorkspaceBrowserPreview
2481 environmentId={EnvironmentId.make("test")}
2481 - threadRef={{ environmentId: EnvironmentId.make("test"), threadId: ThreadId.make("test") }}
2482 + threadRef={{ environmentId: EnvironmentId.make("test"), threadId }}
2483 draft={false}
2484 absolutePath={path}
2485 workspaceRoot="/repo"
apps/web/src/components/files/AttachmentFilePreview.tsx
+20
@@ -55,6 +55,15 @@ const SourcePreview = lazy(() => import("./ReadOnlySourcePreview"));
55
56 const STALE_URL_MS = 5 * 60_000;
57
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 +
67 export function ReadOnlySourcePreview(props: { name: string; text: string; wordWrap?: boolean }) {
68 return (
69 <Suspense fallback={<FileSurfaceLoading className="p-4" />}>
@@ -325,6 +334,17 @@ export function AttachmentFilePreview(props: {
334 pdf={kind === "pdf"}
335 htmlRender={props.htmlRender === true}
336 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 + }
348 />
349 ) : kind === "audio" ? (
350 <AudioPreview src={url} name={props.name} onError={() => setError("Unable to load audio.")} />
apps/web/src/components/files/BrowserDocumentFrame.tsx
+3
@@ -82,6 +82,7 @@ function PdfDocument(props: { src: string; title: string; documentKey: string })
82 key={props.documentKey}
83 src={props.src}
84 title={props.title}
85 + positionKey={props.documentKey}
86 initialView={view}
87 onViewChange={setView}
88 />
@@ -92,6 +93,7 @@ function PdfDocument(props: { src: string; title: string; documentKey: string })
93 function PdfDocumentRevision(props: {
94 src: string;
95 title: string;
96 + positionKey: string;
97 initialView: PdfViewState;
98 onViewChange: (view: PdfViewState) => void;
99 }) {
@@ -115,6 +117,7 @@ function PdfDocumentRevision(props: {
117 <PdfViewer
118 src={src}
119 title={props.title}
120 + positionKey={props.positionKey}
121 initialView={props.initialView}
122 onViewChange={props.onViewChange}
123 />
apps/web/src/components/files/PdfViewer.browser.test.tsx
+51
@@ -109,3 +109,54 @@ it("fits the width, then finds split and rotated text and jumps to its page", as
109 URL.revokeObjectURL(url);
110 }
111 });
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
+39 -14
@@ -31,6 +31,11 @@ import "./pdfViewer.css";
31 const MAX_PAGES = 2000;
32 const MAX_FIND_TEXT = 4 * 1024 * 1024;
33
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 +
39 export type PdfViewState = {
40 page: number;
41 offset: number;
@@ -126,16 +131,20 @@ function PdfPage(props: {
131 export default function PdfViewer(props: {
132 src: string;
133 title: string;
134 + positionKey?: string;
135 initialView?: PdfViewState;
136 onViewChange?: (view: PdfViewState) => void;
137 }) {
138 + const [savedPosition] = useState(() =>
139 + props.positionKey === undefined ? undefined : positions.get(props.positionKey),
140 + );
141 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 },
143 );
144 const [pdf, setPdf] = useState<PDFDocumentProxy | null>(null);
145 const [error, setError] = useState<string | null>(null);
146 const [revision, setRevision] = useState(0);
138 - const [ratios, setRatios] = useState<number[]>([]);
147 + const [ratios, setRatios] = useState<readonly number[]>([]);
148 const [zoom, setZoom] = useState(initialView.zoom);
149 const [pageWidth, setPageWidth] = useState(612);
150 const [viewport, setViewport] = useState({ width: 600, height: 800 });
@@ -181,10 +190,12 @@ export default function PdfViewer(props: {
190 if (controller.signal.aborted) return;
191 setPageWidth(first.width);
192 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 + ),
199 );
200 setPdf(document);
201 })
@@ -199,7 +210,7 @@ export default function PdfViewer(props: {
210 clearTimeout(timeout);
211 void task?.destroy();
212 };
202 - }, [props.src, revision, initialPage]);
213 + }, [props.src, revision, initialPage, savedPosition]);
214 // 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.
215 useLayoutEffect(() => {
216 const node = scroll.current;
@@ -222,14 +233,22 @@ export default function PdfViewer(props: {
233 const jumpToPage = useEffectEvent((index: number) => {
234 scroll.current?.scrollTo({ top: pdfPageScrollTop(offsets, index) });
235 });
225 - const saveView = (node: HTMLDivElement) => {
236 + const saveView = (node: HTMLDivElement, notify = true) => {
237 const page = currentPdfPage(offsets, ratios.length, node.scrollTop);
227 - props.onViewChange?.({
238 + if (!pdf) return;
239 + const view = {
240 page,
241 offset: Math.max(0, node.scrollTop - (offsets[page]! - 16)),
242 zoom,
243 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 + }
252 };
253 const restoreView = useEffectEvent(() => {
254 const node = scroll.current;
@@ -237,9 +256,15 @@ export default function PdfViewer(props: {
256 const page = Math.min(initialPage, pdf.numPages - 1);
257 node.scrollTo({
258 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 + ),
265 left: initialView.left,
266 });
267 + setScrollTop(node.scrollTop);
268 saveView(node);
269 });
270 // 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: {
287 const anchor = zoomAnchor.current;
288 zoomAnchor.current = null;
289 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) {
292 node.scrollTo({
293 top: offsets[anchor.page]! - 16 + (anchor.offset * width) / anchor.width,
294 });
295 }
271 - saveView(node);
296 + saveView(node, anchor !== null);
297 });
298 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Scroll to the first asynchronous search result after its measured page offsets have committed.
299 useLayoutEffect(() => {