Skip to content

#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere

feat(viewer): Fit to width and fit to page buttons in the viewer (#8485)

EthanHealy01f702e82db4b4
diff --git a/frontend/public/locales/en-US/translation.toml b/frontend/public/locales/en-US/translation.toml
index c8eb2aee89..44dc109471 100644
--- a/frontend/public/locales/en-US/translation.toml
+++ b/frontend/public/locales/en-US/translation.toml
@@ -13710,6 +13710,8 @@ enableSepiaFilter = "Enable Sepia Filter"
engineLoadError = "Failed to initialize PDF viewer engine"
engineSlowWarning = "PDF engine initialization is taking longer than expected. Please check your browser WebAssembly and Worker settings, or reload the page."
firstPage = "First Page"
+fitPage = "Fit to page"
+fitWidth = "Fit to width"
lastPage = "Last Page"
loadingEngine = "Loading PDF Engine..."
moreOptions = "More"
diff --git a/frontend/src/editor/core/components/viewer/PdfViewerToolbar.test.tsx b/frontend/src/editor/core/components/viewer/PdfViewerToolbar.test.tsx
new file mode 100644
index 0000000000..ec26fbe581
--- /dev/null
+++ b/frontend/src/editor/core/components/viewer/PdfViewerToolbar.test.tsx
@@ -0,0 +1,136 @@
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { MantineProvider } from "@mantine/core";
+import { ZoomMode } from "@embedpdf/plugin-zoom/react";
+import type { ZoomLevel } from "@embedpdf/plugin-zoom";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { PdfViewerToolbar } from "@app/components/viewer/PdfViewerToolbar";
+
+const device = vi.hoisted(() => ({ isPhone: false }));
+
+// Built once: the toolbar's effects depend on the identity of these values.
+const viewer = vi.hoisted(() => {
+ const zoomListeners = new Set<(percent: number) => void>();
+ const zoom = { level: undefined as ZoomLevel | undefined, percent: 100 };
+ return {
+ zoom,
+ notifyZoom: (level: ZoomLevel, percent: number) => {
+ zoom.level = level;
+ zoom.percent = percent;
+ for (const listener of [...zoomListeners]) listener(percent);
+ },
+ value: {
+ getScrollState: () => ({ currentPage: 1, totalPages: 3 }),
+ getZoomState: () => ({
+ currentZoom: zoom.percent / 100,
+ zoomPercent: zoom.percent,
+ level: zoom.level,
+ }),
+ getSpreadState: () => ({ isDualPage: false }),
+ scrollActions: {
+ scrollToPage: vi.fn(),
+ scrollToFirstPage: vi.fn(),
+ scrollToLastPage: vi.fn(),
+ },
+ zoomActions: {
+ zoomIn: vi.fn(),
+ zoomOut: vi.fn(),
+ requestZoom: vi.fn(),
+ setZoomLevel: vi.fn(),
+ },
+ spreadActions: { toggleSpreadMode: vi.fn() },
+ zoomRestorePendingRef: { current: false },
+ zoomRestoreSettledTick: 0,
+ registerImmediateZoomUpdate: (listener: (percent: number) => void) => {
+ zoomListeners.add(listener);
+ return () => {
+ zoomListeners.delete(listener);
+ };
+ },
+ registerImmediateScrollUpdate: () => () => {},
+ registerImmediateSpreadUpdate: () => () => {},
+ pdfRenderMode: "normal",
+ cyclePdfRenderMode: vi.fn(),
+ },
+ };
+});
+
+vi.mock("@app/contexts/ViewerContext", () => ({
+ useViewer: () => viewer.value,
+}));
+vi.mock("@app/hooks/useIsMobile", () => ({
+ useIsPhone: () => device.isPhone,
+}));
+
+const renderToolbar = () =>
+ render(
+ <MantineProvider>
+ <PdfViewerToolbar />
+ </MantineProvider>,
+ );
+
+describe("PdfViewerToolbar fit controls", () => {
+ beforeEach(() => {
+ device.isPhone = false;
+ viewer.zoom.level = 1;
+ viewer.zoom.percent = 100;
+ vi.clearAllMocks();
+ });
+
+ it("requests the plugin's fit modes", async () => {
+ const user = userEvent.setup();
+ renderToolbar();
+
+ await user.click(screen.getByRole("button", { name: "viewer.fitWidth" }));
+ await user.click(screen.getByRole("button", { name: "viewer.fitPage" }));
+
+ expect(viewer.value.zoomActions.requestZoom.mock.calls).toEqual([
+ [ZoomMode.FitWidth],
+ [ZoomMode.FitPage],
+ ]);
+ });
+
+ it("presses the button for the mode the plugin reports", () => {
+ renderToolbar();
+ const fitWidth = screen.getByRole("button", { name: "viewer.fitWidth" });
+ const fitPage = screen.getByRole("button", { name: "viewer.fitPage" });
+ expect(fitWidth).toHaveAttribute("aria-pressed", "false");
+ expect(fitPage).toHaveAttribute("aria-pressed", "false");
+
+ act(() => viewer.notifyZoom(ZoomMode.FitWidth, 150));
+ expect(fitWidth).toHaveAttribute("aria-pressed", "true");
+ expect(fitPage).toHaveAttribute("aria-pressed", "false");
+
+ // Same percent as fit width: the level alone has to move the pressed state.
+ act(() => viewer.notifyZoom(ZoomMode.FitPage, 150));
+ expect(fitWidth).toHaveAttribute("aria-pressed", "false");
+ expect(fitPage).toHaveAttribute("aria-pressed", "true");
+
+ act(() => viewer.notifyZoom(1.2, 120));
+ expect(fitWidth).toHaveAttribute("aria-pressed", "false");
+ expect(fitPage).toHaveAttribute("aria-pressed", "false");
+ });
+
+ it("marks the active fit mode in the phone menu", async () => {
+ device.isPhone = true;
+ viewer.zoom.level = ZoomMode.FitPage;
+ renderToolbar();
+
+ fireEvent.click(screen.getByRole("button", { name: "viewer.moreOptions" }));
+ const fitPage = await screen.findByRole("menuitem", {
+ name: "viewer.fitPage",
+ });
+ const fitWidth = await screen.findByRole("menuitem", {
+ name: "viewer.fitWidth",
+ });
+
+ expect(fitPage).toHaveAttribute("aria-current", "true");
+ expect(fitWidth).not.toHaveAttribute("aria-current");
+
+ fireEvent.click(fitWidth);
+ expect(viewer.value.zoomActions.requestZoom).toHaveBeenCalledWith(
+ ZoomMode.FitWidth,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/components/viewer/PdfViewerToolbar.tsx b/frontend/src/editor/core/components/viewer/PdfViewerToolbar.tsx
index 87454aa5ce..43d3f7fe8c 100644
--- a/frontend/src/editor/core/components/viewer/PdfViewerToolbar.tsx
+++ b/frontend/src/editor/core/components/viewer/PdfViewerToolbar.tsx
@@ -1,5 +1,6 @@
import { useState, useEffect } from "react";
import { Paper, Group, Menu, NumberInput, Slider } from "@mantine/core";
+import { ZoomMode } from "@embedpdf/plugin-zoom/react";
import { useTranslation } from "react-i18next";
import { SpreadMode } from "@embedpdf/plugin-spread/react";
import { useViewer } from "@app/contexts/ViewerContext";
@@ -57,6 +58,8 @@ export function PdfViewerToolbar({
const [displayZoomPercent, setDisplayZoomPercent] = useState(
() => zoomState.zoomPercent || 100,
);
+
+ const [zoomLevel, setZoomLevel] = useState(() => zoomState.level);
const [spreadMode, setSpreadMode] = useState(spreadState.spreadMode);
const isDualPageActive = spreadMode !== SpreadMode.None;
const isCoverPageActive = spreadMode === SpreadMode.Even;
@@ -80,20 +83,27 @@ export function PdfViewerToolbar({
const unregister = registerImmediateZoomUpdate((percent) => {
if (zoomRestorePendingRef.current) return;
setDisplayZoomPercent(percent);
+ setZoomLevel(getZoomState().level);
});
if (!zoomRestorePendingRef.current) {
setDisplayZoomPercent(zoomState.zoomPercent || 100);
+ setZoomLevel(zoomState.level);
}
return () => {
unregister?.();
};
}, [
registerImmediateZoomUpdate,
+ getZoomState,
zoomState.zoomPercent,
+ zoomState.level,
zoomRestorePendingRef,
zoomRestoreSettledTick,
]);
+ const isFitWidthActive = zoomLevel === ZoomMode.FitWidth;
+ const isFitPageActive = zoomLevel === ZoomMode.FitPage;
+
useEffect(() => {
const unregister = registerImmediateSpreadUpdate((mode) => {
setSpreadMode(mode);
@@ -112,6 +122,14 @@ export function PdfViewerToolbar({
zoomActions.zoomIn();
};
+ const handleFitWidth = () => {
+ zoomActions.requestZoom(ZoomMode.FitWidth);
+ };
+
+ const handleFitPage = () => {
+ zoomActions.requestZoom(ZoomMode.FitPage);
+ };
+
const handlePageNavigation = (page: number) => {
scrollActions.scrollToPage(page);
if (onPageChange) {
@@ -405,6 +423,36 @@ export function PdfViewerToolbar({
>
{displayZoomPercent}%
</span>
+ <Tooltip
+ content={t("viewer.fitWidth", "Fit to width")}
+ position="top"
+ arrow
+ >
+ <ActionIcon
+ variant={isFitWidthActive ? "primary" : "tertiary"}
+ size={buttonSize}
+ onClick={handleFitWidth}
+ aria-label={t("viewer.fitWidth", "Fit to width")}
+ aria-pressed={isFitWidthActive}
+ >
+ <Icon name="arrow-left-right" size={18} />
+ </ActionIcon>
+ </Tooltip>
+ <Tooltip
+ content={t("viewer.fitPage", "Fit to page")}
+ position="top"
+ arrow
+ >
+ <ActionIcon
+ variant={isFitPageActive ? "primary" : "tertiary"}
+ size={buttonSize}
+ onClick={handleFitPage}
+ aria-label={t("viewer.fitPage", "Fit to page")}
+ aria-pressed={isFitPageActive}
+ >
+ <Icon name="scan" size={18} />
+ </ActionIcon>
+ </Tooltip>
</Group>
)}
@@ -458,6 +506,22 @@ export function PdfViewerToolbar({
>
{t("viewer.zoomIn", "Zoom in")} ({displayZoomPercent}%)
</Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="arrow-left-right" size={18} />}
+ rightSection={isFitWidthActive && <Icon name="check" size={16} />}
+ aria-current={isFitWidthActive || undefined}
+ onClick={handleFitWidth}
+ >
+ {t("viewer.fitWidth", "Fit to width")}
+ </Menu.Item>
+ <Menu.Item
+ leftSection={<Icon name="scan" size={18} />}
+ rightSection={isFitPageActive && <Icon name="check" size={16} />}
+ aria-current={isFitPageActive || undefined}
+ onClick={handleFitPage}
+ >
+ {t("viewer.fitPage", "Fit to page")}
+ </Menu.Item>
<Menu.Divider />
<Menu.Label>{t("viewer.view", "View")}</Menu.Label>
diff --git a/frontend/src/editor/core/components/viewer/ZoomAPIBridge.test.tsx b/frontend/src/editor/core/components/viewer/ZoomAPIBridge.test.tsx
new file mode 100644
index 0000000000..cd63b32ca8
--- /dev/null
+++ b/frontend/src/editor/core/components/viewer/ZoomAPIBridge.test.tsx
@@ -0,0 +1,255 @@
+import { act, render } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { ZoomMode } from "@embedpdf/plugin-zoom/react";
+import { SpreadMode } from "@embedpdf/plugin-spread/react";
+import type { ZoomLevel } from "@embedpdf/plugin-zoom";
+
+import { ZoomAPIBridge } from "@app/components/viewer/ZoomAPIBridge";
+import type { ZoomAPIWrapper } from "@app/contexts/viewer/viewerBridges";
+
+// Matches useFitWidthResize's default debounce.
+const RESIZE_DEBOUNCE_MS = 150;
+
+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);
+ },
+ };
+ };
+
+ // Fit modes resolve to fixed scales, standing in for the plugin's layout maths.
+ const FIT_SCALE: Record<string, number> = {
+ "fit-width": 1.5,
+ "fit-page": 0.8,
+ automatic: 1,
+ };
+
+ const createZoom = () => {
+ let state = {
+ zoomLevel: "fit-width" as ZoomLevel,
+ currentZoomLevel: 1.5,
+ };
+ const stateChanges = emitter<void>();
+ const zoomChanges = emitter<{ newZoom: number; level: ZoomLevel }>();
+ const apply = (level: ZoomLevel) => {
+ const newZoom = typeof level === "number" ? level : FIT_SCALE[level];
+ state = { zoomLevel: level, currentZoomLevel: newZoom };
+ stateChanges.emit();
+ zoomChanges.emit({ newZoom, level });
+ };
+ return {
+ getState: () => state,
+ subscribe: stateChanges.on,
+ provides: {
+ getState: () => state,
+ requestZoom: vi.fn((level: ZoomLevel) => apply(level)),
+ zoomIn: vi.fn(() => apply(state.currentZoomLevel + 0.1)),
+ zoomOut: vi.fn(() => apply(state.currentZoomLevel - 0.1)),
+ toggleMarqueeZoom: vi.fn(),
+ onZoomChange: zoomChanges.on,
+ },
+ };
+ };
+
+ const createSpread = () => {
+ let mode = "none";
+ const changes = emitter<void>();
+ return {
+ getMode: () => mode,
+ subscribe: changes.on,
+ setMode: (next: string) => {
+ mode = next;
+ changes.emit();
+ },
+ provides: { getSpreadPages: () => [[{ index: 0 }]] },
+ };
+ };
+
+ const viewer = {
+ registerBridge: vi.fn(),
+ triggerImmediateZoomUpdate: vi.fn(),
+ };
+ const files = {
+ all: { fileStubs: [{ id: "file-1" }] },
+ selection: { selectedFileIds: ["file-1"] },
+ };
+ const page = { aspectRatio: 1.414 };
+
+ return {
+ zoom: createZoom(),
+ spread: createSpread(),
+ createZoom,
+ createSpread,
+ viewer,
+ files,
+ page,
+ };
+});
+
+vi.mock("@embedpdf/plugin-zoom/react", async () => {
+ const { useSyncExternalStore } = await import("react");
+ return {
+ ZoomMode: {
+ Automatic: "automatic",
+ FitPage: "fit-page",
+ FitWidth: "fit-width",
+ },
+ useZoom: () => {
+ const state = useSyncExternalStore(
+ fixture.zoom.subscribe,
+ fixture.zoom.getState,
+ );
+ return { provides: fixture.zoom.provides, state };
+ },
+ };
+});
+vi.mock("@embedpdf/plugin-spread/react", async () => {
+ const { useSyncExternalStore } = await import("react");
+ return {
+ SpreadMode: { None: "none", Odd: "odd", Even: "even" },
+ useSpread: () => {
+ const spreadMode = useSyncExternalStore(
+ fixture.spread.subscribe,
+ fixture.spread.getMode,
+ );
+ return { provides: fixture.spread.provides, spreadMode };
+ },
+ };
+});
+vi.mock("@embedpdf/plugin-scroll/react", () => ({
+ useScroll: () => ({ state: { totalPages: 3 } }),
+}));
+vi.mock("@app/components/viewer/useActiveDocumentId", () => ({
+ useActiveDocumentId: () => "doc-1",
+}));
+vi.mock("@app/components/viewer/hooks/useDocumentReady", () => ({
+ useDocumentReady: () => true,
+}));
+vi.mock("@app/contexts/ViewerContext", () => ({
+ useViewer: () => fixture.viewer,
+}));
+vi.mock("@app/contexts/FileContext", () => ({
+ useAllFiles: () => fixture.files.all,
+ useFileSelection: () => fixture.files.selection,
+}));
+vi.mock("@app/utils/pageMetadata", () => ({
+ getFirstPageAspectRatioFromStub: () => fixture.page.aspectRatio,
+}));
+vi.mock("@app/services/preferencesService", () => ({
+ preferencesService: { getPreference: () => "auto" },
+}));
+
+function contextZoomApi(): ZoomAPIWrapper {
+ const registrations = fixture.viewer.registerBridge.mock.calls.filter(
+ ([type]) => type === "zoom",
+ );
+ return registrations[registrations.length - 1][1].api;
+}
+
+function zoomLevel(): ZoomLevel {
+ return fixture.zoom.getState().zoomLevel;
+}
+
+function resizeWindow(height: number) {
+ act(() => {
+ window.innerHeight = height;
+ window.dispatchEvent(new Event("resize"));
+ });
+ act(() => {
+ vi.advanceTimersByTime(RESIZE_DEBOUNCE_MS);
+ });
+}
+
+describe("ZoomAPIBridge fit modes", () => {
+ const initialHeight = window.innerHeight;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ fixture.zoom = fixture.createZoom();
+ fixture.spread = fixture.createSpread();
+ fixture.page.aspectRatio = 1.414;
+ window.innerHeight = 768;
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ window.innerHeight = initialHeight;
+ });
+
+ it("auto-zooms a portrait page below fit width on open", () => {
+ render(<ZoomAPIBridge />);
+
+ expect(typeof zoomLevel()).toBe("number");
+ });
+
+ it("keeps an explicit fit width across a window resize", () => {
+ render(<ZoomAPIBridge />);
+
+ act(() => contextZoomApi().requestZoom(ZoomMode.FitWidth));
+ resizeWindow(600);
+
+ expect(zoomLevel()).toBe(ZoomMode.FitWidth);
+ });
+
+ it("keeps an explicit fit width across a spread change", () => {
+ // Tall enough that auto-zoom would still drop below fit width side by side.
+ fixture.page.aspectRatio = 3;
+ render(<ZoomAPIBridge />);
+
+ act(() => contextZoomApi().requestZoom(ZoomMode.FitWidth));
+ act(() => fixture.spread.setMode(SpreadMode.Odd));
+
+ expect(zoomLevel()).toBe(ZoomMode.FitWidth);
+ });
+
+ it("re-evaluates a fit width it chose itself when the window resizes", () => {
+ // A landscape page fits its whole height at fit width in a 768px window.
+ fixture.page.aspectRatio = 0.5;
+ render(<ZoomAPIBridge />);
+ expect(zoomLevel()).toBe(ZoomMode.FitWidth);
+
+ resizeWindow(300);
+
+ expect(typeof zoomLevel()).toBe("number");
+ });
+
+ it("hands fit width back to auto-zoom once the user zooms manually", () => {
+ fixture.page.aspectRatio = 0.5;
+ render(<ZoomAPIBridge />);
+
+ act(() => contextZoomApi().requestZoom(ZoomMode.FitWidth));
+ act(() => contextZoomApi().zoomIn());
+ act(() => fixture.zoom.provides.requestZoom(ZoomMode.FitWidth));
+ resizeWindow(300);
+
+ expect(typeof zoomLevel()).toBe("number");
+ });
+
+ it("re-arms the auto heuristic when Automatic replaces an explicit fit", () => {
+ fixture.page.aspectRatio = 0.5;
+ render(<ZoomAPIBridge />);
+
+ act(() => contextZoomApi().requestZoom(ZoomMode.FitWidth));
+ act(() => contextZoomApi().requestZoom(ZoomMode.Automatic));
+ fixture.zoom.provides.requestZoom.mockClear();
+
+ resizeWindow(300);
+
+ // The resize hook refits width on its own; the auto heuristic adding its
+ // pass on top of that is what shows the explicit fit was cleared.
+ expect(fixture.zoom.provides.requestZoom.mock.calls.length).toBeGreaterThan(
+ 1,
+ );
+ });
+});
diff --git a/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx b/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx
index 861efed8c3..a276abf377 100644
--- a/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx
+++ b/frontend/src/editor/core/components/viewer/ZoomAPIBridge.tsx
@@ -2,13 +2,16 @@ import {
useCallback,
useEffect,
useLayoutEffect,
+ useMemo,
useRef,
useState,
} from "react";
import { useZoom, ZoomMode } from "@embedpdf/plugin-zoom/react";
+import type { Point, ZoomLevel } from "@embedpdf/plugin-zoom";
import { useSpread, SpreadMode } from "@embedpdf/plugin-spread/react";
import { useScroll } from "@embedpdf/plugin-scroll/react";
import { useViewer } from "@app/contexts/ViewerContext";
+import type { ZoomAPIWrapper } from "@app/contexts/viewer/viewerBridges";
import { useActiveDocumentId } from "@app/components/viewer/useActiveDocumentId";
import { useAllFiles, useFileSelection } from "@app/contexts/FileContext";
import {
@@ -24,13 +27,23 @@ import {
type ViewerZoomSetting,
} from "@app/services/preferencesService";
+function isFitMode(level: ZoomLevel): boolean {
+ return level === ZoomMode.FitWidth || level === ZoomMode.FitPage;
+}
+
/**
* Connects the PDF zoom plugin to the shared ViewerContext.
+ *
+ * A fit mode requested through the context's zoom API is the user's choice and
+ * stays put: the plugin re-fits it on resize, spread and rotation itself. Only
+ * the fit width this bridge lands on while auto-zooming is re-evaluated by the
+ * auto heuristic on resize and spread changes.
*/
export function ZoomAPIBridge() {
const activeDocumentId = useActiveDocumentId();
const documentReady = useDocumentReady();
const lastAutoZoomedRootIdRef = useRef<string | null>(null);
+ const explicitFitRef = useRef(false);
// Don't render the inner component until we have a valid document ID and document is ready
if (!activeDocumentId || !documentReady) {
@@ -42,6 +55,7 @@ export function ZoomAPIBridge() {
key={activeDocumentId}
documentId={activeDocumentId}
lastAutoZoomedRootIdRef={lastAutoZoomedRootIdRef}
+ explicitFitRef={explicitFitRef}
/>
);
}
@@ -49,9 +63,11 @@ export function ZoomAPIBridge() {
function ZoomAPIBridgeInner({
documentId,
lastAutoZoomedRootIdRef,
+ explicitFitRef,
}: {
documentId: string;
lastAutoZoomedRootIdRef: React.MutableRefObject<string | null>;
+ explicitFitRef: React.MutableRefObject<boolean>;
}) {
const { provides: zoom, state: zoomState } = useZoom(documentId);
const liveZoomState = zoom?.getState() ?? zoomState;
@@ -118,6 +134,11 @@ function ZoomAPIBridgeInner({
setAutoZoomTick((tick) => tick + 1);
}, []);
+ const rescheduleAutoZoom = useCallback(() => {
+ if (explicitFitRef.current) return;
+ scheduleAutoZoom();
+ }, [explicitFitRef, scheduleAutoZoom]);
+
const requestFitWidth = useCallback(() => {
if (zoomRef.current && checkSpreadReady()) {
try {
@@ -140,15 +161,17 @@ function ZoomAPIBridgeInner({
hasSetInitialZoom.current = false;
lastAutoZoomedRootIdRef.current = null;
lastAppliedZoom.current = null;
+ explicitFitRef.current = false;
return;
}
// Only reset zoom when opening a genuinely different document, not on version increments
if (activeFileRootId !== lastAutoZoomedRootIdRef.current) {
lastAutoZoomedRootIdRef.current = activeFileRootId;
+ explicitFitRef.current = false;
scheduleAutoZoom();
}
- }, [activeFileRootId, scheduleAutoZoom]);
+ }, [activeFileRootId, explicitFitRef, scheduleAutoZoom]);
useEffect(() => {
const currentSpreadMode = spreadMode ?? SpreadMode.None;
@@ -157,10 +180,10 @@ function ZoomAPIBridgeInner({
if (zoomLevel === ZoomMode.FitWidth || zoomLevel === ZoomMode.Automatic) {
requestFitWidth();
- scheduleAutoZoom();
+ rescheduleAutoZoom();
}
}
- }, [spreadMode, zoomLevel, scheduleAutoZoom, requestFitWidth]);
+ }, [spreadMode, zoomLevel, rescheduleAutoZoom, requestFitWidth]);
const isManagedZoom =
checkSpreadReady() &&
@@ -170,7 +193,7 @@ function ZoomAPIBridgeInner({
useFitWidthResize({
isManaged: isManagedZoom,
requestFitWidth,
- onDebouncedResize: scheduleAutoZoom,
+ onDebouncedResize: rescheduleAutoZoom,
});
useEffect(() => {
@@ -182,7 +205,7 @@ function ZoomAPIBridgeInner({
return;
}
- if (hasSetInitialZoom.current) {
+ if (hasSetInitialZoom.current || explicitFitRef.current) {
return;
}
@@ -286,6 +309,7 @@ function ZoomAPIBridgeInner({
autoZoomTick,
spreadMode,
triggerImmediateZoomUpdate,
+ explicitFitRef,
]);
// Subscribe to zoom changes - use ref to avoid re-subscribing when zoom reference changes
@@ -303,7 +327,12 @@ function ZoomAPIBridgeInner({
}
zoomSubscriptionRef.current = zoom.onZoomChange(
- (event: { newZoom?: number }) => {
+ (event: { newZoom?: number; level?: ZoomLevel }) => {
+ // Wheel, pinch and marquee zoom reach the plugin directly, so a numeric
+ // level, not the context API, is what ends an explicit fit.
+ if (typeof event?.level === "number") {
+ explicitFitRef.current = false;
+ }
if (typeof event?.newZoom !== "number") {
return;
}
@@ -318,7 +347,22 @@ function ZoomAPIBridgeInner({
zoomSubscriptionRef.current = null;
}
};
- }, [zoom, triggerImmediateZoomUpdate]);
+ }, [zoom, triggerImmediateZoomUpdate, explicitFitRef]);
+
+ const contextZoomApi = useMemo<ZoomAPIWrapper>(
+ () => ({
+ zoomIn: () => zoomRef.current?.zoomIn(),
+ zoomOut: () => zoomRef.current?.zoomOut(),
+ toggleMarqueeZoom: () => zoomRef.current?.toggleMarqueeZoom(),
+ requestZoom: (level: ZoomLevel, center?: Point) => {
+ // Set from the requested mode, not just the fit ones: Automatic hands
+ // the fit back to the auto heuristic, so it has to clear the flag.
+ explicitFitRef.current = isFitMode(level);
+ zoomRef.current?.requestZoom(level, center);
+ },
+ }),
+ [explicitFitRef],
+ );
// Extract primitive values to avoid dependency on object reference
const zoomStateCurrentZoomLevel = liveZoomState?.currentZoomLevel;
@@ -339,17 +383,20 @@ function ZoomAPIBridgeInner({
level: zoomLevel,
};
- triggerImmediateZoomUpdate(newState.zoomPercent);
-
+ // Registered before notifying, so a listener that reads getZoomState()
+ // sees the level this notification is about.
registerBridge("zoom", {
state: newState,
- api: currentZoom,
+ api: contextZoomApi,
});
+
+ triggerImmediateZoomUpdate(newState.zoomPercent);
}, [
zoomStateCurrentZoomLevel,
zoomLevel,
registerBridge,
triggerImmediateZoomUpdate,
+ contextZoomApi,
]);
return null;