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(webv2): snap layer moves and transform handles to the grid
joshistoaste62125c596ac
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.tsindex 174b70d7e5..e6c6202012 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.test.ts@@ -5,6 +5,7 @@ import { describe, expect, it } from 'vitest';import {clampZoom,constrainAspect,+ snapMovedPoint,snapRectToGrid,snapToGrid,snapZoom,@@ -80,6 +81,23 @@ describe('snapToGrid', () => {});});+describe('snapMovedPoint', () => {+ it('snaps the resulting position rather than the delta', () => {+ // An off-grid origin seats ONTO the grid: 3+21=24, 5+15=20 -> 24.+ expect(snapMovedPoint({ x: 3, y: 5 }, { x: 21, y: 15 }, 8)).toEqual({ x: 24, y: 24 });+ });++ it('passes an axis with a zero delta through untouched', () => {+ // Shift-locked (or simply unmoved) axes must not drift onto a grid line.+ expect(snapMovedPoint({ x: 3, y: 5 }, { x: 21, y: 0 }, 8)).toEqual({ x: 24, y: 5 });+ expect(snapMovedPoint({ x: 3, y: 5 }, { x: 0, y: 15 }, 8)).toEqual({ x: 3, y: 24 });+ });++ it('is a plain translation for a non-positive grid', () => {+ expect(snapMovedPoint({ x: 3, y: 5 }, { x: 21, y: 15 }, 0)).toEqual({ x: 24, y: 20 });+ });+});+describe('snapRectToGrid', () => {it('snaps position and the far edge to the grid, deriving size', () => {const r: Rect = { x: 3, y: 5, width: 30, height: 30 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.tsindex 70c849277f..cef4531427 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/math/snapping.ts@@ -4,7 +4,7 @@* No classes, no mutation — every function returns a new value.*/-import type { Rect } from '@workbench/canvas-engine/types';+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';/** Zoom levels the viewport snaps to when close enough. Single source of truth for the HUD. */export const ZOOM_SNAP_CANDIDATES: readonly number[] = [0.25, 0.33, 0.5, 0.67, 0.75, 1, 1.25, 1.5, 2, 3, 4, 5];@@ -50,6 +50,21 @@ export const snapToGrid = (value: number, grid: number): number => {return Math.round(value / grid) * grid;};+/**+ * The snapped absolute position for a drag of `delta` away from `origin`.+ *+ * Snaps the RESULT, not the delta, so something that starts off-grid seats onto+ * the grid instead of carrying its misalignment along forever.+ *+ * Per axis, and only for axes the drag actually moved: an axis with a zero delta+ * (shift locked it, or the pointer simply never moved along it) is passed through+ * untouched rather than being pulled onto a grid line the user never crossed.+ */+export const snapMovedPoint = (origin: Vec2, delta: Vec2, grid: number): Vec2 => ({+ x: delta.x === 0 ? origin.x : snapToGrid(origin.x + delta.x, grid),+ y: delta.y === 0 ? origin.y : snapToGrid(origin.y + delta.y, grid),+});+/** Snaps a rect's position and size to the nearest multiple of `grid`. */export const snapRectToGrid = (rect: Rect, grid: number): Rect => {const x = snapToGrid(rect.x, grid);diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.tsnew file mode 100644index 0000000000..1cc144a511--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gridSnap.ts@@ -0,0 +1,29 @@+/**+ * The grid-snapping gate for the tools that position LAYERS (move, transform).+ *+ * The canvas has exactly one grid: `stores.bboxGrid`, the model grid that the bbox+ * tool snaps to and that `overlayRenderer` actually paints. Layer positions snap to+ * that same grid, so a layer lands on the lines the user can see — there is no+ * second, invisible positional grid (legacy's 64/8 pair does not apply here; its+ * drawn grid was decoupled from the bbox grid).+ *+ * The math itself lives in `math/snapping` (`snapToGrid`, `snapMovedPoint`), which+ * stays pure and store-free; this module only answers "which grid, right now".+ *+ * Zero React, zero import-time side effects.+ */++import type { ToolContext } from './tool';++/**+ * The grid layer positions should snap to right now, or `0` for no snap —+ * `snapToGrid` treats `grid <= 0` as "leave the value alone", so callers never+ * need a second boolean.+ *+ * `bypass` is the per-gesture escape hatch (alt, matching the bbox tool). Alt+ * reaches the tool rather than switching to the color picker because+ * `pointerPipeline.beginTempTool` refuses to start a temp-tool hold while a+ * gesture is active — the same mechanism the bbox tool's alt bypass relies on.+ */+export const positionGrid = (ctx: ToolContext, bypass: boolean): number =>+ !bypass && ctx.stores.snapToGrid.get() ? ctx.stores.bboxGrid.get() : 0;diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.tsindex ae0f5e6a9f..fa033c83e1 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts@@ -60,10 +60,14 @@ const makeDoc = (layers: CanvasLayerContract[], selectedLayerId: string | null):width: 100,});-const pointer = (x: number, y: number, opts: { shift?: boolean; buttons?: number } = {}): PointerInput => ({+const pointer = (+ x: number,+ y: number,+ opts: { shift?: boolean; alt?: boolean; buttons?: number } = {}+): PointerInput => ({buttons: opts.buttons ?? 1,documentPoint: { x, y },- modifiers: { alt: false, ctrl: false, meta: false, shift: opts.shift ?? false },+ modifiers: { alt: opts.alt ?? false, ctrl: false, meta: false, shift: opts.shift ?? false },pointerType: 'mouse',pressure: 0.5,screenPoint: { x, y },@@ -95,6 +99,14 @@ interface HarnessOptions {canLift?: boolean;/** A float that is already in flight before the gesture starts. */existingFloat?: boolean;+ /**+ * Grid-snapping state. Defaults to OFF so the drag/commit-contract tests below+ * assert raw pointer deltas; the snapping tests opt in explicitly. (The product+ * default is on — see `createEngineStores`.)+ */+ snapToGrid?: boolean;+ /** The grid snapping uses when enabled; defaults to the engine's own default. */+ bboxGrid?: number;}const IDENTITY: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };@@ -113,6 +125,11 @@ const createHarness = (doc: CanvasDocumentContractV2, options: HarnessOptions =current: options.existingFloat ? fakeFloat(doc.selectedLayerId ?? 'a') : null,};const commitFloat = vi.fn();+ const stores = createEngineStores();+ stores.snapToGrid.set(options.snapToGrid ?? false);+ if (options.bboxGrid !== undefined) {+ stores.bboxGrid.set(options.bboxGrid);+ }const ctx: ToolContext = {backend: null as never,commitFloatingSelection: commitFloat,@@ -145,7 +162,7 @@ const createHarness = (doc: CanvasDocumentContractV2, options: HarnessOptions =},setLayerTransformOverride: (layerId, override) => overrides.push({ layerId, override }),setOverlayCursor: vi.fn(),- stores: createEngineStores(),+ stores,updateCursor: vi.fn(),viewport: null as never,};@@ -355,6 +372,107 @@ describe('move tool: drag', () => {});});+describe('move tool: grid snapping', () => {+ const snapDoc = () => makeDoc([imageLayer('a', { x: 0, y: 0, width: 50, height: 50 })], 'a');++ it('snaps the committed position to the grid, and previews the same value', () => {+ const h = createHarness(snapDoc(), { bboxGrid: 8, snapToGrid: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(31, 25)); // raw delta (21, 15) → snapped (24, 16)+ up(tool, h.ctx, pointer(31, 25));++ // The preview shows exactly what the commit lands on — no jump on release.+ expect(h.overrides).toEqual([+ { layerId: 'a', override: { x: 24, y: 16 } },+ { layerId: 'a', override: null },+ ]);+ expect(h.commits[0]!.forward).toEqual({+ id: 'a',+ patch: { transform: { x: 24, y: 16 } },+ type: 'updateCanvasLayer',+ });+ });++ it('seats an off-grid layer onto the grid rather than carrying its offset', () => {+ const doc = makeDoc([imageLayer('a', { x: 3, y: 5, width: 50, height: 50 })], 'a');+ const h = createHarness(doc, { bboxGrid: 8, snapToGrid: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 30)); // 3+20=23 → 24, 5+20=25 → 24+ up(tool, h.ctx, pointer(30, 30));++ expect(h.commits[0]!.forward).toMatchObject({ patch: { transform: { x: 24, y: 24 } } });+ });++ it('leaves the position raw when the setting is off', () => {+ const h = createHarness(snapDoc(), { snapToGrid: false });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(31, 25));+ up(tool, h.ctx, pointer(31, 25));++ expect(h.commits[0]!.forward).toMatchObject({ patch: { transform: { x: 21, y: 15 } } });+ });++ it('bypasses the snap while alt is held', () => {+ const h = createHarness(snapDoc(), { bboxGrid: 8, snapToGrid: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(31, 25, { alt: true }));+ up(tool, h.ctx, pointer(31, 25, { alt: true }));++ expect(h.commits[0]!.forward).toMatchObject({ patch: { transform: { x: 21, y: 15 } } });+ });++ it('keeps a shift-locked axis exactly on its origin instead of snapping it', () => {+ // y starts off-grid at 5 and shift zeroes its delta — snapping it to 8 would+ // move the layer along an axis the user locked.+ const doc = makeDoc([imageLayer('a', { x: 0, y: 5, width: 50, height: 50 })], 'a');+ const h = createHarness(doc, { bboxGrid: 8, snapToGrid: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(41, 15, { shift: true }));+ up(tool, h.ctx, pointer(41, 15, { shift: true }));++ expect(h.commits[0]!.forward).toMatchObject({ patch: { transform: { x: 32, y: 5 } } });+ });++ it('commits nothing when the snap lands the layer back on its origin', () => {+ const h = createHarness(snapDoc(), { bboxGrid: 64, snapToGrid: true });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(30, 30)); // past the threshold, but (20,20) snaps back to (0,0)+ up(tool, h.ctx, pointer(30, 30));++ expect(h.commits).toHaveLength(0);+ expect(h.overrides.at(-1)).toEqual({ layerId: 'a', override: null });+ });++ it('does not snap a floating selection (its transform is layer-local)', () => {+ const h = createHarness(snapDoc(), {+ bboxGrid: 8,+ canLift: true,+ selectionContainsPoint: true,+ snapToGrid: true,+ });+ const tool = createMoveTool();++ down(tool, h.ctx, pointer(10, 10));+ move(tool, h.ctx, pointer(31, 25));+ up(tool, h.ctx, pointer(31, 25));++ expect(h.transforms.at(-1)).toMatchObject({ x: 21, y: 15 });+ expect(h.commits).toHaveLength(0);+ });+});+describe('move tool: cancel', () => {it('drops the override and commits nothing on Esc mid-drag', () => {const doc = makeDoc([imageLayer('a', { width: 50, height: 50 })], 'a');diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.tsindex 6439e2fafa..ea8d6be12e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts@@ -22,6 +22,10 @@* irrelevant). Pointer-move only sets a transient transform override (live* preview) — it never dispatches.* - **`shift`** constrains motion to the dominant axis, for both modes.+ * - **Snap**: with the snap-to-grid setting on, a LAYER drag lands its origin on+ * the model grid (the one the overlay draws); hold **alt** to bypass. Moving+ * PIXELS never snaps — a float's transform is layer-local, so document-space+ * grid math would skew it on a rotated or scaled layer.* - **Commit** (pointer-up after a real layer move): one `commitStructural` with* the new/old transform x/y. A zero-delta drag commits nothing. Moving a float* commits nothing here — the float's own commit does that later.@@ -35,8 +39,12 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';+import { snapMovedPoint } from '@workbench/canvas-engine/math/snapping';+import type { Tool, ToolContext } from './tool';+import { positionGrid } from './gridSnap';+/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */const PRIMARY_BUTTON = 1;@@ -121,13 +129,22 @@ export const createMoveTool = (): Tool => {input.modifiers.shift);+ /**+ * Where a layer drag puts the layer's origin, snapped to the grid unless the+ * setting is off or alt bypasses it. Shared by the live preview and the commit+ * so the layer lands exactly where the drag showed it.+ */+ const nextLayerPosition = (+ ctx: ToolContext,+ origin: { x: number; y: number },+ input: PointerInput,+ delta: Vec2+ ): Vec2 => snapMovedPoint(origin, delta, positionGrid(ctx, input.modifiers.alt));+const applyDelta = (ctx: ToolContext, current: GestureState, input: PointerInput): void => {const delta = deltaFor(current, input);if (current.mode.kind === 'layer') {- ctx.setLayerTransformOverride(current.mode.targetId, {- x: current.mode.origin.x + delta.x,- y: current.mode.origin.y + delta.y,- });+ ctx.setLayerTransformOverride(current.mode.targetId, nextLayerPosition(ctx, current.mode.origin, input, delta));return;}if (current.mode.kind === 'float') {@@ -209,17 +226,17 @@ export const createMoveTool = (): Tool => {}if (current.mode.kind === 'float') {// The float keeps the drag; it bakes later, as one entry for the whole- // move however many drags it took.+ // move however many drags it took. Floats never snap — see the header.applyDelta(ctx, current, input);return;}- const delta = deltaFor(current, input);const origin = current.mode.origin;- const next = { x: origin.x + delta.x, y: origin.y + delta.y };+ const next = nextLayerPosition(ctx, origin, input, deltaFor(current, input));if (next.x === origin.x && next.y === origin.y) {- // Zero-delta drag: drop the preview, commit nothing.+ // Nothing moved — either a zero-delta drag, or a drag whose snapped+ // result landed back on the origin. Drop the preview, commit nothing.ctx.setLayerTransformOverride(current.mode.targetId, null);return;}diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.tsindex 77e5410032..084f896346 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts@@ -5,7 +5,12 @@ import type { LayerTransform } from '@workbench/canvas-engine/transform/transforimport type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';import { createEngineStores } from '@workbench/canvas-engine/engineStores';-import { TRANSFORM_ROTATE_NUB_PX, transformOverlayGeometry } from '@workbench/canvas-engine/transform/transformMath';+import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';+import {+ layerTransformMatrix,+ TRANSFORM_ROTATE_NUB_PX,+ transformOverlayGeometry,+} from '@workbench/canvas-engine/transform/transformMath';import { describe, expect, it, vi } from 'vitest';import { createTransformTool } from './transformTool';@@ -100,9 +105,13 @@ interface Harness {* A ToolContext whose transform-session seams mutate a real `transformSession`* store (mirroring the engine), so the tool's reads reflect its own writes across* a down→move→up drag. The viewport projects document→screen 1:1.+ *+ * Grid snapping starts OFF so the gesture-math tests assert raw pointer deltas;+ * the snapping tests re-enable it on `h.ctx.stores`. (The product default is on.)*/const createHarness = (doc: CanvasDocumentContractV2, zoom = 1, float?: FloatingSelection | null): Harness => {const stores = createEngineStores();+ stores.snapToGrid.set(false);const overrides: { layerId: string; override: unknown }[] = [];const state = { applyCount: 0, commitFloatCount: 0, cancelFloatCount: 0 };const floatRef: { current: FloatingSelection | null } = { current: float ?? null };@@ -323,6 +332,85 @@ describe('transform tool: gestures', () => {});});+describe('transform tool: grid snapping', () => {+ /** A harness with snapping on at `grid`. */+ const snapHarness = (grid: number, float?: FloatingSelection) => {+ const doc = makeDoc([imageLayer('a', { width: 100, height: 100 })], 'a');+ const h = createHarness(doc, 1, float);+ h.ctx.stores.snapToGrid.set(true);+ h.ctx.stores.bboxGrid.set(grid);+ return h;+ };++ it('snaps an interior move to the grid', () => {+ const h = snapHarness(8);+ const tool = createTransformTool();+ activate(tool, h.ctx);++ down(tool, h.ctx, pointer(50, 50));+ move(tool, h.ctx, pointer(71, 65)); // raw (21, 15) → (24, 16)+ up(tool, h.ctx, pointer(71, 65));++ expect(h.session()?.transform.x).toBeCloseTo(24, 5);+ expect(h.session()?.transform.y).toBeCloseTo(16, 5);+ });++ it('bypasses the move snap while alt is held', () => {+ const h = snapHarness(8);+ const tool = createTransformTool();+ activate(tool, h.ctx);++ down(tool, h.ctx, pointer(50, 50));+ move(tool, h.ctx, pointer(71, 65, { alt: true }));++ expect(h.session()?.transform.x).toBeCloseTo(21, 5);+ expect(h.session()?.transform.y).toBeCloseTo(15, 5);+ });++ it('lands a dragged scale handle on the grid', () => {+ const h = snapHarness(8);+ const tool = createTransformTool();+ activate(tool, h.ctx);++ // se corner at doc (100,100) dragged to (153,153) → snaps to (152,152).+ down(tool, h.ctx, pointer(100, 100));+ move(tool, h.ctx, pointer(153, 153));++ expect(h.session()?.transform.scaleX).toBeCloseTo(1.52, 5);+ expect(h.session()?.transform.scaleY).toBeCloseTo(1.52, 5);+ });++ it('still scales about center under alt (alt is not a bypass on a handle)', () => {+ const h = snapHarness(8);+ const tool = createTransformTool();+ activate(tool, h.ctx);++ down(tool, h.ctx, pointer(100, 100));+ move(tool, h.ctx, pointer(153, 153, { alt: true }));++ // The layer center (50,50) stays put — the alt anchor, not a snap bypass.+ const next = h.session()!.transform;+ const center = applyToPoint(layerTransformMatrix(next), { x: 50, y: 50 });+ expect(center.x).toBeCloseTo(50, 5);+ expect(center.y).toBeCloseTo(50, 5);+ });++ it('does not snap a float gesture (its transform is layer-local)', () => {+ const float = {+ layerId: 'a',+ pixels: { rect: { height: 100, width: 100, x: 0, y: 0 } },+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ } as FloatingSelection;+ const h = snapHarness(8, float);+ const tool = createTransformTool();++ down(tool, h.ctx, pointer(50, 50));+ move(tool, h.ctx, pointer(71, 65));++ expect(h.floatTransforms.at(-1)).toMatchObject({ x: 21, y: 15 });+ });+});+describe('transform tool: rotation nub (regression — a nub press must rotate, not reset)', () => {const transformed: LayerTransform = { rotation: 0.4, scaleX: 1.6, scaleY: 1.3, x: 30, y: 20 };const layerSize = { height: 100, width: 100, x: 0, y: 0 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.tsindex e88093a72a..80c89bac48 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts@@ -15,6 +15,11 @@* corners); a corner rotate zone rotates about the center (shift = 15° snap);* the interior moves (shift = axis constrain). Pointer-move only updates the* session preview — it never dispatches.+ * - **Snap**: with the snap-to-grid setting on, a LAYER gesture lands its origin+ * (move) or the dragged handle (scale) on the model grid. Alt bypasses the snap+ * on a move; on a scale handle it does not, because alt already means+ * scale-about-center there. Float gestures never snap — their transform is+ * layer-local, so a document-space grid would skew rotated/scaled layers.* - **Apply** (`enter` / options button): the engine commits — a param edit for* image layers, a pixel bake for paint layers — as ONE undoable entry.* - **Cancel** (`esc` / options button / a REAL tool switch): drops the@@ -45,6 +50,7 @@ import {import type { Tool, ToolContext } from './tool';+import { positionGrid } from './gridSnap';import { hittableLayerRect, layerMatrix } from './moveHitTest';/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */@@ -186,7 +192,7 @@ export const createTransformTool = (): Tool => {transform: subject.transform,});- const nextTransform = (state: GestureState, input: PointerInput): LayerTransform => {+ const nextTransform = (ctx: ToolContext, state: GestureState, input: PointerInput): LayerTransform => {// The pointer arrives in document space; the gesture math runs in the// subject's space, so convert before doing anything with it.const pointer = state.fromDocument(input.documentPoint);@@ -194,12 +200,17 @@ export const createTransformTool = (): Tool => {x: pointer.x - state.startPointerDoc.x,y: pointer.y - state.startPointerDoc.y,};+ // A float works in its layer's LOCAL space, so a document-space grid would+ // skew it on a rotated/scaled layer — only layer gestures snap.+ const gridFor = (bypass: boolean): number => (state.kind === 'layer' ? positionGrid(ctx, bypass) : 0);switch (state.target.kind) {case 'move':- return applyMove(state.startTransform, delta, input.modifiers.shift);+ return applyMove(state.startTransform, delta, input.modifiers.shift, gridFor(input.modifiers.alt));case 'scale':return applyScale({alt: input.modifiers.alt,+ // No alt bypass on a scale handle — alt already means scale-about-center.+ grid: gridFor(false),handle: state.target.handle,pointerDoc: pointer,shift: input.modifiers.shift,@@ -378,7 +389,7 @@ export const createTransformTool = (): Tool => {}gesture.moved = true;}- publish(ctx, gesture.kind, nextTransform(gesture, input));+ publish(ctx, gesture.kind, nextTransform(ctx, gesture, input));return;}// Idle hover over a framed subject: reflect the target under the pointer.diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.tsindex 4a4951d355..ab9a0d85ec 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.test.ts@@ -411,6 +411,71 @@ describe('applyMove', () => {});});+describe('applyMove: grid snapping', () => {+ const offGrid: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 3, y: 5 };++ it('is a no-op at grid 0, reproducing the unsnapped result exactly', () => {+ expect(applyMove(offGrid, { x: 5, y: -3 }, false, 0)).toEqual(applyMove(offGrid, { x: 5, y: -3 }, false));+ });+ it('snaps the resulting position, not the delta', () => {+ // 3+21=24 (already a multiple), 5+15=20 → 24 (nearest, ties round up).+ expect(applyMove(offGrid, { x: 21, y: 15 }, false, 8)).toMatchObject({ x: 24, y: 24 });+ });+ it('passes a shift-locked axis through untouched', () => {+ // Shift zeroes dy, so y keeps its off-grid 5 rather than being pulled to 8.+ expect(applyMove(offGrid, { x: 21, y: 2 }, true, 8)).toMatchObject({ x: 24, y: 5 });+ });+ it('leaves rotation and scale alone', () => {+ const start: LayerTransform = { rotation: 0.5, scaleX: 2, scaleY: 3, x: 0, y: 0 };+ expect(applyMove(start, { x: 5, y: 5 }, false, 8)).toMatchObject({ rotation: 0.5, scaleX: 2, scaleY: 3 });+ });+});++describe('applyScale: grid snapping', () => {+ const scaleAt = (grid: number, pointerDoc: { x: number; y: number }): LayerTransform =>+ applyScale({+ alt: false,+ grid,+ handle: 'se',+ pointerDoc,+ shift: false,+ rect,+ start: identity,+ startPointerDoc: { x: 100, y: 100 },+ });++ it('is a no-op at grid 0', () => {+ const withZero = scaleAt(0, { x: 153, y: 100 });+ const withNone = applyScale({+ alt: false,+ handle: 'se',+ pointerDoc: { x: 153, y: 100 },+ shift: false,+ rect,+ start: identity,+ startPointerDoc: { x: 100, y: 100 },+ });+ expect(withZero).toEqual(withNone);+ });++ it('lands the dragged handle on a grid multiple', () => {+ // se handle starts at doc (100,100); a 53px x-drag targets 153 → snaps to 152.+ const next = scaleAt(8, { x: 153, y: 100 });+ const handleDoc = applyToPoint(layerTransformMatrix(next), localHandlePoint(rect, 'se'));+ expect(close(handleDoc.x, 152)).toBe(true);+ expect(close(handleDoc.y, 100)).toBe(true);+ // The scale is derived from the snapped target, not rounded itself.+ expect(close(next.scaleX, 1.52)).toBe(true);+ });++ it('keeps the opposite anchor fixed while snapping', () => {+ const next = scaleAt(8, { x: 153, y: 141 });+ const anchorDoc = applyToPoint(layerTransformMatrix(next), localHandlePoint(rect, 'nw'));+ expect(close(anchorDoc.x, 0)).toBe(true);+ expect(close(anchorDoc.y, 0)).toBe(true);+ });+});+describe('bakeMatrix', () => {it('equals the layer matrix so bake-then-draw ≡ transform-then-draw', () => {const transform: LayerTransform = { rotation: Math.PI / 6, scaleX: 1.5, scaleY: 0.8, x: 12, y: 34 };diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.tsindex 0b81fe61ef..e2fc0ceffb 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/transform/transformMath.ts@@ -21,6 +21,7 @@ import type { CanvasLayerBaseContract } from '@workbench/canvas-engine/contractsimport type { Mat2d, Vec2 } from '@workbench/canvas-engine/types';import { applyToPoint, fromTRS } from '@workbench/canvas-engine/math/mat2d';+import { snapMovedPoint } from '@workbench/canvas-engine/math/snapping';/** The editable layer transform (translate + per-axis scale + rotation in radians). */export type LayerTransform = CanvasLayerBaseContract['transform'];@@ -297,11 +298,18 @@ export const constrainMoveDelta = (delta: Vec2, shift: boolean): Vec2 => {return Math.abs(delta.x) >= Math.abs(delta.y) ? { x: delta.x, y: 0 } : { x: 0, y: delta.y };};-/** Translates `start` by a document-space pointer delta (shift = axis constrain). */-export const applyMove = (start: LayerTransform, deltaDoc: Vec2, shift: boolean): LayerTransform => {- const d = constrainMoveDelta(deltaDoc, shift);- return { ...start, x: start.x + d.x, y: start.y + d.y };-};+/**+ * Translates `start` by a document-space pointer delta (shift = axis constrain).+ *+ * A positive `grid` snaps the RESULTING origin to that grid, per axis and only+ * for axes the drag moved — an axis that shift has locked carries a zero delta,+ * so it passes through exactly rather than being pulled onto a grid line.+ * `grid = 0` (the default) leaves the position untouched.+ */+export const applyMove = (start: LayerTransform, deltaDoc: Vec2, shift: boolean, grid = 0): LayerTransform => ({+ ...start,+ ...snapMovedPoint(start, constrainMoveDelta(deltaDoc, shift), grid),+});/** Parameters for {@link applyScale}. */export interface ScaleParams {@@ -316,6 +324,8 @@ export interface ScaleParams {shift: boolean;/** Scale about the layer center instead of the opposite handle. */alt: boolean;+ /** Grid the dragged handle lands on (document space); `0`/absent = no snap. */+ grid?: number;}/**@@ -324,6 +334,10 @@ export interface ScaleParams {* one axis, corners scale both (`shift` forces a uniform, aspect-preserving* factor). Dragging past the anchor flips the axis (negative scale), which is* kept correct; each axis is clamped to {@link MIN_ABS_SCALE}.+ *+ * `grid` snaps where the HANDLE lands in document space (the equivalent of the+ * legacy Konva `anchorDragBoundFunc`); the scale factors stay derived from that+ * snapped target rather than being rounded themselves, so the anchor never drifts.*/export const applyScale = (p: ScaleParams): LayerTransform => {const { alt, handle, rect, shift, start } = p;@@ -332,10 +346,14 @@ export const applyScale = (p: ScaleParams): LayerTransform => {const anchorLocal = alt ? localCenter(rect) : localHandlePoint(rect, OPPOSITE[handle]);const anchorDoc = applyToPoint(m, anchorLocal);const handleDoc = applyToPoint(m, handleLocal);- const targetDoc: Vec2 = {- x: handleDoc.x + (p.pointerDoc.x - p.startPointerDoc.x),- y: handleDoc.y + (p.pointerDoc.y - p.startPointerDoc.y),- };+ // `snapMovedPoint`'s per-axis rule matters here too: an axis the pointer never+ // moved along must keep its scale, or a purely horizontal corner drag would+ // resize the layer vertically just because the handle did not start on a line.+ const targetDoc = snapMovedPoint(+ handleDoc,+ { x: p.pointerDoc.x - p.startPointerDoc.x, y: p.pointerDoc.y - p.startPointerDoc.y },+ p.grid ?? 0+ );// Un-rotate the anchor→target vector into the layer's scaled-local frame.const cos = Math.cos(start.rotation);