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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(preview): pinch to zoom the preview on touch screens
Lincoln Steina7cc3204a448
diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts b/invokeai/frontend/webv2/src/workbench/panZoom.test.tsindex 72cfa56a4b..a58d12244f 100644--- a/invokeai/frontend/webv2/src/workbench/panZoom.test.ts+++ b/invokeai/frontend/webv2/src/workbench/panZoom.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { panBy, wheelZoomAtPoint, zoomAtPoint } from './panZoom';+import { panBy, pinchZoomAtPoints, wheelZoomAtPoint, zoomAtPoint } from './panZoom';const clamp = (min: number, max: number) => (zoom: number) => Math.max(min, Math.min(max, zoom));@@ -49,4 +49,47 @@ describe('panZoom', () => {zoom: 2,});});++ it('scales a pinch by how far the fingers spread and follows their midpoint', () => {+ const start = { pan: { x: 0, y: 0 }, zoom: 1 };++ const next = pinchZoomAtPoints(+ start,+ { center: { x: 140, y: 60 }, distance: 200, startCenter: { x: 100, y: 50 }, startDistance: 100 },+ clamp(1, 8)+ );++ expect(next.zoom).toBe(2);+ // The content point under the starting midpoint — (100, 50) at zoom 1 —+ // ends up under the midpoint's new position.+ expect(next.zoom * 100 + next.pan.x).toBeCloseTo(140, 6);+ expect(next.zoom * 50 + next.pan.y).toBeCloseTo(60, 6);+ });++ it('keeps panning with the fingers after the pinch is clamped at its zoom limit', () => {+ const start = { pan: { x: -100, y: -50 }, zoom: 4 };+ const gesture = { center: { x: 180, y: 90 }, startCenter: { x: 100, y: 50 }, startDistance: 100 };++ const atLimit = pinchZoomAtPoints(start, { ...gesture, distance: 200 }, clamp(1, 8));+ const pastLimit = pinchZoomAtPoints(start, { ...gesture, distance: 400 }, clamp(1, 8));++ expect(atLimit.zoom).toBe(8);+ expect(pastLimit.zoom).toBe(8);+ // Spreading further cannot zoom past the limit, but the gesture is still a+ // move: both agree on where the anchored content point was dragged to.+ expect(pastLimit.pan).toEqual(atLimit.pan);+ expect(pastLimit.zoom * 50 + pastLimit.pan.x).toBeCloseTo(180, 6);+ });++ it('leaves the transform untouched when the pinch has no measurable start', () => {+ const start = { pan: { x: 3, y: 7 }, zoom: 2 };++ expect(+ pinchZoomAtPoints(+ start,+ { center: { x: 10, y: 10 }, distance: 50, startCenter: { x: 0, y: 0 }, startDistance: 0 },+ clamp(1, 8)+ )+ ).toBe(start);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/panZoom.ts b/invokeai/frontend/webv2/src/workbench/panZoom.tsindex a3807279b3..a2a8d660e5 100644--- a/invokeai/frontend/webv2/src/workbench/panZoom.ts+++ b/invokeai/frontend/webv2/src/workbench/panZoom.ts@@ -23,6 +23,15 @@ export interface PanZoomTransform {export type ConstrainZoom = (zoom: number) => number;+/** Separation of two pointers, for measuring a pinch. */+export const distanceBetween = (a: PanZoomPoint, b: PanZoomPoint): number => Math.hypot(a.x - b.x, a.y - b.y);++/** Point halfway between two pointers — what a pinch zooms and pans around. */+export const midpointOf = (a: PanZoomPoint, b: PanZoomPoint): PanZoomPoint => ({+ x: (a.x + b.x) / 2,+ y: (a.y + b.y) / 2,+});+/** Sets zoom while keeping the content point under `screenAnchor` fixed. */export const zoomAtPoint = (transform: PanZoomTransform,@@ -67,3 +76,38 @@ export const panBy = (transform: PanZoomTransform, screenDelta: PanZoomPoint): Ppan: { x: transform.pan.x + screenDelta.x, y: transform.pan.y + screenDelta.y },zoom: transform.zoom,});++/**+ * Applies a two-pointer pinch: zoom scales by how far the pointers have spread+ * since the gesture began, and the content point under the gesture's starting+ * midpoint is carried to the midpoint's current position — so the image tracks+ * the fingers rather than just growing around a fixed anchor.+ *+ * Every argument is measured against the transform the gesture *started* from,+ * so each move is one transition from that origin instead of a step on top of+ * the last one: clamping at a zoom limit never accumulates into drift, and+ * spreading past the limit still pans with the fingers.+ */+export const pinchZoomAtPoints = (+ start: PanZoomTransform,+ gesture: { center: PanZoomPoint; distance: number; startCenter: PanZoomPoint; startDistance: number },+ constrainZoom: ConstrainZoom+): PanZoomTransform => {+ if (gesture.startDistance <= 0) {+ return start;+ }++ const zoom = constrainZoom(start.zoom * (gesture.distance / gesture.startDistance));+ const contentAnchor = {+ x: (gesture.startCenter.x - start.pan.x) / start.zoom,+ y: (gesture.startCenter.y - start.pan.y) / start.zoom,+ };++ return {+ pan: {+ x: gesture.center.x - zoom * contentAnchor.x,+ y: gesture.center.y - zoom * contentAnchor.y,+ },+ zoom,+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsxindex d12aa38f27..31aa3df10a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx@@ -403,6 +403,9 @@ const CompareSidePane = ({overflow="hidden"position="relative"rounded="lg"+ // Keeps the browser's own pan and pinch off the pane, so a two-finger+ // gesture reaches the shared loupe instead of scrolling the page.+ touchAction="none"{...pane?.frameProps}><imgdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsxindex 9727d12556..7063af98ab 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrame.tsx@@ -179,6 +179,11 @@ const PreviewImageFrame = ({fill="flex"padding={padding}paddingBottom={paddingBottom}+ // The whole stage is the loupe's viewport, so it — not just the media+ // card — has to keep the browser's own pan and pinch off the surface:+ // otherwise the first finger of a pinch is claimed as a page gesture and+ // the pointer stream stops mid-zoom.+ touchAction="none"{...loupe.stageProps}>{/* Never armed over a live render: arming a comparison pauses live-followdiff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsxindex 649893e50c..6e9440a368 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewFrameDrag.browser.test.tsx@@ -146,6 +146,21 @@ const pointer = (type: string, target: EventTarget, clientX: number, clientY: nu);};+/** A non-primary touch — a second finger joining the one already down. */+const secondFinger = (type: string, target: EventTarget, clientX: number, clientY: number): void => {+ target.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ button: type === 'pointermove' ? -1 : 0,+ clientX,+ clientY,+ isPrimary: false,+ pointerId: 2,+ pointerType: 'touch',+ })+ );+};+afterEach(async () => {await interact(() => root?.unmount());host?.remove();@@ -174,6 +189,35 @@ describe('PreviewFrame image drag', () => {});});+ it('gives a second finger the pinch and abandons the drag it interrupted', async () => {+ // On a touch screen a pinch starts as one finger on the image, which the+ // pointer sensor has already taken as the start of a drag. The second+ // finger has to take the gesture over outright: a drag left running would+ // keep the image following finger one and drop it somewhere on release.+ const onDrop = await renderHarness();+ const image = host!.querySelector<HTMLImageElement>('img[alt="preview.png"]')!;+ const frame = image.parentElement!;++ await interact(() => pointer('pointerdown', image, 140, 140));+ // Past the sensor's 6px activation distance: the drag is running.+ await interact(() => pointer('pointermove', image, 170, 140));+ await interact(() => secondFinger('pointerdown', image, 220, 140));+ // The fingers spread from 50px apart to 150px, so the pinch trebles the image.+ await interact(() => {+ pointer('pointermove', image, 150, 140);+ secondFinger('pointermove', image, 300, 140);+ });++ expect(frame.style.transform).toContain('scale(3)');++ await interact(() => {+ pointer('pointerup', image, 150, 140);+ secondFinger('pointerup', image, 300, 140);+ });++ expect(onDrop).not.toHaveBeenCalled();+ });+it('does not offer its own compare target to the image it is showing', async () => {// Dropping the previewed image back on the frame used to arm a comparison// of the image with itself: invisible, because compare mode requires thediff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.tsnew file mode 100644index 0000000000..d7f2a9d90e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/loupeGestures.ts@@ -0,0 +1,57 @@+import type { PanZoomPoint } from '@workbench/panZoom';++/**+ * Pointer bookkeeping shared by the preview's two loupes — the stage loupe and+ * the side-by-side comparison one. Both track every finger that is down so a+ * second one can turn a pan into a pinch; only the coordinate space they zoom+ * in differs.+ */++/**+ * Records a pointer that just went down and reports the pair that should pinch,+ * once there is one.+ *+ * The first finger of a touch (and any mouse press) starts a fresh set: a+ * pointer whose release lands outside the surface is never seen going up, so+ * this is what stops a stale entry from pairing into a phantom pinch on the+ * next touch.+ */+export const trackPointerDown = (+ pointers: Map<number, PanZoomPoint>,+ event: { clientX: number; clientY: number; isPrimary: boolean; pointerId: number }+): [number, number] | null => {+ if (event.isPrimary) {+ pointers.clear();+ }++ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });++ if (pointers.size !== 2) {+ return null;+ }++ const [first, second] = [...pointers.keys()];++ return [first!, second!];+};++/**+ * Capture, tolerating a pointer that is already gone: the browser can queue a+ * `pointerdown` behind the release of another finger, and `setPointerCapture`+ * throws for a pointer that is no longer active. A gesture that misses its+ * capture still tracks — it only loses the fingers that wander off the surface.+ */+export const capturePointer = (element: Element, pointerId: number): void => {+ try {+ element.setPointerCapture(pointerId);+ } catch {+ // Pointer ended before the gesture could claim it.+ }+};++/** Releases a capture this surface holds, if it holds one. */+export const releasePointer = (element: Element, pointerId: number): void => {+ if (element.hasPointerCapture(pointerId)) {+ element.releasePointerCapture(pointerId);+ }+};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.tsxindex 55d36c186d..6163d23c78 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.browser.test.tsx@@ -80,4 +80,49 @@ describe('useCompareLoupe', () => {expect(images.map((image) => image.style.transform)).toEqual(transformsAtMaximum);});++ it('pinches both panes together around the fingers on one of them', 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 rect = frame.getBoundingClientRect();+ const touch = (+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ pointerId: number,+ paneX: number,+ { isPrimary = false }: { isPrimary?: boolean } = {}+ ) =>+ frame.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ button: type === 'pointermove' ? -1 : 0,+ cancelable: true,+ clientX: rect.left + paneX,+ clientY: rect.top + 75,+ isPrimary,+ pointerId,+ pointerType: 'touch',+ })+ );++ await interact(() => {+ touch('pointerdown', 1, 50, { isPrimary: true });+ touch('pointerdown', 2, 150);+ });+ // The fingers double their 100px spread around the pane's centre, and the+ // pane that was not touched follows — one transform drives both eyes.+ await interact(() => {+ touch('pointermove', 1, 0);+ touch('pointermove', 2, 200);+ });++ expect(images.map((image) => image.style.transform)).toEqual([+ 'translate(-100px, -75px) scale(2)',+ 'translate(-100px, -75px) scale(2)',+ ]);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.tsindex c9b9e5e76d..dbe4502ee5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/useCompareLoupe.ts@@ -1,13 +1,26 @@-import { panBy, WHEEL_ZOOM_STEP, zoomAtPoint as calculateZoomAtPoint } from '@workbench/panZoom';+import {+ distanceBetween,+ midpointOf,+ panBy,+ pinchZoomAtPoints,+ WHEEL_ZOOM_STEP,+ zoomAtPoint as calculateZoomAtPoint,+ type PanZoomPoint,+} from '@workbench/panZoom';/* eslint-disable react/react-compiler */import { useCallback, useRef, useState, type MouseEvent, type PointerEvent } from 'react';+import { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';+/*** Shared zoom/pan for the side-by-side comparison panes: one transform, kept* in image-fraction space (scale is unitless; translation is a fraction of the* pane's rendered size), applied imperatively to every registered pane. Zoom* into the left eye and the right pane's left eye follows. Gated by the caller* to matching-dimension pairs, where fraction space is exact.+ *+ * On a touch screen two fingers pinch — zooming and panning in one gesture,+ * against the pane they landed on — and one finger pans an already-zoomed pair.*/const MAX_ACTUAL_ZOOM = 8;@@ -24,6 +37,21 @@ interface PaneElements {image: HTMLImageElement | null;}+/**+ * A live two-finger pinch. Like the transform it drives, the gesture is+ * measured in the fraction space of the pane it started on, all of it captured+ * up front so each move resolves to one transition from where it began.+ */+interface PinchGesture {+ paneIndex: 0 | 1;+ pointerIds: [number, number];+ /** The starting pane's client rect, frozen for the gesture. */+ rect: { height: number; left: number; top: number; width: number };+ startCenter: PanZoomPoint;+ startDistance: number;+ startTransform: FractionTransform;+}+export interface CompareLoupePane {frameProps: {onDoubleClick: (event: MouseEvent<HTMLDivElement>) => void;@@ -54,6 +82,9 @@ export const useCompareLoupe = ({]);const rafRef = useRef<number | null>(null);const panRef = useRef<{ pointerId: number; startX: number; startY: number; fx: number; fy: number } | null>(null);+ /** Every pointer currently down on either pane, in client space, in arrival order. */+ const pointersRef = useRef(new Map<number, PanZoomPoint>());+ const pinchRef = useRef<PinchGesture | null>(null);const naturalWidthRef = useRef(naturalWidth);naturalWidthRef.current = naturalWidth;const [isZoomed, setIsZoomed] = useState(false);@@ -102,15 +133,24 @@ export const useCompareLoupe = ({[apply]);+ /** Never below fit, never past `MAX_ACTUAL_ZOOM` of the images' own pixels. */+ const constrainScale = useCallback((scale: number): number => {+ const firstFrame = panesRef.current.find((pane) => pane.frame)?.frame ?? null;+ const maxScale = firstFrame+ ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidthRef.current) / Math.max(1, firstFrame.clientWidth))+ : MAX_ACTUAL_ZOOM;++ return Math.max(1, Math.min(scale, maxScale));+ }, []);+const zoomAroundFraction = useCallback((pfx: number, pfy: number, nextScale: number) => {const { fx, fy, scale } = transformRef.current;- const firstFrame = panesRef.current.find((pane) => pane.frame)?.frame ?? null;- const maxScale = firstFrame- ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidthRef.current) / 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))+ const next = calculateZoomAtPoint(+ { pan: { x: fx, y: fy }, zoom: scale },+ nextScale,+ { x: pfx, y: pfy },+ constrainScale);setTransform({@@ -119,7 +159,7 @@ export const useCompareLoupe = ({scale: next.zoom,});},- [setTransform]+ [constrainScale, setTransform]);const handleWheel = useCallback(@@ -167,24 +207,54 @@ export const useCompareLoupe = ({Math.max(1, naturalWidthRef.current / frame.clientWidth));},- onLostPointerCapture: (event) => endPan(event),- onPointerCancel: (event) => endPan(event),+ onLostPointerCapture: (event) => endPointer(event),+ onPointerCancel: (event) => endPointer(event),onPointerDown: (event) => {- if (event.button !== 0 || transformRef.current.scale === 1) {+ if (event.button !== 0) {+ return;+ }++ if (event.isPrimary) {+ pinchRef.current = null;+ }++ const pointers = pointersRef.current;+ const pair = trackPointerDown(pointers, event);++ if (pair && !pinchRef.current) {+ event.preventDefault();+ const pinch = beginPinch(index, pair);++ if (pinch) {+ // Both fingers are captured for the whole gesture, so one that+ // strays off the pane keeps reporting instead of sticking.+ for (const pointerId of pinch.pointerIds) {+ capturePointer(event.currentTarget, pointerId);+ }+ }++ return;+ }++ if (pointers.size !== 1 || transformRef.current.scale === 1) {return;}event.preventDefault();- event.currentTarget.setPointerCapture(event.pointerId);- panRef.current = {- fx: transformRef.current.fx,- fy: transformRef.current.fy,- pointerId: event.pointerId,- startX: event.clientX,- startY: event.clientY,- };+ capturePointer(event.currentTarget, event.pointerId);+ beginPan(event.pointerId, { x: event.clientX, y: event.clientY });},onPointerMove: (event) => {+ const pointers = pointersRef.current;++ if (pointers.has(event.pointerId)) {+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });+ }++ if (applyPinch(event)) {+ return;+ }+const pan = panRef.current;const frame = panesRef.current[index].frame;@@ -202,7 +272,7 @@ export const useCompareLoupe = ({);setTransform({ fx: next.pan.x, fy: next.pan.y, scale: next.zoom });},- onPointerUp: (event) => endPan(event),+ onPointerUp: (event) => endPointer(event),},frameRefCallback: (node) => {panesRef.current[index].frame = node;@@ -228,13 +298,127 @@ export const useCompareLoupe = ({}},});- const endPan = (event: PointerEvent<HTMLDivElement>): void => {- if (panRef.current?.pointerId !== event.pointerId) {+ /** Starts a pan from the given pointer's position, at the current transform. */+ const beginPan = (pointerId: number, from: PanZoomPoint): void => {+ panRef.current = {+ fx: transformRef.current.fx,+ fy: transformRef.current.fy,+ pointerId,+ startX: from.x,+ startY: from.y,+ };+ };++ /**+ * Arms a pinch on two down pointers, measured in the fraction space of the+ * pane given. Returns null — leaving no gesture — if that pane cannot be+ * measured or the fingers landed on the same spot.+ */+ const beginPinch = (paneIndex: 0 | 1, pointerIds: [number, number]): PinchGesture | null => {+ const frame = panesRef.current[paneIndex].frame;+ const first = pointersRef.current.get(pointerIds[0]);+ const second = pointersRef.current.get(pointerIds[1]);++ if (!frame || !first || !second) {+ return null;+ }++ const rect = frame.getBoundingClientRect();+ const distance = distanceBetween(first, second);++ if (rect.width === 0 || rect.height === 0 || distance === 0) {+ return null;+ }++ const center = midpointOf(first, second);++ panRef.current = null;+ pinchRef.current = {+ paneIndex,+ pointerIds,+ rect: { height: rect.height, left: rect.left, top: rect.top, width: rect.width },+ startCenter: { x: (center.x - rect.left) / rect.width, y: (center.y - rect.top) / rect.height },+ startDistance: distance,+ startTransform: transformRef.current,+ };++ return pinchRef.current;+ };++ /** Applies a move to the live pinch; reports whether the pinch owns it. */+ const applyPinch = (event: PointerEvent<HTMLDivElement>): boolean => {+ const pinch = pinchRef.current;++ if (!pinch) {+ return false;+ }++ const first = pointersRef.current.get(pinch.pointerIds[0]);+ const second = pointersRef.current.get(pinch.pointerIds[1]);++ if (!pinch.pointerIds.includes(event.pointerId) || !first || !second) {+ return true;+ }++ event.preventDefault();+ const center = midpointOf(first, second);+ const next = pinchZoomAtPoints(+ { pan: { x: pinch.startTransform.fx, y: pinch.startTransform.fy }, zoom: pinch.startTransform.scale },+ {+ center: {+ x: (center.x - pinch.rect.left) / pinch.rect.width,+ y: (center.y - pinch.rect.top) / pinch.rect.height,+ },+ distance: distanceBetween(first, second),+ startCenter: pinch.startCenter,+ startDistance: pinch.startDistance,+ },+ constrainScale+ );++ setTransform({ fx: next.pan.x, fy: next.pan.y, scale: next.zoom });++ return true;+ };++ const endPointer = (event: PointerEvent<HTMLDivElement>): void => {+ const pointers = pointersRef.current;++ if (pointers.delete(event.pointerId)) {+ releasePointer(event.currentTarget, event.pointerId);+ }++ const pinch = pinchRef.current;++ if (pinch?.pointerIds.includes(event.pointerId)) {+ pinchRef.current = null;+ const remaining = [...pointers.keys()];++ // Lifting one finger of a three-finger gesture re-pinches on what is+ // left; lifting to a single finger hands the gesture over to a pan, so+ // the images keep following that finger without a release and retouch.+ if (remaining.length >= 2) {+ const next = beginPinch(pinch.paneIndex, [remaining[0]!, remaining[1]!]);++ for (const pointerId of next?.pointerIds ?? []) {+ capturePointer(event.currentTarget, pointerId);+ }++ return;+ }++ const last = remaining[0];+ const lastPoint = last === undefined ? undefined : pointers.get(last);++ if (last !== undefined && lastPoint && transformRef.current.scale !== 1) {+ beginPan(last, lastPoint);+ }+return;}- if (event.currentTarget.hasPointerCapture(event.pointerId)) {- event.currentTarget.releasePointerCapture(event.pointerId);+ if (panRef.current?.pointerId !== event.pointerId) {+ return;}panRef.current = null;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.tsxindex 45c02f3d40..1693f4c98d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.browser.test.tsx@@ -48,6 +48,53 @@ afterEach(async () => {root = null;});+/**+ * The stage is 400×300 with a 200×150 content box centred in it, so the content+ * box's origin sits at (100, 75) in stage space. Coordinates below are given in+ * stage space and converted to client space against the live rect.+ */+const mountHarness = async (): Promise<{ content: HTMLElement; stage: HTMLElement }> => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await interact(() => root?.render(<Harness />));++ return {+ content: host.querySelector<HTMLElement>('[data-testid="content"]')!,+ stage: host.querySelector<HTMLElement>('[data-testid="stage"]')!,+ };+};++const touch = (+ stage: HTMLElement,+ type: 'pointerdown' | 'pointermove' | 'pointerup',+ pointerId: number,+ stageX: number,+ stageY: number,+ { isPrimary = false }: { isPrimary?: boolean } = {}+): void => {+ const rect = stage.getBoundingClientRect();++ stage.dispatchEvent(+ new PointerEvent(type, {+ bubbles: true,+ button: type === 'pointermove' ? -1 : 0,+ cancelable: true,+ clientX: rect.left + stageX,+ clientY: rect.top + stageY,+ isPrimary,+ pointerId,+ pointerType: 'touch',+ })+ );+};++/** Two fingers down, 100px apart, centred on the content box's centre. */+const startPinch = (stage: HTMLElement): void => {+ touch(stage, 'pointerdown', 1, 150, 150, { isPrimary: true });+ touch(stage, 'pointerdown', 2, 250, 150);+};+describe('usePreviewLoupe', () => {it('does not pan when wheel zoom is already at its maximum', async () => {host = document.createElement('div');@@ -77,4 +124,67 @@ describe('usePreviewLoupe', () => {expect(content.style.transform).toBe(transformAtMaximum);});++ it("zooms by the fingers' spread around the point they pinched", async () => {+ const { content, stage } = await mountHarness();++ await interact(() => startPinch(stage));+ // Both fingers move outward by 50px: a 100px start becomes 200px, so the+ // image doubles around the midpoint they started from.+ await interact(() => {+ touch(stage, 'pointermove', 1, 100, 150);+ touch(stage, 'pointermove', 2, 300, 150);+ });++ expect(content.style.transform).toBe('translate(-100px, -75px) scale(2)');+ });++ it('carries the image with the fingers while they pinch', async () => {+ const { content, stage } = await mountHarness();++ await interact(() => startPinch(stage));+ await interact(() => {+ touch(stage, 'pointermove', 1, 50, 150);+ touch(stage, 'pointermove', 2, 350, 150);+ });+ expect(content.style.transform).toBe('translate(-200px, -150px) scale(3)');++ // Sliding both fingers 40px right at the same spread pans by 40 without+ // changing the zoom — one gesture, both transforms.+ await interact(() => {+ touch(stage, 'pointermove', 1, 90, 150);+ touch(stage, 'pointermove', 2, 390, 150);+ });++ expect(content.style.transform).toBe('translate(-160px, -150px) scale(3)');+ });++ it('hands a pinch over to a one-finger pan when the second finger lifts', async () => {+ const { content, stage } = await mountHarness();++ await interact(() => startPinch(stage));+ await interact(() => {+ touch(stage, 'pointermove', 1, 50, 150);+ touch(stage, 'pointermove', 2, 350, 150);+ });+ await interact(() => touch(stage, 'pointerup', 2, 350, 150));++ // The remaining finger keeps moving from where it is — no jump back to+ // where it first went down, and no release-and-retouch to start panning.+ await interact(() => touch(stage, 'pointermove', 1, 70, 160));++ expect(content.style.transform).toBe('translate(-180px, -140px) scale(3)');+ });++ it('does not pair a finger that was never seen lifting with the next touch', async () => {+ const { content, stage } = await mountHarness();++ // A finger released outside the stage never reports its `pointerup`, so it+ // would otherwise sit in the tracked set and pinch against a later touch.+ await interact(() => touch(stage, 'pointerdown', 1, 150, 150, { isPrimary: true }));+ await interact(() => touch(stage, 'pointerdown', 2, 250, 150, { isPrimary: true }));+ await interact(() => touch(stage, 'pointermove', 2, 350, 150));++ expect(content.style.transform).toBe('');+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.tsindex 5b2f2bfcf0..0ca760a5d4 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/usePreviewLoupe.ts@@ -1,4 +1,12 @@-import { panBy, WHEEL_ZOOM_STEP, zoomAtPoint as calculateZoomAtPoint } from '@workbench/panZoom';+import {+ distanceBetween,+ midpointOf,+ panBy,+ pinchZoomAtPoints,+ WHEEL_ZOOM_STEP,+ zoomAtPoint as calculateZoomAtPoint,+ type PanZoomPoint,+} from '@workbench/panZoom';import {useCallback,useImperativeHandle,@@ -9,16 +17,19 @@ import {type Ref,} from 'react';+import { capturePointer, releasePointer, trackPointerDown } from './loupeGestures';+/*** Lightweight zoom/pan for the preview: wheel zooms around the cursor,- * left-drag pans, double-click toggles fit ⇄ 100%. The *stage* (the dot-grid- * area) is the viewport — the fitted, framed image scales and pans across the- * whole stage and clips at its edges, instead of being inspected through its- * own small wrapper. Implemented as a CSS transform applied imperatively- * (rAF-batched) to the fitted content box; high-frequency pointer data never- * passes through React state — only the rounded zoom percent does, for the- * corner chip. `scale === 1` is "fit"; the chip reports percent of the image's- * actual pixels.+ * left-drag pans, double-click toggles fit ⇄ 100%, and on a touch screen two+ * fingers pinch (zooming and panning in one gesture) while one finger pans an+ * already-zoomed image. The *stage* (the dot-grid area) is the viewport — the+ * fitted, framed image scales and pans across the whole stage and clips at its+ * edges, instead of being inspected through its own small wrapper. Implemented+ * as a CSS transform applied imperatively (rAF-batched) to the fitted content+ * box; high-frequency pointer data never passes through React state — only the+ * rounded zoom percent does, for the corner chip. `scale === 1` is "fit"; the+ * chip reports percent of the image's actual pixels.*//** Max zoom, as a fraction of the image's actual pixel size. */@@ -38,6 +49,23 @@ interface LoupeTransform {ty: number;}+/**+ * A live two-finger pinch. Everything the gesture needs is captured when it+ * starts — the transform it grew from, the pointers' separation and midpoint,+ * and the client-space origin of the content box — so each move resolves to a+ * single transition from that origin instead of compounding deltas.+ */+interface PinchGesture {+ /** Client-space position of the content box's untransformed origin. */+ originLeft: number;+ originTop: number;+ pointerIds: [number, number];+ /** Midpoint at gesture start, in content-box space. */+ startCenter: PanZoomPoint;+ startDistance: number;+ startTransform: LoupeTransform;+}+/*** Clamp one axis of the translation: content smaller than the stage is* centered; content larger may pan but never leaves a gap at either edge.@@ -62,6 +90,9 @@ export const usePreviewLoupe = ({const panPointerRef = useRef<{ pointerId: number; startX: number; startY: number; tx: number; ty: number } | null>(null);+ /** Every pointer currently down on the stage, in client space, in arrival order. */+ const pointersRef = useRef(new Map<number, PanZoomPoint>());+ const pinchRef = useRef<PinchGesture | null>(null);const lastSourceTokenRef = useRef<string | null | undefined>(undefined);const [zoomPercent, setZoomPercent] = useState<number | null>(null);@@ -124,6 +155,9 @@ export const usePreviewLoupe = ({transformRef.current = { scale: 1, tx: 0, ty: 0 };panPointerRef.current = null;+ // A gesture in flight is measured against a transform that no longer+ // exists; dropping it leaves the fresh fit alone until the fingers lift.+ pinchRef.current = null;if (rafRef.current === null) {rafRef.current = requestAnimationFrame(() => {@@ -164,6 +198,17 @@ export const usePreviewLoupe = ({[apply]);+ /** Never below fit, never past `MAX_ACTUAL_ZOOM` of the image's own pixels. */+ const constrainScale = useCallback(+ (scale: number): number => {+ const renderedWidth = contentRef.current?.clientWidth ?? 0;+ const maxScale = renderedWidth > 0 ? Math.max(1, (MAX_ACTUAL_ZOOM * naturalWidth) / renderedWidth) : 1;++ return Math.max(1, Math.min(scale, maxScale));+ },+ [naturalWidth]+ );+/** Zoom keeping the content point under the given stage-space coordinates fixed. */const zoomAroundPoint = useCallback((stageX: number, stageY: number, nextScale: number) => {@@ -174,12 +219,11 @@ export const usePreviewLoupe = ({}const { scale, tx, ty } = transformRef.current;- 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))+ constrainScale);setTransform({@@ -188,7 +232,7 @@ export const usePreviewLoupe = ({ty: next.pan.y,});},- [naturalWidth, setTransform]+ [constrainScale, setTransform]);const reset = useCallback(() => setTransform({ scale: 1, tx: 0, ty: 0 }), [setTransform]);@@ -245,23 +289,140 @@ export const usePreviewLoupe = ({[zoomAroundPoint]);+ /** Starts a pan from the given pointer's current position, at the current transform. */+ const beginPan = (pointerId: number, from: PanZoomPoint): void => {+ panPointerRef.current = {+ pointerId,+ startX: from.x,+ startY: from.y,+ tx: transformRef.current.tx,+ ty: transformRef.current.ty,+ };+ };++ /**+ * Arms a pinch on two down pointers and returns it, or null — leaving no+ * gesture — if the stage cannot be measured or the fingers landed on the+ * same spot.+ */+ const beginPinch = (stage: HTMLDivElement, pointerIds: [number, number]): PinchGesture | null => {+ const content = contentRef.current;+ const first = pointersRef.current.get(pointerIds[0]);+ const second = pointersRef.current.get(pointerIds[1]);++ if (!content || content.clientWidth === 0 || !first || !second) {+ return null;+ }++ const distance = distanceBetween(first, second);++ if (distance === 0) {+ return null;+ }++ const rect = stage.getBoundingClientRect();+ const originLeft = rect.left + content.offsetLeft;+ const originTop = rect.top + content.offsetTop;+ const center = midpointOf(first, second);++ panPointerRef.current = null;+ pinchRef.current = {+ originLeft,+ originTop,+ pointerIds,+ startCenter: { x: center.x - originLeft, y: center.y - originTop },+ startDistance: distance,+ startTransform: transformRef.current,+ };++ return pinchRef.current;+ };++ /**+ * A pinch begins with one finger already down, which dnd-kit's pointer sensor+ * has taken as the start of dragging the image out of the preview. The sensor+ * listens for `pointercancel` on the document, so dispatching one there aborts+ * that drag — pending or already started — without disturbing the stage's own+ * handlers, which never see a document-targeted, non-bubbling event.+ */+ const cancelPointerDrag = (stage: HTMLDivElement): void => {+ stage.ownerDocument.dispatchEvent(new PointerEvent('pointercancel'));+ };+const handlePointerDown = (event: PointerEvent<HTMLDivElement>): void => {- if (event.button !== 0 || transformRef.current.scale === 1) {+ if (event.button !== 0) {+ return;+ }++ const pointers = pointersRef.current;++ if (event.isPrimary) {+ pinchRef.current = null;+ }++ const pair = trackPointerDown(pointers, event);++ if (pair && !pinchRef.current) {+ event.preventDefault();+ const stage = event.currentTarget;+ const pinch = beginPinch(stage, pair);++ if (pinch) {+ // Both fingers are captured for the whole gesture, so a finger that+ // strays off the stage keeps reporting instead of silently sticking.+ for (const pointerId of pinch.pointerIds) {+ capturePointer(stage, pointerId);+ }++ cancelPointerDrag(stage);+ }++ return;+ }++ if (pointers.size !== 1 || transformRef.current.scale === 1) {return;}event.preventDefault();- event.currentTarget.setPointerCapture(event.pointerId);- panPointerRef.current = {- pointerId: event.pointerId,- startX: event.clientX,- startY: event.clientY,- tx: transformRef.current.tx,- ty: transformRef.current.ty,- };+ capturePointer(event.currentTarget, event.pointerId);+ beginPan(event.pointerId, { x: event.clientX, y: event.clientY });};const handlePointerMove = (event: PointerEvent<HTMLDivElement>): void => {+ const pointers = pointersRef.current;++ if (pointers.has(event.pointerId)) {+ pointers.set(event.pointerId, { x: event.clientX, y: event.clientY });+ }++ const pinch = pinchRef.current;++ if (pinch) {+ const first = pointers.get(pinch.pointerIds[0]);+ const second = pointers.get(pinch.pointerIds[1]);++ if (!pinch.pointerIds.includes(event.pointerId) || !first || !second) {+ return;+ }++ event.preventDefault();+ const center = midpointOf(first, second);+ const next = pinchZoomAtPoints(+ { pan: { x: pinch.startTransform.tx, y: pinch.startTransform.ty }, zoom: pinch.startTransform.scale },+ {+ center: { x: center.x - pinch.originLeft, y: center.y - pinch.originTop },+ distance: distanceBetween(first, second),+ startCenter: pinch.startCenter,+ startDistance: pinch.startDistance,+ },+ constrainScale+ );++ setTransform({ scale: next.zoom, tx: next.pan.x, ty: next.pan.y });+ return;+ }+const pan = panPointerRef.current;if (!pan || pan.pointerId !== event.pointerId) {@@ -277,12 +438,44 @@ export const usePreviewLoupe = ({};const handlePointerEnd = (event: PointerEvent<HTMLDivElement>): void => {- if (panPointerRef.current?.pointerId !== event.pointerId) {+ const pointers = pointersRef.current;++ if (pointers.delete(event.pointerId)) {+ releasePointer(event.currentTarget, event.pointerId);+ }++ const pinch = pinchRef.current;++ if (pinch?.pointerIds.includes(event.pointerId)) {+ pinchRef.current = null;+ const remaining = [...pointers.keys()];++ // Lifting one finger of a three-finger gesture re-pinches on what is+ // left; lifting to a single finger hands the gesture over to a pan, so+ // the image keeps following that finger without a release and re-touch.+ if (remaining.length >= 2) {+ const stage = event.currentTarget;+ const next = beginPinch(stage, [remaining[0]!, remaining[1]!]);++ for (const pointerId of next?.pointerIds ?? []) {+ capturePointer(stage, pointerId);+ }++ return;+ }++ const last = remaining[0];+ const lastPoint = last === undefined ? undefined : pointers.get(last);++ if (last !== undefined && lastPoint && transformRef.current.scale !== 1) {+ beginPan(last, lastPoint);+ }+return;}- if (event.currentTarget.hasPointerCapture(event.pointerId)) {- event.currentTarget.releasePointerCapture(event.pointerId);+ if (panPointerRef.current?.pointerId !== event.pointerId) {+ return;}panPointerRef.current = null;