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
fix(webv2): image map zoom across input devices, and one-shot fit correctness
Lincoln Stein3b5fd1494cc0
diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.tsnew file mode 100644index 0000000000..8ca7d35397--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.browser.test.ts@@ -0,0 +1,130 @@+import { afterEach, describe, expect, it } from 'vitest';++import type { AxisRanges } from './imageMapViewport';++import { attachWheelZoom } from './attachWheelZoom';++/**+ * The gesture bookkeeping needs real pointer and touch events, so this runs in+ * the browser suite; the range arithmetic it drives is unit-tested against+ * `imageMapViewport` directly.+ */++let detach: (() => void) | null = null;+let host: HTMLElement | null = null;++const mountHost = (): HTMLElement => {+ const element = document.createElement('div');++ element.style.height = '400px';+ element.style.left = '0';+ element.style.position = 'fixed';+ element.style.top = '0';+ element.style.width = '400px';+ document.body.append(element);+ host = element;++ return element;+};++const attach = (element: HTMLElement, ranges: AxisRanges): { current: AxisRanges } => {+ const state = { current: ranges };++ detach = attachWheelZoom(element, {+ applyRanges: (next) => {+ state.current = next;+ },+ readRanges: () => state.current,+ });++ return state;+};++const spanOf = (ranges: AxisRanges): number => ranges.x[1] - ranges.x[0];++const touchAt = (element: HTMLElement, identifier: number, clientX: number): Touch =>+ new Touch({ clientX, clientY: 200, identifier, target: element });++const dispatchTouch = (element: HTMLElement, type: string, touches: Touch[]): void => {+ element.dispatchEvent(new TouchEvent(type, { bubbles: true, cancelable: true, touches }));+};++afterEach(() => {+ detach?.();+ detach = null;+ host?.remove();+ host = null;+});++describe('attachWheelZoom pinch bookkeeping', () => {+ it('re-baselines when a third finger lifts instead of jumping the viewport', () => {+ const element = mountHost();+ const state = attach(element, { x: [0, 100], y: [0, 100] });++ // Two fingers 100px apart establish the baseline.+ dispatchTouch(element, 'touchstart', [touchAt(element, 1, 100), touchAt(element, 2, 200)]);++ // A third finger suspends the pinch; plotly pans while it is down.+ dispatchTouch(element, 'touchstart', [+ touchAt(element, 1, 100),+ touchAt(element, 2, 200),+ touchAt(element, 3, 300),+ ]);+ dispatchTouch(element, 'touchmove', [touchAt(element, 1, 10), touchAt(element, 2, 390), touchAt(element, 3, 300)]);++ // Back to two fingers, now far apart. Measuring against the stale 100px+ // baseline would scale the view by ~1/3.8 in a single frame.+ dispatchTouch(element, 'touchend', [touchAt(element, 1, 10), touchAt(element, 2, 390)]);+ const spanBefore = spanOf(state.current);++ dispatchTouch(element, 'touchmove', [touchAt(element, 1, 10), touchAt(element, 2, 390)]);++ expect(spanOf(state.current)).toBeCloseTo(spanBefore, 6);+ });++ it('still pinches normally after the interruption', () => {+ const element = mountHost();+ const state = attach(element, { x: [0, 100], y: [0, 100] });++ dispatchTouch(element, 'touchstart', [touchAt(element, 1, 150), touchAt(element, 2, 250)]);+ const spanBefore = spanOf(state.current);++ // Fingers apart by 2x zooms in, halving the visible span.+ dispatchTouch(element, 'touchmove', [touchAt(element, 1, 100), touchAt(element, 2, 300)]);++ expect(spanOf(state.current)).toBeCloseTo(spanBefore / 2, 6);+ });+});++describe('attachWheelZoom wheel deltas', () => {+ it('zooms usefully for a line-mode wheel, as Firefox reports one', () => {+ const element = mountHost();+ const state = attach(element, { x: [0, 100], y: [0, 100] });++ element.dispatchEvent(+ new WheelEvent('wheel', { bubbles: true, cancelable: true, clientX: 200, clientY: 200, deltaMode: 1, deltaY: 3 })+ );++ // Read as pixels this would be a 0.3% change, which is no zoom at all.+ expect(spanOf(state.current)).toBeGreaterThan(102);+ });++ it('does not let ctrl held over a real wheel jump the view', () => {+ const element = mountHost();+ const state = attach(element, { x: [0, 100], y: [0, 100] });++ element.dispatchEvent(+ new WheelEvent('wheel', {+ bubbles: true,+ cancelable: true,+ clientX: 200,+ clientY: 200,+ ctrlKey: true,+ deltaY: 100,+ })+ );++ // The trackpad-pinch gain on a mouse-sized delta would be ~2.7x.+ expect(spanOf(state.current)).toBeLessThan(125);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.tsindex b669cc4a94..4f8e040fde 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/attachWheelZoom.ts@@ -48,11 +48,15 @@ export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => voconst handleWheel = (event: WheelEvent) => {// Also stops ctrl+wheel browser page zoom over the map.event.preventDefault();- zoomAtClientPoint(event.clientX, event.clientY, zoomFactorFromWheel(event.deltaY, event.ctrlKey));+ zoomAtClientPoint(event.clientX, event.clientY, zoomFactorFromWheel(event.deltaY, event.deltaMode, event.ctrlKey));};let pinchDistance: number | null = null;+ // Re-baselined on any transition INTO two touches, in either direction. A+ // third finger landing mid-pinch suspends the gesture without clearing the+ // baseline, so measuring against it after that finger lifts — with the other+ // two moved meanwhile — would snap the viewport by an arbitrary factor.const handleTouchStart = (event: TouchEvent) => {if (event.touches.length === 2) {pinchDistance = touchDistance(event.touches);@@ -88,7 +92,13 @@ export const attachWheelZoom = (element: HTMLElement, host: ZoomHost): (() => vo};const handleTouchEnd = (event: TouchEvent) => {- if (event.touches.length < 2 && pinchDistance !== null) {+ if (event.touches.length === 2) {+ pinchDistance = touchDistance(event.touches);++ return;+ }++ if (pinchDistance !== null) {pinchDistance = null;// Stamp gesture end too: a pinch held still before lifting would// otherwise let plotly's synthetic click through.diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.tsindex bf9d07ad8c..27c3881b99 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.test.ts@@ -68,10 +68,36 @@ describe('zoomRangesAroundFraction', () => {});describe('zoomFactorFromWheel', () => {- it('zooms out on positive deltas, in on negative, faster for pinch', () => {- expect(zoomFactorFromWheel(100, false)).toBeCloseTo(Math.exp(0.1), 10);- expect(zoomFactorFromWheel(-100, false)).toBeCloseTo(Math.exp(-0.1), 10);- expect(zoomFactorFromWheel(100, true)).toBeCloseTo(Math.exp(1), 10);+ const PIXEL = 0;+ const LINE = 1;+ const PAGE = 2;++ it('zooms out on positive deltas and in on negative', () => {+ expect(zoomFactorFromWheel(100, PIXEL, false)).toBeCloseTo(Math.exp(0.1), 10);+ expect(zoomFactorFromWheel(-100, PIXEL, false)).toBeCloseTo(Math.exp(-0.1), 10);+ });++ it('normalizes line and page deltas, so a Firefox wheel is not inert', () => {+ // Firefox reports a classic mouse wheel as ±3 LINES. Read as pixels that+ // is a 0.3% zoom — ~230 notches to double the view.+ const firefoxNotch = zoomFactorFromWheel(3, LINE, false);+ expect(firefoxNotch).toBeGreaterThan(1.02);+ expect(firefoxNotch).toBeCloseTo(zoomFactorFromWheel(48, PIXEL, false), 10);+ expect(zoomFactorFromWheel(1, PAGE, false)).toBeGreaterThan(firefoxNotch);+ });++ it('gives the trackpad-pinch gain only to trackpad-sized deltas', () => {+ // A pinch arrives as ctrl+wheel in small synthetic steps...+ expect(zoomFactorFromWheel(5, PIXEL, true)).toBeCloseTo(Math.exp(0.05), 10);+ // ...but so does ctrl held over a real wheel, where the pinch gain would+ // zoom 2.7x in a single notch.+ expect(zoomFactorFromWheel(100, PIXEL, true)).toBeCloseTo(zoomFactorFromWheel(100, PIXEL, false), 10);+ expect(zoomFactorFromWheel(3, LINE, true)).toBeCloseTo(zoomFactorFromWheel(3, LINE, false), 10);+ });++ it('clamps any single event to a usable step in both directions', () => {+ expect(zoomFactorFromWheel(10000, PIXEL, true)).toBeLessThanOrEqual(1.25);+ expect(zoomFactorFromWheel(-10000, PIXEL, true)).toBeGreaterThanOrEqual(1 / 1.25);});});diff --git a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.tsindex 2302517c89..03fa80fa59 100644--- a/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts+++ b/invokeai/frontend/webv2/src/workbench/image-map/imageMapViewport.ts@@ -107,9 +107,48 @@ export const fitRangesToAspect = (ranges: AxisRanges, aspectRatio: number): Axisreturn { x: ranges.x, y: [centerY - nextSpanY / 2, centerY + nextSpanY / 2] };};-/** exp() gain per wheel tick; ctrl+wheel is trackpad pinch and moves faster. */-export const zoomFactorFromWheel = (deltaY: number, isPinch: boolean): number =>- Math.exp(deltaY * (isPinch ? 0.01 : 0.001));+/** Approximate pixels per line and per page, for non-pixel wheel deltas. */+const WHEEL_LINE_HEIGHT_PX = 16;+const WHEEL_PAGE_HEIGHT_PX = 400;++/**+ * Above this many pixels a ctrl+wheel came from a real wheel, not a trackpad+ * pinch: browsers report a pinch as ctrl+wheel too, but in small synthetic+ * steps, while one mouse notch is 100px (Chrome) or 3 lines (Firefox).+ */+const PINCH_DELTA_LIMIT_PX = 40;++/** The most a single wheel event may scale the view, in either direction. */+const MAX_WHEEL_ZOOM_STEP = 1.25;++/**+ * Wheel deltas do not arrive in the same unit everywhere. Firefox reports a+ * classic mouse wheel in LINES (deltaY ±3), so treating deltaY as pixels made+ * one notch a 0.3% zoom — and since the handler preventDefaults, the user got+ * neither zoom nor scroll.+ */+export const normalizeWheelDeltaY = (deltaY: number, deltaMode: number): number => {+ if (deltaMode === 1) {+ return deltaY * WHEEL_LINE_HEIGHT_PX;+ }++ if (deltaMode === 2) {+ return deltaY * WHEEL_PAGE_HEIGHT_PX;+ }++ return deltaY;+};++/** exp() gain per wheel tick; a trackpad pinch moves faster per unit. */+export const zoomFactorFromWheel = (deltaY: number, deltaMode: number, isCtrlHeld: boolean): number => {+ const pixels = normalizeWheelDeltaY(deltaY, deltaMode);+ const isPinch = isCtrlHeld && Math.abs(pixels) < PINCH_DELTA_LIMIT_PX;+ const factor = Math.exp(pixels * (isPinch ? 0.01 : 0.001));++ // The pinch gain applied to a mouse-sized delta would zoom 2.7x in one+ // notch; clamping keeps every input device to a usable step.+ return Math.min(Math.max(factor, 1 / MAX_WHEEL_ZOOM_STEP), MAX_WHEEL_ZOOM_STEP);+};/*** Scale both ranges by `factor` while keeping the point at the givendiff --git a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsxindex 9e8ce15d7d..2e53f7ff7b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/image-map/ImageMapPlot.tsx@@ -215,6 +215,20 @@ const ImageMapPlot = () => {}const point = selectedImageName ? points.find((candidate) => candidate.imageName === selectedImageName) : undefined;+ const suppression = lastMapSelectionRef.current;+ const isSuppressionFresh = suppression !== null && Date.now() - suppression.at < MAP_CLICK_SUPPRESS_MS;+ const cameFromMapClick = isSuppressionFresh && suppression.name === selectedImageName;++ // Consume a matching entry; an interleaved external selection keeps a+ // pending map click's suppression intact for when it lands. Expired+ // entries go regardless — a click whose selection never arrived (the+ // image was deleted, or the selection resolved to a non-image) would+ // otherwise sit here and swallow the recenter for a later, unrelated+ // gallery pick of the same name. Both run before the `!point` return,+ // which is the path a never-arriving selection actually takes.+ if (suppression !== null && (cameFromMapClick || !isSuppressionFresh)) {+ lastMapSelectionRef.current = null;+ }if (!point) {swallow(Plotly.restyle(container, { x: [[]], y: [[]] }, [markerIndex]));@@ -224,18 +238,6 @@ const ImageMapPlot = () => {swallow(Plotly.restyle(container, { x: [[point.x]], y: [[point.y]] }, [markerIndex]));- const suppression = lastMapSelectionRef.current;- const cameFromMapClick =- suppression !== null &&- suppression.name === selectedImageName &&- Date.now() - suppression.at < MAP_CLICK_SUPPRESS_MS;-- if (suppression !== null && suppression.name === selectedImageName) {- // Consume only a matching entry; an interleaved external selection- // keeps a pending map click's suppression intact for when it lands.- lastMapSelectionRef.current = null;- }-if (cameFromMapClick) {return;}@@ -269,23 +271,38 @@ const ImageMapPlot = () => {const observer = new ResizeObserver(() => {if (container.offsetWidth > 0 && container.offsetHeight > 0) {- void Plotly.Plots.resize(container);-- // A plot first built while the container was unmeasured never got- // its whole-map fit; apply it on the first real layout.- if (!initialFitDoneRef.current) {- const fitted = computeInitialFit(- pointsRef.current ?? [],- selectedImageNameRef.current,- container.offsetWidth,- container.offsetHeight- );-- if (fitted) {- swallow(Plotly.relayout(container, { 'xaxis.range': fitted.x, 'yaxis.range': fitted.y }));+ // `@types/plotly.js` declares this `void`; plotly resolves a promise+ // once the resize has actually been applied.+ const resized = Plotly.Plots.resize(container) as unknown as Promise<unknown>;++ // Chained, not fired alongside: the resize defers its own autosize+ // relayout, so a fit applied immediately would be solved against the+ // plot's previous dimensions — and with the axes scale-anchored, that+ // re-solve crops one of them.+ swallow(+ resized.then(() => {+ // A plot first built while the container was unmeasured never got+ // its whole-map fit; apply it on the first real layout.+ if (initialFitDoneRef.current) {+ return undefined;+ }++ const fitted = computeInitialFit(+ pointsRef.current ?? [],+ selectedImageNameRef.current,+ container.offsetWidth,+ container.offsetHeight+ );++ if (!fitted) {+ return undefined;+ }+initialFitDoneRef.current = true;- }- }++ return Plotly.relayout(container, { 'xaxis.range': fitted.x, 'yaxis.range': fitted.y });+ })+ );}});observer.observe(container);@@ -294,6 +311,10 @@ const ImageMapPlot = () => {detachZoom();observer.disconnect();Plotly.purge(container);+ // Purging drops the layout the flag stands for. Leaving it set costs+ // the whole-map fit on any remount of this same component instance —+ // StrictMode's double-mount in development, for one.+ initialFitDoneRef.current = false;};}, []);