Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix: preview zoom/pan behavior

joshistoast4589155601d2
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts
index 1715e8b9aa..c5d5600a5f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/viewport.ts
@@ -31,13 +31,17 @@ import type { Mat2d, Rect, Vec2 } from '@workbench/canvas-engine/types';
import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';
import { clampZoom, snapZoom } from '@workbench/canvas-engine/math/snapping';
+import {
+ panBy as calculatePanBy,
+ wheelZoomAtPoint as calculateWheelZoomAtPoint,
+ zoomAtPoint as calculateZoomAtPoint,
+} from '@workbench/panZoom';
+
+export { WHEEL_ZOOM_STEP } from '@workbench/panZoom';
/** Maximum device-pixel ratio the engine honors; higher DPRs are clamped to bound backing-store size. */
export const MAX_DPR = 2;
-/** Wheel exponential zoom sensitivity: `zoom *= exp(-deltaY * step)`. */
-export const WHEEL_ZOOM_STEP = 0.0015;
-
/** The mutable view state. */
export interface ViewState {
pan: Vec2;
@@ -111,21 +115,25 @@ export const createViewport = (initial?: Partial<ViewState>): Viewport => {
};
const zoomAtPoint = (newZoom: number, screenAnchor: Vec2): void => {
- const clamped = clampZoom(newZoom);
- // Keep the document point currently under the anchor fixed on screen.
- const docAnchor = screenToDocument(screenAnchor);
- zoom = clamped;
- pan = { x: screenAnchor.x - clamped * docAnchor.x, y: screenAnchor.y - clamped * docAnchor.y };
+ const next = calculateZoomAtPoint({ pan, zoom }, newZoom, screenAnchor, clampZoom);
+ zoom = next.zoom;
+ pan = next.pan;
emit();
};
const wheelZoom = (deltaY: number, screenAnchor: Vec2): void => {
- const target = clampZoom(zoom * Math.exp(-deltaY * WHEEL_ZOOM_STEP));
- zoomAtPoint(snapZoom(target), screenAnchor);
+ const next = calculateWheelZoomAtPoint({ pan, zoom }, deltaY, screenAnchor, {
+ constrainZoom: clampZoom,
+ snapZoom,
+ });
+ zoom = next.zoom;
+ pan = next.pan;
+ emit();
};
const panBy = (screenDelta: Vec2): void => {
- pan = { x: pan.x + screenDelta.x, y: pan.y + screenDelta.y };
+ const next = calculatePanBy({ pan, zoom }, screenDelta);
+ pan = next.pan;
emit();
};
diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts b/invokeai/frontend/webv2/src/workbench/panZoom.test.ts
new file mode 100644
index 0000000000..0e4573f327
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/panZoom.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+
+import { panBy, wheelZoomAtPoint, zoomAtPoint } from './panZoom';
+
+const clamp = (min: number, max: number) => (zoom: number) => Math.max(min, Math.min(max, zoom));
+
+describe('panZoom', () => {
+ it('keeps the anchored content point fixed when zoom changes', () => {
+ const initial = { pan: { x: 30, y: -12 }, zoom: 1.5 };
+ const anchor = { x: 200, y: 120 };
+ const contentPoint = {
+ x: (anchor.x - initial.pan.x) / initial.zoom,
+ y: (anchor.y - initial.pan.y) / initial.zoom,
+ };
+
+ const next = zoomAtPoint(initial, 3, anchor, clamp(0.1, 20));
+
+ expect(next.zoom).toBe(3);
+ expect(next.zoom * contentPoint.x + next.pan.x).toBeCloseTo(anchor.x, 6);
+ expect(next.zoom * contentPoint.y + next.pan.y).toBeCloseTo(anchor.y, 6);
+ });
+
+ it('applies the zoom constraint before calculating anchor translation', () => {
+ const atMaximum = { pan: { x: -700, y: -525 }, zoom: 8 };
+
+ const next = zoomAtPoint(atMaximum, 9.5, { x: 200, y: 150 }, clamp(1, 8));
+
+ expect(next).toBe(atMaximum);
+ });
+
+ it('applies wheel sensitivity and optional snapping through the same constrained transition', () => {
+ const next = wheelZoomAtPoint(
+ { pan: { x: 0, y: 0 }, zoom: 1 },
+ -1,
+ { x: 100, y: 50 },
+ {
+ constrainZoom: clamp(0.1, 20),
+ snapZoom: () => 1,
+ }
+ );
+
+ expect(next).toEqual({ pan: { x: 0, y: 0 }, zoom: 1 });
+ });
+
+ it('pans in screen space without changing zoom', () => {
+ expect(panBy({ pan: { x: 5, y: 5 }, zoom: 2 }, { x: 10, y: -4 })).toEqual({
+ pan: { x: 15, y: 1 },
+ zoom: 2,
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.ts b/invokeai/frontend/webv2/src/workbench/panZoom.ts
new file mode 100644
index 0000000000..67c731ce1a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/panZoom.ts
@@ -0,0 +1,77 @@
+/**
+ * DOM-free pan/zoom state transitions shared by every workbench viewport.
+ *
+ * Coordinate convention: `screen = zoom * content + pan`. Callers provide
+ * their own zoom constraint because canvas, preview, and comparison viewports
+ * have different limits. Constraints are applied before anchor translation is
+ * calculated, so reaching a zoom limit is an exact no-op instead of becoming
+ * an accidental pan.
+ */
+
+/** Wheel exponential zoom sensitivity: `zoom *= exp(-deltaY * step)`. */
+export const WHEEL_ZOOM_STEP = 0.0015;
+
+export interface PanZoomPoint {
+ x: number;
+ y: number;
+}
+
+export interface PanZoomTransform {
+ pan: PanZoomPoint;
+ zoom: number;
+}
+
+export type ConstrainZoom = (zoom: number) => number;
+
+/** Sets zoom while keeping the content point under `screenAnchor` fixed. */
+export const zoomAtPoint = (
+ transform: PanZoomTransform,
+ requestedZoom: number,
+ screenAnchor: PanZoomPoint,
+ constrainZoom: ConstrainZoom
+): PanZoomTransform => {
+ const zoom = constrainZoom(requestedZoom);
+
+ if (zoom === transform.zoom) {
+ return transform;
+ }
+
+ const contentAnchor = {
+ x: (screenAnchor.x - transform.pan.x) / transform.zoom,
+ y: (screenAnchor.y - transform.pan.y) / transform.zoom,
+ };
+
+ return {
+ pan: {
+ x: screenAnchor.x - zoom * contentAnchor.x,
+ y: screenAnchor.y - zoom * contentAnchor.y,
+ },
+ zoom,
+ };
+};
+
+/** Applies exponential wheel zoom around `screenAnchor`. */
+export const wheelZoomAtPoint = (
+ transform: PanZoomTransform,
+ deltaY: number,
+ screenAnchor: PanZoomPoint,
+ {
+ constrainZoom,
+ snapZoom = (zoom) => zoom,
+ step = WHEEL_ZOOM_STEP,
+ }: {
+ constrainZoom: ConstrainZoom;
+ snapZoom?: (zoom: number) => number;
+ step?: number;
+ }
+): PanZoomTransform => {
+ const target = constrainZoom(transform.zoom * Math.exp(-deltaY * step));
+
+ return zoomAtPoint(transform, snapZoom(target), screenAnchor, constrainZoom);
+};
+
+/** Pans by a screen-space delta. */
+export const panBy = (transform: PanZoomTransform, screenDelta: PanZoomPoint): PanZoomTransform => ({
+ pan: { x: transform.pan.x + screenDelta.x, y: transform.pan.y + screenDelta.y },
+ zoom: transform.zoom,
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx
new file mode 100644
index 0000000000..55d36c186d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx
@@ -0,0 +1,83 @@
+import { WHEEL_ZOOM_STEP } from '@workbench/panZoom';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { useCompareLoupe } from './useCompareLoupe';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 20);
+ });
+ });
+
+const Harness = () => {
+ const loupe = useCompareLoupe({ enabled: true, naturalWidth: 200 });
+
+ return ([0, 1] as const).map((index) => {
+ const pane = loupe.getPane(index)!;
+
+ return (
+ <div
+ key={index}
+ ref={pane.frameRefCallback}
+ data-testid={`frame-${index}`}
+ style={{ height: 150, overflow: 'hidden', width: 200 }}
+ {...pane.frameProps}
+ >
+ <img
+ ref={pane.imageRefCallback}
+ alt={`pane-${index}`}
+ height="150"
+ src="data:image/gif;base64,R0lGODlhAQABAAD/ACwAAAAAAQABAAACADs="
+ style={{ display: 'block', height: 150, width: 200 }}
+ width="200"
+ />
+ </div>
+ );
+ });
+};
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('useCompareLoupe', () => {
+ it('keeps both panes stationary when wheel zoom is already at its maximum', async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await interact(() => root?.render(<Harness />));
+
+ const frame = host.querySelector<HTMLElement>('[data-testid="frame-0"]')!;
+ const images = Array.from(host.querySelectorAll<HTMLImageElement>('img'));
+ const frameRect = frame.getBoundingClientRect();
+ const wheelAtCenter = (deltaY: number) =>
+ frame.dispatchEvent(
+ new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: frameRect.left + frame.clientWidth / 2,
+ clientY: frameRect.top + frame.clientHeight / 2,
+ deltaY,
+ })
+ );
+
+ await interact(() => wheelAtCenter(-Math.log(8) / WHEEL_ZOOM_STEP));
+ const transformsAtMaximum = images.map((image) => image.style.transform);
+ expect(transformsAtMaximum).toEqual(['translate(-700px, -525px) scale(8)', 'translate(-700px, -525px) scale(8)']);
+
+ await interact(() => wheelAtCenter(-100));
+
+ expect(images.map((image) => image.style.transform)).toEqual(transformsAtMaximum);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts
index 9618999c32..0b5c481770 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts
@@ -1,3 +1,4 @@
+import { panBy, WHEEL_ZOOM_STEP, zoomAtPoint as calculateZoomAtPoint } from '@workbench/panZoom';
/* eslint-disable react/react-compiler */
import { useEffectEvent, useRef, useState, type MouseEvent, type PointerEvent } from 'react';
@@ -10,7 +11,6 @@ import { useEffectEvent, useRef, useState, type MouseEvent, type PointerEvent }
*/
const MAX_ACTUAL_ZOOM = 8;
-const WHEEL_ZOOM_FACTOR = 0.0015;
const PIXELATED_ACTUAL_ZOOM = 2;
interface FractionTransform {
@@ -88,11 +88,7 @@ export const useCompareLoupe = ({
});
const setTransform = useEffectEvent((next: FractionTransform) => {
- const firstFrame = panesRef.current.find((pane) => pane.frame)?.frame ?? null;
- const maxScale = firstFrame
- ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidth) / Math.max(1, firstFrame.clientWidth))
- : MAX_ACTUAL_ZOOM;
- const scale = Math.max(1, Math.min(next.scale, maxScale));
+ const scale = next.scale;
transformRef.current =
scale === 1
@@ -103,12 +99,18 @@ export const useCompareLoupe = ({
const zoomAroundFraction = useEffectEvent((pfx: number, pfy: number, nextScale: number) => {
const { fx, fy, scale } = transformRef.current;
- const ratio = nextScale / scale;
+ const firstFrame = panesRef.current.find((pane) => pane.frame)?.frame ?? null;
+ const maxScale = firstFrame
+ ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidth) / Math.max(1, firstFrame.clientWidth))
+ : MAX_ACTUAL_ZOOM;
+ const next = calculateZoomAtPoint({ pan: { x: fx, y: fy }, zoom: scale }, nextScale, { x: pfx, y: pfy }, (zoom) =>
+ Math.max(1, Math.min(zoom, maxScale))
+ );
setTransform({
- fx: pfx - (pfx - fx) * ratio,
- fy: pfy - (pfy - fy) * ratio,
- scale: nextScale,
+ fx: next.pan.x,
+ fy: next.pan.y,
+ scale: next.zoom,
});
});
@@ -120,7 +122,7 @@ export const useCompareLoupe = ({
return;
}
- const sensitivity = event.ctrlKey ? WHEEL_ZOOM_FACTOR * 4 : WHEEL_ZOOM_FACTOR;
+ const sensitivity = event.ctrlKey ? WHEEL_ZOOM_STEP * 4 : WHEEL_ZOOM_STEP;
zoomAroundFraction(
(event.clientX - rect.left) / rect.width,
@@ -180,11 +182,14 @@ export const useCompareLoupe = ({
}
event.preventDefault();
- setTransform({
- fx: pan.fx + (event.clientX - pan.startX) / frame.clientWidth,
- fy: pan.fy + (event.clientY - pan.startY) / frame.clientHeight,
- scale: transformRef.current.scale,
- });
+ const next = panBy(
+ { pan: { x: pan.fx, y: pan.fy }, zoom: transformRef.current.scale },
+ {
+ x: (event.clientX - pan.startX) / frame.clientWidth,
+ y: (event.clientY - pan.startY) / frame.clientHeight,
+ }
+ );
+ setTransform({ fx: next.pan.x, fy: next.pan.y, scale: next.zoom });
},
onPointerUp: (event) => endPan(event),
},
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
new file mode 100644
index 0000000000..45c02f3d40
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx
@@ -0,0 +1,80 @@
+/* eslint-disable react/react-compiler */
+import { WHEEL_ZOOM_STEP } from '@workbench/panZoom';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { usePreviewLoupe } from './usePreviewLoupe';
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 20);
+ });
+ });
+
+const Harness = () => {
+ const loupe = usePreviewLoupe({ enabled: true, naturalWidth: 200 });
+
+ return (
+ <div
+ ref={loupe.stageRefCallback}
+ data-testid="stage"
+ style={{
+ alignItems: 'center',
+ display: 'flex',
+ height: 300,
+ justifyContent: 'center',
+ overflow: 'hidden',
+ position: 'relative',
+ width: 400,
+ }}
+ {...loupe.stageProps}
+ >
+ <div ref={loupe.contentRef} data-testid="content" style={{ height: 150, width: 200 }} />
+ </div>
+ );
+};
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('usePreviewLoupe', () => {
+ it('does not pan when wheel zoom is already at its maximum', async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await interact(() => root?.render(<Harness />));
+
+ const stage = host.querySelector<HTMLElement>('[data-testid="stage"]')!;
+ const content = host.querySelector<HTMLElement>('[data-testid="content"]')!;
+ const stageRect = stage.getBoundingClientRect();
+ const wheelAtCenter = (deltaY: number) =>
+ stage.dispatchEvent(
+ new WheelEvent('wheel', {
+ bubbles: true,
+ cancelable: true,
+ clientX: stageRect.left + stage.clientWidth / 2,
+ clientY: stageRect.top + stage.clientHeight / 2,
+ deltaY,
+ })
+ );
+
+ await interact(() => wheelAtCenter(-Math.log(8) / WHEEL_ZOOM_STEP));
+ const transformAtMaximum = content.style.transform;
+ expect(transformAtMaximum).toContain('scale(8)');
+
+ await interact(() => wheelAtCenter(-100));
+
+ expect(content.style.transform).toBe(transformAtMaximum);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
index 34dec4922c..fe45032e39 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts
@@ -1,3 +1,4 @@
+import { panBy, WHEEL_ZOOM_STEP, zoomAtPoint as calculateZoomAtPoint } from '@workbench/panZoom';
import {
useEffectEvent,
useImperativeHandle,
@@ -22,8 +23,6 @@ import {
/** Max zoom, as a fraction of the image's actual pixel size. */
const MAX_ACTUAL_ZOOM = 8;
-/** Wheel-to-zoom sensitivity. */
-const WHEEL_ZOOM_FACTOR = 0.0015;
/** Switch to pixelated rendering at/above this actual-pixel zoom. */
const PIXELATED_ACTUAL_ZOOM = 2;
@@ -146,8 +145,7 @@ export const usePreviewLoupe = ({
return;
}
- const maxScale = Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidth) / content.clientWidth);
- const scale = Math.max(1, Math.min(next.scale, maxScale));
+ const scale = next.scale;
transformRef.current =
scale === 1
@@ -169,14 +167,18 @@ export const usePreviewLoupe = ({
}
const { scale, tx, ty } = transformRef.current;
- const ratio = nextScale / scale;
- const anchorX = stageX - content.offsetLeft;
- const anchorY = stageY - content.offsetTop;
+ const maxScale = Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidth) / content.clientWidth);
+ const next = calculateZoomAtPoint(
+ { pan: { x: tx, y: ty }, zoom: scale },
+ nextScale,
+ { x: stageX - content.offsetLeft, y: stageY - content.offsetTop },
+ (zoom) => Math.max(1, Math.min(zoom, maxScale))
+ );
setTransform({
- scale: nextScale,
- tx: anchorX - (anchorX - tx) * ratio,
- ty: anchorY - (anchorY - ty) * ratio,
+ scale: next.zoom,
+ tx: next.pan.x,
+ ty: next.pan.y,
});
});
@@ -210,7 +212,7 @@ export const usePreviewLoupe = ({
const rect = node.getBoundingClientRect();
const { scale } = transformRef.current;
// Trackpad pinch arrives as ctrl+wheel with finer deltas.
- const sensitivity = event.ctrlKey ? WHEEL_ZOOM_FACTOR * 4 : WHEEL_ZOOM_FACTOR;
+ const sensitivity = event.ctrlKey ? WHEEL_ZOOM_STEP * 4 : WHEEL_ZOOM_STEP;
zoomAroundPoint(
event.clientX - rect.left,
@@ -255,11 +257,11 @@ export const usePreviewLoupe = ({
}
event.preventDefault();
- setTransform({
- scale: transformRef.current.scale,
- tx: pan.tx + (event.clientX - pan.startX),
- ty: pan.ty + (event.clientY - pan.startY),
- });
+ const next = panBy(
+ { pan: { x: pan.tx, y: pan.ty }, zoom: transformRef.current.scale },
+ { x: event.clientX - pan.startX, y: event.clientY - pan.startY }
+ );
+ setTransform({ scale: next.zoom, tx: next.pan.x, ty: next.pan.y });
};
const handlePointerEnd = (event: PointerEvent<HTMLDivElement>): void => {