#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 state restoration after document replacement (#8130)
ConnorYoha7c869dec2c9
diff --git a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsxindex c0f9b69afd..3e4b5d9376 100644--- a/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx+++ b/frontend/editor/src/core/components/viewer/EmbedPdfViewer.tsx@@ -211,7 +211,6 @@ const EmbedPdfViewerContent = ({// 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 spreadRestoreAttemptsRef = useRef(0);// 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(() => {@@ -258,8 +257,7 @@ const EmbedPdfViewerContent = ({// 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);- // The swap bridge activates replacements, and React can reuse the page- // nodes, so node identity alone cannot tell that a new document is mounted.+ // Activation and the replacement pages' React commit happen separately.const documentSwappedRef = useRef(false);const scrollIntentCleanupRef = useRef<(() => void) | null>(null);@@ -323,7 +321,8 @@ const EmbedPdfViewerContent = ({// 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 &&+ (pendingZoomRestoreRef.current !== null ||+ pendingSpreadRestoreRef.current !== null) &&performance.now() < swapRevealRef.current.deadline) {arm();@@ -378,6 +377,23 @@ const EmbedPdfViewerContent = ({documentSwappedRef.current = false;}, []);+ 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 (totalPages < 1) return null;+ const targetPage = Math.min(pending.page, totalPages);+ const page = document.querySelector<HTMLElement>(+ `[data-page-index="${targetPage - 1}"]`,+ );+ if (!page) return null;+ pending.page = targetPage;+ return page;+ }, [getScrollState]);+const applyScrollNow = useCallback((useFraction: boolean): boolean => {const pending = pendingScrollPositionRef.current;@@ -389,9 +405,7 @@ const EmbedPdfViewerContent = ({clearPendingScrollRestore();return false;}- const pageEl = document.querySelector<HTMLElement>(- `[data-page-index="${pending.page - 1}"]`,- );+ const pageEl = resolvePendingScrollPage();// The scroller survives document swaps; walking ancestors on every frame// of the hold is what made it expensive.const scroller =@@ -410,7 +424,8 @@ const EmbedPdfViewerContent = ({// though it differs; a carried zoom keeps it unsettled until it lands.const geometrySettled =(!heightChanged || pending.fractionApplied) &&- pendingZoomRestoreRef.current === null;+ 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.@@ -452,7 +467,7 @@ const EmbedPdfViewerContent = ({}return true;},- [revealSwappedDocument],+ [revealSwappedDocument, resolvePendingScrollPage],);// Re-apply the captured position to the swapped document. Returns false until@@ -462,18 +477,10 @@ const EmbedPdfViewerContent = ({const pending = pendingScrollPositionRef.current;if (!pending) return false;- const pageEl = document.querySelector<HTMLElement>(- `[data-page-index="${pending.page - 1}"]`,- );+ const pageEl = resolvePendingScrollPage();+ if (!pageEl) return false;if (!pendingScrollSwappedRef.current) {- const replaced =- !!pageEl && (pending.element ? pageEl !== pending.element : true);- // Same-document restores apply straight away; a byte replacement waits- // for the swap bridge or the new page node.const sameDocument = !pending.expectSwap;- if (!replaced && !documentSwappedRef.current && !sameDocument) {- return false;- }if (!pending.scroller?.isConnected) {pending.scroller = findScrollableAncestor(pageEl);}@@ -513,6 +520,7 @@ const EmbedPdfViewerContent = ({hideUntilSettled,attachScrollIntentListeners,revealSwappedDocument,+ resolvePendingScrollPage,],);@@ -1433,6 +1441,11 @@ const EmbedPdfViewerContent = ({getSpreadState,queueScrollRestore,]);+ const replacementPagesMounted = useCallback(() => {+ const pending = pendingScrollPositionRef.current;+ if (!pending?.expectSwap) return true;+ return resolvePendingScrollPage() !== null;+ }, [resolvePendingScrollPage]);// Restore scroll position after file replacement or tool switch// Uses polling with retries to ensure the scroll succeedsuseEffect(() => {@@ -1525,55 +1538,11 @@ const EmbedPdfViewerContent = ({clearPendingScrollRestore,]);- // The swap bridge reports activation; reused page nodes need this layout-pass- // backstop to apply the position before paint.+ // Activation precedes React's commit; restoration waits for the new page nodes.const handleDocumentSwapped = useCallback(() => {documentSwappedRef.current = true;- const zoomToRestore = pendingZoomRestoreRef.current;- if (zoomToRestore !== null) {- // The incoming document is still hidden, so a carried mode or level can- // land before anything is shown.- try {- const current = getZoomState();- const alreadyApplied =- current.level === zoomToRestore &&- (typeof zoomToRestore !== "number" ||- Math.abs((current.currentZoom ?? 0) - zoomToRestore) < 0.001);- if (!alreadyApplied) {- zoomActions.requestZoom(zoomToRestore);- }- } catch {- // Handled by retry effect- }- }- const spreadToRestore = pendingSpreadRestoreRef.current;- if (spreadToRestore !== null) {- try {- if (spreadActions.getSpreadMode() !== spreadToRestore) {- spreadActions.setSpreadMode(spreadToRestore);- }- } catch {- // Handled by retry effect- }- }- const rotationToRestore = pendingRotationRestoreRef.current;- if (rotationToRestore !== null && rotationToRestore !== 0) {- try {- if (rotationActions.getRotation() !== rotationToRestore) {- rotationActions.setRotation(rotationToRestore);- }- } catch {- // Handled by retry effect- }- }- if (pendingScrollRestoreRef.current === null) return;- if (!pendingScrollPositionRef.current) return;- if (pendingScrollSwappedRef.current) return;- applyPendingScrollPosition({- useFraction: pendingZoomRestoreRef.current !== null,- });- }, [applyPendingScrollPosition, zoomActions, spreadActions, rotationActions]);-+ setRestoreTick((tick) => tick + 1);+ }, []);const handleDocumentSwapFailed = useCallback(() => {clearPendingScrollRestore();}, [clearPendingScrollRestore]);@@ -1594,10 +1563,12 @@ const EmbedPdfViewerContent = ({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]);+ }, [applyPendingScrollPosition, replacementPagesMounted]);// Never leave the viewer hidden or holding a scroll if this unmounts mid-swap.useEffect(() => clearPendingScrollRestore, [clearPendingScrollRestore]);@@ -1671,7 +1642,7 @@ const EmbedPdfViewerContent = ({const attemptRotation = () => {if (pendingScrollPositionRef.current?.expectSwap &&- !documentSwappedRef.current+ (!documentSwappedRef.current || !replacementPagesMounted())) {return;}@@ -1719,7 +1690,13 @@ const EmbedPdfViewerContent = ({// Start attempting after initial delayconst timer = setTimeout(attemptRotation, 150);return () => clearTimeout(timer);- }, [restoreTick, scrollState.totalPages, rotationActions, getScrollState]);+ }, [+ 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.@@ -1727,19 +1704,31 @@ const EmbedPdfViewerContent = ({if (pendingSpreadRestoreRef.current === null) return;const modeToRestore = pendingSpreadRestoreRef.current;- const maxAttempts = 10;- const attemptInterval = 100;+ 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+ (!documentSwappedRef.current || !replacementPagesMounted())) {+ retry();return;}if (getScrollState().totalPages > 0) {- pendingSpreadRestoreRef.current = null;- if (spreadActions.getSpreadMode() !== modeToRestore) {+ 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.@@ -1749,20 +1738,23 @@ const EmbedPdfViewerContent = ({applyPendingScrollPosition({ useFraction: true });}}- return;- }- spreadRestoreAttemptsRef.current++;- if (spreadRestoreAttemptsRef.current < maxAttempts) {- setTimeout(attemptSpread, attemptInterval);- } else {- pendingSpreadRestoreRef.current = null;- spreadRestoreAttemptsRef.current = 0;}+ retry();};- const timer = setTimeout(attemptSpread, 150);- return () => clearTimeout(timer);- }, [restoreTick, scrollState.totalPages, spreadActions, getScrollState]);+ 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.@@ -1789,7 +1781,7 @@ const EmbedPdfViewerContent = ({// A byte replacement must land before this document's zoom can apply.if (pendingScrollPositionRef.current?.expectSwap &&- !documentSwappedRef.current+ (!documentSwappedRef.current || !replacementPagesMounted())) {if (performance.now() < deadline) {setTimeout(attemptZoom, 100);@@ -1840,6 +1832,7 @@ const EmbedPdfViewerContent = ({getZoomState,applyPendingScrollPosition,settleZoomRestore,+ replacementPagesMounted,]);// Register applyChanges with ViewerContext so tools can access it directlyuseEffect(() => {diff --git a/frontend/editor/src/core/components/viewer/RotateAPIBridge.tsx b/frontend/editor/src/core/components/viewer/RotateAPIBridge.tsxindex a713aac519..ea5795ef70 100644--- a/frontend/editor/src/core/components/viewer/RotateAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/RotateAPIBridge.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef } from "react";+import { useEffect, useLayoutEffect, useRef } from "react";import { useRotate } from "@embedpdf/plugin-rotate/react";import { useViewer } from "@app/contexts/ViewerContext";import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";@@ -16,7 +16,12 @@ export function RotateAPIBridge() {return null;}- return <RotateAPIBridgeInner documentId={activeDocumentId} />;+ return (+ <RotateAPIBridgeInner+ key={activeDocumentId}+ documentId={activeDocumentId}+ />+ );}function RotateAPIBridgeInner({ documentId }: { documentId: string }) {@@ -26,7 +31,7 @@ function RotateAPIBridgeInner({ documentId }: { documentId: string }) {// Keep rotate ref updated to avoid re-running effect when object reference changesconst rotateRef = useRef(rotate);- useEffect(() => {+ useLayoutEffect(() => {rotateRef.current = rotate;}, [rotate]);@@ -42,7 +47,7 @@ function RotateAPIBridgeInner({ documentId }: { documentId: string }) {});}, [documentId, isRotateAvailable, triggerImmediateRotationUpdate]);- useEffect(() => {+ useLayoutEffect(() => {const currentRotate = rotateRef.current;if (currentRotate) {const newState = {diff --git a/frontend/editor/src/core/components/viewer/ScrollAPIBridge.tsx b/frontend/editor/src/core/components/viewer/ScrollAPIBridge.tsxindex a3e497835f..e80b5121b7 100644--- a/frontend/editor/src/core/components/viewer/ScrollAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/ScrollAPIBridge.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef } from "react";+import { useLayoutEffect, useRef } from "react";import { useScroll } from "@embedpdf/plugin-scroll/react";import { useViewer } from "@app/contexts/ViewerContext";import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";@@ -16,7 +16,12 @@ export function ScrollAPIBridge() {return null;}- return <ScrollAPIBridgeInner documentId={activeDocumentId} />;+ return (+ <ScrollAPIBridgeInner+ key={activeDocumentId}+ documentId={activeDocumentId}+ />+ );}function ScrollAPIBridgeInner({ documentId }: { documentId: string }) {@@ -25,7 +30,7 @@ function ScrollAPIBridgeInner({ documentId }: { documentId: string }) {// Keep scroll ref updated to avoid re-running effect when object reference changesconst scrollRef = useRef(scroll);- useEffect(() => {+ useLayoutEffect(() => {scrollRef.current = scroll;}, [scroll]);@@ -33,7 +38,7 @@ function ScrollAPIBridgeInner({ documentId }: { documentId: string }) {const currentPage = scrollState?.currentPage;const totalPages = scrollState?.totalPages;- useEffect(() => {+ useLayoutEffect(() => {const currentScroll = scrollRef.current;if (currentScroll &&diff --git a/frontend/editor/src/core/components/viewer/SpreadAPIBridge.tsx b/frontend/editor/src/core/components/viewer/SpreadAPIBridge.tsxindex 9beeb78a78..0b8e3c5d47 100644--- a/frontend/editor/src/core/components/viewer/SpreadAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/SpreadAPIBridge.tsx@@ -1,4 +1,4 @@-import { useEffect, useRef } from "react";+import { useLayoutEffect, useRef } from "react";import { useSpread, SpreadMode } from "@embedpdf/plugin-spread/react";import { useViewer } from "@app/contexts/ViewerContext";import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";@@ -17,7 +17,12 @@ export function SpreadAPIBridge() {return null;}- return <SpreadAPIBridgeInner documentId={activeDocumentId} />;+ return (+ <SpreadAPIBridgeInner+ key={activeDocumentId}+ documentId={activeDocumentId}+ />+ );}function SpreadAPIBridgeInner({ documentId }: { documentId: string }) {@@ -26,11 +31,11 @@ function SpreadAPIBridgeInner({ documentId }: { documentId: string }) {// Keep spread ref updated to avoid re-running effect when object reference changesconst spreadRef = useRef(spread);- useEffect(() => {+ useLayoutEffect(() => {spreadRef.current = spread;}, [spread]);- useEffect(() => {+ useLayoutEffect(() => {const currentSpread = spreadRef.current;if (!currentSpread || spreadMode === undefined) {return;diff --git a/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsx b/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsxnew file mode 100644index 0000000000..a0aa69680b--- /dev/null+++ b/frontend/editor/src/core/components/viewer/ViewerDocumentBridges.test.tsx@@ -0,0 +1,119 @@+import { useLayoutEffect } from "react";+import { render } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { SpreadAPIBridge } from "@app/components/viewer/SpreadAPIBridge";+import { ScrollAPIBridge } from "@app/components/viewer/ScrollAPIBridge";+import { RotateAPIBridge } from "@app/components/viewer/RotateAPIBridge";++const fixture = vi.hoisted(() => {+ const document = () => ({+ setSpreadMode: vi.fn(),+ getSpreadMode: () => 0,+ scrollToPage: vi.fn(),+ setRotation: vi.fn(),+ getRotation: () => 0,+ onRotateChange: () => () => {},+ });+ const bridges = new Map<+ string,+ { api: Record<string, (value: number) => void> }+ >();+ return {+ activeId: "first" as "first" | "second",+ documents: { first: document(), second: document() },+ bridges,+ registerBridge: (+ kind: string,+ bridge: { api: Record<string, (value: number) => void> } | null,+ ) => {+ if (bridge) bridges.set(kind, bridge);+ else bridges.delete(kind);+ },+ notify: vi.fn(),+ };+});++vi.mock("@app/components/viewer/useActiveDocumentId", () => ({+ useActiveDocumentId: () => fixture.activeId,+ useDocumentReady: () => true,+}));+vi.mock("@app/contexts/ViewerContext", () => ({+ useViewer: () => ({+ registerBridge: fixture.registerBridge,+ triggerImmediateSpreadUpdate: fixture.notify,+ triggerImmediateScrollUpdate: fixture.notify,+ triggerImmediateRotationUpdate: fixture.notify,+ }),+}));+vi.mock("@embedpdf/plugin-spread/react", () => ({+ SpreadMode: { None: 0, Odd: 1 },+ useSpread: (id: "first" | "second") => ({+ provides: fixture.documents[id],+ spreadMode: 0,+ }),+}));+vi.mock("@embedpdf/plugin-scroll/react", () => ({+ useScroll: (id: "first" | "second") => ({+ provides: fixture.documents[id],+ state: { currentPage: 1, totalPages: 3 },+ }),+}));+vi.mock("@embedpdf/plugin-rotate/react", () => ({+ useRotate: (id: "first" | "second") => ({+ provides: fixture.documents[id],+ rotation: 0,+ }),+}));++function RestoreOnLayout({ kind, action }: { kind: string; action: string }) {+ useLayoutEffect(() => {+ fixture.bridges.get(kind)?.api[action](1);+ });+ return null;+}++describe("viewer controls after replacing a document", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ fixture.activeId = "first";+ fixture.bridges.clear();+ });++ it.each([+ {+ Bridge: SpreadAPIBridge,+ kind: "spread",+ action: "setSpreadMode" as const,+ },+ {+ Bridge: ScrollAPIBridge,+ kind: "scroll",+ action: "scrollToPage" as const,+ },+ {+ Bridge: RotateAPIBridge,+ kind: "rotation",+ action: "setRotation" as const,+ },+ ])(+ "restores $kind on the replacement before paint, even with identical state",+ ({ Bridge, kind, action }) => {+ const view = () => (+ <>+ <Bridge />+ <RestoreOnLayout kind={kind} action={action} />+ </>+ );+ const { rerender } = render(view());+ expect(fixture.documents.first[action]).toHaveBeenCalledOnce();++ fixture.activeId = "second";+ rerender(view());++ expect(fixture.documents.first[action]).toHaveBeenCalledOnce();+ expect(fixture.documents.second[action]).toHaveBeenCalledExactlyOnceWith(+ 1,+ );+ },+ );+});diff --git a/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx b/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsxindex e13cc0e888..861efed8c3 100644--- a/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx+++ b/frontend/editor/src/core/components/viewer/ZoomAPIBridge.tsx@@ -1,4 +1,10 @@-import { useCallback, useEffect, useRef, useState } from "react";+import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+} from "react";import { useZoom, ZoomMode } from "@embedpdf/plugin-zoom/react";import { useSpread, SpreadMode } from "@embedpdf/plugin-spread/react";import { useScroll } from "@embedpdf/plugin-scroll/react";@@ -77,7 +83,7 @@ function ZoomAPIBridgeInner({// Keep zoom ref updated; the capability identity can change and// requestFitWidth plus bridge registration read through this ref.- useEffect(() => {+ useLayoutEffect(() => {zoomRef.current = zoom;}, [zoom]);@@ -318,7 +324,7 @@ function ZoomAPIBridgeInner({const zoomStateCurrentZoomLevel = liveZoomState?.currentZoomLevel;// Register bridge - only re-run when actual values change- useEffect(() => {+ useLayoutEffect(() => {const currentZoom = zoomRef.current;if (!currentZoom || zoomStateCurrentZoomLevel === undefined) {return;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 3cb670e81b..f30d193e6f 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@@ -2,14 +2,6 @@ import fs from "node:fs";import path from "path";import { test, expect } from "@app/tests/helpers/stub-test-base";-// Quarantined on WebKit: restoring zoom/scroll after an in-place byte swap-// races the settle on the slow CI WebKit engine and flakes. Passes on Chromium-// and Firefox.-test.skip(- ({ browserName }) => browserName === "webkit",- "viewer swap-restore flakes on slow CI WebKit",-);-interface SteadyZoomSamplerState {stop: boolean;widths: number[];@@ -127,10 +119,22 @@ async function openCompressPanel(page: import("@playwright/test").Page) {}async function applyCompress(page: import("@playwright/test").Page) {+ await page.locator("[data-page-index]").evaluateAll((pages) => {+ for (const node of pages) node.setAttribute("data-outgoing-page", "true");+ });+ const response = page.waitForResponse(+ (response) =>+ response.url().includes("/api/v1/misc/compress-pdf") && response.ok(),+ );await page.getByRole("button", { name: "Compress", exact: true }).first().click();+ await response;+ // Page counts and toolbar values can still describe the outgoing document.+ await expect(page.locator("[data-outgoing-page]")).toHaveCount(0, {+ timeout: 30_000,+ });}test("a rotated document saves annotations without reopening", async ({@@ -174,21 +178,20 @@ test("rotated and landscape pages reload a tool output in place", async ({await page.mouse.wheel(0, 200);await page.waitForTimeout(500);- const pageInput = page.getByRole("textbox").first();- const pageBefore = await pageInput.inputValue();await mockCompress(page, ROTATED_PAGES_PDF);await openCompressPanel(page);+ const topBefore = await pageTopOf(page, 1);const zoomBefore = await page.getByText(/%$/).first().textContent();await applyCompress(page);await expect.poll(() => page.locator("[data-page-index]").count(), { timeout: 60_000 }).toBe(4);- // The reload keeps the reader on the same page at the same zoom; the tool- // panel itself can reset the pixel offset, which predates this work.await expect- .poll(async () => pageInput.inputValue(), { timeout: 15_000 })- .toBe(pageBefore);+ .poll(async () => Math.abs((await pageTopOf(page, 1)) - topBefore), {+ timeout: 15_000,+ })+ .toBeLessThanOrEqual(3);await expect.poll(async () => page.getByText(/%$/).first().textContent(), {timeout: 15_000,@@ -196,7 +199,10 @@ test("rotated and landscape pages reload a tool output in place", async ({.toBe(zoomBefore);});-test("dual page view survives a save and a tool output", async ({ page }) => {+test("dual page view survives a save and a tool output", async ({+ page,+ browserName,+}) => {test.setTimeout(300_000);await loadFixture(page, MULTIPAGE_PDF, 3);@@ -213,21 +219,81 @@ test("dual page view survives a save and a tool output", async ({ page }) => {await mockCompress(page, MULTIPAGE_PDF);await openCompressPanel(page);- const pageInput = page.getByRole("textbox").first();+ if (browserName === "chromium") {+ const session = await page.context().newCDPSession(page);+ await session.send("Emulation.setCPUThrottlingRate", { rate: 4 });+ }+ const topBefore = await pageTopOf(page, 0);+ const zoomBefore = await page.getByText(/%$/).first().textContent();await applyCompress(page);await expect.poll(() => page.locator("[data-page-index]").count(), { timeout: 60_000 }).toBe(3);- // Dual mode holds across the byte swap, and the reader stays on page one.+ // Either page in a dual spread can be reported as current; its geometry is+ // the reading position, not the page counter's tie-break between neighbours.await expect(page.getByRole("button", { name: "Single Page View" }).first(),).toBeVisible({ timeout: 15_000 });await expect- .poll(async () => pageInput.inputValue(), { timeout: 15_000 })- .toBe("1");+ .poll(async () => Math.abs((await pageTopOf(page, 0)) - topBefore), {+ timeout: 15_000,+ })+ .toBeLessThanOrEqual(3);+ await expect(page.getByText(/%$/).first()).toHaveText(zoomBefore ?? "");});+for (const dualRotated of [false, true]) {+ test(`a shorter replacement restores the last available page (${dualRotated ? "dual rotated" : "single"})`, async ({+ page,+ }) => {+ await loadFixture(page, MULTIPAGE_PDF, 3);+ await mockCompress(page, FORM_PDF);+ await openCompressPanel(page);+ if (dualRotated) {+ await page+ .getByRole("button", { name: "Dual Page View" })+ .first()+ .click();+ await page.getByRole("button", { name: "Rotate Left" }).first().click();+ await expect+ .poll(async () => {+ const box = await page.locator('[data-page-index="2"]').boundingBox();+ return !!box && box.width > box.height;+ })+ .toBe(true);+ }+ const zoom = page.getByText(/%$/).first();+ const initialZoom = await zoom.textContent();+ await page.getByRole("button", { name: "Zoom In" }).first().click();+ await expect(zoom).not.toHaveText(initialZoom ?? "");+ await page.getByRole("button", { name: "Last Page" }).first().click();+ const pageInput = page.locator(".pdf-viewer-toolbar").getByRole("textbox");+ await expect(pageInput).toHaveValue("3");+ await expect(page.locator('[data-page-index="2"]')).toBeInViewport();+ const zoomBefore = await zoom.textContent();++ await applyCompress(page);++ await expect(page.locator("[data-page-index]")).toHaveCount(2);+ await expect(zoom).toHaveText(zoomBefore ?? "");+ await expect(page.locator('[data-page-index="1"]')).toBeInViewport();+ if (dualRotated) {+ await expect(+ page.getByRole("button", { name: "Single Page View" }).first(),+ ).toBeVisible();+ await expect+ .poll(async () => {+ const box = await page.locator('[data-page-index="1"]').boundingBox();+ return !!box && box.width > box.height;+ })+ .toBe(true);+ } else {+ await expect(pageInput).toHaveValue("2");+ }+ });+}+test("a tool output keeps the page width and zoom readout steady", async ({page,}) => {diff --git a/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.ts b/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.tsindex 88232e7177..2fe3f987fb 100644--- a/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.ts+++ b/frontend/editor/src/core/tests/stubbed/viewer-in-place-reload.spec.ts@@ -2,14 +2,6 @@ import fs from "node:fs";import path from "path";import { test, expect } from "@app/tests/helpers/stub-test-base";-// Quarantined on WebKit: restoring zoom/scroll after an in-place byte swap-// races the settle on the slow CI WebKit engine and flakes. Passes on Chromium-// and Firefox.-test.skip(- ({ browserName }) => browserName === "webkit",- "viewer swap-restore flakes on slow CI WebKit",-);-interface SwapSamplerState {swapMs: number;swapAt: number;@@ -469,6 +461,7 @@ test("tool output reloads the document in place", async ({ page }) => {test("a tool output reload shows the saved position in its first frame", async ({page,+ browserName,}) => {test.setTimeout(240_000);await loadViewer(page);@@ -509,6 +502,10 @@ test("a tool output reload shows the saved position in its first frame", async (// Read the baseline once the panel has settled; the tool page can otherwise// contribute its own preview pages to the sample stream.+ if (browserName === "chromium") {+ const session = await page.context().newCDPSession(page);+ await session.send("Emulation.setCPUThrottlingRate", { rate: 4 });+ }const pageTopBefore = await page.locator('[data-page-index="1"]').first()