#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
fix(viewer): carry view state across a reload on plugin events, not timers (#8285)
ConnorYoh8c8f3bc7259d
diff --git a/frontend/editor/src/core/components/viewer/DocumentRestoreBridge.test.tsx b/frontend/editor/src/core/components/viewer/DocumentRestoreBridge.test.tsxnew file mode 100644index 0000000000..9ddb02f5ce--- /dev/null+++ b/frontend/editor/src/core/components/viewer/DocumentRestoreBridge.test.tsx@@ -0,0 +1,403 @@+import { act, render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SpreadMode } from "@embedpdf/plugin-spread/react";+import { ZoomMode } from "@embedpdf/plugin-zoom/react";+import {+ DocumentRestoreBridge,+ type DocumentRestoreEvent,+ type DocumentRestoreRequest,+} from "@app/components/viewer/DocumentRestoreBridge";+import type { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";++const activeDocument = vi.hoisted<{+ id: ReturnType<typeof useActiveDocumentId>;+}>(() => ({ id: "second" }));++const fixture = vi.hoisted(() => {+ type Listener<T> = (value: T) => void;+ const emitter = <T,>() => {+ const listeners = new Set<Listener<T>>();+ return {+ on: (listener: Listener<T>) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ emit: (value: T) => {+ for (const listener of [...listeners]) listener(value);+ },+ size: () => listeners.size,+ };+ };++ // Requests apply synchronously and fire the change hook unless dropped or clamped.+ const zoomScope = () => {+ const state = {+ zoomLevel: "fit-width" as string | number,+ currentZoomLevel: 1.97,+ isMarqueeZoomActive: false,+ };+ const changes = emitter<typeof state>();+ const passes = emitter<{ newZoom: number }>();+ const scope = {+ drop: false,+ clampTo: null as number | null,+ requestZoom: vi.fn((level: string | number) => {+ if (scope.drop) return;+ const zoomValue = typeof level === "number" ? level : 1.97;+ state.zoomLevel =+ typeof level === "number" ? (scope.clampTo ?? zoomValue) : level;+ state.currentZoomLevel = scope.clampTo ?? zoomValue;+ changes.emit({ ...state });+ passes.emit({ newZoom: state.currentZoomLevel });+ }),+ getState: () => ({ ...state }),+ onStateChange: changes.on,+ onZoomChange: passes.on,+ preset: (zoomLevel: string | number, currentZoomLevel: number) => {+ state.zoomLevel = zoomLevel;+ state.currentZoomLevel = currentZoomLevel;+ },+ };+ return scope;+ };+ const spreadScope = () => {+ let mode = "none";+ const changes = emitter<string>();+ return {+ setSpreadMode: vi.fn((next: string) => {+ if (next === mode) return;+ mode = next;+ changes.emit(next);+ }),+ getSpreadMode: () => mode,+ onSpreadChange: changes.on,+ preset: (next: string) => {+ mode = next;+ },+ };+ };+ const rotateScope = () => {+ let rotation = 0;+ const changes = emitter<number>();+ return {+ setRotation: vi.fn((next: number) => {+ rotation = next;+ changes.emit(next);+ }),+ getRotation: () => rotation,+ onRotateChange: changes.on,+ preset: (next: number) => {+ rotation = next;+ },+ };+ };+ const perDocument = <T,>(make: () => T) => {+ const scopes = new Map<string, T>();+ return {+ forDocument: (id: string) => {+ let scope = scopes.get(id);+ if (!scope) {+ scope = make();+ scopes.set(id, scope);+ }+ return scope;+ },+ };+ };++ const createFixture = () => {+ const layoutReady = emitter<{ documentId: string; totalPages: number }>();+ const layoutChange = emitter<{ documentId: string }>();+ const viewportResize = emitter<{ documentId: string }>();+ const scrollRequests = perDocument(() =>+ emitter<{ x: number; y: number }>(),+ );+ return {+ zoom: perDocument(zoomScope),+ spread: perDocument(spreadScope),+ rotate: perDocument(rotateScope),+ layoutReady,+ layoutChange,+ viewportResize,+ scrollRequests,+ scroll: {+ onLayoutReady: layoutReady.on,+ onLayoutChange: layoutChange.on,+ },+ viewport: { onViewportResize: viewportResize.on },+ viewportPlugin: {+ onScrollRequest: (+ documentId: string,+ listener: (request: { x: number; y: number }) => void,+ ) => scrollRequests.forDocument(documentId).on(listener),+ },+ };+ };+ return { current: createFixture(), createFixture };+});++vi.mock("@app/components/viewer/useActiveDocumentId", () => ({+ useActiveDocumentId: () => activeDocument.id,+ useDocumentReady: () => true,+}));+vi.mock("@embedpdf/plugin-zoom/react", () => ({+ ZoomMode: {+ Automatic: "automatic",+ FitPage: "fit-page",+ FitWidth: "fit-width",+ },+ useZoomCapability: () => ({ provides: fixture.current.zoom }),+}));+vi.mock("@embedpdf/plugin-spread/react", () => ({+ SpreadMode: { None: "none", Odd: "odd", Even: "even" },+ useSpreadCapability: () => ({ provides: fixture.current.spread }),+}));+vi.mock("@embedpdf/plugin-rotate/react", () => ({+ useRotateCapability: () => ({ provides: fixture.current.rotate }),+}));+vi.mock("@embedpdf/plugin-scroll/react", () => ({+ useScrollCapability: () => ({ provides: fixture.current.scroll }),+}));+vi.mock("@embedpdf/plugin-viewport/react", () => ({+ useViewportCapability: () => ({ provides: fixture.current.viewport }),+ useViewportPlugin: () => ({ plugin: fixture.current.viewportPlugin }),+}));++const request = (+ overrides?: Partial<DocumentRestoreRequest>,+): DocumentRestoreRequest => ({+ documentId: "second",+ zoom: 1.42,+ spread: SpreadMode.Odd,+ rotation: 1,+ ...overrides,+});++function layoutReady(documentId = "second", totalPages = 3) {+ act(() => fixture.current.layoutReady.emit({ documentId, totalPages }));+}++function renderBridge(props: {+ request: DocumentRestoreRequest | null;+ restorePending?: boolean;+ laidOut?: boolean;+}) {+ const events: DocumentRestoreEvent[] = [];+ const view = () => (+ <DocumentRestoreBridge+ request={props.request}+ restorePending={props.restorePending ?? false}+ onEvent={(event) => events.push(event)}+ />+ );+ const utils = render(view());+ if (props.laidOut ?? true) layoutReady();+ return {+ events,+ types: () =>+ events+ .map((event) => event.type)+ .filter((type) => type !== "layout-ready"),+ rerender: () => utils.rerender(view()),+ };+}++describe("DocumentRestoreBridge", () => {+ beforeEach(() => {+ activeDocument.id = "second";+ fixture.current = fixture.createFixture();+ });++ it("lands the carried values on the replacement and confirms each from the plugin's own change", () => {+ const { types } = renderBridge({ request: request() });++ const replacement = {+ zoom: fixture.current.zoom.forDocument("second"),+ spread: fixture.current.spread.forDocument("second"),+ rotate: fixture.current.rotate.forDocument("second"),+ };+ expect(replacement.rotate.setRotation).toHaveBeenCalledExactlyOnceWith(1);+ expect(replacement.spread.setSpreadMode).toHaveBeenCalledExactlyOnceWith(+ "odd",+ );+ expect(replacement.zoom.requestZoom).toHaveBeenCalledExactlyOnceWith(1.42);+ expect(types()).toEqual(["rotation", "spread", "zoom"]);+ });++ it("leaves a replacement alone whose state already matches", () => {+ const replacement = {+ zoom: fixture.current.zoom.forDocument("second"),+ spread: fixture.current.spread.forDocument("second"),+ rotate: fixture.current.rotate.forDocument("second"),+ };+ replacement.zoom.preset(1.42, 1.42);+ replacement.spread.preset("odd");+ replacement.rotate.preset(1);++ const { types } = renderBridge({ request: request() });++ expect(replacement.rotate.setRotation).not.toHaveBeenCalled();+ expect(replacement.spread.setSpreadMode).not.toHaveBeenCalled();+ expect(replacement.zoom.requestZoom).not.toHaveBeenCalled();+ expect(types()).toEqual(["rotation", "spread", "zoom"]);+ });++ it("re-requests a zoom the plugin dropped once the viewport reports a size", () => {+ const zoom = fixture.current.zoom.forDocument("second");+ zoom.drop = true;++ const { types } = renderBridge({+ request: request({ spread: null, rotation: null }),+ });+ expect(zoom.requestZoom).toHaveBeenCalledTimes(1);+ expect(types()).toEqual([]);++ zoom.drop = false;+ act(() => fixture.current.viewportResize.emit({ documentId: "second" }));++ expect(zoom.requestZoom).toHaveBeenCalledTimes(2);+ expect(types()).toEqual(["zoom"]);+ });++ it("re-requests a zoom the plugin's own fit pass overrode", () => {+ const zoom = fixture.current.zoom.forDocument("second");+ zoom.drop = true;++ renderBridge({ request: request({ spread: null, rotation: null }) });+ zoom.drop = false;+ act(() => zoom.requestZoom("fit-width"));++ expect(zoom.requestZoom).toHaveBeenLastCalledWith(1.42);+ expect(zoom.getState().currentZoomLevel).toBe(1.42);+ });++ it("confirms a carried mode only once the plugin has fitted the replacement", () => {+ const zoom = fixture.current.zoom.forDocument("second");+ zoom.preset("fit-width", 1);+ zoom.drop = true;++ const { types } = renderBridge({+ request: request({+ zoom: ZoomMode.FitWidth,+ spread: null,+ rotation: null,+ }),+ });+ expect(zoom.requestZoom).toHaveBeenCalledExactlyOnceWith("fit-width");+ expect(types()).toEqual([]);++ zoom.drop = false;+ act(() => fixture.current.viewportResize.emit({ documentId: "second" }));++ expect(zoom.requestZoom).toHaveBeenCalledTimes(2);+ expect(zoom.getState().currentZoomLevel).toBe(1.97);+ expect(types()).toEqual(["zoom"]);+ });++ it("keeps asking while requests are dropped and counts only the plugin's answers", () => {+ const zoom = fixture.current.zoom.forDocument("second");+ zoom.drop = true;++ renderBridge({ request: request({ spread: null, rotation: null }) });+ for (let i = 0; i < 8; i += 1) {+ act(() => fixture.current.layoutChange.emit({ documentId: "second" }));+ }+ expect(zoom.requestZoom).toHaveBeenCalledTimes(9);++ zoom.drop = false;+ act(() => fixture.current.viewportResize.emit({ documentId: "second" }));+ expect(zoom.getState().currentZoomLevel).toBe(1.42);+ });++ it("stops asking after repeated refusals instead of fighting the plugin", () => {+ const zoom = fixture.current.zoom.forDocument("second");+ zoom.clampTo = 1.5;++ const { types } = renderBridge({+ request: request({ spread: null, rotation: null }),+ });++ expect(zoom.requestZoom).toHaveBeenCalledTimes(5);+ expect(types()).toEqual(["zoom"]);+ });++ it("waits for the replacement's layout before asking for anything", () => {+ const { types } = renderBridge({ request: request(), laidOut: false });+ const replacement = {+ zoom: fixture.current.zoom.forDocument("second"),+ spread: fixture.current.spread.forDocument("second"),+ rotate: fixture.current.rotate.forDocument("second"),+ };+ expect(replacement.rotate.setRotation).not.toHaveBeenCalled();+ expect(replacement.spread.setSpreadMode).not.toHaveBeenCalled();+ expect(replacement.zoom.requestZoom).not.toHaveBeenCalled();+ expect(types()).toEqual([]);++ layoutReady("first");+ expect(replacement.spread.setSpreadMode).not.toHaveBeenCalled();++ layoutReady("second");+ expect(replacement.spread.setSpreadMode).toHaveBeenCalledExactlyOnceWith(+ "odd",+ );+ expect(types()).toEqual(["rotation", "spread", "zoom"]);+ });++ it("forwards the replacement's layout and scroll events and ignores other documents'", () => {+ const { events } = renderBridge({+ request: null,+ restorePending: true,+ laidOut: false,+ });++ act(() => {+ fixture.current.layoutReady.emit({ documentId: "first", totalPages: 9 });+ fixture.current.scrollRequests+ .forDocument("first")+ .emit({ x: 0, y: 400 });+ });+ expect(events).toEqual([]);++ act(() => {+ fixture.current.layoutReady.emit({ documentId: "second", totalPages: 2 });+ fixture.current.layoutChange.emit({ documentId: "second" });+ fixture.current.scrollRequests+ .forDocument("second")+ .emit({ x: 0, y: 120 });+ });+ expect(events).toEqual([+ { type: "layout-ready", totalPages: 2 },+ { type: "layout-change" },+ { type: "scroll-request", top: 120 },+ ]);+ });++ it("waits for the document the request is addressed to", () => {+ activeDocument.id = "first";+ const { types, rerender } = renderBridge({ request: request() });++ expect(+ fixture.current.rotate.forDocument("first").setRotation,+ ).not.toHaveBeenCalled();+ expect(types()).toEqual([]);++ activeDocument.id = "second";+ rerender();+ layoutReady();++ expect(+ fixture.current.rotate.forDocument("second").setRotation,+ ).toHaveBeenCalledExactlyOnceWith(1);+ expect(types()).toEqual(["rotation", "spread", "zoom"]);+ });++ it("subscribes to nothing while no restore is in flight", () => {+ renderBridge({ request: null, restorePending: false, laidOut: false });++ expect(fixture.current.layoutReady.size()).toBe(0);+ expect(fixture.current.viewportResize.size()).toBe(0);+ expect(fixture.current.scrollRequests.forDocument("second").size()).toBe(0);+ });+});diff --git a/frontend/editor/src/core/components/viewer/DocumentRestoreBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentRestoreBridge.tsxnew file mode 100644index 0000000000..fd31d53814--- /dev/null+++ b/frontend/editor/src/core/components/viewer/DocumentRestoreBridge.tsx@@ -0,0 +1,236 @@+import { useCallback, useLayoutEffect, useRef, useState } from "react";+import type { Rotation } from "@embedpdf/models";+import type { ZoomDocumentState, ZoomLevel } from "@embedpdf/plugin-zoom";+import { useZoomCapability } from "@embedpdf/plugin-zoom/react";+import type { SpreadMode } from "@embedpdf/plugin-spread/react";+import { useSpreadCapability } from "@embedpdf/plugin-spread/react";+import { useRotateCapability } from "@embedpdf/plugin-rotate/react";+import { useScrollCapability } from "@embedpdf/plugin-scroll/react";+import {+ useViewportCapability,+ useViewportPlugin,+} from "@embedpdf/plugin-viewport/react";+import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";+import { useDocumentReady } from "@app/components/viewer/hooks/useDocumentReady";++/** View state captured from the outgoing document, addressed to its replacement. */+export interface DocumentRestoreRequest {+ documentId: string;+ zoom: ZoomLevel | null;+ spread: SpreadMode | null;+ rotation: number | null;+}++/** `scroll-request` fires before the viewport applies that scroll, on its next frame. */+export type DocumentRestoreEvent =+ | { type: "zoom" }+ | { type: "spread" }+ | { type: "rotation" }+ | { type: "layout-ready"; totalPages: number }+ | { type: "layout-change" }+ | { type: "scroll-request"; top: number };++type CarriedKind = "zoom" | "spread" | "rotation";++interface DocumentRestoreBridgeProps {+ request: DocumentRestoreRequest | null;+ restorePending: boolean;+ onEvent?: (event: DocumentRestoreEvent) => void;+}++// Answers that are not the carried value; a dropped request does not count.+const MAX_REFUSALS = 5;++const zoomMatches = (state: ZoomDocumentState, target: ZoomLevel) =>+ typeof target === "number"+ ? typeof state.zoomLevel === "number" &&+ Math.abs(state.currentZoomLevel - target) < 0.001+ : state.zoomLevel === target;++/**+ * Carries zoom, spread and rotation onto a replacement document. The zoom+ * plugin silently drops a request made before the viewport is measured, so+ * every later plugin event re-checks; the viewport applies plugin scrolls a+ * frame later, so those requests are forwarded for the viewer to correct.+ */+export function DocumentRestoreBridge({+ request,+ restorePending,+ onEvent,+}: DocumentRestoreBridgeProps) {+ const activeDocumentId = useActiveDocumentId();+ const documentReady = useDocumentReady();+ const addressed = request !== null && request.documentId === activeDocumentId;++ if (!activeDocumentId || !documentReady) return null;+ if (!restorePending && !addressed) return null;++ return (+ <DocumentRestoreBridgeInner+ key={activeDocumentId}+ documentId={activeDocumentId}+ request={addressed ? request : null}+ onEvent={onEvent}+ />+ );+}++function DocumentRestoreBridgeInner({+ documentId,+ request,+ onEvent,+}: {+ documentId: string;+ request: DocumentRestoreRequest | null;+ onEvent?: (event: DocumentRestoreEvent) => void;+}) {+ // forDocument() returns a fresh object per call: derive scopes inside effects.+ const { provides: zoom } = useZoomCapability();+ const { provides: spread } = useSpreadCapability();+ const { provides: rotate } = useRotateCapability();+ const { provides: scroll } = useScrollCapability();+ const { provides: viewport } = useViewportCapability();+ const { plugin: viewportPlugin } = useViewportPlugin();+ const [tick, setTick] = useState(0);+ const bump = useCallback(() => setTick((value) => value + 1), []);+ const onEventRef = useRef(onEvent);+ onEventRef.current = onEvent;+ const landedRef = useRef<Record<CarriedKind, boolean>>({+ zoom: false,+ spread: false,+ rotation: false,+ });+ const requestedRef = useRef<Record<CarriedKind, boolean>>({+ zoom: false,+ spread: false,+ rotation: false,+ });+ const refusalsRef = useRef<Record<CarriedKind, number>>({+ zoom: 0,+ spread: 0,+ rotation: 0,+ });+ // Until measured, a replacement sits at a placeholder scale in its default mode.+ const zoomPassSeenRef = useRef(false);+ // A spread changed while the state bridges mount reaches the toolbar out of order.+ const layoutReadyRef = useRef(false);++ useLayoutEffect(() => {+ const forDocument = (event: { documentId: string }) =>+ event.documentId === documentId;+ const emit = (event: DocumentRestoreEvent) => onEventRef.current?.(event);+ const answered = (kind: CarriedKind) => () => {+ if (requestedRef.current[kind]) {+ requestedRef.current[kind] = false;+ refusalsRef.current[kind] += 1;+ }+ bump();+ };+ const unsubscribes = [+ zoom?.forDocument(documentId).onStateChange(answered("zoom")),+ zoom?.forDocument(documentId).onZoomChange(() => {+ zoomPassSeenRef.current = true;+ bump();+ }),+ spread?.forDocument(documentId).onSpreadChange(answered("spread")),+ rotate?.forDocument(documentId).onRotateChange(answered("rotation")),+ scroll?.onLayoutReady((event) => {+ if (!forDocument(event)) return;+ layoutReadyRef.current = true;+ emit({ type: "layout-ready", totalPages: event.totalPages });+ bump();+ }),+ scroll?.onLayoutChange((event) => {+ if (!forDocument(event)) return;+ emit({ type: "layout-change" });+ bump();+ }),+ viewport?.onViewportResize((event) => {+ if (forDocument(event)) bump();+ }),+ viewportPlugin?.onScrollRequest(documentId, (scrollRequest) => {+ emit({ type: "scroll-request", top: scrollRequest.y });+ }),+ ];+ return () => {+ for (const unsubscribe of unsubscribes) unsubscribe?.();+ };+ }, [+ zoom,+ spread,+ rotate,+ scroll,+ viewport,+ viewportPlugin,+ documentId,+ bump,+ ]);++ useLayoutEffect(() => {+ if (!request || !layoutReadyRef.current) return;+ const landed = landedRef.current;+ const requested = requestedRef.current;+ const refusals = refusalsRef.current;+ const settle = (kind: CarriedKind) => {+ landed[kind] = true;+ onEventRef.current?.({ type: kind });+ };+ // Never confirmed in the run that requested it: the pages have not re-rendered.+ const reconcile = (+ kind: CarriedKind,+ matches: () => boolean,+ apply: () => void,+ ) => {+ if (landed[kind]) return;+ if (matches() || refusals[kind] >= MAX_REFUSALS) {+ settle(kind);+ return;+ }+ requested[kind] = true;+ try {+ apply();+ } catch {+ requested[kind] = false;+ }+ };++ // Rotation and spread first: a fit zoom is computed against their layout.+ if (request.rotation === null) {+ landed.rotation = true;+ } else if (rotate) {+ const scope = rotate.forDocument(documentId);+ const target = request.rotation as Rotation;+ reconcile(+ "rotation",+ () => scope.getRotation() === target,+ () => scope.setRotation(target),+ );+ }+ if (request.spread === null) {+ landed.spread = true;+ } else if (spread) {+ const scope = spread.forDocument(documentId);+ const target = request.spread;+ reconcile(+ "spread",+ () => scope.getSpreadMode() === target,+ () => scope.setSpreadMode(target),+ );+ }+ if (request.zoom === null) {+ landed.zoom = true;+ } else if (zoom) {+ const scope = zoom.forDocument(documentId);+ const target = request.zoom;+ reconcile(+ "zoom",+ () =>+ zoomMatches(scope.getState(), target) &&+ (typeof target === "number" || zoomPassSeenRef.current),+ () => scope.requestZoom(target),+ );+ }+ }, [request, zoom, spread, rotate, documentId, tick]);++ return null;+}diff --git a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsxindex 53dd9812b6..8685b01d4e 100644--- a/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx+++ b/frontend/editor/src/core/components/viewer/DocumentSwapBridge.tsx@@ -8,7 +8,7 @@ interface PendingDocument {interface DocumentSwapBridgeProps {pending: PendingDocument | null;- onSwapped: () => void;+ onSwapped: (documentId: string) => void;onFailed: (error: unknown) => void;}@@ -60,7 +60,7 @@ export function DocumentSwapBridge({try {documentManager.setActiveDocument(response.documentId);- onSwapped();+ onSwapped(response.documentId);if (previousId && previousId !== response.documentId) {// A failed close only leaks a background document until unmount.void documentManagerdiff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex 819d68008c..a5c3131d2e 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -20,6 +20,10 @@ import {} from "@app/contexts/FileContext";import { useFileWithUrl } from "@app/hooks/useFileWithUrl";import { ZoomMode } from "@embedpdf/plugin-zoom/react";+import type {+ DocumentRestoreEvent,+ DocumentRestoreRequest,+} from "@app/components/viewer/DocumentRestoreBridge";import { useViewer } from "@app/contexts/ViewerContext";import { LocalEmbedPDF } from "@app/components/viewer/LocalEmbedPDF";import { PdfViewerToolbar } from "@app/components/viewer/PdfViewerToolbar";@@ -86,11 +90,10 @@ export interface EmbedPdfViewerProps {const documentCacheKey = (file: StirlingFile): string =>`${file.fileId}|${file.quickKey}`;-// Slow engines can take seconds to report the replacement's page count and-// land the carried zoom; the hide lasts until then, not for a fixed flash.-const SWAP_REVEAL_DEADLINE_MS = 5_000;-// Re-checks how often the hide decides whether the carried zoom has landed.-const SWAP_REVEAL_HIDE_RECHECK_MS = 250;+// Guards only; a restore completes on plugin events. A missed event costs a+// wrong-scale frame after the hide cap, not a blank viewer until the other.+const RESTORE_SETTLE_CAP_MS = 15_000;+const HIDE_CAP_MS = 5_000;const findScrollableAncestor = (el: HTMLElement | null): HTMLElement | null => {let node = el?.parentElement ?? null;@@ -142,7 +145,6 @@ const EmbedPdfViewerContent = ({getSpreadState,getZoomState,getRotationState,- spreadActions,zoomRestorePendingRef,notifyZoomRestoreSettled,setAnnotationMode,@@ -200,24 +202,23 @@ const EmbedPdfViewerContent = ({const pendingScrollRestoreRef = useRef<number | null>(null);const scrollRestoreAttemptsRef = useRef<number>(0);- // Rotation preservation system- // Similar to scroll preservation - track rotation across file reloadsconst pendingRotationRestoreRef = useRef<number | null>(null);- const rotationRestoreAttemptsRef = useRef<number>(0);-- // The zoom survives an in-place reload, mode or number: a replacement opens- // at the plugin default otherwise, which reads as the zoom changing.const pendingZoomRestoreRef = useRef<ZoomLevel | null>(null);- // Spread mode is per document, so a replacement opens single-page unless it- // is carried over like the position.const pendingSpreadRestoreRef = useRef<SpreadMode | null>(null);+ const [restoreRequest, setRestoreRequest] =+ useState<DocumentRestoreRequest | null>(null);+ const replacementLayoutReadyRef = useRef(false);+ // From layout-ready; the scroll bridge can still hold the outgoing document's.+ const replacementTotalPagesRef = useRef(0);+ // Plugin scrolls the viewport has yet to apply on its next animation frame.+ const pluginScrollsRef = useRef(0);+ const restoreCapTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);// The toolbar must not show the plugin's intermediate fit pass while a// carried zoom lands, so the bridge publishes nothing until this settles.const settleZoomRestore = useCallback(() => {zoomRestorePendingRef.current = false;notifyZoomRestoreSettled();}, [zoomRestorePendingRef, notifyZoomRestoreSettled]);- const zoomRestoreAttemptsRef = useRef<number>(0);// Reading position captured from the outgoing document: the page's node// identifies the swap, the offsets restore the exact spot within the page.const pendingScrollPositionRef = useRef<{@@ -228,48 +229,30 @@ const EmbedPdfViewerContent = ({element: HTMLElement | null;scroller: HTMLElement | null;expectSwap: boolean;- /** A fraction apply landed against the replacement's own geometry. */- fractionApplied: boolean;} | null>(null);const pendingScrollSwappedRef = useRef(false);- const pendingScrollReassertTimerRef = useRef<number | null>(null);// Content key of a just-saved file whose visual state the live document// already shows: skip the reopen so a save cannot move the view.const skipReloadContentKeyRef = useRef<string | null>(null);- // Bumped when a replacement seeds the pending refs, so the restore effects- // run even when the page count does not change across the swap.const [restoreTick, setRestoreTick] = useState(0);- // True only while a restore is in flight, so the per-page layout hook and- // the swap backstop cost nothing during ordinary scrolling.const [restorePending, setRestorePending] = useState(false);- // A replacement renders at the wrong scale until its zoom lands, so the- // scroller hides for that window. The hide survives until the carried zoom- // lands (revealing early shows a wrong-scale frame), capped so a failed- // restore can never leave it hidden.- const swapRevealRef = useRef<{- scroller: HTMLElement | null;- timer: ReturnType<typeof setTimeout> | null;- deadline: number;- }>({ scroller: null, timer: null, deadline: 0 });- // Last scroll target the restore computed, used to reveal only once the- // layout has stopped moving the target around.+ const hiddenScrollerRef = useRef<HTMLElement | null>(null);+ const hideCapTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);const swapTargetRef = useRef<number | null>(null);- // Layout signature (page height + content height) of the last apply, so the- // per-frame hold can skip when the page already sits at the target.const swapLayoutRef = useRef<string | null>(null);// Activation and the replacement pages' React commit happen separately.const documentSwappedRef = useRef(false);const scrollIntentCleanupRef = useRef<(() => void) | null>(null);const revealSwappedDocument = useCallback(() => {- const state = swapRevealRef.current;- if (state.timer !== null) {- clearTimeout(state.timer);- state.timer = null;+ if (hideCapTimerRef.current !== null) {+ clearTimeout(hideCapTimerRef.current);+ hideCapTimerRef.current = null;}- if (state.scroller) {- state.scroller.style.visibility = "";- state.scroller = null;+ const scroller = hiddenScrollerRef.current;+ if (scroller) {+ scroller.style.visibility = "";+ hiddenScrollerRef.current = null;}}, []);@@ -278,23 +261,61 @@ const EmbedPdfViewerContent = ({scrollIntentCleanupRef.current = null;}, []);- // Single release path: drop the target, stop the hold, stop listening for- // intent and show the content again.+ const clearRestoreCap = useCallback(() => {+ if (restoreCapTimerRef.current !== null) {+ clearTimeout(restoreCapTimerRef.current);+ restoreCapTimerRef.current = null;+ }+ }, []);+const clearPendingScrollRestore = useCallback(() => {pendingScrollPositionRef.current = null;- if (pendingScrollReassertTimerRef.current !== null) {- cancelAnimationFrame(pendingScrollReassertTimerRef.current);- pendingScrollReassertTimerRef.current = null;- }detachScrollIntentListeners();revealSwappedDocument();setRestorePending(false);}, [detachScrollIntentListeners, revealSwappedDocument]);+ const finishScrollRestore = useCallback(() => {+ pendingScrollRestoreRef.current = null;+ scrollRestoreAttemptsRef.current = 0;+ swapTargetRef.current = null;+ swapLayoutRef.current = null;+ clearPendingScrollRestore();+ }, [clearPendingScrollRestore]);++ const completeRestore = useCallback(() => {+ clearRestoreCap();+ documentSwappedRef.current = false;+ replacementLayoutReadyRef.current = false;+ replacementTotalPagesRef.current = 0;+ pluginScrollsRef.current = 0;+ setRestoreRequest(null);+ finishScrollRestore();+ }, [clearRestoreCap, finishScrollRestore]);++ const abandonRestore = useCallback(() => {+ pendingZoomRestoreRef.current = null;+ pendingSpreadRestoreRef.current = null;+ pendingRotationRestoreRef.current = null;+ if (zoomRestorePendingRef.current) settleZoomRestore();+ completeRestore();+ }, [zoomRestorePendingRef, settleZoomRestore, completeRestore]);++ const armRestoreCap = useCallback(() => {+ clearRestoreCap();+ restoreCapTimerRef.current = setTimeout(() => {+ restoreCapTimerRef.current = null;+ console.warn(+ "[EmbedPdfViewer] Carried view state never settled on the replacement; showing it as is.",+ );+ abandonRestore();+ }, RESTORE_SETTLE_CAP_MS);+ }, [clearRestoreCap, abandonRestore]);+const attachScrollIntentListeners = useCallback(() => {const scroller = pendingScrollPositionRef.current?.scroller;if (!scroller || scrollIntentCleanupRef.current) return;- const release = () => clearPendingScrollRestore();+ const release = () => finishScrollRestore();const events = ["wheel", "touchstart", "pointerdown", "keydown"];for (const name of events) {scroller.addEventListener(name, release, { passive: true });@@ -304,86 +325,77 @@ const EmbedPdfViewerContent = ({scroller.removeEventListener(name, release);}};- }, [clearPendingScrollRestore]);+ }, [finishScrollRestore]);- const hideUntilSettled = useCallback(+ const hideSwappedDocument = useCallback((scroller: HTMLElement | null) => {- if (!scroller) return;- swapRevealRef.current.scroller = scroller;- swapRevealRef.current.deadline =- performance.now() + SWAP_REVEAL_DEADLINE_MS;+ if (!scroller || hiddenScrollerRef.current === scroller) return;+ revealSwappedDocument();+ hiddenScrollerRef.current = scroller;scroller.style.visibility = "hidden";- const arm = () => {- if (swapRevealRef.current.timer !== null) {- clearTimeout(swapRevealRef.current.timer);- }- swapRevealRef.current.timer = setTimeout(() => {- // The carried zoom is the reason the scroller is hidden: a reveal- // before it lands paints the wrong scale on the next frame.- if (- (pendingZoomRestoreRef.current !== null ||- pendingSpreadRestoreRef.current !== null) &&- performance.now() < swapRevealRef.current.deadline- ) {- arm();- return;- }- clearPendingScrollRestore();- }, SWAP_REVEAL_HIDE_RECHECK_MS);- };- arm();+ // Carried values keep landing after this reveal.+ hideCapTimerRef.current = setTimeout(() => {+ hideCapTimerRef.current = null;+ revealSwappedDocument();+ if (zoomRestorePendingRef.current) settleZoomRestore();+ }, HIDE_CAP_MS);},- [clearPendingScrollRestore],+ [revealSwappedDocument, zoomRestorePendingRef, settleZoomRestore],);- const queueScrollRestore = useCallback((page: number, expectSwap = false) => {- pendingScrollRestoreRef.current = page;- scrollRestoreAttemptsRef.current = 0;- pendingScrollSwappedRef.current = false;+ const queueScrollRestore = useCallback(+ (page: number, expectSwap = false) => {+ pendingScrollRestoreRef.current = page;+ scrollRestoreAttemptsRef.current = 0;+ pendingScrollSwappedRef.current = false;- const element = document.querySelector<HTMLElement>(- `[data-page-index="${page - 1}"]`,- );- const scroller = findScrollableAncestor(element);- if (!element || !scroller) {- pendingScrollPositionRef.current = null;+ const element = document.querySelector<HTMLElement>(+ `[data-page-index="${page - 1}"]`,+ );+ const scroller = findScrollableAncestor(element);+ if (!element || !scroller) {+ pendingScrollPositionRef.current = null;+ swapTargetRef.current = null;+ swapLayoutRef.current = null;+ documentSwappedRef.current = false;+ return;+ }+ const scrollerTop = scroller.getBoundingClientRect().top;+ const pageTopInContent =+ element.getBoundingClientRect().top - scrollerTop + scroller.scrollTop;+ const offsetPx = scroller.scrollTop - pageTopInContent;+ const offsetFraction =+ element.clientHeight > 0 ? offsetPx / element.clientHeight : 0;+ pendingScrollPositionRef.current = {+ page,+ offsetPx,+ offsetFraction,+ pageHeight: element.clientHeight,+ element,+ scroller,+ expectSwap,+ };+ setRestorePending(true);+ armRestoreCap();swapTargetRef.current = null;swapLayoutRef.current = null;documentSwappedRef.current = false;- return;- }- const scrollerTop = scroller.getBoundingClientRect().top;- const pageTopInContent =- element.getBoundingClientRect().top - scrollerTop + scroller.scrollTop;- const offsetPx = scroller.scrollTop - pageTopInContent;- const offsetFraction =- element.clientHeight > 0 ? offsetPx / element.clientHeight : 0;- pendingScrollPositionRef.current = {- page,- offsetPx,- offsetFraction,- pageHeight: element.clientHeight,- element,- scroller,- expectSwap,- fractionApplied: false,- };- // Arm the pre-paint restore gates (the per-page layout hook and the swap- // layout effect); every completion path clears through- // clearPendingScrollRestore.- setRestorePending(true);- swapTargetRef.current = null;- swapLayoutRef.current = null;- documentSwappedRef.current = false;- }, []);+ },+ [armRestoreCap],+ );const resolvePendingScrollPage = useCallback(() => {const pending = pendingScrollPositionRef.current;if (!pending) return null;- // A clamped index can also exist in the outgoing document. Wait for its- // captured node to detach before resolving any replacement page.- if (pending.expectSwap && pending.element?.isConnected) return null;- const totalPages = getScrollState().totalPages;+ if (pending.expectSwap) {+ // The ready pass resets the offset and fixes the page count.+ if (!replacementLayoutReadyRef.current) return null;+ // A clamped index can also exist in the outgoing document.+ if (pending.element?.isConnected) return null;+ }+ const totalPages = pending.expectSwap+ ? replacementTotalPagesRef.current+ : getScrollState().totalPages;if (totalPages < 1) return null;const targetPage = Math.min(pending.page, totalPages);const page = document.querySelector<HTMLElement>(@@ -394,135 +406,73 @@ const EmbedPdfViewerContent = ({return page;}, [getScrollState]);- const applyScrollNow = useCallback(- (useFraction: boolean): boolean => {- const pending = pendingScrollPositionRef.current;- if (- !pending ||- pending.offsetPx === null ||- pending.offsetFraction === null- ) {- clearPendingScrollRestore();- return false;- }- const pageEl = resolvePendingScrollPage();- // The scroller survives document swaps; walking ancestors on every frame- // of the hold is what made it expensive.- const scroller =- pending.scroller && pending.scroller.isConnected- ? pending.scroller- : findScrollableAncestor(pageEl);- if (!pageEl || !scroller) return false;- pending.scroller = scroller;-- // The fraction only matters when the page geometry changed (a zoom- // restore); otherwise the captured pixel offset is exact.- const heightChanged =- pending.pageHeight !== null &&- Math.abs(pageEl.clientHeight - pending.pageHeight) > 1;- // A fraction apply means the replacement's geometry is settled even- // though it differs; a carried zoom keeps it unsettled until it lands.- const geometrySettled =- (!heightChanged || pending.fractionApplied) &&- pendingZoomRestoreRef.current === null &&- pendingSpreadRestoreRef.current === null;-- // Nothing moved since the last apply: no rect reads needed, but the- // settled scale still has to reveal the content.- const layoutSignature = `${pageEl.clientHeight}|${scroller.scrollHeight}`;- const lastTarget = swapTargetRef.current;- if (- layoutSignature === swapLayoutRef.current &&- lastTarget !== null &&- Math.abs(scroller.scrollTop - lastTarget) <= 1- ) {- if (geometrySettled) {- revealSwappedDocument();- }- return true;- }- const offset =- useFraction && heightChanged- ? pending.offsetFraction * pageEl.clientHeight- : pending.offsetPx;- const scrollerTop = scroller.getBoundingClientRect().top;- const pageTopInContent =- pageEl.getBoundingClientRect().top - scrollerTop + scroller.scrollTop;- const target = Math.max(0, pageTopInContent + offset);- swapLayoutRef.current = layoutSignature;- scroller.scrollTop = target;- // Reveal once the scale settled and two frames agree on the target: a- // neighbour still moves it while the height already matches.- const stable =- geometrySettled &&- swapTargetRef.current !== null &&- Math.abs(swapTargetRef.current - target) <= 2;- swapTargetRef.current = target;- if (useFraction && heightChanged) {- // The fraction now maps to the replacement's own page height.- pending.fractionApplied = true;- }- if (stable) {- revealSwappedDocument();- }+ const applyScrollNow = useCallback((): boolean => {+ const pending = pendingScrollPositionRef.current;+ if (+ !pending ||+ pending.offsetPx === null ||+ pending.offsetFraction === null+ ) {+ finishScrollRestore();+ return false;+ }+ const pageEl = resolvePendingScrollPage();+ const scroller =+ pending.scroller && pending.scroller.isConnected+ ? pending.scroller+ : findScrollableAncestor(pageEl);+ if (!pageEl || !scroller) return false;+ pending.scroller = scroller;++ const layoutSignature = `${pageEl.clientHeight}|${scroller.scrollHeight}`;+ const lastTarget = swapTargetRef.current;+ if (+ layoutSignature === swapLayoutRef.current &&+ lastTarget !== null &&+ Math.abs(scroller.scrollTop - lastTarget) <= 1+ ) {return true;- },- [revealSwappedDocument, resolvePendingScrollPage],- );+ }+ const heightChanged =+ pending.pageHeight !== null &&+ Math.abs(pageEl.clientHeight - pending.pageHeight) > 1;+ const offset = heightChanged+ ? pending.offsetFraction * pageEl.clientHeight+ : pending.offsetPx;+ const scrollerTop = scroller.getBoundingClientRect().top;+ const pageTopInContent =+ pageEl.getBoundingClientRect().top - scrollerTop + scroller.scrollTop;+ const target = Math.max(0, pageTopInContent + offset);+ swapLayoutRef.current = layoutSignature;+ swapTargetRef.current = target;+ scroller.scrollTop = target;+ return true;+ }, [finishScrollRestore, resolvePendingScrollPage]);++ const applyPendingScrollPosition = useCallback((): boolean => {+ const pending = pendingScrollPositionRef.current;+ if (!pending) return false;- // Re-apply the captured position to the swapped document. Returns false until- // the replacement page node exists and while no offset was captured.- const applyPendingScrollPosition = useCallback(- (options?: { useFraction?: boolean }): boolean => {- const pending = pendingScrollPositionRef.current;- if (!pending) return false;-- const pageEl = resolvePendingScrollPage();- if (!pageEl) return false;- if (!pendingScrollSwappedRef.current) {- const sameDocument = !pending.expectSwap;- if (!pending.scroller?.isConnected) {- pending.scroller = findScrollableAncestor(pageEl);- }- if (!sameDocument) {- // First frame of the replacement: hide it until it settles so no- // wrong-scale or wrong-position frame can be seen.- hideUntilSettled(pending.scroller);- }- attachScrollIntentListeners();+ const pageEl = resolvePendingScrollPage();+ if (!pageEl) return false;+ if (!pendingScrollSwappedRef.current) {+ if (!pending.scroller?.isConnected) {+ pending.scroller = findScrollableAncestor(pageEl);}- if (!applyScrollNow(options?.useFraction ?? false)) return false;- pendingScrollSwappedRef.current = true;-- // The replacement's own ready pass can still reset the scroll, so hold- // the position per frame for a short bounded window.- if (pendingScrollReassertTimerRef.current) {- cancelAnimationFrame(pendingScrollReassertTimerRef.current);+ if (pending.expectSwap) {+ hideSwappedDocument(pending.scroller);}- const useFraction = options?.useFraction ?? false;- const holdUntil = performance.now() + 1_500;- const reassert = () => {- if (!pendingScrollPositionRef.current) return;- if (performance.now() >= holdUntil) {- clearPendingScrollRestore();- return;- }- applyScrollNow(useFraction);- pendingScrollReassertTimerRef.current = requestAnimationFrame(reassert);- };- pendingScrollReassertTimerRef.current = requestAnimationFrame(reassert);-- return true;- },- [- applyScrollNow,- clearPendingScrollRestore,- hideUntilSettled,- attachScrollIntentListeners,- revealSwappedDocument,- resolvePendingScrollPage,- ],- );+ attachScrollIntentListeners();+ }+ if (!applyScrollNow()) return false;+ pendingScrollSwappedRef.current = true;+ return true;+ }, [+ applyScrollNow,+ hideSwappedDocument,+ attachScrollIntentListeners,+ resolvePendingScrollPage,+ ]);const formApplyInProgressRef = useRef(false);const applyChangesInFlightRef = useRef<Promise<void> | null>(null);@@ -1159,12 +1109,6 @@ const EmbedPdfViewerContent = ({"[Viewer] Applying form fill changes - reloading filled PDF",);- // Use the continuously tracked scroll position- const pageToRestore = lastKnownScrollPageRef.current;-- // Save the current rotation to restore after reload- const currentRotation = rotationState.rotation ?? 0;-// Convert Blob to Fileconst filename = currentFile.name || "document.pdf";const file = new File([filledBlob], filename, {@@ -1185,13 +1129,6 @@ const EmbedPdfViewerContent = ({selectedTool ?? "multiTool",);- // Store the page to restore after file replacement- queueScrollRestore(pageToRestore, true);-- // Store the rotation to restore after file replacement- pendingRotationRestoreRef.current = currentRotation;- rotationRestoreAttemptsRef.current = 0;-const newFileId = stubs[0]?.id;if (newFileId) setActiveFileId(newFileId);@@ -1235,9 +1172,6 @@ const EmbedPdfViewerContent = ({layerApplyInProgressRef.current = true;try {- const pageToRestore = lastKnownScrollPageRef.current;- const currentRotation = rotationState.rotation ?? 0;-const filename = currentFile.name || "document.pdf";const file = new File([modifiedBlob], filename, {type: "application/pdf",@@ -1255,10 +1189,6 @@ const EmbedPdfViewerContent = ({selectedTool ?? "multiTool",);- queueScrollRestore(pageToRestore, true);- pendingRotationRestoreRef.current = currentRotation;- rotationRestoreAttemptsRef.current = 0;-const newFileId = stubs[0]?.id;if (newFileId) setActiveFileId(newFileId);@@ -1294,10 +1224,6 @@ const EmbedPdfViewerContent = ({"[Viewer] Discarding pending marks but saving applied redactions",);- // Save current view state to restore after file replacement- const pageToRestore = lastKnownScrollPageRef.current;- const currentRotation = rotationState.rotation ?? 0;-// Export PDF WITHOUT committing pending marks - this saves only applied redactionsconst arrayBuffer = await exportActions.saveAsCopy();if (!arrayBuffer) {@@ -1322,11 +1248,6 @@ const EmbedPdfViewerContent = ({selectedTool ?? "multiTool",);- // Store view state to restore after file replacement- queueScrollRestore(pageToRestore, true);- pendingRotationRestoreRef.current = currentRotation;- rotationRestoreAttemptsRef.current = 0;-const newFileId = stubs[0]?.id;if (newFileId) setActiveFileId(newFileId);@@ -1408,7 +1329,13 @@ const EmbedPdfViewerContent = ({if (!previous || !root || !content) return;if (previous.encrypted || encrypted) return;if (previous.root !== root || previous.content === content) return;+ // A save the live document already shows is not reopened (shouldSkipBytes),+ // so no replacement would ever report back.+ if (skipReloadContentKeyRef.current === content) return;+ // Only a replacement already activated shows intermediate values; any+ // earlier state is re-read rather than carried over.+ const keepTargets = documentSwappedRef.current;const page = getScrollState().currentPage || lastKnownScrollPageRef.current;if (page > 0) {// Captures the within-page offset and waits for the replacement node, so@@ -1416,23 +1343,29 @@ const EmbedPdfViewerContent = ({queueScrollRestore(page, true);}- pendingRotationRestoreRef.current = getRotationState().rotation ?? 0;- rotationRestoreAttemptsRef.current = 0;-- const zoom = getZoomState();- // Automatic re-evaluates against the unmounted shell; preserve the numeric scale.- const level =- zoom.level === ZoomMode.Automatic && typeof zoom.currentZoom === "number"- ? zoom.currentZoom- : (zoom.level ?? zoom.currentZoom);- if (level !== undefined && level !== null) {- pendingZoomRestoreRef.current = level;- zoomRestoreAttemptsRef.current = 0;- zoomRestorePendingRef.current = true;+ if (!keepTargets || pendingRotationRestoreRef.current === null) {+ pendingRotationRestoreRef.current = getRotationState().rotation ?? 0;}- pendingSpreadRestoreRef.current = getSpreadState().spreadMode ?? null;+ if (!keepTargets || pendingZoomRestoreRef.current === null) {+ const zoom = getZoomState();+ // Automatic re-evaluates against the unmounted shell; preserve the numeric scale.+ const level =+ zoom.level === ZoomMode.Automatic &&+ typeof zoom.currentZoom === "number"+ ? zoom.currentZoom+ : (zoom.level ?? zoom.currentZoom);+ if (level !== undefined && level !== null) {+ pendingZoomRestoreRef.current = level;+ zoomRestorePendingRef.current = true;+ }+ }++ if (!keepTargets || pendingSpreadRestoreRef.current === null) {+ pendingSpreadRestoreRef.current = getSpreadState().spreadMode ?? null;+ }+ armRestoreCap();setRestoreTick((tick) => tick + 1);}, [currentFileRootId,@@ -1443,6 +1376,8 @@ const EmbedPdfViewerContent = ({getZoomState,getSpreadState,queueScrollRestore,+ armRestoreCap,+ zoomRestorePendingRef,]);const replacementPagesMounted = useCallback(() => {const pending = pendingScrollPositionRef.current;@@ -1471,35 +1406,18 @@ const EmbedPdfViewerContent = ({const finish = () => {if (cancelled) return;- pendingScrollRestoreRef.current = null;- scrollRestoreAttemptsRef.current = 0;- swapTargetRef.current = null;- swapLayoutRef.current = null;- clearPendingScrollRestore();+ finishScrollRestore();};const attemptScroll = () => {if (cancelled) return;const currentState = getScrollState();const targetPage = Math.min(pageToRestore, currentState.totalPages);- const captured = pendingScrollPositionRef.current;- if (captured) {- // An exact capture never falls back to the page top; wait for the- // replacement (or apply straight away for a same-document restore).- if (- !applyPendingScrollPosition({- useFraction: pendingZoomRestoreRef.current !== null,- })- ) {- if (performance.now() < deadline) {- retry();- } else {- finish();- }- return;- }- pendingScrollRestoreRef.current = null;- scrollRestoreAttemptsRef.current = 0;+ // A captured, finished or released restore is never snapped to the page top.+ if (+ pendingScrollPositionRef.current ||+ pendingScrollRestoreRef.current === null+ ) {return;}@@ -1537,44 +1455,112 @@ const EmbedPdfViewerContent = ({scrollState.totalPages,scrollActions,getScrollState,- applyPendingScrollPosition,- clearPendingScrollRestore,+ finishScrollRestore,]);- // Activation precedes React's commit; restoration waits for the new page nodes.- const handleDocumentSwapped = useCallback(() => {+ const handleDocumentSwapped = useCallback((documentId: string) => {documentSwappedRef.current = true;+ replacementLayoutReadyRef.current = false;+ replacementTotalPagesRef.current = 0;+ pluginScrollsRef.current = 0;+ const zoom = pendingZoomRestoreRef.current;+ const spread = pendingSpreadRestoreRef.current;+ const rotation = pendingRotationRestoreRef.current;+ setRestoreRequest(+ zoom === null && spread === null && rotation === null+ ? null+ : { documentId, zoom, spread, rotation },+ );setRestoreTick((tick) => tick + 1);}, []);const handleDocumentSwapFailed = useCallback(() => {- clearPendingScrollRestore();- }, [clearPendingScrollRestore]);+ abandonRestore();+ }, [abandonRestore]);++ const maybeFinishRestore = useCallback(() => {+ if (+ pendingZoomRestoreRef.current !== null ||+ pendingSpreadRestoreRef.current !== null ||+ pendingRotationRestoreRef.current !== null+ ) {+ return;+ }+ if (pluginScrollsRef.current > 0) return;+ const pending = pendingScrollPositionRef.current;+ if (pending?.expectSwap) {+ if (!documentSwappedRef.current) return;+ if (!replacementLayoutReadyRef.current) return;+ if (!pendingScrollSwappedRef.current) return;+ }+ completeRestore();+ }, [completeRestore]);++ const handleRestoreEvent = useCallback(+ (event: DocumentRestoreEvent) => {+ switch (event.type) {+ case "zoom":+ pendingZoomRestoreRef.current = null;+ settleZoomRestore();+ break;+ case "spread":+ pendingSpreadRestoreRef.current = null;+ break;+ case "rotation":+ pendingRotationRestoreRef.current = null;+ break;+ case "layout-ready":+ replacementLayoutReadyRef.current = true;+ replacementTotalPagesRef.current = event.totalPages;+ break;+ case "layout-change":+ break;+ case "scroll-request": {+ // Queued behind the viewport's own rAF callback: same frame, before paint.+ if (!pendingScrollPositionRef.current) return;+ pluginScrollsRef.current += 1;+ const correct = (retry: boolean) => {+ const scroller = pendingScrollPositionRef.current?.scroller;+ const landed =+ !scroller || Math.abs(scroller.scrollTop - event.top) <= 1;+ if (!landed && retry) {+ requestAnimationFrame(() => correct(false));+ return;+ }+ pluginScrollsRef.current = Math.max(+ 0,+ pluginScrollsRef.current - 1,+ );+ applyPendingScrollPosition();+ maybeFinishRestore();+ };+ queueMicrotask(() => requestAnimationFrame(() => correct(true)));+ return;+ }+ }+ applyPendingScrollPosition();+ maybeFinishRestore();+ },+ [settleZoomRestore, applyPendingScrollPosition, maybeFinishRestore],+ );+useLayoutEffect(() => {if (!restorePending) return;if (pendingScrollRestoreRef.current === null) return;if (!pendingScrollPositionRef.current) return;if (!documentSwappedRef.current) return;if (pendingScrollSwappedRef.current) return;- applyPendingScrollPosition({- useFraction: pendingZoomRestoreRef.current !== null,- });+ applyPendingScrollPosition();});- // Runs from the layout pass that mounts the replacement's pages, so the saved- // position lands before their first frame paints.const handleViewerPageLayout = useCallback(() => {if (pendingScrollRestoreRef.current === null) return;if (!pendingScrollPositionRef.current) return;- if (pendingScrollSwappedRef.current) return;if (!replacementPagesMounted()) return;- setRestoreTick((tick) => tick + 1);- applyPendingScrollPosition({- useFraction: pendingZoomRestoreRef.current !== null,- });- }, [applyPendingScrollPosition, replacementPagesMounted]);+ applyPendingScrollPosition();+ maybeFinishRestore();+ }, [applyPendingScrollPosition, maybeFinishRestore, replacementPagesMounted]);- // Never leave the viewer hidden or holding a scroll if this unmounts mid-swap.- useEffect(() => clearPendingScrollRestore, [clearPendingScrollRestore]);+ useEffect(() => abandonRestore, [abandonRestore]);// Uses polling with retries to ensure the scroll succeedsuseEffect(() => {if (pendingScrollRestoreRef.current === null) return;@@ -1587,9 +1573,12 @@ const EmbedPdfViewerContent = ({const currentState = getScrollState();const targetPage = Math.min(pageToRestore, currentState.totalPages);- // An exact-offset capture is restored by the layout attempt and held by- // the reassert chain; the page-level fallback would snap to the page top.- if (pendingScrollPositionRef.current) return;+ if (+ pendingScrollPositionRef.current ||+ pendingScrollRestoreRef.current === null+ ) {+ return;+ }// Only attempt if we have valid state (totalPages > 0 means PDF is loaded)if (currentState.totalPages > 0 && targetPage > 0) {@@ -1633,210 +1622,6 @@ const EmbedPdfViewerContent = ({return () => clearTimeout(timer);}, [restoreTick, scrollState.totalPages, scrollActions, getScrollState]);- // Restore rotation after file replacement or tool switch- // Uses polling with retries to ensure rotation is applied- useEffect(() => {- if (pendingRotationRestoreRef.current === null) return;-- const rotationToRestore = pendingRotationRestoreRef.current;- const maxAttempts = 10;- const attemptInterval = 100; // ms between attempts-- const attemptRotation = () => {- if (- pendingScrollPositionRef.current?.expectSwap &&- (!documentSwappedRef.current || !replacementPagesMounted())- ) {- return;- }- if (getScrollState().totalPages > 0) {- // Check if rotation already matches- const currentRotation = rotationActions.getRotation();- if (currentRotation === rotationToRestore) {- pendingRotationRestoreRef.current = null;- rotationRestoreAttemptsRef.current = 0;- return;- }-- // Apply rotation- rotationActions.setRotation(rotationToRestore);-- // Verify rotation succeeded after a brief delay- setTimeout(() => {- const afterRotation = rotationActions.getRotation();- if (afterRotation === rotationToRestore) {- pendingRotationRestoreRef.current = null;- rotationRestoreAttemptsRef.current = 0;- } else {- // Rotation might not have worked, retry- rotationRestoreAttemptsRef.current++;- if (rotationRestoreAttemptsRef.current < maxAttempts) {- setTimeout(attemptRotation, attemptInterval);- } else {- // Give up after max attempts- pendingRotationRestoreRef.current = null;- rotationRestoreAttemptsRef.current = 0;- }- }- }, 50);- } else if (rotationRestoreAttemptsRef.current < maxAttempts) {- // PDF not ready yet, retry- rotationRestoreAttemptsRef.current++;- setTimeout(attemptRotation, attemptInterval);- } else {- // Give up after max attempts- pendingRotationRestoreRef.current = null;- rotationRestoreAttemptsRef.current = 0;- }- };-- // Start attempting after initial delay- const timer = setTimeout(attemptRotation, 150);- return () => clearTimeout(timer);- }, [- restoreTick,- scrollState.totalPages,- rotationActions,- getScrollState,- replacementPagesMounted,- ]);-- // A replacement starts single-page, so the spread lands before the reading- // position settles or the pages reflow under it.- useEffect(() => {- if (pendingSpreadRestoreRef.current === null) return;-- const modeToRestore = pendingSpreadRestoreRef.current;- const deadline = performance.now() + 30_000;- let cancelled = false;- let timer: ReturnType<typeof setTimeout>;- const retry = () => {- if (performance.now() < deadline) {- timer = setTimeout(attemptSpread, 100);- } else {- pendingSpreadRestoreRef.current = null;- }- };-- const attemptSpread = () => {- if (cancelled) return;- if (- pendingScrollPositionRef.current?.expectSwap &&- (!documentSwappedRef.current || !replacementPagesMounted())- ) {- retry();- return;- }- if (getScrollState().totalPages > 0) {- if (spreadActions.getSpreadMode() === modeToRestore) {- pendingSpreadRestoreRef.current = null;- return;- } else {- spreadActions.setSpreadMode(modeToRestore);- // The spread reflows the pages, so any held position has to be- // recomputed against the new geometry.- swapLayoutRef.current = null;- swapTargetRef.current = null;- if (pendingScrollPositionRef.current) {- applyPendingScrollPosition({ useFraction: true });- }- }- }- retry();- };-- timer = setTimeout(attemptSpread, 0);- return () => {- cancelled = true;- clearTimeout(timer);- };- }, [- restoreTick,- scrollState.totalPages,- spreadActions,- getScrollState,- replacementPagesMounted,- applyPendingScrollPosition,- ]);-- // Re-asserts the carried zoom until it sticks; the plugin's own fit pass can- // override the first request and zoomRestorePendingRef keeps the UI quiet.- useEffect(() => {- const levelToRestore = pendingZoomRestoreRef.current;- if (levelToRestore === null) return;-- let cancelled = false;- // Matches the reveal cap: the scroller stays hidden until this loop either- // lands the zoom or runs out, so the two deadlines must not disagree.- const deadline = performance.now() + SWAP_REVEAL_DEADLINE_MS;-- const matchesLevel = () => {- const current = getZoomState();- if (current.level !== levelToRestore) return false;- return (- typeof levelToRestore !== "number" ||- Math.abs((current.currentZoom ?? 0) - levelToRestore) < 0.001- );- };-- const attemptZoom = () => {- if (cancelled) return;- // A byte replacement must land before this document's zoom can apply.- if (- pendingScrollPositionRef.current?.expectSwap &&- (!documentSwappedRef.current || !replacementPagesMounted())- ) {- if (performance.now() < deadline) {- setTimeout(attemptZoom, 100);- }- return;- }- if (getScrollState().totalPages === 0) {- if (performance.now() < deadline) {- setTimeout(attemptZoom, 100);- } else {- pendingZoomRestoreRef.current = null;- settleZoomRestore();- }- return;- }- if (matchesLevel()) {- pendingZoomRestoreRef.current = null;- zoomRestoreAttemptsRef.current = 0;- settleZoomRestore();- return;- }-- try {- zoomActions.requestZoom(levelToRestore);- } catch {- // Retried below while the deadline holds.- }- // The rescale moves the page geometry, so re-apply the reading offset.- applyPendingScrollPosition({ useFraction: true });- if (performance.now() < deadline) {- setTimeout(attemptZoom, 100);- } else {- pendingZoomRestoreRef.current = null;- settleZoomRestore();- }- };-- const timer = setTimeout(attemptZoom, 0);- return () => {- cancelled = true;- clearTimeout(timer);- };- }, [- restoreTick,- scrollState.totalPages,- zoomActions,- getScrollState,- getZoomState,- applyPendingScrollPosition,- settleZoomRestore,- replacementPagesMounted,- ]);// Register applyChanges with ViewerContext so tools can access it directlyuseEffect(() => {setApplyChanges(applyChanges);@@ -2013,6 +1798,8 @@ const EmbedPdfViewerContent = ({onDocumentSwapped={handleDocumentSwapped}onDocumentSwapFailed={handleDocumentSwapFailed}restorePending={restorePending}+ restoreRequest={restoreRequest}+ onRestoreEvent={handleRestoreEvent}pdfRenderMode={pdfRenderMode}file={effectiveFile.file}url={effectiveFile.url}diff --git a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsxindex dcdf1f1f12..abd296799a 100644--- a/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx+++ b/frontend/editor/src/core/components/viewer/LocalEmbedPDF.tsx@@ -95,6 +95,11 @@ import { RedactionSelectionMenu } from "@app/components/viewer/RedactionSelectioimport { AnnotationSelectionMenu } from "@app/components/viewer/AnnotationSelectionMenu";import { AnnotationMenuEvents } from "@app/components/viewer/AnnotationMenuEvents";import { DocumentSwapBridge } from "@app/components/viewer/DocumentSwapBridge";+import {+ DocumentRestoreBridge,+ type DocumentRestoreEvent,+ type DocumentRestoreRequest,+} from "@app/components/viewer/DocumentRestoreBridge";import { AnnotationDeletedMenu } from "@app/components/viewer/AnnotationDeletedMenu";import { TextSelectionMenu } from "@app/components/viewer/TextSelectionMenu";import {@@ -162,11 +167,13 @@ interface LocalEmbedPDFProps {/** Fires from the layout pass that mounts a page, before it paints. */onPageLayout?: () => void;/** Fires when the swap bridge activates a replacement document. */- onDocumentSwapped?: () => void;+ onDocumentSwapped?: (documentId: string) => void;/** Fires when the swap bridge fails to open or activate a replacement document. */onDocumentSwapFailed?: (error: unknown) => void;/** True while a view restore is in flight; gates the per-page layout hook. */restorePending?: boolean;+ restoreRequest?: DocumentRestoreRequest | null;+ onRestoreEvent?: (event: DocumentRestoreEvent) => void;}interface ViewerPageContainerProps {@@ -685,6 +692,8 @@ export function LocalEmbedPDF({onDocumentSwapped,onDocumentSwapFailed,restorePending = false,+ restoreRequest = null,+ onRestoreEvent,}: LocalEmbedPDFProps) {const { t } = useTranslation();const { config } = useAppConfig();@@ -909,12 +918,15 @@ export function LocalEmbedPDF({const [swapAnnouncement, setSwapAnnouncement] = useState<string | null>(null);- const handleDocumentSwapped = useCallback(() => {- onDocumentSwapped?.();- setPendingDocument(null);- setSwapAnnouncement(t("viewer.documentUpdated", "Document updated"));- setTimeout(() => setSwapAnnouncement(null), 3000);- }, [onDocumentSwapped, t]);+ const handleDocumentSwapped = useCallback(+ (documentId: string) => {+ onDocumentSwapped?.(documentId);+ setPendingDocument(null);+ setSwapAnnouncement(t("viewer.documentUpdated", "Document updated"));+ setTimeout(() => setSwapAnnouncement(null), 3000);+ },+ [onDocumentSwapped, t],+ );const handleDocumentSwapFailed = useCallback((error: unknown) => {// The outgoing document stays active; the replacement never landed.@@ -1278,6 +1290,11 @@ export function LocalEmbedPDF({onSwapped={handleDocumentSwapped}onFailed={handleDocumentSwapFailed}/>+ <DocumentRestoreBridge+ request={restoreRequest}+ restorePending={restorePending}+ onEvent={onRestoreEvent}+ /><ZoomAPIBridge /><ScrollAPIBridge /><SelectionAPIBridge />diff --git a/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.tsindex f30d193e6f..80eeae49d4 100644--- a/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/viewer-hot-reload-matrix.spec.ts@@ -164,6 +164,15 @@ test("a rotated document saves annotations without reopening", async ({await expect.poll(() => page.locator("[data-page-index]").count(), { timeout: 15_000 }).toBe(pageCount);++ // Nothing was reopened, so no restore may hold the zoom readout.+ const zoomBefore = await page.getByText(/%$/).first().textContent();+ await page.getByRole("button", { name: "Zoom In" }).first().click();+ await expect+ .poll(async () => page.getByText(/%$/).first().textContent(), {+ timeout: 5_000,+ })+ .not.toBe(zoomBefore);});test("rotated and landscape pages reload a tool output in place", async ({