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): add rectangular and elliptical marquee selection

joshistoast8d950c98d04f
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 1f277f2039..4d77bf6beb 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1212,6 +1212,7 @@
"selectEraserTool": "Select eraser tool",
"selectGradientTool": "Select gradient tool",
"selectLassoTool": "Select lasso tool",
+ "selectMarqueeTool": "Select marquee tool",
"selectMoveTool": "Select move tool",
"selectShapeTool": "Select shape tool",
"selectTextTool": "Select text tool",
@@ -1336,6 +1337,8 @@
"invertSelection": "Invert",
"lassoHint": "Draw a shape to select. Shift adds, Alt subtracts.",
"lockAspect": "Lock aspect ratio",
+ "marqueeHint": "Drag to select a region. Shift constrains, Alt draws from centre.",
+ "marqueeKind": "Marquee shape",
"movePosition": "Move layer",
"opacity": "Opacity",
"positionX": "X",
@@ -1375,6 +1378,7 @@
"gradient": "Gradient",
"label": "Tools",
"lasso": "Lasso select",
+ "marquee": "Marquee select",
"move": "Move",
"shape": "Shape",
"text": "Text",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index c8571c9567..219a235f8b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -18,6 +18,7 @@ import type {
GradientToolOptions,
LassoToolOptions,
LayerThumbnailStatus,
+ MarqueeToolOptions,
ShapeToolOptions,
TextEditSession,
TextToolOptions,
@@ -83,6 +84,7 @@ export interface CanvasInteractionState {
hasSelection: boolean;
invertBrushSizeScroll: boolean;
lassoOptions: LassoToolOptions;
+ marqueeOptions: MarqueeToolOptions;
ruleOfThirds: boolean;
shapeOptions: ShapeToolOptions;
showBbox: boolean;
@@ -375,6 +377,7 @@ export type {
GradientToolOptions,
LassoToolOptions,
LayerThumbnailStatus,
+ MarqueeToolOptions,
ShapeToolOptions,
TextEditSession,
TextToolOptions,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 0013dff12b..c623d45b1c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -161,6 +161,7 @@ import { createColorPickerTool } from '@workbench/canvas-engine/tools/colorPicke
import { createEraserTool } from '@workbench/canvas-engine/tools/eraserTool';
import { createGradientTool } from '@workbench/canvas-engine/tools/gradientTool';
import { createLassoTool } from '@workbench/canvas-engine/tools/lassoTool';
+import { createMarqueeTool } from '@workbench/canvas-engine/tools/marqueeTool';
import { hittableLayerRect, layerOutlineCorners } from '@workbench/canvas-engine/tools/moveHitTest';
import { createMoveTool } from '@workbench/canvas-engine/tools/moveTool';
import { stepBrushSize } from '@workbench/canvas-engine/tools/paintConstants';
@@ -481,6 +482,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
hasSelection: stores.hasSelection,
invertBrushSizeScroll: stores.invertBrushSizeScroll,
lassoOptions: stores.lassoOptions,
+ marqueeOptions: stores.marqueeOptions,
ruleOfThirds: stores.ruleOfThirds,
shapeOptions: stores.shapeOptions,
showBbox: stores.showBbox,
@@ -515,6 +517,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
['bbox', createBboxTool()],
['colorPicker', createColorPickerTool()],
['lasso', createLassoTool()],
+ ['marquee', createMarqueeTool()],
['shape', createShapeTool()],
['gradient', createGradientTool()],
['text', createTextTool()],
@@ -1811,6 +1814,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
gradientPreview: stores.gradientPreview.get(),
lassoPreview: stores.lassoPreview.get(),
marchingAnts: selection.hasSelection() ? { paths: selection.antsPaths(), phase: antsPhase } : null,
+ marqueePreview: stores.marqueePreview.get(),
samInput: samSession?.input.type === 'visual' ? samSession.input : null,
samPreview: samPreview ? { opacity: 0.45, rect: samPreview.rect, surface: samPreview.data } : null,
bboxOverlay: stores.bboxOverlay.get(),
@@ -1892,6 +1896,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// any in-progress lasso preview), stopping the ants loop via onChange.
cleanup.run(() => selection.clear());
cleanup.run(() => stores.lassoPreview.set(null));
+ cleanup.run(() => stores.marqueePreview.set(null));
const doc = mirror.getDocument();
const present = new Set(doc ? doc.layers.map((layer) => layer.id) : []);
rasterController.clearMirroredImages();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index b1628aeff8..58c0c47454 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -54,6 +54,23 @@ export const DEFAULT_LASSO_OPTIONS: LassoToolOptions = {
mode: 'replace',
};
+/**
+ * Marquee (selection) tool options: the shape the next drag traces, and the
+ * boolean op it applies when no modifier overrides it. One tool covers both
+ * shapes — see `tools/marqueeTool.ts`.
+ */
+export interface MarqueeToolOptions {
+ kind: 'rect' | 'ellipse';
+ /** The op a committed marquee applies to the selection, when no modifier overrides it. */
+ mode: SelectionOp;
+}
+
+/** Default marquee options: a rectangle that replaces the selection. */
+export const DEFAULT_MARQUEE_OPTIONS: MarqueeToolOptions = {
+ kind: 'rect',
+ mode: 'replace',
+};
+
/** A single gradient stop (offset in [0,1], any CSS color). */
export interface GradientStop {
offset: number;
@@ -390,6 +407,8 @@ export interface EngineStores {
bboxOptions: ScalarStore<BboxToolOptions>;
/** Lasso tool options (the committed boolean op mode). */
lassoOptions: ScalarStore<LassoToolOptions>;
+ /** Marquee tool options (shape kind / the committed boolean op mode). */
+ marqueeOptions: ScalarStore<MarqueeToolOptions>;
/** Shape tool options (kind / fill / stroke / stroke width). */
shapeOptions: ScalarStore<ShapeToolOptions>;
/** Gradient tool options (kind / angle / stops). */
@@ -432,6 +451,12 @@ export interface EngineStores {
* it is a transient channel — no dispatch, no React subscriber.
*/
lassoPreview: ScalarStore<readonly Vec2[] | null>;
+ /**
+ * The live marquee-tool drag outline (document-space rect + shape), or `null`
+ * when idle. Like `lassoPreview`, a transient overlay-only channel: the mask
+ * is untouched until the drag commits.
+ */
+ marqueePreview: ScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>;
/** Model-dependent grid size (document px) the bbox snaps to. React feeds this from generate settings. */
bboxGrid: ScalarStore<number>;
/**
@@ -520,6 +545,9 @@ const bboxOptionsEqual = (a: BboxToolOptions, b: BboxToolOptions): boolean =>
const lassoOptionsEqual = (a: LassoToolOptions, b: LassoToolOptions): boolean => a.mode === b.mode;
+const marqueeOptionsEqual = (a: MarqueeToolOptions, b: MarqueeToolOptions): boolean =>
+ a.kind === b.kind && a.mode === b.mode;
+
const shapeOptionsEqual = (a: ShapeToolOptions, b: ShapeToolOptions): boolean =>
a.kind === b.kind && a.fill === b.fill && a.stroke === b.stroke && a.strokeWidth === b.strokeWidth;
@@ -529,7 +557,8 @@ const stopsEqual = (a: readonly GradientStop[], b: readonly GradientStop[]): boo
const gradientOptionsEqual = (a: GradientToolOptions, b: GradientToolOptions): boolean =>
a.kind === b.kind && a.angle === b.angle && stopsEqual(a.stops, b.stops);
-const shapePreviewEqual = (
+/** Shared by the shape and marquee previews — both are a rect plus a shape kind. */
+const rectShapePreviewEqual = (
a: { rect: Rect; kind: 'rect' | 'ellipse' } | null,
b: { rect: Rect; kind: 'rect' | 'ellipse' } | null
): boolean => {
@@ -627,10 +656,12 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
gradientPreview: createScalarStore<{ start: Vec2; end: Vec2 } | null>(null, gradientPreviewEqual),
lassoOptions: createScalarStore<LassoToolOptions>({ ...DEFAULT_LASSO_OPTIONS }, lassoOptionsEqual),
lassoPreview: createScalarStore<readonly Vec2[] | null>(null),
+ marqueeOptions: createScalarStore<MarqueeToolOptions>({ ...DEFAULT_MARQUEE_OPTIONS }, marqueeOptionsEqual),
+ marqueePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, rectShapePreviewEqual),
ruleOfThirds: createScalarStore<boolean>(false),
samInteraction: createScalarStore(null),
shapeOptions: createScalarStore<ShapeToolOptions>({ ...DEFAULT_SHAPE_OPTIONS }, shapeOptionsEqual),
- shapePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, shapePreviewEqual),
+ shapePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, rectShapePreviewEqual),
showBbox: createScalarStore<boolean>(true),
showGrid: createScalarStore<boolean>(false),
snapToGrid: createScalarStore<boolean>(true),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
index a83e8232cf..105fff768f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
@@ -50,6 +50,12 @@ export interface OverlayCursor {
radiusDoc: number;
}
+/** A live rect-or-ellipse drag outline in document space (shape and marquee tools). */
+export interface RectShapePreview {
+ rect: Rect;
+ kind: 'rect' | 'ellipse';
+}
+
/** Everything the overlay needs to draw a frame. */
export interface OverlayState {
/** Document→screen transform. */
@@ -97,7 +103,13 @@ export interface OverlayState {
* The in-progress shape-tool drag (document-space rect + kind), drawn as a
* live outline while a shape is being created. Absent/`null` when idle.
*/
- shapePreview?: { rect: Rect; kind: 'rect' | 'ellipse' } | null;
+ shapePreview?: RectShapePreview | null;
+ /**
+ * The in-progress marquee-tool drag (document-space rect + kind), drawn as a
+ * live outline while a pixel selection is being dragged out. Absent/`null`
+ * when idle; the committed selection shows as marching ants instead.
+ */
+ marqueePreview?: RectShapePreview | null;
/**
* The in-progress gradient-tool drag vector (document-space start/end),
* drawn as a direction indicator. Absent/`null` when idle.
@@ -316,9 +328,12 @@ const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {
ctx.restore();
};
-/** Draws the shape-tool drag preview (rect or ellipse outline) in screen space. */
-const drawShapePreview = (ctx: Ctx, state: OverlayState): void => {
- const preview = state.shapePreview;
+/**
+ * Draws a rect-or-ellipse drag outline in screen space. Shared by the shape tool
+ * (previewing the layer it will create) and the marquee tool (previewing the
+ * region it will select) — the same dashed outline in both cases.
+ */
+const drawRectShapePreview = (ctx: Ctx, state: OverlayState, preview: RectShapePreview | null | undefined): void => {
if (!preview || preview.rect.width <= 0 || preview.rect.height <= 0) {
return;
}
@@ -538,7 +553,8 @@ export const renderOverlay = (target: RasterSurface, state: OverlayState): void
drawMarchingAnts(ctx, state.view, state.marchingAnts);
}
drawLassoPreview(ctx, state);
- drawShapePreview(ctx, state);
+ drawRectShapePreview(ctx, state, state.marqueePreview);
+ drawRectShapePreview(ctx, state, state.shapePreview);
drawGradientPreview(ctx, state);
drawCursor(ctx, state);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.test.ts
new file mode 100644
index 0000000000..8de1166d6d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest';
+
+import { selectionOpFor } from './selectionOpMode';
+
+const none = { alt: false, ctrl: false, meta: false, shift: false };
+
+describe('selectionOpFor', () => {
+ it('falls back to the persistent mode when no modifier is held', () => {
+ expect(selectionOpFor(none, 'replace')).toBe('replace');
+ expect(selectionOpFor(none, 'add')).toBe('add');
+ expect(selectionOpFor(none, 'subtract')).toBe('subtract');
+ expect(selectionOpFor(none, 'intersect')).toBe('intersect');
+ });
+
+ it('lets held modifiers override the persistent mode', () => {
+ expect(selectionOpFor({ ...none, shift: true }, 'replace')).toBe('add');
+ expect(selectionOpFor({ ...none, alt: true }, 'replace')).toBe('subtract');
+ expect(selectionOpFor({ ...none, alt: true, shift: true }, 'replace')).toBe('intersect');
+ });
+
+ it('overrides a non-replace mode too, so the modifier always wins', () => {
+ expect(selectionOpFor({ ...none, shift: true }, 'subtract')).toBe('add');
+ expect(selectionOpFor({ ...none, alt: true }, 'add')).toBe('subtract');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.ts
new file mode 100644
index 0000000000..7353ce45a9
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionOpMode.ts
@@ -0,0 +1,29 @@
+/**
+ * How a selection gesture's boolean op is resolved.
+ *
+ * Every selection tool (lasso, marquee) offers the same choice: a persistent op
+ * mode from its options bar, transiently overridden by modifiers held at commit
+ * time. Keeping the resolution here means the tools agree by construction rather
+ * than by convention, and neither has to import the other.
+ *
+ * Zero React, zero import-time side effects.
+ */
+
+import type { PointerModifiers, SelectionOp } from '@workbench/canvas-engine/types';
+
+/**
+ * Resolves the boolean op for a commit: held modifiers win over the persistent
+ * `mode`. shift = add, alt = subtract, shift+alt = intersect.
+ */
+export const selectionOpFor = (modifiers: Pick<PointerModifiers, 'shift' | 'alt'>, mode: SelectionOp): SelectionOp => {
+ if (modifiers.shift && modifiers.alt) {
+ return 'intersect';
+ }
+ if (modifiers.shift) {
+ return 'add';
+ }
+ if (modifiers.alt) {
+ return 'subtract';
+ }
+ return mode;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.test.ts
new file mode 100644
index 0000000000..ed116fdb43
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it } from 'vitest';
+
+import { ellipsePathData, rectPathData, selectionShapePathData } from './selectionPaths';
+
+describe('rectPathData', () => {
+ it('traces the four corners clockwise and closes', () => {
+ expect(rectPathData({ height: 30, width: 40, x: 10, y: 20 })).toBe('M 10 20 L 50 20 L 50 50 L 10 50 Z');
+ });
+
+ it('handles a negative origin', () => {
+ expect(rectPathData({ height: 4, width: 6, x: -5, y: -2 })).toBe('M -5 -2 L 1 -2 L 1 2 L -5 2 Z');
+ });
+});
+
+describe('ellipsePathData', () => {
+ it('traces two half-arcs between the horizontal extremes and closes', () => {
+ // Inscribed in [0,0,40,20]: radii 20×10, spanning x 0→40 at y 10.
+ expect(ellipsePathData({ height: 20, width: 40, x: 0, y: 0 })).toBe(
+ 'M 0 10 A 20 10 0 1 0 40 10 A 20 10 0 1 0 0 10 Z'
+ );
+ });
+
+ it('offsets with the rect and tolerates half-pixel radii', () => {
+ expect(ellipsePathData({ height: 5, width: 3, x: 10, y: 20 })).toBe(
+ 'M 10 22.5 A 1.5 2.5 0 1 0 13 22.5 A 1.5 2.5 0 1 0 10 22.5 Z'
+ );
+ });
+});
+
+describe('selectionShapePathData', () => {
+ const rect = { height: 30, width: 40, x: 10, y: 20 };
+
+ it('dispatches on the shape kind', () => {
+ expect(selectionShapePathData('rect', rect)).toBe(rectPathData(rect));
+ expect(selectionShapePathData('ellipse', rect)).toBe(ellipsePathData(rect));
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.ts
new file mode 100644
index 0000000000..3f41efc0b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionPaths.ts
@@ -0,0 +1,40 @@
+/**
+ * SVG path data for the primitive selection shapes.
+ *
+ * Selection geometry reaches the engine as a closed `Path2D` (see
+ * {@link SelectionCommit}), built through the injected {@link CreatePath2D} seam
+ * so it stays node-safe. These builders produce the path DATA — the string — so
+ * they are pure, trivially testable, and usable on the node raster stub where
+ * `Path2D` is a fake.
+ *
+ * All coordinates are DOCUMENT space, matching the space the selection mask is
+ * placed in.
+ *
+ * Zero React, zero import-time side effects.
+ */
+
+import type { Rect } from '@workbench/canvas-engine/types';
+
+/** SVG path data for a closed rectangle. */
+export const rectPathData = (r: Rect): string =>
+ `M ${r.x} ${r.y} L ${r.x + r.width} ${r.y} L ${r.x + r.width} ${r.y + r.height} L ${r.x} ${r.y + r.height} Z`;
+
+/**
+ * SVG path data for a closed ellipse inscribed in `r`, as two half-arcs from the
+ * left extreme to the right and back. `A` (elliptical arc) is used rather than a
+ * Bézier approximation so the curve is exact; a full ellipse cannot be a single
+ * arc segment (start and end would coincide and the arc would be dropped), hence
+ * the pair.
+ */
+export const ellipsePathData = (r: Rect): string => {
+ const rx = r.width / 2;
+ const ry = r.height / 2;
+ const cy = r.y + ry;
+ const left = r.x;
+ const right = r.x + r.width;
+ return `M ${left} ${cy} A ${rx} ${ry} 0 1 0 ${right} ${cy} A ${rx} ${ry} 0 1 0 ${left} ${cy} Z`;
+};
+
+/** SVG path data for `kind` inscribed in `rect`. */
+export const selectionShapePathData = (kind: 'rect' | 'ellipse', rect: Rect): string =>
+ kind === 'ellipse' ? ellipsePathData(rect) : rectPathData(rect);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts
index 9862a9298e..708833b08e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts
@@ -42,6 +42,7 @@ import type { PlacedSurface, Rect, SelectionOp, Vec2 } from '@workbench/canvas-e
import { intersect, isEmpty, roundOut, union } from '@workbench/canvas-engine/math/rect';
import { traceMaskOutlinePath } from '@workbench/canvas-engine/selection/maskOutline';
+import { rectPathData } from '@workbench/canvas-engine/selection/selectionPaths';
/** A committed selection contribution: the closed path and the op it applied. */
export interface SelectionCommit {
@@ -98,12 +99,8 @@ export interface SelectionStateDeps {
const MASK_FILL = '#ffffff';
-/** SVG path data for a closed rectangle in document space. */
-const rectToPathData = (r: Rect): string =>
- `M ${r.x} ${r.y} L ${r.x + r.width} ${r.y} L ${r.x + r.width} ${r.y + r.height} L ${r.x} ${r.y + r.height} Z`;
-
/** Builds a closed rectangle `Path2D` (document space) via the injected factory. */
-const rectPath = (createPath2D: CreatePath2D, r: Rect): Path2D => createPath2D(rectToPathData(r));
+const rectPath = (createPath2D: CreatePath2D, r: Rect): Path2D => createPath2D(rectPathData(r));
/** The canvas composite op that realizes each boolean selection op on the mask. */
const compositeForOp = (op: SelectionOp): GlobalCompositeOperation => {
@@ -259,7 +256,7 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =
// back to tracing any non-zero coverage rather than showing no outline.
const alphaSource = { data: copiedData, height: source.height, width: source.width };
const outline =
- traceMaskOutlinePath(alphaSource, rect) || traceMaskOutlinePath(alphaSource, rect, 1) || rectToPathData(rect);
+ traceMaskOutlinePath(alphaSource, rect) || traceMaskOutlinePath(alphaSource, rect, 1) || rectPathData(rect);
const nextPath = createPath2D(outline);
mask = nextMask;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts
index 1701bae609..4de861f29c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.test.ts
@@ -4,7 +4,7 @@ import type { PointerInput } from '@workbench/canvas-engine/types';
import type { WorkbenchAction } from '@workbench/workbenchState.testing';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
-import { createLassoTool, lassoOpFor } from '@workbench/canvas-engine/tools/lassoTool';
+import { createLassoTool } from '@workbench/canvas-engine/tools/lassoTool';
import { describe, expect, it, vi } from 'vitest';
const pointer = (
@@ -39,17 +39,6 @@ const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDo
const move = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerMove?.(ctx, i, [i]);
const up = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerUp?.(ctx, i);
-describe('lassoOpFor', () => {
- it('maps modifiers to ops, falling back to the persistent mode', () => {
- const none = { alt: false, ctrl: false, meta: false, shift: false };
- expect(lassoOpFor(none, 'replace')).toBe('replace');
- expect(lassoOpFor(none, 'add')).toBe('add');
- expect(lassoOpFor({ ...none, shift: true }, 'replace')).toBe('add');
- expect(lassoOpFor({ ...none, alt: true }, 'replace')).toBe('subtract');
- expect(lassoOpFor({ ...none, alt: true, shift: true }, 'replace')).toBe('intersect');
- });
-});
-
describe('lassoTool: drag → commit', () => {
const drag = (tool: Tool, ctx: ToolContext, upOpts: { shift?: boolean; alt?: boolean } = {}): void => {
down(tool, ctx, pointer(0, 0));
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
index 48322c750f..86bec05d0d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
@@ -16,9 +16,10 @@
* changes aren't undoable). Zero React, zero import-time side effects.
*/
-import type { PointerInput, SelectionOp, Vec2 } from '@workbench/canvas-engine/types';
+import type { Vec2 } from '@workbench/canvas-engine/types';
import { polygonBounds, polygonToSvgPath } from '@workbench/canvas-engine/freehand';
+import { selectionOpFor } from '@workbench/canvas-engine/selection/selectionOpMode';
import type { Tool, ToolContext } from './tool';
@@ -31,20 +32,6 @@ export const LASSO_MIN_POINT_DISTANCE = 2;
/** Fewest distinct points that make a fillable selection polygon. */
const MIN_POLYGON_POINTS = 3;
-/** Resolves the boolean op for a commit: modifiers win, else the persistent mode. */
-export const lassoOpFor = (modifiers: PointerInput['modifiers'], mode: SelectionOp): SelectionOp => {
- if (modifiers.shift && modifiers.alt) {
- return 'intersect';
- }
- if (modifiers.shift) {
- return 'add';
- }
- if (modifiers.alt) {
- return 'subtract';
- }
- return mode;
-};
-
const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
/** Creates a fresh lasso tool with its own per-gesture point buffer. */
@@ -116,7 +103,7 @@ export const createLassoTool = (): Tool => {
}
const path = ctx.createPath2D(polygonToSvgPath(polygon));
const bounds = polygonBounds(polygon);
- const op = lassoOpFor(input.modifiers, ctx.stores.lassoOptions.get().mode);
+ const op = selectionOpFor(input.modifiers, ctx.stores.lassoOptions.get().mode);
ctx.commitSelection({ bounds, op, path });
},
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts
new file mode 100644
index 0000000000..3953429653
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts
@@ -0,0 +1,234 @@
+import type { SelectionCommit } from '@workbench/canvas-engine/selection/selectionState';
+import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
+import type { PointerInput } from '@workbench/canvas-engine/types';
+
+import { createEngineStores } from '@workbench/canvas-engine/engineStores';
+import { ellipsePathData, rectPathData } from '@workbench/canvas-engine/selection/selectionPaths';
+import { createMarqueeTool, marqueeRect } from '@workbench/canvas-engine/tools/marqueeTool';
+import { describe, expect, it, vi } from 'vitest';
+
+const pointer = (
+ x: number,
+ y: number,
+ opts: { shift?: boolean; alt?: boolean; buttons?: number } = {}
+): PointerInput => ({
+ buttons: opts.buttons ?? 1,
+ documentPoint: { x, y },
+ modifiers: { alt: opts.alt ?? false, ctrl: false, meta: false, shift: opts.shift ?? false },
+ pointerType: 'mouse',
+ pressure: 0.5,
+ screenPoint: { x, y },
+ timeStamp: 0,
+});
+
+const createHarness = () => {
+ const stores = createEngineStores();
+ const commits: SelectionCommit[] = [];
+ const ctx = {
+ commitSelection: (commit: SelectionCommit) => commits.push(commit),
+ createPath2D: (d?: string) => ({ d }) as unknown as Path2D,
+ getDocument: () => ({ layers: [] }),
+ invalidate: vi.fn(),
+ stores,
+ } as unknown as ToolContext;
+ return { commits, ctx, stores };
+};
+
+const down = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerDown?.(ctx, i);
+const move = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerMove?.(ctx, i, [i]);
+const up = (t: Tool, ctx: ToolContext, i: PointerInput): void => t.onPointerUp?.(ctx, i);
+
+/** A press at `from`, a move past the drag threshold, and a release at `to`. */
+const drag = (tool: Tool, ctx: ToolContext, from: PointerInput, to: PointerInput): void => {
+ down(tool, ctx, from);
+ move(tool, ctx, to);
+ up(tool, ctx, to);
+};
+
+describe('marqueeRect', () => {
+ const plain = { fromCenter: false, square: false };
+
+ it('normalizes a drag in any direction', () => {
+ expect(marqueeRect({ x: 10, y: 10 }, { x: 40, y: 30 }, plain)).toEqual({ height: 20, width: 30, x: 10, y: 10 });
+ // Dragging up and to the left produces the same rect.
+ expect(marqueeRect({ x: 40, y: 30 }, { x: 10, y: 10 }, plain)).toEqual({ height: 20, width: 30, x: 10, y: 10 });
+ });
+
+ it('constrains to a square under shift, keeping the drag direction', () => {
+ expect(marqueeRect({ x: 0, y: 0 }, { x: 30, y: 10 }, { fromCenter: false, square: true })).toEqual({
+ height: 30,
+ width: 30,
+ x: 0,
+ y: 0,
+ });
+ // Up-left: the square grows away from the press point on both axes.
+ expect(marqueeRect({ x: 50, y: 50 }, { x: 20, y: 40 }, { fromCenter: false, square: true })).toEqual({
+ height: 30,
+ width: 30,
+ x: 20,
+ y: 20,
+ });
+ });
+
+ it('treats the press point as the centre under alt, doubling the extent', () => {
+ expect(marqueeRect({ x: 50, y: 50 }, { x: 60, y: 70 }, { fromCenter: true, square: false })).toEqual({
+ height: 40,
+ width: 20,
+ x: 40,
+ y: 30,
+ });
+ });
+
+ it('composes shift and alt into a square centred on the press point', () => {
+ expect(marqueeRect({ x: 50, y: 50 }, { x: 60, y: 70 }, { fromCenter: true, square: true })).toEqual({
+ height: 40,
+ width: 40,
+ x: 30,
+ y: 30,
+ });
+ });
+
+ it('rounds to whole pixels', () => {
+ expect(marqueeRect({ x: 10.4, y: 10.6 }, { x: 20.4, y: 20.6 }, plain)).toEqual({
+ height: 10,
+ width: 10,
+ x: 10,
+ y: 11,
+ });
+ });
+});
+
+describe('marqueeTool: drag → commit', () => {
+ it('commits a rect path with the persistent op mode', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ drag(tool, h.ctx, pointer(10, 10), pointer(40, 30));
+
+ expect(h.commits).toHaveLength(1);
+ expect(h.commits[0]!.op).toBe('replace');
+ expect(h.commits[0]!.bounds).toEqual({ height: 20, width: 30, x: 10, y: 10 });
+ expect(h.commits[0]!.path).toEqual({ d: rectPathData({ height: 20, width: 30, x: 10, y: 10 }) });
+ });
+
+ it('commits an ellipse path when the options say so', () => {
+ const h = createHarness();
+ h.stores.marqueeOptions.set({ kind: 'ellipse', mode: 'replace' });
+ const tool = createMarqueeTool();
+
+ drag(tool, h.ctx, pointer(0, 0), pointer(40, 20));
+
+ expect(h.commits[0]!.path).toEqual({ d: ellipsePathData({ height: 20, width: 40, x: 0, y: 0 }) });
+ });
+
+ it('resolves the boolean op from the modifiers held at release', () => {
+ const cases: [{ shift?: boolean; alt?: boolean }, string][] = [
+ [{ shift: true }, 'add'],
+ [{ alt: true }, 'subtract'],
+ [{ alt: true, shift: true }, 'intersect'],
+ ];
+ for (const [modifiers, expected] of cases) {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+ drag(tool, h.ctx, pointer(10, 10, modifiers), pointer(40, 30, modifiers));
+ expect(h.commits[0]!.op).toBe(expected);
+ }
+ });
+
+ it('honours the persistent mode when no modifier is held', () => {
+ const h = createHarness();
+ h.stores.marqueeOptions.set({ kind: 'rect', mode: 'subtract' });
+ const tool = createMarqueeTool();
+
+ drag(tool, h.ctx, pointer(10, 10), pointer(40, 30));
+
+ expect(h.commits[0]!.op).toBe('subtract');
+ });
+
+ it('publishes a live preview during the drag and clears it on commit', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(40, 30));
+ expect(h.stores.marqueePreview.get()).toEqual({ kind: 'rect', rect: { height: 20, width: 30, x: 10, y: 10 } });
+
+ up(tool, h.ctx, pointer(40, 30));
+ expect(h.stores.marqueePreview.get()).toBeNull();
+ });
+
+ it('stays below the drag threshold without previewing or committing', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(11, 11));
+ up(tool, h.ctx, pointer(11, 11));
+
+ expect(h.stores.marqueePreview.get()).toBeNull();
+ expect(h.commits).toHaveLength(0);
+ });
+
+ it('commits nothing for a degenerate drag rather than wiping the selection', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ // Past the threshold vertically, but the rect collapses to zero width.
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(10, 30));
+ up(tool, h.ctx, pointer(10, 30));
+
+ expect(h.commits).toHaveLength(0);
+ });
+
+ it('ignores a non-primary button press', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ drag(tool, h.ctx, pointer(10, 10, { buttons: 2 }), pointer(40, 30, { buttons: 2 }));
+
+ expect(h.commits).toHaveLength(0);
+ });
+});
+
+describe('marqueeTool: cancel', () => {
+ it('drops the preview and commits nothing on pointercancel', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(40, 30));
+ tool.onPointerCancel?.(h.ctx);
+
+ expect(h.stores.marqueePreview.get()).toBeNull();
+ expect(h.commits).toHaveLength(0);
+
+ // A trailing pointerup from the released pointer does nothing.
+ up(tool, h.ctx, pointer(40, 30));
+ expect(h.commits).toHaveLength(0);
+ });
+
+ it('drops the preview on Escape', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(40, 30));
+ tool.onKeyCommand?.(h.ctx, 'cancel');
+
+ expect(h.stores.marqueePreview.get()).toBeNull();
+ expect(h.commits).toHaveLength(0);
+ });
+
+ it('drops the preview when the tool is deactivated mid-drag', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(40, 30));
+ tool.onDeactivate?.(h.ctx);
+
+ expect(h.stores.marqueePreview.get()).toBeNull();
+ expect(h.commits).toHaveLength(0);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts
new file mode 100644
index 0000000000..7bd36c0d5c
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts
@@ -0,0 +1,171 @@
+/**
+ * The marquee tool: rectangular and elliptical pixel-selection by drag.
+ *
+ * One tool covers both shapes, switched by `marqueeOptions.kind` — they share
+ * every part of the gesture, and splitting them would double the entry in the
+ * `ToolId` union, the tool strip, and the options bar for one differing line.
+ * This mirrors `ShapeToolOptions.kind`.
+ *
+ * Interaction contract:
+ * - **Pointer-down** (primary button) anchors the drag.
+ * - **Pointer-move** (past a small threshold) publishes a live outline to
+ * `stores.marqueePreview` — it never dispatches and never touches the mask.
+ * **shift** constrains to a square/circle; **alt** draws from the press point
+ * as the CENTRE rather than a corner. Both compose.
+ * - **Commit** (pointer-up after a real drag): one `ctx.commitSelection` with
+ * the shape's closed path and the boolean op resolved from the modifiers, or
+ * the persistent op mode when none are held — the same resolution the lasso
+ * uses (`selectionOpFor`), so the whole mask/boolean pipeline is reused
+ * unchanged. A degenerate (sub-pixel) drag commits nothing.
+ * - **Cancel** (Esc / pointercancel): drops the preview, no commit.
+ *
+ * Note the modifier overlap: shift/alt pick the boolean op AND shape the rect.
+ * That is deliberate and matches Photoshop — alt-dragging a marquee subtracts a
+ * region drawn from its centre.
+ *
+ * Selection edits are transient interaction state: not dispatches, not undoable.
+ * Zero React, zero import-time side effects.
+ */
+
+import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
+
+import { selectionOpFor } from '@workbench/canvas-engine/selection/selectionOpMode';
+import { selectionShapePathData } from '@workbench/canvas-engine/selection/selectionPaths';
+
+import type { Tool, ToolContext } from './tool';
+
+/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */
+const PRIMARY_BUTTON = 1;
+
+/** Screen-space distance (CSS px) the pointer must travel before a press becomes a drag. */
+export const MARQUEE_DRAG_THRESHOLD_PX = 3;
+
+interface GestureState {
+ startDoc: Vec2;
+ startScreen: Vec2;
+ moved: boolean;
+}
+
+/** How the drag modifiers shape the rect. */
+export interface MarqueeConstraints {
+ /** Equal width and height (shift). */
+ square: boolean;
+ /** The press point is the rect's centre rather than a corner (alt). */
+ fromCenter: boolean;
+}
+
+/** The drag delta, optionally forced to equal magnitude on both axes (sign kept). */
+const constrainedDelta = (start: Vec2, end: Vec2, square: boolean): Vec2 => {
+ const dx = end.x - start.x;
+ const dy = end.y - start.y;
+ if (!square) {
+ return { x: dx, y: dy };
+ }
+ const side = Math.max(Math.abs(dx), Math.abs(dy));
+ return { x: (dx < 0 ? -1 : 1) * side, y: (dy < 0 ? -1 : 1) * side };
+};
+
+/**
+ * The integer, normalized document rect for a marquee drag from `start` to
+ * `end`. With `fromCenter` the press point is the centre, so the constrained
+ * delta is mirrored through it — giving a rect twice the drag extent.
+ */
+export const marqueeRect = (start: Vec2, end: Vec2, constraints: MarqueeConstraints): Rect => {
+ const delta = constrainedDelta(start, end, constraints.square);
+ const a = constraints.fromCenter ? { x: start.x - delta.x, y: start.y - delta.y } : start;
+ const b = { x: start.x + delta.x, y: start.y + delta.y };
+ const left = Math.round(Math.min(a.x, b.x));
+ const top = Math.round(Math.min(a.y, b.y));
+ return {
+ height: Math.round(Math.max(a.y, b.y)) - top,
+ width: Math.round(Math.max(a.x, b.x)) - left,
+ x: left,
+ y: top,
+ };
+};
+
+/** Reads the shaping constraints out of a pointer sample's modifiers. */
+const constraintsFor = (modifiers: { shift: boolean; alt: boolean }): MarqueeConstraints => ({
+ fromCenter: modifiers.alt,
+ square: modifiers.shift,
+});
+
+/** Creates a fresh marquee tool with its own gesture state. */
+export const createMarqueeTool = (): Tool => {
+ let state: GestureState | null = null;
+
+ const clearPreview = (ctx: ToolContext): void => {
+ ctx.stores.marqueePreview.set(null);
+ ctx.invalidate({ overlay: true });
+ };
+
+ const end = (): void => {
+ state = null;
+ };
+
+ return {
+ cursor: () => 'crosshair',
+ id: 'marquee',
+ onDeactivate: (ctx) => {
+ end();
+ clearPreview(ctx);
+ },
+ onKeyCommand: (ctx, command) => {
+ if (command === 'cancel' && state) {
+ end();
+ clearPreview(ctx);
+ }
+ },
+ onPointerCancel: (ctx) => {
+ end();
+ clearPreview(ctx);
+ },
+ onPointerDown: (ctx, input) => {
+ if (state || (input.buttons & PRIMARY_BUTTON) === 0 || !ctx.getDocument()) {
+ return;
+ }
+ state = { moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };
+ },
+ onPointerMove: (ctx, input) => {
+ if (!state) {
+ return;
+ }
+ if (!state.moved) {
+ const dxs = input.screenPoint.x - state.startScreen.x;
+ const dys = input.screenPoint.y - state.startScreen.y;
+ if (Math.hypot(dxs, dys) < MARQUEE_DRAG_THRESHOLD_PX) {
+ return;
+ }
+ state.moved = true;
+ }
+ const rect = marqueeRect(state.startDoc, input.documentPoint, constraintsFor(input.modifiers));
+ ctx.stores.marqueePreview.set({ kind: ctx.stores.marqueeOptions.get().kind, rect });
+ ctx.invalidate({ overlay: true });
+ },
+ onPointerUp: (ctx, input) => {
+ if (!state) {
+ return;
+ }
+ const current = state;
+ end();
+ clearPreview(ctx);
+
+ if (!current.moved || !ctx.commitSelection) {
+ return;
+ }
+ const rect = marqueeRect(current.startDoc, input.documentPoint, constraintsFor(input.modifiers));
+ if (rect.width < 1 || rect.height < 1) {
+ // Degenerate drag: selecting nothing would silently wipe the selection
+ // under `replace`, so treat it as a no-op instead.
+ return;
+ }
+ const { kind } = ctx.stores.marqueeOptions.get();
+ const op = selectionOpFor(input.modifiers, ctx.stores.marqueeOptions.get().mode);
+ ctx.commitSelection({
+ bounds: rect,
+ op,
+ path: ctx.createPath2D(selectionShapePathData(kind, rect)),
+ });
+ },
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
index a7678c5342..3abf3af755 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/types.ts
@@ -61,6 +61,7 @@ export type ToolId =
| 'shape'
| 'gradient'
| 'lasso'
+ | 'marquee'
| 'move'
| 'transform'
| 'bbox'
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index 00610b37ec..396118f0f8 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -145,7 +145,7 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'incrementToolWidth', [']']),
hotkey('canvas', 'selectEraserTool', ['e']),
hotkey('canvas', 'selectMoveTool', ['v']),
- hotkey('canvas', 'selectRectTool', ['u']),
+ hotkey('canvas', 'selectMarqueeTool', ['u']),
hotkey('canvas', 'selectLassoTool', ['l']),
hotkey('canvas', 'selectViewTool', ['h']),
hotkey('canvas', 'selectColorPickerTool', ['i']),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 38c7bbae12..6a7fc54659 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -403,6 +403,20 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
engine?.tools.setTool('eraser');
} else if (commandId === 'canvas.tool.lasso') {
engine?.tools.setTool('lasso');
+ } else if (commandId === 'canvas.tool.marquee') {
+ if (engine) {
+ // Pressing the shortcut while already on the marquee cycles its shape
+ // (Photoshop-style) rather than re-selecting the tool it is already on.
+ if (engine.interaction.get('activeTool') === 'marquee') {
+ const marquee = engine.interaction.get('marqueeOptions');
+ engine.interaction.set('marqueeOptions', {
+ ...marquee,
+ kind: marquee.kind === 'rect' ? 'ellipse' : 'rect',
+ });
+ } else {
+ engine.tools.setTool('marquee');
+ }
+ }
} else if (commandId === 'canvas.tool.shape') {
engine?.tools.setTool('shape');
} else if (commandId === 'canvas.tool.text') {
@@ -457,6 +471,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
['canvas.tool.brush', t('widgets.canvas.commands.selectBrushTool'), ['b']],
['canvas.tool.eraser', t('widgets.canvas.commands.selectEraserTool'), ['e']],
['canvas.tool.lasso', t('widgets.canvas.commands.selectLassoTool'), ['l']],
+ ['canvas.tool.marquee', t('widgets.canvas.commands.selectMarqueeTool'), ['u']],
['canvas.tool.shape', t('widgets.canvas.commands.selectShapeTool'), ['r']],
['canvas.tool.text', t('widgets.canvas.commands.selectTextTool'), ['t']],
['canvas.tool.gradient', t('widgets.canvas.commands.selectGradientTool'), ['g']],
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
index 1b5631c8c5..29a10612dc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
@@ -11,6 +11,7 @@ import {
MoveIcon,
PaintBucketIcon,
Rotate3dIcon,
+ SquareDashedIcon,
SquareIcon,
TypeIcon,
} from 'lucide-react';
@@ -121,6 +122,13 @@ const ToolStripRoot = ({
label={t('widgets.canvas.tools.text')}
toolId="text"
/>
+ <ToolStripButton
+ engine={engine}
+ icon={SquareDashedIcon}
+ isInteractionLocked={isInteractionLocked}
+ label={t('widgets.canvas.tools.marquee')}
+ toolId="marquee"
+ />
<ToolStripButton
engine={engine}
icon={LassoIcon}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index fa68198ff3..579ac9c6d7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -16,6 +16,7 @@ import type {
EraserOptions,
GradientToolOptions,
LassoToolOptions,
+ MarqueeToolOptions,
ShapeToolOptions,
TextEditSession,
TextToolOptions,
@@ -172,6 +173,10 @@ export const useCanvasHasSelection = (engine: CanvasCoreStoreCapability): boolea
export const useLassoOptions = (engine: CanvasCoreStoreCapability): LassoToolOptions =>
useCanvasInteractionState(engine, 'lassoOptions');
+/** The marquee tool's current options (shape kind / boolean op mode). Write through `engine.interaction.set`. */
+export const useMarqueeOptions = (engine: CanvasCoreStoreCapability): MarqueeToolOptions =>
+ useCanvasInteractionState(engine, 'marqueeOptions');
+
/** The shape tool's current options (kind / fill / stroke / stroke width). Write through `engine.interaction.set`. */
export const useShapeOptions = (engine: CanvasCoreStoreCapability): ShapeToolOptions =>
useCanvasInteractionState(engine, 'shapeOptions');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx
index d6707d1e20..da60a32d7e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx
@@ -1,93 +1,30 @@
-import type { CanvasCoreStoreCapability, CanvasSelectionCapability, SelectionOp } from '@workbench/canvas-engine/api';
+import type { SelectionOp } from '@workbench/canvas-engine/api';
-import { HStack, Text } from '@chakra-ui/react';
-import { Button } from '@platform/ui';
-import { isLayerPixelEditEligible } from '@workbench/canvas-engine/api';
-import { useCanvasHasSelection, useLassoOptions } from '@workbench/widgets/canvas/engineStoreHooks';
-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { useLassoOptions } from '@workbench/widgets/canvas/engineStoreHooks';
import { useCallback } from 'react';
-import { useTranslation } from 'react-i18next';
import type { ToolOptionsComponentProps } from './ToolOptionsBar';
-const OP_MODES: readonly SelectionOp[] = ['replace', 'add', 'subtract', 'intersect'];
-
-const OP_MODE_LABEL_KEYS: Record<SelectionOp, string> = {
- add: 'widgets.canvas.toolOptions.selectionAdd',
- intersect: 'widgets.canvas.toolOptions.selectionIntersect',
- replace: 'widgets.canvas.toolOptions.selectionReplace',
- subtract: 'widgets.canvas.toolOptions.selectionSubtract',
-};
-
-type LassoEngine = CanvasCoreStoreCapability & { readonly selection: CanvasSelectionCapability };
-
-/** One op-mode button with a stable click handler (avoids a per-render closure in the map). */
-const OpModeButton = ({ engine, mode, active }: { engine: LassoEngine; mode: SelectionOp; active: boolean }) => {
- const { t } = useTranslation();
- const onClick = useCallback(() => engine.interaction.set('lassoOptions', { mode }), [engine, mode]);
- return (
- <Button aria-pressed={active} size="xs" variant={active ? 'solid' : 'ghost'} onClick={onClick}>
- {t(OP_MODE_LABEL_KEYS[mode])}
- </Button>
- );
-};
+import { SelectionOptionsRow } from './SelectionOptionsRow';
/**
- * Lasso tool options: the boolean op-mode selector (replace / add / subtract /
- * intersect — also settable transiently by holding shift / alt / shift+alt while
- * committing a path) plus fill / erase / invert / deselect actions. Fill and
- * erase require an eligible (unlocked, visible) paint layer selected; invert and
- * deselect only require a live selection. Reads/writes the engine's transient
- * selection state directly — no reducer mirror.
+ * Lasso tool options: the shared selection controls, bound to the lasso's own
+ * persistent op mode.
*/
export const LassoOptions = ({ engine }: ToolOptionsComponentProps) => {
- const { t } = useTranslation();
const options = useLassoOptions(engine);
- const hasSelection = useCanvasHasSelection(engine);
-
- // Whether the selected layer can receive a masked fill/erase (paint, unlocked,
- // visible). Same eligibility the engine enforces; used to disable the buttons.
- const canPaintTarget = useActiveProjectSelector((project) => {
- const { document } = project.canvas;
- const layer = document.selectedLayerId
- ? document.layers.find((entry) => entry.id === document.selectedLayerId)
- : undefined;
- return isLayerPixelEditEligible(layer);
- });
- const onFill = useCallback(() => engine.selection.fillSelection(), [engine]);
- const onErase = useCallback(() => engine.selection.eraseSelection(), [engine]);
- const onInvert = useCallback(() => engine.selection.invertSelection(), [engine]);
- const onDeselect = useCallback(() => engine.selection.deselect(), [engine]);
-
- const canEdit = hasSelection && canPaintTarget;
+ const onModeChange = useCallback(
+ (mode: SelectionOp) => engine.interaction.set('lassoOptions', { ...options, mode }),
+ [engine, options]
+ );
return (
- <HStack align="center" gap="3">
- <HStack align="center" gap="1" role="group" aria-label={t('widgets.canvas.toolOptions.selectionMode')}>
- {OP_MODES.map((mode) => (
- <OpModeButton key={mode} active={options.mode === mode} engine={engine} mode={mode} />
- ))}
- </HStack>
- <HStack align="center" gap="1">
- <Button disabled={!canEdit} size="xs" variant="ghost" onClick={onFill}>
- {t('widgets.canvas.toolOptions.fillSelection')}
- </Button>
- <Button disabled={!canEdit} size="xs" variant="ghost" onClick={onErase}>
- {t('widgets.canvas.toolOptions.eraseSelection')}
- </Button>
- <Button disabled={!hasSelection} size="xs" variant="ghost" onClick={onInvert}>
- {t('widgets.canvas.toolOptions.invertSelection')}
- </Button>
- <Button disabled={!hasSelection} size="xs" variant="ghost" onClick={onDeselect}>
- {t('widgets.canvas.toolOptions.deselect')}
- </Button>
- </HStack>
- {!hasSelection ? (
- <Text color="fg.muted" fontSize="2xs">
- {t('widgets.canvas.toolOptions.lassoHint')}
- </Text>
- ) : null}
- </HStack>
+ <SelectionOptionsRow
+ engine={engine}
+ hintKey="widgets.canvas.toolOptions.lassoHint"
+ mode={options.mode}
+ onModeChange={onModeChange}
+ />
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsx
new file mode 100644
index 0000000000..8efbd474e3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsx
@@ -0,0 +1,77 @@
+import type { SelectValueChangeDetails } from '@chakra-ui/react';
+import type { MarqueeToolOptions, SelectionOp } from '@workbench/canvas-engine/api';
+
+import { createListCollection, HStack, Text } from '@chakra-ui/react';
+import { Select } from '@platform/ui';
+import { useMarqueeOptions } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ToolOptionsComponentProps } from './ToolOptionsBar';
+
+import { SelectionOptionsRow } from './SelectionOptionsRow';
+
+type MarqueeKind = MarqueeToolOptions['kind'];
+
+const SELECT_POSITIONING = { placement: 'top-start', sameWidth: false } as const;
+const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;
+
+/**
+ * Marquee tool options: the shape the next drag traces (rectangle / ellipse),
+ * plus the shared selection controls bound to the marquee's own op mode.
+ */
+export const MarqueeOptions = ({ engine }: ToolOptionsComponentProps) => {
+ const { t } = useTranslation();
+ const options = useMarqueeOptions(engine);
+
+ const kindCollection = useMemo(
+ () =>
+ createListCollection<{ label: string; value: MarqueeKind }>({
+ items: [
+ { label: t('widgets.canvas.toolOptions.shapeRect'), value: 'rect' },
+ { label: t('widgets.canvas.toolOptions.shapeEllipse'), value: 'ellipse' },
+ ],
+ }),
+ [t]
+ );
+ const kindValue = useMemo(() => [options.kind], [options.kind]);
+
+ const onKindChange = useCallback(
+ ({ value }: SelectValueChangeDetails<{ label: string; value: MarqueeKind }>) => {
+ const next = value[0] as MarqueeKind | undefined;
+ if (next && next !== options.kind) {
+ engine.interaction.set('marqueeOptions', { ...options, kind: next });
+ }
+ },
+ [engine, options]
+ );
+
+ const onModeChange = useCallback(
+ (mode: SelectionOp) => engine.interaction.set('marqueeOptions', { ...options, mode }),
+ [engine, options]
+ );
+
+ return (
+ <HStack align="center" gap="3">
+ <HStack align="center" gap="1.5">
+ <Text color="fg.muted" fontSize="2xs">
+ {t('widgets.canvas.toolOptions.marqueeKind')}
+ </Text>
+ <Select
+ collection={kindCollection}
+ positioning={SELECT_POSITIONING}
+ size="xs"
+ triggerProps={SELECT_TRIGGER_PROPS}
+ value={kindValue}
+ onValueChange={onKindChange}
+ />
+ </HStack>
+ <SelectionOptionsRow
+ engine={engine}
+ hintKey="widgets.canvas.toolOptions.marqueeHint"
+ mode={options.mode}
+ onModeChange={onModeChange}
+ />
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
new file mode 100644
index 0000000000..fba234cf5d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
@@ -0,0 +1,109 @@
+import type { SelectionOp } from '@workbench/canvas-engine/api';
+
+import { HStack, Text } from '@chakra-ui/react';
+import { Button } from '@platform/ui';
+import { isLayerPixelEditEligible } from '@workbench/canvas-engine/api';
+import { useCanvasHasSelection } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { ToolOptionsComponentProps } from './ToolOptionsBar';
+
+const OP_MODES: readonly SelectionOp[] = ['replace', 'add', 'subtract', 'intersect'];
+
+const OP_MODE_LABEL_KEYS: Record<SelectionOp, string> = {
+ add: 'widgets.canvas.toolOptions.selectionAdd',
+ intersect: 'widgets.canvas.toolOptions.selectionIntersect',
+ replace: 'widgets.canvas.toolOptions.selectionReplace',
+ subtract: 'widgets.canvas.toolOptions.selectionSubtract',
+};
+
+interface OpModeButtonProps {
+ mode: SelectionOp;
+ active: boolean;
+ onSelect: (mode: SelectionOp) => void;
+}
+
+/** One op-mode button with a stable click handler (avoids a per-render closure in the map). */
+const OpModeButton = ({ active, mode, onSelect }: OpModeButtonProps) => {
+ const { t } = useTranslation();
+ const onClick = useCallback(() => onSelect(mode), [mode, onSelect]);
+ return (
+ <Button aria-pressed={active} size="xs" variant={active ? 'solid' : 'ghost'} onClick={onClick}>
+ {t(OP_MODE_LABEL_KEYS[mode])}
+ </Button>
+ );
+};
+
+export interface SelectionOptionsRowProps extends ToolOptionsComponentProps {
+ /** The tool's persistent boolean op mode. */
+ mode: SelectionOp;
+ /** Writes the tool's op mode back to its own options store. */
+ onModeChange: (mode: SelectionOp) => void;
+ /** Shown when there is no live selection — tells the user what the gesture does. */
+ hintKey: string;
+}
+
+/**
+ * The controls every pixel-selection tool shares: the boolean op-mode selector
+ * (replace / add / subtract / intersect — also settable transiently by holding
+ * shift / alt / shift+alt while committing) plus fill / erase / invert /
+ * deselect actions.
+ *
+ * Fill and erase require an eligible (unlocked, visible) paint layer selected;
+ * invert and deselect only require a live selection. Reads and writes the
+ * engine's transient selection state directly — no reducer mirror. The op mode
+ * itself lives in each tool's own options store, so it is passed in rather than
+ * read here.
+ */
+export const SelectionOptionsRow = ({ engine, hintKey, mode, onModeChange }: SelectionOptionsRowProps) => {
+ const { t } = useTranslation();
+ const hasSelection = useCanvasHasSelection(engine);
+
+ // Whether the selected layer can receive a masked fill/erase (paint, unlocked,
+ // visible). Same eligibility the engine enforces; used to disable the buttons.
+ const canPaintTarget = useActiveProjectSelector((project) => {
+ const { document } = project.canvas;
+ const layer = document.selectedLayerId
+ ? document.layers.find((entry) => entry.id === document.selectedLayerId)
+ : undefined;
+ return isLayerPixelEditEligible(layer);
+ });
+
+ const onFill = useCallback(() => engine.selection.fillSelection(), [engine]);
+ const onErase = useCallback(() => engine.selection.eraseSelection(), [engine]);
+ const onInvert = useCallback(() => engine.selection.invertSelection(), [engine]);
+ const onDeselect = useCallback(() => engine.selection.deselect(), [engine]);
+
+ const canEdit = hasSelection && canPaintTarget;
+
+ return (
+ <HStack align="center" gap="3">
+ <HStack align="center" gap="1" role="group" aria-label={t('widgets.canvas.toolOptions.selectionMode')}>
+ {OP_MODES.map((opMode) => (
+ <OpModeButton key={opMode} active={mode === opMode} mode={opMode} onSelect={onModeChange} />
+ ))}
+ </HStack>
+ <HStack align="center" gap="1">
+ <Button disabled={!canEdit} size="xs" variant="ghost" onClick={onFill}>
+ {t('widgets.canvas.toolOptions.fillSelection')}
+ </Button>
+ <Button disabled={!canEdit} size="xs" variant="ghost" onClick={onErase}>
+ {t('widgets.canvas.toolOptions.eraseSelection')}
+ </Button>
+ <Button disabled={!hasSelection} size="xs" variant="ghost" onClick={onInvert}>
+ {t('widgets.canvas.toolOptions.invertSelection')}
+ </Button>
+ <Button disabled={!hasSelection} size="xs" variant="ghost" onClick={onDeselect}>
+ {t('widgets.canvas.toolOptions.deselect')}
+ </Button>
+ </HStack>
+ {!hasSelection ? (
+ <Text color="fg.muted" fontSize="2xs">
+ {t(hintKey)}
+ </Text>
+ ) : null}
+ </HStack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.test.ts
index a3bb5f49ca..d4866a975c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.test.ts
@@ -3,13 +3,14 @@ import { describe, expect, it } from 'vitest';
import { resolveCanvasOptionsContent, TOOL_OPTIONS_COMPONENTS } from './ToolOptionsBar';
describe('TOOL_OPTIONS_COMPONENTS', () => {
- it('has an entry for exactly the tools with dedicated options today (bbox, brush, eraser, gradient, lasso, move, shape, text, transform)', () => {
+ it('has an entry for exactly the tools with dedicated options today (bbox, brush, eraser, gradient, lasso, marquee, move, shape, text, transform)', () => {
expect(Object.keys(TOOL_OPTIONS_COMPONENTS).sort()).toEqual([
'bbox',
'brush',
'eraser',
'gradient',
'lasso',
+ 'marquee',
'move',
'shape',
'text',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx
index 18650e44a9..aae3b7ebd5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx
@@ -16,6 +16,7 @@ import { CanvasOptionsBar } from './CanvasOptionsBar';
import { EraserOptions } from './EraserOptions';
import { GradientOptions } from './GradientOptions';
import { LassoOptions } from './LassoOptions';
+import { MarqueeOptions } from './MarqueeOptions';
import { MoveOptions } from './MoveOptions';
import { ShapeOptions } from './ShapeOptions';
import { TextOptions } from './TextOptions';
@@ -42,6 +43,7 @@ export const TOOL_OPTIONS_COMPONENTS: Partial<Record<ToolId, ComponentType<ToolO
eraser: EraserOptions,
gradient: GradientOptions,
lasso: LassoOptions,
+ marquee: MarqueeOptions,
move: MoveOptions,
shape: ShapeOptions,
text: TextOptions,