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.

feat(webv2): transform floating selections

joshistoasta48afe4fe384
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 219a235f8b..3b1df2f41a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -81,6 +81,7 @@ export interface CanvasInteractionState {
documentEditingLocked: boolean;
eraserOptions: EraserOptions;
gradientOptions: GradientToolOptions;
+ hasFloatingSelection: boolean;
hasSelection: boolean;
invertBrushSizeScroll: boolean;
lassoOptions: LassoToolOptions;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
index f6267355fa..60bc810e74 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
@@ -73,6 +73,7 @@ const createFloatingSelectionOptions = () => ({
layers: {} as never,
markDirty: vi.fn(),
notifyPainted: vi.fn(),
+ onChange: vi.fn(),
});
const createSelectionImageOptions = () => ({
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts
index 7f4119d3b9..1c9e9f3531 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.test.ts
@@ -67,6 +67,7 @@ const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect;
invalidateLayer: vi.fn(),
markDirty: vi.fn(),
notifyPainted: vi.fn(),
+ onChange: vi.fn(),
};
const controller = new FloatingSelectionController({
@@ -80,6 +81,7 @@ const createHarness = (options: { layer?: CanvasLayerContract; maskRect?: Rect;
layers,
markDirty: calls.markDirty,
notifyPainted: calls.notifyPainted,
+ onChange: calls.onChange,
selection,
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts
index ff3a999797..7c26a2f1cf 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/floatingSelectionController.ts
@@ -32,6 +32,8 @@ export interface FloatingSelectionControllerOptions {
readonly notifyPainted: (layerId: string) => void;
readonly markDirty: (layerId: string) => void;
readonly invalidateLayer: (layerId: string) => void;
+ /** Called whenever a float appears or disappears (the engine mirrors it to a store). */
+ readonly onChange: () => void;
}
const isIdentity = (transform: LayerTransform): boolean =>
@@ -138,6 +140,7 @@ export class FloatingSelectionController {
// Bump the cache version so the hole composites, WITHOUT marking dirty.
this.deps.notifyPainted(layerId);
this.deps.invalidateLayer(layerId);
+ this.deps.onChange();
return true;
}
@@ -165,6 +168,7 @@ export class FloatingSelectionController {
if (!layer) {
// The layer went away under the float; the pixels have nowhere to land.
this.float = null;
+ this.deps.onChange();
return;
}
if (isIdentity(float.transform)) {
@@ -211,6 +215,7 @@ export class FloatingSelectionController {
);
this.float = null;
+ this.deps.onChange();
this.deps.notifyPainted(float.layerId);
this.deps.markDirty(float.layerId);
this.deps.invalidateLayer(float.layerId);
@@ -257,6 +262,7 @@ export class FloatingSelectionController {
return;
}
this.float = null;
+ this.deps.onChange();
if (!this.layerOf(float)) {
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 8b34907540..df64121b40 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -138,7 +138,7 @@ import {
import { LayerFilterOutputDimensionError } from '@workbench/canvas-engine/filterError';
import { createPointerPipeline, type PointerPipeline } from '@workbench/canvas-engine/input/pointerPipeline';
import { createWheelHandler } from '@workbench/canvas-engine/input/wheel';
-import { fromTRS } from '@workbench/canvas-engine/math/mat2d';
+import { applyToPoint, fromTRS } from '@workbench/canvas-engine/math/mat2d';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
import {
type CompositeOptions,
@@ -485,6 +485,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
documentEditingLocked: stores.documentEditingLocked,
eraserOptions: stores.eraserOptions,
gradientOptions: stores.gradientOptions,
+ hasFloatingSelection: stores.hasFloatingSelection,
hasSelection: stores.hasSelection,
invertBrushSizeScroll: stores.invertBrushSizeScroll,
lassoOptions: stores.lassoOptions,
@@ -901,6 +902,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
layers: layerCache,
markDirty: (layerId) => bitmapStore.markLayerDirty(layerId),
notifyPainted: notifyLayerPainted,
+ onChange: () => stores.hasFloatingSelection.set(floatingSelection.has()),
},
getDocument: () => mirror.getDocument(),
selection: {
@@ -1707,6 +1709,24 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
if (interactionController.getActiveToolId() !== 'transform') {
return null;
}
+ const float = floatingSelection.get();
+ if (float) {
+ // The float frames its own pixels. Its rect and transform are LAYER-LOCAL,
+ // so the resulting geometry is projected out through the layer's matrix to
+ // reach the document space the overlay draws in.
+ const floatLayer = doc.layers.find((candidate) => candidate.id === float.layerId);
+ if (!floatLayer) {
+ return null;
+ }
+ const toDocument = layerMatrix(floatLayer.transform);
+ const geometry = transformOverlayGeometry(float.transform, float.pixels.rect);
+ return {
+ center: applyToPoint(toDocument, geometry.center),
+ corners: geometry.corners.map((point) => applyToPoint(toDocument, point)),
+ handles: geometry.handles.map((point) => applyToPoint(toDocument, point)),
+ rotationAnchor: applyToPoint(toDocument, geometry.rotationAnchor),
+ };
+ }
const session = stores.transformSession.get();
if (!session) {
return null;
@@ -2761,8 +2781,22 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const beginTransformSession = (layerId: string): void => editingController.transform.begin(layerId);
const updateTransformSession = (transform: LayerTransform): void => editingController.transform.update(transform);
- const cancelTransform = (): void => editingController.transform.cancel();
- const applyTransform = (): void => editingController.transform.apply();
+ // A framed float is the session — Apply banks it, Cancel abandons it. Only
+ // with no float in flight do these reach the layer transform session.
+ const cancelTransform = (): void => {
+ if (floatingSelection.has()) {
+ floatingSelection.cancel();
+ return;
+ }
+ editingController.transform.cancel();
+ };
+ const applyTransform = (): void => {
+ if (floatingSelection.has()) {
+ floatingSelection.commit();
+ return;
+ }
+ editingController.transform.apply();
+ };
// ---- Text editing session -----------------------------------------------
//
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index b040f56454..ff29976a63 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -445,6 +445,12 @@ export interface EngineStores {
* mask gains/loses content.
*/
hasSelection: ScalarStore<boolean>;
+ /**
+ * Whether pixels are currently in flight as a floating selection. React reads
+ * it to enable the transform bar's Apply/Cancel while a float is framed (there
+ * is no `transformSession` in that case — the float is the session).
+ */
+ hasFloatingSelection: ScalarStore<boolean>;
/** Core-only visual SAM interaction state; application session status remains outside the engine. */
samInteraction: ScalarStore<SamInteractionState | null>;
/**
@@ -651,6 +657,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
cursor: createScalarStore<string>('default'),
eraserOptions: createScalarStore<EraserOptions>({ ...DEFAULT_ERASER_OPTIONS }, eraserOptionsEqual),
documentEditingLocked: createScalarStore<boolean>(false),
+ hasFloatingSelection: createScalarStore<boolean>(false),
hasSelection: createScalarStore<boolean>(false),
invertBrushSizeScroll: createScalarStore<boolean>(false),
gradientOptions: createScalarStore<GradientToolOptions>(
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.ts
index f4bc0ee051..77e5410032 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
@@ -1,4 +1,5 @@
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FloatingSelection } from '@workbench/canvas-engine/selection/floatingSelection';
import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
@@ -87,8 +88,12 @@ const rotateAbout = (p: Vec2, pivot: Vec2, rad: number): Vec2 => {
interface Harness {
ctx: ToolContext;
applyCount: () => number;
+ commitFloatCount: () => number;
+ cancelFloatCount: () => number;
session: () => ReturnType<ReturnType<typeof createEngineStores>['transformSession']['get']>;
overrides: { layerId: string; override: unknown }[];
+ float: { current: FloatingSelection | null };
+ floatTransforms: LayerTransform[];
}
/**
@@ -96,10 +101,12 @@ interface Harness {
* 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.
*/
-const createHarness = (doc: CanvasDocumentContractV2, zoom = 1): Harness => {
+const createHarness = (doc: CanvasDocumentContractV2, zoom = 1, float?: FloatingSelection | null): Harness => {
const stores = createEngineStores();
const overrides: { layerId: string; override: unknown }[] = [];
- const state = { applyCount: 0 };
+ const state = { applyCount: 0, commitFloatCount: 0, cancelFloatCount: 0 };
+ const floatRef: { current: FloatingSelection | null } = { current: float ?? null };
+ const floatTransforms: LayerTransform[] = [];
const beginTransformSession = (layerId: string): void => {
const layer = doc.layers.find((entry) => entry.id === layerId);
@@ -132,16 +139,31 @@ const createHarness = (doc: CanvasDocumentContractV2, zoom = 1): Harness => {
},
backend: null as never,
beginTransformSession,
+ cancelFloatingSelection: () => {
+ state.cancelFloatCount += 1;
+ floatRef.current = null;
+ },
cancelTransform,
+ commitFloatingSelection: () => {
+ state.commitFloatCount += 1;
+ floatRef.current = null;
+ },
commitStructural: vi.fn(),
createLayerId: () => 'x',
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: vi.fn(),
emitStrokeCommitted: vi.fn(),
getDocument: () => doc,
+ getFloatingSelection: () => floatRef.current,
invalidate: vi.fn(),
layers: null as never,
notifyLayerPainted: vi.fn(),
+ setFloatingTransform: (transform) => {
+ floatTransforms.push(transform);
+ if (floatRef.current) {
+ floatRef.current.transform = transform;
+ }
+ },
setLayerTransformOverride: vi.fn(),
setOverlayCursor: vi.fn(),
stores,
@@ -155,7 +177,11 @@ const createHarness = (doc: CanvasDocumentContractV2, zoom = 1): Harness => {
return {
applyCount: () => state.applyCount,
+ cancelFloatCount: () => state.cancelFloatCount,
+ commitFloatCount: () => state.commitFloatCount,
ctx,
+ float: floatRef,
+ floatTransforms,
overrides,
session: () => stores.transformSession.get(),
};
@@ -460,3 +486,114 @@ describe('transform tool: temp-tool switch (space/alt hold)', () => {
expect(h.session()).toBeNull();
});
});
+
+describe('transform tool: floating selections', () => {
+ const IDENTITY: LayerTransform = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };
+
+ /** A stand-in float over `layerId`, holding pixels at a known layer-local rect. */
+ const makeFloat = (layerId: string, rect = { height: 100, width: 100, x: 0, y: 0 }): FloatingSelection =>
+ ({ layerId, pixels: { rect }, transform: { ...IDENTITY } }) as FloatingSelection;
+
+ const doc = (layerOpts: Parameters<typeof imageLayer>[1] = { height: 100, width: 100 }) =>
+ makeDoc([imageLayer('a', layerOpts)], 'a');
+
+ it('frames the float instead of opening a layer session on activate', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ activate(tool, h.ctx);
+
+ expect(h.session()).toBeNull();
+ });
+
+ it('moves the float when the frame interior is dragged', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ down(tool, h.ctx, pointer(50, 50));
+ move(tool, h.ctx, pointer(70, 60));
+
+ expect(h.floatTransforms.at(-1)).toMatchObject({ x: 20, y: 10 });
+ // The layer session is untouched.
+ expect(h.session()).toBeNull();
+ });
+
+ it('scales the float from a corner handle', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ // The float's own se corner, at the pixels' layer-local bounds (100,100).
+ down(tool, h.ctx, pointer(100, 100));
+ move(tool, h.ctx, pointer(150, 150));
+
+ const scaled = h.floatTransforms.at(-1)!;
+ expect(scaled.scaleX).toBeCloseTo(1.5, 5);
+ expect(scaled.scaleY).toBeCloseTo(1.5, 5);
+ });
+
+ it('maps the pointer through the layer matrix, so a scaled layer drags true', () => {
+ // On a 2× layer, dragging 40 document px must move the float 20 layer-local px.
+ const h = createHarness(doc({ height: 100, width: 100 }), 1, makeFloat('a'));
+ (h.ctx.getDocument() as CanvasDocumentContractV2).layers[0]!.transform.scaleX = 2;
+ (h.ctx.getDocument() as CanvasDocumentContractV2).layers[0]!.transform.scaleY = 2;
+ const tool = createTransformTool();
+
+ down(tool, h.ctx, pointer(50, 50));
+ move(tool, h.ctx, pointer(90, 50));
+
+ expect(h.floatTransforms.at(-1)).toMatchObject({ x: 20, y: 0 });
+ });
+
+ it('banks the float on Enter rather than applying a layer transform', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ tool.onKeyCommand?.(h.ctx, 'apply');
+
+ expect(h.commitFloatCount()).toBe(1);
+ expect(h.applyCount()).toBe(0);
+ });
+
+ it('abandons the float on Escape', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ tool.onKeyCommand?.(h.ctx, 'cancel');
+
+ expect(h.cancelFloatCount()).toBe(1);
+ });
+
+ it('reverts only the current drag on pointercancel, keeping the float', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ down(tool, h.ctx, pointer(50, 50));
+ move(tool, h.ctx, pointer(70, 60));
+ tool.onPointerCancel?.(h.ctx);
+
+ expect(h.floatTransforms.at(-1)).toEqual(IDENTITY);
+ expect(h.float.current).not.toBeNull();
+ expect(h.cancelFloatCount()).toBe(0);
+ });
+
+ it('does not cancel the float on a real tool switch — the engine banks it', () => {
+ const h = createHarness(doc(), 1, makeFloat('a'));
+ const tool = createTransformTool();
+
+ tool.onDeactivate?.(h.ctx);
+
+ expect(h.cancelFloatCount()).toBe(0);
+ expect(h.float.current).not.toBeNull();
+ });
+
+ it('presses off the frame are a no-op — the float stays framed', () => {
+ const h = createHarness(doc(), 1, makeFloat('a', { height: 20, width: 20, x: 0, y: 0 }));
+ const tool = createTransformTool();
+
+ down(tool, h.ctx, pointer(400, 400));
+ move(tool, h.ctx, pointer(420, 420));
+
+ expect(h.floatTransforms).toHaveLength(0);
+ expect(h.float.current).not.toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
index 7cb7ba962e..e88093a72a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
@@ -34,6 +34,7 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { LayerTransform, TransformRect, TransformTarget } from '@workbench/canvas-engine/transform/transformMath';
import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
+import { applyToPoint, invert } from '@workbench/canvas-engine/math/mat2d';
import {
applyMove,
applyRotate,
@@ -44,7 +45,7 @@ import {
import type { Tool, ToolContext } from './tool';
-import { hittableLayerRect } from './moveHitTest';
+import { hittableLayerRect, layerMatrix } from './moveHitTest';
/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */
const PRIMARY_BUTTON = 1;
@@ -54,18 +55,23 @@ export const TRANSFORM_DRAG_THRESHOLD_PX = 3;
interface GestureState {
target: TransformTarget;
- /** The session transform captured at gesture start (revert target for cancel). */
+ /** Whether this drag moves the layer session or a floating selection. */
+ kind: 'layer' | 'float';
+ /** The subject transform captured at gesture start (revert target for cancel). */
startTransform: LayerTransform;
+ /** The press point, in the SUBJECT's space (not necessarily document space). */
startPointerDoc: Vec2;
startScreen: Vec2;
- /** The session layer's local content rect (off-origin aware). */
+ /** The subject's content rect, in its own space (off-origin aware). */
rect: TransformRect;
+ /** Converts a document-space pointer into the subject's space. */
+ fromDocument: (point: Vec2) => Vec2;
/** The cursor held for the duration of this gesture. */
cursor: string;
moved: boolean;
}
-/** The cursor for a hovered/grabbed target, given the layer's current transform. */
+/** The cursor for a hovered/grabbed target, given the subject's current transform. */
const cursorForTarget = (transform: LayerTransform, target: TransformTarget): string => {
if (target.kind === 'scale') {
return resizeCursorForHandle(transform, target.handle);
@@ -73,6 +79,29 @@ const cursorForTarget = (transform: LayerTransform, target: TransformTarget): st
return target.kind === 'rotate' ? 'grab' : 'move';
};
+/**
+ * What a transform gesture acts on. A layer works in DOCUMENT space; a floating
+ * selection works in its layer's LOCAL space (that is where its pixels and its
+ * transform live). The gesture math is space-agnostic as long as `rect`,
+ * `transform`, and the pointer are all expressed in the same space — `toDocument`
+ * / `fromDocument` bridge that space to the viewport, so both cases run through
+ * exactly the same handle hit-testing and scale/rotate/move code.
+ */
+interface TransformSubject {
+ readonly kind: 'layer' | 'float';
+ readonly rect: TransformRect;
+ readonly transform: LayerTransform;
+ toDocument(point: Vec2): Vec2;
+ fromDocument(point: Vec2): Vec2;
+ /**
+ * Rotation the subject's own space adds on top of `transform.rotation`, so a
+ * resize cursor points the right way for a float on a rotated layer.
+ */
+ readonly spaceRotation: number;
+}
+
+const identityPoint = (point: Vec2): Vec2 => point;
+
/** Creates a fresh transform tool with its own session/gesture state. */
export const createTransformTool = (): Tool => {
let gesture: GestureState | null = null;
@@ -89,30 +118,81 @@ export const createTransformTool = (): Tool => {
layer.type !== 'regional_guidance' &&
hittableLayerRect(layer, doc) !== null;
- /** Hit-tests the active session's frame at a screen point (or `null`). */
- const targetAt = (ctx: ToolContext, screenPoint: Vec2): TransformTarget | null => {
- const session = ctx.stores.transformSession.get();
+ /**
+ * What the tool currently acts on: a live floating selection takes precedence
+ * over the layer session — the pixels are already detached, so the frame must
+ * wrap them, not the layer they came from.
+ */
+ const subjectOf = (ctx: ToolContext): TransformSubject | null => {
const doc = ctx.getDocument();
- if (!session || !doc) {
+ if (!doc) {
return null;
}
- const layer = doc.layers.find((candidate) => candidate.id === session.layerId);
- const rect = layer ? hittableLayerRect(layer, doc) : null;
- if (!rect) {
+ const float = ctx.getFloatingSelection?.() ?? null;
+ if (float) {
+ const layer = doc.layers.find((candidate) => candidate.id === float.layerId);
+ if (!layer) {
+ return null;
+ }
+ const matrix = layerMatrix(layer.transform);
+ const inverse = invert(matrix);
+ if (!inverse) {
+ return null;
+ }
+ return {
+ fromDocument: (point) => applyToPoint(inverse, point),
+ kind: 'float',
+ rect: float.pixels.rect,
+ spaceRotation: layer.transform.rotation,
+ toDocument: (point) => applyToPoint(matrix, point),
+ transform: float.transform,
+ };
+ }
+ const session = ctx.stores.transformSession.get();
+ const layer = session ? doc.layers.find((candidate) => candidate.id === session.layerId) : undefined;
+ const rect = session && layer ? hittableLayerRect(layer, doc) : null;
+ if (!session || !rect) {
return null;
}
- return transformTargetAt({
- point: screenPoint,
+ return {
+ fromDocument: identityPoint,
+ kind: 'layer',
rect,
- toScreen: (p) => ctx.viewport.documentToScreen(p),
+ spaceRotation: 0,
+ toDocument: identityPoint,
transform: session.transform,
- });
+ };
};
+ /** Publishes a live transform to whichever subject the gesture is driving. */
+ const publish = (ctx: ToolContext, kind: TransformSubject['kind'], transform: LayerTransform): void => {
+ if (kind === 'float') {
+ ctx.setFloatingTransform?.(transform);
+ } else {
+ ctx.updateTransformSession?.(transform);
+ }
+ };
+
+ /** The cursor for a target, accounting for any rotation the subject's space adds. */
+ const cursorFor = (subject: TransformSubject, transform: LayerTransform, target: TransformTarget): string =>
+ cursorForTarget({ ...transform, rotation: transform.rotation + subject.spaceRotation }, target);
+
+ /** Hit-tests the current subject's frame at a screen point (or `null`). */
+ const targetAt = (ctx: ToolContext, subject: TransformSubject, screenPoint: Vec2): TransformTarget | null =>
+ transformTargetAt({
+ point: screenPoint,
+ rect: subject.rect,
+ toScreen: (p) => ctx.viewport.documentToScreen(subject.toDocument(p)),
+ transform: subject.transform,
+ });
+
const nextTransform = (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);
const delta: Vec2 = {
- x: input.documentPoint.x - state.startPointerDoc.x,
- y: input.documentPoint.y - state.startPointerDoc.y,
+ x: pointer.x - state.startPointerDoc.x,
+ y: pointer.y - state.startPointerDoc.y,
};
switch (state.target.kind) {
case 'move':
@@ -121,7 +201,7 @@ export const createTransformTool = (): Tool => {
return applyScale({
alt: input.modifiers.alt,
handle: state.target.handle,
- pointerDoc: input.documentPoint,
+ pointerDoc: pointer,
shift: input.modifiers.shift,
rect: state.rect,
start: state.startTransform,
@@ -129,7 +209,7 @@ export const createTransformTool = (): Tool => {
});
case 'rotate':
return applyRotate({
- pointerDoc: input.documentPoint,
+ pointerDoc: pointer,
shift: input.modifiers.shift,
rect: state.rect,
start: state.startTransform,
@@ -161,6 +241,11 @@ export const createTransformTool = (): Tool => {
// layer-change teardown already cancelled it — leave that alone too.
return;
}
+ // A live float IS the session — entering the tool frames the pixels in
+ // flight, so no layer session is opened over the top of them.
+ if (ctx.getFloatingSelection?.()) {
+ return;
+ }
// Entering the tool on an eligible selected layer opens a session on it.
const doc = ctx.getDocument();
const selectedId = doc?.selectedLayerId;
@@ -182,6 +267,8 @@ export const createTransformTool = (): Tool => {
return;
}
// A real tool switch mid-session cancels it (drops the preview, no dispatch).
+ // A float is NOT cancelled here — the engine banks it on a real switch, so
+ // the pixels land rather than snapping back.
endGesture();
ctx.cancelTransform?.();
},
@@ -194,6 +281,16 @@ export const createTransformTool = (): Tool => {
// guard (`pipeline.isGestureActive()`) for the same reason.
return;
}
+ // A float owns Apply/Cancel while it is in flight: baking it is what
+ // "apply" means, and abandoning it is what "cancel" means.
+ if (ctx.getFloatingSelection?.()) {
+ if (command === 'apply') {
+ ctx.commitFloatingSelection?.();
+ } else {
+ ctx.cancelFloatingSelection?.();
+ }
+ return;
+ }
if (command === 'apply') {
ctx.applyTransform?.();
} else {
@@ -201,10 +298,14 @@ export const createTransformTool = (): Tool => {
}
},
onPointerCancel: (ctx) => {
- // Revert just this drag (keep the session); Escape's session cancel is separate.
+ // Revert just this drag (keep the session / the float); Escape's own
+ // session-level cancel is separate.
if (gesture) {
- const session = ctx.stores.transformSession.get();
- if (session) {
+ if (gesture.kind === 'float') {
+ if (ctx.getFloatingSelection?.()) {
+ ctx.setFloatingTransform?.(gesture.startTransform);
+ }
+ } else if (ctx.stores.transformSession.get()) {
ctx.updateTransformSession?.(gesture.startTransform);
}
endGesture();
@@ -219,34 +320,32 @@ export const createTransformTool = (): Tool => {
if (!doc) {
return;
}
- const session = ctx.stores.transformSession.get();
-
- // 1) An open session: a press on its frame starts a scale/rotate/move gesture.
- if (session) {
- const layer = doc.layers.find((candidate) => candidate.id === session.layerId);
- const rect = layer ? hittableLayerRect(layer, doc) : null;
- const target = rect ? targetAt(ctx, input.screenPoint) : null;
- if (rect && target) {
+ // 1) A framed subject (a float, or an open layer session): a press on its
+ // frame starts a scale/rotate/move gesture.
+ const subject = subjectOf(ctx);
+ if (subject) {
+ const target = targetAt(ctx, subject, input.screenPoint);
+ if (target) {
gesture = {
- cursor: target.kind === 'rotate' ? 'grabbing' : cursorForTarget(session.transform, target),
+ cursor: target.kind === 'rotate' ? 'grabbing' : cursorFor(subject, subject.transform, target),
+ fromDocument: subject.fromDocument,
+ kind: subject.kind,
moved: false,
- rect,
- startPointerDoc: input.documentPoint,
+ rect: subject.rect,
+ startPointerDoc: subject.fromDocument(input.documentPoint),
startScreen: input.screenPoint,
- startTransform: session.transform,
+ startTransform: subject.transform,
target,
};
return;
}
- }
-
- // 2) No session yet: open one on the SELECTED layer (the layers panel is the
- // sole authority on which layer is active — a press never re-targets it)
- // and start a move gesture. A press off an existing session's frame is a
- // no-op; the session persists.
- if (session) {
+ // A press off the frame is a no-op; the subject persists.
return;
}
+
+ // 2) Nothing framed yet: open a session on the SELECTED layer (the layers
+ // panel is the sole authority on which layer is active — a press never
+ // re-targets it) and start a move gesture.
const selectedId = doc.selectedLayerId;
const selected = selectedId ? doc.layers.find((layer) => layer.id === selectedId) : undefined;
if (!selected || !isEligible(selected, doc)) {
@@ -259,6 +358,8 @@ export const createTransformTool = (): Tool => {
ctx.beginTransformSession?.(selected.id);
gesture = {
cursor: 'move',
+ fromDocument: identityPoint,
+ kind: 'layer',
moved: false,
rect,
startPointerDoc: input.documentPoint,
@@ -277,27 +378,27 @@ export const createTransformTool = (): Tool => {
}
gesture.moved = true;
}
- ctx.updateTransformSession?.(nextTransform(gesture, input));
+ publish(ctx, gesture.kind, nextTransform(gesture, input));
return;
}
- // Idle hover over a session frame: reflect the target under the pointer.
- const session = ctx.stores.transformSession.get();
- if (!session) {
+ // Idle hover over a framed subject: reflect the target under the pointer.
+ const subject = subjectOf(ctx);
+ if (!subject) {
if (hoverCursor !== null) {
hoverCursor = null;
ctx.updateCursor();
}
return;
}
- const target = targetAt(ctx, input.screenPoint);
- const cursor = target ? cursorForTarget(session.transform, target) : 'default';
+ const target = targetAt(ctx, subject, input.screenPoint);
+ const cursor = target ? cursorFor(subject, subject.transform, target) : 'default';
if (cursor !== hoverCursor) {
hoverCursor = cursor;
ctx.updateCursor();
}
},
onPointerUp: () => {
- // The session's live transform already reflects the drag; keep the session.
+ // The subject's live transform already reflects the drag; keep it framed.
endGesture();
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index 579ac9c6d7..cd72b1fb3c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -169,6 +169,10 @@ export const useTransformSession = (engine: CanvasCoreStoreCapability): Transfor
export const useCanvasHasSelection = (engine: CanvasCoreStoreCapability): boolean =>
useCanvasInteractionState(engine, 'hasSelection');
+/** Whether pixels are in flight as a floating selection (enables the transform bar while framed). */
+export const useCanvasHasFloatingSelection = (engine: CanvasCoreStoreCapability): boolean =>
+ useCanvasInteractionState(engine, 'hasFloatingSelection');
+
/** The lasso tool's current options (the committed boolean op mode). Write through `engine.interaction.set`. */
export const useLassoOptions = (engine: CanvasCoreStoreCapability): LassoToolOptions =>
useCanvasInteractionState(engine, 'lassoOptions');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx
index a5967357f4..df44885360 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx
@@ -3,7 +3,7 @@ import type { LayerTransform } from '@workbench/canvas-engine/api';
import { HStack, NumberInput, Text } from '@chakra-ui/react';
import { Button } from '@platform/ui';
-import { useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCanvasHasFloatingSelection, useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -24,12 +24,18 @@ const round2 = (n: number): number => Math.round(n * 100) / 100;
* dimensions), so a percent is the resolution-independent, self-contained
* representation. Edits update the session preview through the engine (no
* dispatch until Apply); the whole session is one undo entry. Disabled with no
- * session.
+ * session — except Apply / Cancel, which stay live for a floating selection.
*/
export const TransformOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
const session = useTransformSession(engine);
const transform = session?.transform ?? null;
+ // A floating selection frames its own pixels instead of opening a layer
+ // session, so Apply / Cancel must still act — they bank or abandon the float.
+ // The numerics stay disabled: the float's transform is LAYER-LOCAL, and
+ // showing those numbers in a bar that otherwise reads document space would
+ // misreport where the pixels are.
+ const hasFloat = useCanvasHasFloatingSelection(engine);
const patch = useCallback(
(next: Partial<LayerTransform>) => {
@@ -86,6 +92,7 @@ export const TransformOptions = ({ engine }: ToolOptionsComponentProps) => {
const onCancel = useCallback(() => engine.layers.cancelTransform(), [engine]);
const disabled = !transform;
+ const commitDisabled = disabled && !hasFloat;
return (
<HStack align="center" gap="3">
@@ -164,10 +171,10 @@ export const TransformOptions = ({ engine }: ToolOptionsComponentProps) => {
<NumberInput.Input aria-label={t('widgets.canvas.toolOptions.rotation')} fontSize="xs" />
</NumberInput.Root>
</HStack>
- <Button disabled={disabled} size="xs" variant="solid" onClick={onApply}>
+ <Button disabled={commitDisabled} size="xs" variant="solid" onClick={onApply}>
{t('widgets.canvas.toolOptions.applyTransform')}
</Button>
- <Button disabled={disabled} size="xs" variant="ghost" onClick={onCancel}>
+ <Button disabled={commitDisabled} size="xs" variant="ghost" onClick={onCancel}>
{t('widgets.canvas.toolOptions.cancelTransform')}
</Button>
</HStack>