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 polygonal lasso mode

joshistoast1c612f2efe29
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 4d77bf6beb..3e103e76e9 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1335,7 +1335,11 @@
"gradientStart": "Start",
"gradientStartOpacity": "Start opacity",
"invertSelection": "Invert",
+ "lassoFreehand": "Freehand",
"lassoHint": "Draw a shape to select. Shift adds, Alt subtracts.",
+ "lassoPolygon": "Polygon",
+ "lassoPolygonHint": "Click to place points. Double-click, Enter, or click the first point to close.",
+ "lassoShape": "Lasso mode",
"lockAspect": "Lock aspect ratio",
"marqueeHint": "Drag to select a region. Shift constrains, Alt draws from centre.",
"marqueeKind": "Marquee shape",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 58c0c47454..b040f56454 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -43,15 +43,18 @@ export interface EraserOptions {
opacity: number;
}
-/** Lasso (selection) tool options: the boolean op applied when a path commits. */
+/** Lasso (selection) tool options: how the path is drawn, and the op it applies. */
export interface LassoToolOptions {
/** The op a committed lasso path applies to the selection, when no modifier overrides it. */
mode: SelectionOp;
+ /** `freehand` traces a drag; `polygon` places straight-edged vertices by click. */
+ shape: 'freehand' | 'polygon';
}
-/** Default lasso options: a fresh path replaces the selection. */
+/** Default lasso options: a freehand path that replaces the selection. */
export const DEFAULT_LASSO_OPTIONS: LassoToolOptions = {
mode: 'replace',
+ shape: 'freehand',
};
/**
@@ -543,7 +546,8 @@ const checkerColorsEqual = (a: CheckerColors, b: CheckerColors): boolean => a.a
const bboxOptionsEqual = (a: BboxToolOptions, b: BboxToolOptions): boolean =>
a.aspectLocked === b.aspectLocked && a.aspectRatio === b.aspectRatio;
-const lassoOptionsEqual = (a: LassoToolOptions, b: LassoToolOptions): boolean => a.mode === b.mode;
+const lassoOptionsEqual = (a: LassoToolOptions, b: LassoToolOptions): boolean =>
+ a.mode === b.mode && a.shape === b.shape;
const marqueeOptionsEqual = (a: MarqueeToolOptions, b: MarqueeToolOptions): boolean =>
a.kind === b.kind && a.mode === b.mode;
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 4de861f29c..0ba251b71e 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
@@ -10,7 +10,7 @@ import { describe, expect, it, vi } from 'vitest';
const pointer = (
x: number,
y: number,
- opts: { shift?: boolean; alt?: boolean; buttons?: number } = {}
+ opts: { shift?: boolean; alt?: boolean; buttons?: number; timeStamp?: number } = {}
): PointerInput => ({
buttons: opts.buttons ?? 1,
documentPoint: { x, y },
@@ -18,7 +18,7 @@ const pointer = (
pointerType: 'mouse',
pressure: 0.5,
screenPoint: { x, y },
- timeStamp: 0,
+ timeStamp: opts.timeStamp ?? 0,
});
const createHarness = () => {
@@ -31,6 +31,9 @@ const createHarness = () => {
dispatch: (action: WorkbenchAction) => dispatched.push(action),
invalidate: vi.fn(),
stores,
+ // Identity viewport: document and screen coordinates coincide, so the
+ // polygon's close-on-first-vertex hit test is expressed in the same numbers.
+ viewport: { documentToScreen: (p: { x: number; y: number }) => p },
} as unknown as ToolContext;
return { commits, ctx, dispatched, stores };
};
@@ -81,7 +84,7 @@ describe('lassoTool: drag → commit', () => {
it('uses the persistent lasso op mode when no modifier is held', () => {
const tool = createLassoTool();
const { commits, ctx, stores } = createHarness();
- stores.lassoOptions.set({ mode: 'subtract' });
+ stores.lassoOptions.set({ mode: 'subtract', shape: 'freehand' });
drag(tool, ctx);
expect(commits[0]!.op).toBe('subtract');
});
@@ -125,3 +128,162 @@ describe('lassoTool: cancel + guards', () => {
expect(preview).toHaveLength(1);
});
});
+
+describe('lassoTool: polygon mode', () => {
+ const createPolygonHarness = () => {
+ const h = createHarness();
+ h.stores.lassoOptions.set({ mode: 'replace', shape: 'polygon' });
+ return h;
+ };
+
+ /** One vertex placement: a press and release at the same spot. */
+ const click = (tool: Tool, ctx: ToolContext, x: number, y: number, timeStamp: number): void => {
+ down(tool, ctx, pointer(x, y, { timeStamp }));
+ up(tool, ctx, pointer(x, y, { timeStamp }));
+ };
+
+ it('accumulates vertices across clicks without committing', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+
+ expect(commits).toHaveLength(0);
+ expect(stores.lassoPreview.get()).toHaveLength(3);
+ });
+
+ it('shows a rubber-band segment to the cursor between clicks', () => {
+ const tool = createLassoTool();
+ const { ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ move(tool, ctx, pointer(30, 10));
+
+ // The placed vertex plus the live cursor endpoint.
+ expect(stores.lassoPreview.get()).toEqual([
+ { x: 0, y: 0 },
+ { x: 30, y: 10 },
+ ]);
+ });
+
+ it('closes and commits on Enter', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ tool.onKeyCommand?.(ctx, 'apply');
+
+ expect(commits).toHaveLength(1);
+ expect(commits[0]!.bounds).toEqual({ height: 40, width: 40, x: 0, y: 0 });
+ expect(stores.lassoPreview.get()).toBeNull();
+ });
+
+ it('closes on a click landing on the first vertex', () => {
+ const tool = createLassoTool();
+ const { commits, ctx } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ // Within POLYGON_CLOSE_HIT_PX of the first vertex (identity viewport).
+ click(tool, ctx, 3, 2, 3000);
+
+ expect(commits).toHaveLength(1);
+ expect(commits[0]!.bounds).toEqual({ height: 40, width: 40, x: 0, y: 0 });
+ });
+
+ it('does not close on the first vertex before the polygon is fillable', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ // A second click back near the start must add a vertex, not close a 2-gon.
+ click(tool, ctx, 2, 0, 1000);
+
+ expect(commits).toHaveLength(0);
+ expect(stores.lassoPreview.get()).toHaveLength(2);
+ });
+
+ it('closes on a double-click', () => {
+ const tool = createLassoTool();
+ const { commits, ctx } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ // A second press at the same spot, inside the double-click window.
+ click(tool, ctx, 40, 40, 2100);
+
+ expect(commits).toHaveLength(1);
+ });
+
+ it('treats a slow second click at the same spot as a new vertex, not a close', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ click(tool, ctx, 40, 40, 9000);
+
+ expect(commits).toHaveLength(0);
+ expect(stores.lassoPreview.get()).toHaveLength(4);
+ });
+
+ it('drops the session on Escape without committing', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ tool.onKeyCommand?.(ctx, 'cancel');
+
+ expect(commits).toHaveLength(0);
+ expect(stores.lassoPreview.get()).toBeNull();
+ });
+
+ it('survives a temporary tool switch so the user can pan mid-polygon', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ tool.onDeactivate?.(ctx, { temporary: true });
+ expect(stores.lassoPreview.get()).toHaveLength(2);
+
+ tool.onActivate?.(ctx, { temporary: true });
+ click(tool, ctx, 40, 40, 2000);
+ tool.onKeyCommand?.(ctx, 'apply');
+
+ expect(commits).toHaveLength(1);
+ });
+
+ it('drops the session on a real tool switch', () => {
+ const tool = createLassoTool();
+ const { commits, ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ tool.onDeactivate?.(ctx);
+
+ expect(stores.lassoPreview.get()).toBeNull();
+ expect(commits).toHaveLength(0);
+ });
+
+ it('applies the modifiers held on the closing click', () => {
+ const tool = createLassoTool();
+ const { commits, ctx } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ down(tool, ctx, pointer(1, 1, { shift: true, timeStamp: 3000 }));
+
+ expect(commits[0]!.op).toBe('add');
+ });
+});
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 86bec05d0d..a79c293912 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
@@ -1,19 +1,30 @@
/**
- * The lasso tool: freehand pixel-selection.
+ * The lasso tool: freehand and polygonal pixel-selection.
*
- * A primary-button drag accumulates document-space polygon points (coalesced by
- * the pipeline, then distance-decimated here like the brush thins its input); a
- * live dashed preview of the in-progress path is published to the engine's
+ * Both shapes commit the same thing — a closed polygon through
+ * {@link ToolContext.commitSelection}, with the boolean op resolved by
+ * {@link selectionOpFor} (shift = add, alt = subtract, shift+alt = intersect;
+ * with none held, the persistent op mode from `lassoOptions`). Only the way the
+ * points are gathered differs, so they share one tool rather than two:
+ *
+ * - **freehand** (`shape: 'freehand'`) — a primary-button DRAG accumulates
+ * document-space points, coalesced by the pipeline then distance-decimated
+ * here like the brush thins its input. Pointer-up closes and commits.
+ * - **polygon** (`shape: 'polygon'`) — a click-to-place-vertex SESSION spanning
+ * many clicks. Each press appends a vertex; a rubber-band segment tracks the
+ * cursor. The session closes and commits on a double-click, on Enter, or on a
+ * click landing within {@link POLYGON_CLOSE_HIT_PX} screen pixels of the first
+ * vertex. Escape drops it.
+ *
+ * A live dashed preview of the in-progress path is published to the engine's
* `lassoPreview` store (a transient channel — no dispatch, no reducer traffic).
- * Pointer-up closes the path and commits it to the engine's selection through
- * {@link ToolContext.commitSelection}, with the boolean op resolved from the
- * modifiers (shift = add, alt = subtract, shift+alt = intersect) or, with none
- * held, the persistent op mode from `lassoOptions`. Escape / pointercancel drops
- * the in-progress path.
+ * The polygon session survives a temporary modifier-hold tool switch (space →
+ * view, so the user can pan mid-polygon), the same way the transform session
+ * does; a REAL tool switch drops it.
*
* Selection edits are transient interaction state: they are NOT dispatches and
- * NOT recorded on the engine's undo history this phase (legacy parity — selection
- * changes aren't undoable). Zero React, zero import-time side effects.
+ * NOT recorded on the engine's undo history (legacy parity — selection changes
+ * aren't undoable). Zero React, zero import-time side effects.
*/
import type { Vec2 } from '@workbench/canvas-engine/types';
@@ -32,28 +43,66 @@ export const LASSO_MIN_POINT_DISTANCE = 2;
/** Fewest distinct points that make a fillable selection polygon. */
const MIN_POLYGON_POINTS = 3;
+/** Screen-pixel radius around the first vertex where a click closes the polygon. */
+export const POLYGON_CLOSE_HIT_PX = 8;
+
+/** Longest gap (ms) between two presses that still reads as a double-click. */
+export const POLYGON_DOUBLE_CLICK_MS = 350;
+
+/** Screen-pixel radius within which two presses count as the same spot. */
+const POLYGON_DOUBLE_CLICK_PX = 4;
+
const distance = (a: Vec2, b: Vec2): number => Math.hypot(a.x - b.x, a.y - b.y);
+/** A freehand drag in progress. */
+interface FreehandSession {
+ kind: 'freehand';
+ points: Vec2[];
+}
+
+/** A polygon vertex-placing session spanning multiple clicks. */
+interface PolygonSession {
+ kind: 'polygon';
+ points: Vec2[];
+ /** The rubber-band endpoint (the last cursor position), or `null` before any move. */
+ cursor: Vec2 | null;
+ /** Screen position and time of the previous press, for double-click detection. */
+ lastPressScreen: Vec2;
+ lastPressAt: number;
+}
+
+type Session = FreehandSession | PolygonSession;
+
/** Creates a fresh lasso tool with its own per-gesture point buffer. */
export const createLassoTool = (): Tool => {
- let points: Vec2[] = [];
- let active = false;
+ let session: Session | null = null;
const reset = (): void => {
- points = [];
- active = false;
+ session = null;
};
/** Appends a point if it is far enough from the last stored one. */
- const pushPoint = (p: Vec2): void => {
+ const pushDecimated = (points: Vec2[], p: Vec2): void => {
const last = points[points.length - 1];
if (!last || distance(last, p) >= LASSO_MIN_POINT_DISTANCE) {
points.push({ x: p.x, y: p.y });
}
};
+ /**
+ * Publishes the in-progress outline. For a polygon the rubber-band endpoint is
+ * appended, so the overlay (which closes the loop) shows both the segment to
+ * the cursor and the implied closing edge.
+ */
const publishPreview = (ctx: ToolContext): void => {
- ctx.stores.lassoPreview.set(points.length > 0 ? points.slice() : null);
+ if (!session) {
+ ctx.stores.lassoPreview.set(null);
+ ctx.invalidate({ overlay: true });
+ return;
+ }
+ const points =
+ session.kind === 'polygon' && session.cursor ? [...session.points, session.cursor] : session.points.slice();
+ ctx.stores.lassoPreview.set(points.length > 0 ? points : null);
ctx.invalidate({ overlay: true });
};
@@ -62,49 +111,140 @@ export const createLassoTool = (): Tool => {
ctx.invalidate({ overlay: true });
};
+ /** Commits `polygon` as a selection under the modifiers held at close time. */
+ const commit = (ctx: ToolContext, polygon: readonly Vec2[], modifiers: { shift: boolean; alt: boolean }): void => {
+ if (polygon.length < MIN_POLYGON_POINTS || !ctx.commitSelection) {
+ return;
+ }
+ ctx.commitSelection({
+ bounds: polygonBounds(polygon),
+ op: selectionOpFor(modifiers, ctx.stores.lassoOptions.get().mode),
+ path: ctx.createPath2D(polygonToSvgPath(polygon)),
+ });
+ };
+
+ /** True when a press at `screenPoint` lands on the polygon's first vertex. */
+ const isOnFirstVertex = (ctx: ToolContext, polygon: PolygonSession, screenPoint: Vec2): boolean => {
+ const first = polygon.points[0];
+ if (!first || polygon.points.length < MIN_POLYGON_POINTS) {
+ return false;
+ }
+ // Project through the viewport rather than caching the vertex's screen
+ // position: the user may pan (space-hold) between vertices.
+ return distance(ctx.viewport.documentToScreen(first), screenPoint) <= POLYGON_CLOSE_HIT_PX;
+ };
+
+ const closePolygon = (
+ ctx: ToolContext,
+ polygon: PolygonSession,
+ modifiers: { shift: boolean; alt: boolean }
+ ): void => {
+ const points = polygon.points.slice();
+ reset();
+ clearPreview(ctx);
+ commit(ctx, points, modifiers);
+ };
+
return {
cursor: () => 'crosshair',
id: 'lasso',
- onDeactivate: (ctx) => {
+ onDeactivate: (ctx, opts) => {
+ if (opts?.temporary) {
+ // A modifier-hold switch (space → view to pan mid-polygon) must not
+ // discard the session; the pipeline suppresses temp switches mid-drag,
+ // so a freehand gesture cannot be interrupted here either.
+ return;
+ }
reset();
clearPreview(ctx);
},
+ onKeyCommand: (ctx, command) => {
+ if (!session) {
+ return;
+ }
+ if (command === 'cancel') {
+ reset();
+ clearPreview(ctx);
+ return;
+ }
+ if (session.kind === 'polygon') {
+ // Enter closes the polygon. No modifiers are in play on a key command,
+ // so the persistent op mode applies.
+ closePolygon(ctx, session, { alt: false, shift: false });
+ }
+ },
onPointerCancel: (ctx) => {
reset();
clearPreview(ctx);
},
onPointerDown: (ctx, input) => {
- if (active || (input.buttons & PRIMARY_BUTTON) === 0) {
+ if ((input.buttons & PRIMARY_BUTTON) === 0) {
return;
}
- active = true;
- points = [{ x: input.documentPoint.x, y: input.documentPoint.y }];
+ const shape = ctx.stores.lassoOptions.get().shape;
+
+ if (shape === 'freehand') {
+ if (session) {
+ return;
+ }
+ session = { kind: 'freehand', points: [{ x: input.documentPoint.x, y: input.documentPoint.y }] };
+ publishPreview(ctx);
+ return;
+ }
+
+ if (!session) {
+ session = {
+ cursor: null,
+ kind: 'polygon',
+ lastPressAt: input.timeStamp,
+ lastPressScreen: input.screenPoint,
+ points: [{ x: input.documentPoint.x, y: input.documentPoint.y }],
+ };
+ publishPreview(ctx);
+ return;
+ }
+ if (session.kind !== 'polygon') {
+ // The shape option flipped mid-drag; let the freehand gesture finish.
+ return;
+ }
+
+ const isDoubleClick =
+ input.timeStamp - session.lastPressAt <= POLYGON_DOUBLE_CLICK_MS &&
+ distance(session.lastPressScreen, input.screenPoint) <= POLYGON_DOUBLE_CLICK_PX;
+ if (isDoubleClick || isOnFirstVertex(ctx, session, input.screenPoint)) {
+ closePolygon(ctx, session, input.modifiers);
+ return;
+ }
+
+ session.points.push({ x: input.documentPoint.x, y: input.documentPoint.y });
+ session.lastPressAt = input.timeStamp;
+ session.lastPressScreen = input.screenPoint;
publishPreview(ctx);
},
onPointerMove: (ctx, input, batch) => {
- if (!active) {
+ if (!session) {
return;
}
- for (const sample of batch) {
- pushPoint(sample.documentPoint);
+ if (session.kind === 'polygon') {
+ session.cursor = { x: input.documentPoint.x, y: input.documentPoint.y };
+ } else {
+ for (const sample of batch) {
+ pushDecimated(session.points, sample.documentPoint);
+ }
}
publishPreview(ctx);
},
onPointerUp: (ctx, input) => {
- if (!active) {
+ // A polygon session spans many clicks — it closes on double-click, Enter,
+ // or a click on the first vertex, never on a plain release.
+ if (!session || session.kind === 'polygon') {
return;
}
- pushPoint(input.documentPoint);
- const polygon = points.slice();
+ pushDecimated(session.points, input.documentPoint);
+ const polygon = session.points.slice();
reset();
clearPreview(ctx);
- if (polygon.length < MIN_POLYGON_POINTS || !ctx.commitSelection) {
- return;
- }
- const path = ctx.createPath2D(polygonToSvgPath(polygon));
- const bounds = polygonBounds(polygon);
- const op = selectionOpFor(input.modifiers, ctx.stores.lassoOptions.get().mode);
- ctx.commitSelection({ bounds, op, path });
+ commit(ctx, polygon, input.modifiers);
},
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 6a7fc54659..8e90d770b9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -402,11 +402,21 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
} else if (commandId === 'canvas.tool.eraser') {
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
+ // Pressing the shortcut while already on the tool cycles its shape
// (Photoshop-style) rather than re-selecting the tool it is already on.
+ if (engine.interaction.get('activeTool') === 'lasso') {
+ const lasso = engine.interaction.get('lassoOptions');
+ engine.interaction.set('lassoOptions', {
+ ...lasso,
+ shape: lasso.shape === 'freehand' ? 'polygon' : 'freehand',
+ });
+ } else {
+ engine.tools.setTool('lasso');
+ }
+ }
+ } else if (commandId === 'canvas.tool.marquee') {
+ if (engine) {
if (engine.interaction.get('activeTool') === 'marquee') {
const marquee = engine.interaction.get('marqueeOptions');
engine.interaction.set('marqueeOptions', {
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 da60a32d7e..e207d446fc 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,30 +1,81 @@
-import type { SelectionOp } from '@workbench/canvas-engine/api';
+import type { SelectValueChangeDetails } from '@chakra-ui/react';
+import type { LassoToolOptions, SelectionOp } from '@workbench/canvas-engine/api';
+import { createListCollection, HStack, Text } from '@chakra-ui/react';
+import { Select } from '@platform/ui';
import { useLassoOptions } from '@workbench/widgets/canvas/engineStoreHooks';
-import { useCallback } from 'react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
import type { ToolOptionsComponentProps } from './ToolOptionsBar';
import { SelectionOptionsRow } from './SelectionOptionsRow';
+type LassoShape = LassoToolOptions['shape'];
+
+const SELECT_POSITIONING = { placement: 'top-start', sameWidth: false } as const;
+const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;
+
/**
- * Lasso tool options: the shared selection controls, bound to the lasso's own
- * persistent op mode.
+ * Lasso tool options: how the path is drawn (freehand drag / polygon clicks),
+ * plus the shared selection controls bound to the lasso's own op mode.
*/
export const LassoOptions = ({ engine }: ToolOptionsComponentProps) => {
+ const { t } = useTranslation();
const options = useLassoOptions(engine);
+ const shapeCollection = useMemo(
+ () =>
+ createListCollection<{ label: string; value: LassoShape }>({
+ items: [
+ { label: t('widgets.canvas.toolOptions.lassoFreehand'), value: 'freehand' },
+ { label: t('widgets.canvas.toolOptions.lassoPolygon'), value: 'polygon' },
+ ],
+ }),
+ [t]
+ );
+ const shapeValue = useMemo(() => [options.shape], [options.shape]);
+
+ const onShapeChange = useCallback(
+ ({ value }: SelectValueChangeDetails<{ label: string; value: LassoShape }>) => {
+ const next = value[0] as LassoShape | undefined;
+ if (next && next !== options.shape) {
+ engine.interaction.set('lassoOptions', { ...options, shape: next });
+ }
+ },
+ [engine, options]
+ );
+
const onModeChange = useCallback(
(mode: SelectionOp) => engine.interaction.set('lassoOptions', { ...options, mode }),
[engine, options]
);
return (
- <SelectionOptionsRow
- engine={engine}
- hintKey="widgets.canvas.toolOptions.lassoHint"
- mode={options.mode}
- onModeChange={onModeChange}
- />
+ <HStack align="center" gap="3">
+ <HStack align="center" gap="1.5">
+ <Text color="fg.muted" fontSize="2xs">
+ {t('widgets.canvas.toolOptions.lassoShape')}
+ </Text>
+ <Select
+ collection={shapeCollection}
+ positioning={SELECT_POSITIONING}
+ size="xs"
+ triggerProps={SELECT_TRIGGER_PROPS}
+ value={shapeValue}
+ onValueChange={onShapeChange}
+ />
+ </HStack>
+ <SelectionOptionsRow
+ engine={engine}
+ hintKey={
+ options.shape === 'polygon'
+ ? 'widgets.canvas.toolOptions.lassoPolygonHint'
+ : 'widgets.canvas.toolOptions.lassoHint'
+ }
+ mode={options.mode}
+ onModeChange={onModeChange}
+ />
+ </HStack>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx
similarity index 66%
rename from invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx
rename to invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx
index 49e493da70..7b9de63136 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx
@@ -10,16 +10,17 @@ import { createDraftProject } from '@workbench/workbenchState';
import { renderToStaticMarkup } from 'react-dom/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
-import { LassoOptions } from './LassoOptions';
+import { SelectionOptionsRow } from './SelectionOptionsRow';
interface CapturedButton {
children?: ReactNode;
disabled?: boolean;
}
-const { activeProject, buttons } = vi.hoisted(() => ({
+const { activeProject, buttons, hasSelection } = vi.hoisted(() => ({
activeProject: { current: null as Project | null },
buttons: new Map<string, CapturedButton>(),
+ hasSelection: { current: true },
}));
vi.mock('@platform/ui', () => ({
@@ -29,8 +30,7 @@ vi.mock('@platform/ui', () => ({
},
}));
vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({
- useCanvasHasSelection: () => true,
- useLassoOptions: () => ({ mode: 'replace' }),
+ useCanvasHasSelection: () => hasSelection.current,
}));
vi.mock('@workbench/WorkbenchContext', () => ({
useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject.current!),
@@ -40,14 +40,15 @@ vi.mock('react-i18next', () => ({
}));
const engine = {
- deselect: vi.fn(),
- eraseSelection: vi.fn(),
- fillSelection: vi.fn(),
- invertSelection: vi.fn(),
- stores: { lassoOptions: { set: vi.fn() } },
+ selection: {
+ deselect: vi.fn(),
+ eraseSelection: vi.fn(),
+ fillSelection: vi.fn(),
+ invertSelection: vi.fn(),
+ },
} as unknown as CanvasEngine;
-const renderLassoOptions = (layer: CanvasLayerContract): Map<string, CapturedButton> => {
+const renderRow = (layer: CanvasLayerContract): Map<string, CapturedButton> => {
const project = createDraftProject([]);
project.canvas.document = {
background: 'transparent',
@@ -61,7 +62,12 @@ const renderLassoOptions = (layer: CanvasLayerContract): Map<string, CapturedBut
activeProject.current = project;
renderToStaticMarkup(
<ChakraProvider value={system}>
- <LassoOptions engine={engine} />
+ <SelectionOptionsRow
+ engine={engine}
+ hintKey="widgets.canvas.toolOptions.lassoHint"
+ mode="replace"
+ onModeChange={vi.fn()}
+ />
</ChakraProvider>
);
return new Map(buttons);
@@ -69,9 +75,10 @@ const renderLassoOptions = (layer: CanvasLayerContract): Map<string, CapturedBut
beforeEach(() => {
buttons.clear();
+ hasSelection.current = true;
});
-describe('LassoOptions pixel target eligibility', () => {
+describe('SelectionOptionsRow pixel target eligibility', () => {
const rasterPaint = createEmptyPaintLayer('Raster', 'raster');
const controlPaint = createControlLayer('Control', 'control');
const rasterImage: CanvasLayerContract = {
@@ -86,8 +93,22 @@ describe('LassoOptions pixel target eligibility', () => {
{ disabled: true, layer: { ...controlPaint, isEnabled: false }, scenario: 'disabled control' },
{ disabled: true, layer: rasterImage, scenario: 'raster image' },
])('sets Fill and Erase disabled=$disabled for $scenario', ({ disabled, layer }) => {
- const rendered = renderLassoOptions(layer);
+ const rendered = renderRow(layer);
expect(rendered.get('widgets.canvas.toolOptions.fillSelection')?.disabled).toBe(disabled);
expect(rendered.get('widgets.canvas.toolOptions.eraseSelection')?.disabled).toBe(disabled);
});
+
+ it('disables every action with no live selection, even on an eligible layer', () => {
+ hasSelection.current = false;
+ const rendered = renderRow(rasterPaint);
+ for (const key of ['fillSelection', 'eraseSelection', 'invertSelection', 'deselect']) {
+ expect(rendered.get(`widgets.canvas.toolOptions.${key}`)?.disabled).toBe(true);
+ }
+ });
+
+ it('leaves invert and deselect enabled on an ineligible layer (they need only a selection)', () => {
+ const rendered = renderRow(rasterImage);
+ expect(rendered.get('widgets.canvas.toolOptions.invertSelection')?.disabled).toBe(false);
+ expect(rendered.get('widgets.canvas.toolOptions.deselect')?.disabled).toBe(false);
+ });
});