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.

fix(canvas): make selection modifiers and the polygon lasso close cue work

Josh Corbett9761771a340b
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 15f5576d50..4549eb60dc 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2694,7 +2694,7 @@
"lassoPolygonHint": "Click to place points. Double-click, Enter, or click the first point to close.",
"lassoShape": "Lasso mode",
"liftSelectionToLayer": "New layer",
- "marqueeHint": "Drag to select a region. Shift constrains, Alt draws from centre.",
+ "marqueeHint": "Drag to select a region. Shift adds, Alt subtracts; press them mid-drag to constrain or draw from center.",
"marqueeKind": "Marquee shape",
"movePosition": "Move layer",
"opacity": "Opacity",
@@ -2705,10 +2705,13 @@
"rotation": "Rotation",
"scaleHeight": "H %",
"scaleWidth": "W %",
+ "selectAll": "Select all",
"selectionActions": "Actions",
"selectionAdd": "Add",
"selectionIntersect": "Intersect",
"selectionMode": "Selection mode",
+ "selectionNeedsPaintLayer": "Select an unlocked, visible paint layer first",
+ "selectionNeedsSelection": "Make a selection first",
"selectionReplace": "Replace",
"selectionSubtract": "Subtract",
"setFrame": "Set generation frame",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
index 2438447f2c..8e785c7b97 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engineStores.ts
@@ -130,6 +130,18 @@ export interface GradientToolOptions {
stops: GradientStop[];
}
+/** The lasso tool's in-flight outline: a freehand drag, or a polygon being placed vertex by vertex. */
+export type LassoPreview =
+ | { kind: 'freehand'; points: readonly Vec2[] }
+ | {
+ kind: 'polygon';
+ points: readonly Vec2[];
+ cursor: Vec2 | null;
+ /** Once the polygon can close, a press this many screen px from the first vertex closes it; the overlay rings that radius. */
+ closeRadiusPx: number | null;
+ closeArmed: boolean;
+ };
+
/** The gradient tool's in-flight drag: start → end in document space. */
export interface GradientPreview {
kind: 'linear' | 'radial';
@@ -504,12 +516,13 @@ export interface EngineStores {
/** Core-only visual SAM interaction state; application session status remains outside the engine. */
samInteraction: ScalarStore<SamInteractionState | null>;
/**
- * The in-progress lasso polygon (document-space points) during a lasso drag,
- * or `null` when idle. The overlay renders it as a live dashed preview in
- * place of a committed selection; cleared on commit/cancel. Like `bboxPreview`,
- * it is a transient channel — no dispatch, no React subscriber.
+ * The in-progress lasso outline (document space), or `null` when idle. The
+ * overlay draws a freehand drag as a dashed outline; a polygon session also
+ * shows its placed vertices, the rubber band to the cursor, and whether the
+ * cursor sits on the first vertex (a click there closes). Cleared on
+ * commit/cancel. Like `bboxPreview`, a transient channel — no dispatch.
*/
- lassoPreview: ScalarStore<readonly Vec2[] | null>;
+ lassoPreview: ScalarStore<LassoPreview | null>;
/**
* The live marquee-tool drag outline (document-space rect + shape), or `null`
* when idle. Like `lassoPreview`, a transient overlay-only channel: the mask
@@ -740,7 +753,7 @@ export const createEngineStores = (initialTool: ToolId = 'view'): EngineStores =
),
gradientPreview: createScalarStore<GradientPreview | null>(null, gradientPreviewEqual),
lassoOptions: createScalarStore<LassoToolOptions>({ ...DEFAULT_LASSO_OPTIONS }, lassoOptionsEqual),
- lassoPreview: createScalarStore<readonly Vec2[] | null>(null),
+ lassoPreview: createScalarStore<LassoPreview | null>(null),
marqueeOptions: createScalarStore<MarqueeToolOptions>({ ...DEFAULT_MARQUEE_OPTIONS }, marqueeOptionsEqual),
marqueePreview: createScalarStore<{ rect: Rect; kind: 'rect' | 'ellipse' } | null>(null, rectShapePreviewEqual),
rasterContentEpoch: createScalarStore<number>(0),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
index d6947d58d8..fef214ce9f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.test.ts
@@ -445,6 +445,15 @@ describe('pointer pipeline: temporary modifier tools', () => {
expect(h.setTool).toHaveBeenLastCalledWith('brush', { temporary: true });
});
+ it('leaves alt to a tool that uses it as a gesture modifier', () => {
+ const h = createHarness({ tools: ['view', 'brush', 'colorPicker'] });
+ (h.tool as { usesAltKey?: boolean }).usesAltKey = true;
+ h.pipeline.onPointerEnter();
+ h.pipeline.onKeyDown(makeKeyEvent({ code: 'AltLeft' }));
+ h.pipeline.onKeyUp(makeKeyEvent({ code: 'AltLeft' }));
+ expect(h.setTool).not.toHaveBeenCalled();
+ });
+
it('quick-tapping C sticky-selects the bbox tool after the temporary preview switch', () => {
const h = createHarness({ tools: ['view', 'brush', 'bbox'] });
h.pipeline.onPointerEnter();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
index 55f623fe7d..a2b8996241 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/input/pointerPipeline.ts
@@ -329,7 +329,9 @@ export const createPointerPipeline = (deps: PointerPipelineDeps): PointerPipelin
return;
}
if (isAltKey(event) && !event.repeat) {
- beginTempTool('alt', ALT_TEMP_TOOL);
+ if (!deps.getActiveTool()?.usesAltKey) {
+ beginTempTool('alt', ALT_TEMP_TOOL);
+ }
return;
}
if (isBboxKey(event) && !event.repeat) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
index ec1b6a563d..bf1c87a34a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayFrame.test.ts
@@ -257,7 +257,7 @@ describe('settings pass-through', () => {
it('forwards the in-progress tool previews', () => {
const gradient = { end: { x: 1, y: 1 }, kind: 'linear' as const, start: { x: 0, y: 0 } };
- const lasso = [{ x: 0, y: 0 }];
+ const lasso = { kind: 'freehand' as const, points: [{ x: 0, y: 0 }] };
const marquee = { kind: 'rect' as const, rect: { height: 2, width: 2, x: 0, y: 0 } };
const shape = { kind: 'ellipse' as const, rect: { height: 3, width: 3, x: 1, y: 1 } };
harness.stores.gradientPreview.set(gradient);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
index 1637368e80..f77ce218e3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.test.ts
@@ -157,6 +157,56 @@ describe('renderOverlay', () => {
}
});
+ it("marks a polygon lasso's vertices and fills the first-vertex ring once a click there would close it", () => {
+ const points = [
+ { x: 10, y: 10 },
+ { x: 50, y: 10 },
+ { x: 50, y: 50 },
+ ];
+ const render = (closeArmed: boolean) => {
+ const backend = createTestStubRasterBackend();
+ const target = backend.createSurface(200, 200);
+ renderOverlay(
+ target,
+ baseState({
+ lassoPreview: { closeArmed, closeRadiusPx: 8, cursor: { x: 12, y: 12 }, kind: 'polygon', points },
+ showBbox: false,
+ })
+ );
+ return target.callLog;
+ };
+ const idle = render(false);
+ // The ring is the close hit radius itself, so it never disagrees with the click.
+ expect(idle.filter((e) => e.op === 'arc').map((e) => e.args.slice(0, 3))).toEqual([[10, 10, 8]]);
+ expect(idle.filter((e) => e.op === 'fillRect')).toHaveLength(2);
+ expect(idle.filter((e) => e.op === 'fill')).toHaveLength(0);
+
+ const armed = render(true);
+ expect(armed.filter((e) => e.op === 'fill')).toHaveLength(1);
+ });
+
+ it('draws no close ring while the polygon cannot close yet', () => {
+ const backend = createTestStubRasterBackend();
+ const target = backend.createSurface(200, 200);
+ renderOverlay(
+ target,
+ baseState({
+ lassoPreview: {
+ closeArmed: false,
+ closeRadiusPx: null,
+ cursor: { x: 30, y: 30 },
+ kind: 'polygon',
+ points: [
+ { x: 10, y: 10 },
+ { x: 50, y: 10 },
+ ],
+ },
+ showBbox: false,
+ })
+ );
+ expect(target.callLog.filter((e) => e.op === 'arc')).toHaveLength(0);
+ });
+
it('draws the dedicated SAM mask preview before its bbox, handles, and colored points', () => {
const backend = createTestStubRasterBackend();
const target = backend.createSurface(200, 200);
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 057470e156..013e5ac585 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/render/overlayRenderer.ts
@@ -95,10 +95,19 @@ export interface OverlayState {
*/
transformFrame?: TransformFrameOverlay | null;
/**
- * The in-progress lasso polygon (document-space points), drawn as a live dashed
- * outline while a lasso drag is underway. Absent/`null` when idle.
+ * The in-progress lasso outline (document space): a freehand drag, or a
+ * polygon session with its placed vertices and close cue. Absent/`null` when idle.
*/
- lassoPreview?: readonly Vec2[] | null;
+ lassoPreview?:
+ | { kind: 'freehand'; points: readonly Vec2[] }
+ | {
+ kind: 'polygon';
+ points: readonly Vec2[];
+ cursor: Vec2 | null;
+ closeRadiusPx: number | null;
+ closeArmed: boolean;
+ }
+ | null;
/**
* The committed selection's marching ants: the outline paths (document space)
* plus the animated dash phase. Absent/`null` when there is no selection.
@@ -319,18 +328,30 @@ const drawTransformFrame = (ctx: Ctx, state: OverlayState): void => {
const LASSO_PREVIEW_COLOR = '#38bdf8';
const LASSO_PREVIEW_DASH: readonly number[] = [4, 4];
-/** Draws the in-progress lasso polygon as a dashed screen-space outline. */
+/** Screen-space half-size of a placed polygon vertex knob. */
+const LASSO_VERTEX_HALF_PX = 2;
+
+/**
+ * Draws the in-progress lasso as a dashed screen-space outline. A polygon also
+ * shows its placed vertices and, once it can close, a ring on the first one at
+ * the close hit radius, filled while the cursor is inside it.
+ */
const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {
- const points = state.lassoPreview;
- if (!points || points.length < 2) {
+ const preview = state.lassoPreview;
+ if (!preview) {
+ return;
+ }
+ const outline = preview.kind === 'polygon' && preview.cursor ? [...preview.points, preview.cursor] : preview.points;
+ if (outline.length < 2) {
return;
}
ctx.save();
ctx.strokeStyle = LASSO_PREVIEW_COLOR;
+ ctx.fillStyle = LASSO_PREVIEW_COLOR;
ctx.lineWidth = 1;
ctx.setLineDash([...LASSO_PREVIEW_DASH]);
ctx.beginPath();
- points.forEach((point, index) => {
+ outline.forEach((point, index) => {
const p = applyToPoint(state.view, point);
if (index === 0) {
ctx.moveTo(p.x, p.y);
@@ -342,6 +363,26 @@ const drawLassoPreview = (ctx: Ctx, state: OverlayState): void => {
ctx.closePath();
ctx.stroke();
ctx.setLineDash([]);
+ if (preview.kind === 'polygon') {
+ preview.points.forEach((point, index) => {
+ const p = applyToPoint(state.view, point);
+ if (index === 0 && preview.closeRadiusPx !== null) {
+ ctx.beginPath();
+ ctx.arc(p.x, p.y, preview.closeRadiusPx, 0, Math.PI * 2);
+ if (preview.closeArmed) {
+ ctx.fill();
+ }
+ ctx.stroke();
+ } else {
+ ctx.fillRect(
+ p.x - LASSO_VERTEX_HALF_PX,
+ p.y - LASSO_VERTEX_HALF_PX,
+ LASSO_VERTEX_HALF_PX * 2,
+ LASSO_VERTEX_HALF_PX * 2
+ );
+ }
+ });
+ }
ctx.restore();
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts
index 14868bad99..80f816a5bd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionHistory.test.ts
@@ -16,7 +16,9 @@ const createHarness = () => {
const onChange = vi.fn();
const selection = withSelectionHistory(
createSelectionState({
- backend: createTestStubRasterBackend(),
+ // No readable pixels: boolean ops fall back to path bookkeeping, so the
+ // history is exercised through what it records rather than a traced mask.
+ backend: createTestStubRasterBackend({ readbackAlpha: 0 }),
createPath2D: (d) => ({ d }) as unknown as Path2D,
getDocumentSize: () => DOC,
onChange,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts
index fb0b1d94a1..5191726741 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.test.ts
@@ -31,8 +31,8 @@ const placedMask = (alphas: readonly number[]): { placed: PlacedSurface; pixels:
return { pixels, placed: { rect: rectBounds(7, -3, 2, 2), surface } };
};
-const createHarness = (docSize: { width: number; height: number } | null = DOC) => {
- const backend = createTestStubRasterBackend();
+const createHarness = (docSize: { width: number; height: number } | null = DOC, readbackAlpha?: number) => {
+ const backend = createTestStubRasterBackend(readbackAlpha === undefined ? undefined : { readbackAlpha });
const onChange = vi.fn();
const selection: SelectionState = createSelectionState({
backend,
@@ -79,25 +79,45 @@ describe('selectionState: mask building from a path', () => {
});
describe('selectionState: boolean ops', () => {
- it('add unions bounds with source-over and keeps both ant paths', () => {
+ it('add unions bounds with source-over and re-traces the ants from the mask', () => {
const { selection } = createHarness();
selection.commit({ bounds: rectBounds(10, 10, 10, 10), op: 'replace', path: fakePath('a') });
selection.commit({ bounds: rectBounds(40, 40, 10, 10), op: 'add', path: fakePath('b') });
expect(selection.hasSelection()).toBe(true);
expect(selection.bounds()).toEqual(rectBounds(10, 10, 40, 40));
- expect(selection.antsPaths()).toHaveLength(2);
+ // One traced outline replaces the two source paths (the stub reads back solid pixels).
+ expect(selection.antsPaths()).toHaveLength(1);
+ expect(selection.antsPaths()[0]).not.toEqual(fakePath('b'));
expect(compositeOpsFor(maskLog(selection))).toContain('source-over');
});
- it('subtract composites destination-out', () => {
+ it('add keeps stroking the source paths when the mask cannot be read back', () => {
+ const { selection } = createHarness(DOC, 0);
+ selection.commit({ bounds: rectBounds(10, 10, 10, 10), op: 'replace', path: fakePath('a') });
+ selection.commit({ bounds: rectBounds(40, 40, 10, 10), op: 'add', path: fakePath('b') });
+
+ expect(selection.hasSelection()).toBe(true);
+ expect(selection.antsPaths()).toEqual([fakePath('a'), fakePath('b')]);
+ });
+
+ it('subtract composites destination-out and re-traces the ants', () => {
const { selection } = createHarness();
selection.commit({ bounds: rectBounds(0, 0, 50, 50), op: 'replace', path: fakePath('a') });
selection.commit({ bounds: rectBounds(10, 10, 10, 10), op: 'subtract', path: fakePath('b') });
expect(selection.hasSelection()).toBe(true);
+ expect(selection.antsPaths()).toHaveLength(1);
expect(compositeOpsFor(maskLog(selection))).toContain('destination-out');
});
+ it('subtracting everything deselects instead of leaving a phantom selection', () => {
+ const { selection } = createHarness(DOC, 0);
+ selection.commit({ bounds: rectBounds(0, 0, 50, 50), op: 'replace', path: fakePath('a') });
+ selection.commit({ bounds: rectBounds(0, 0, 50, 50), op: 'subtract', path: fakePath('b') });
+ expect(selection.hasSelection()).toBe(false);
+ expect(selection.bounds()).toBeNull();
+ });
+
it('intersect composites destination-in and intersects the bounds', () => {
const { selection } = createHarness();
selection.commit({ bounds: rectBounds(0, 0, 50, 50), op: 'replace', path: fakePath('a') });
@@ -107,6 +127,14 @@ describe('selectionState: boolean ops', () => {
expect(compositeOpsFor(maskLog(selection))).toContain('destination-in');
});
+ it('an intersect that leaves nothing deselects', () => {
+ const { selection } = createHarness(DOC, 0);
+ selection.commit({ bounds: rectBounds(0, 0, 50, 50), op: 'replace', path: fakePath('a') });
+ selection.commit({ bounds: rectBounds(10, 10, 10, 10), op: 'intersect', path: fakePath('b') });
+ expect(selection.hasSelection()).toBe(false);
+ expect(selection.antsPaths()).toEqual([]);
+ });
+
it('intersect against no existing selection clears to nothing', () => {
const { selection } = createHarness();
selection.commit({ bounds: rectBounds(0, 0, 10, 10), op: 'intersect', path: fakePath('a') });
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 c33627adf2..b08fa05c49 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/selection/selectionState.ts
@@ -14,26 +14,21 @@
* kept only for {@link marchingAnts} rendering (stroking the outlines), not for
* re-deriving the mask.
*
- * ## Marching-ants approximation
+ * ## Marching ants
*
- * Ants are stroked from the committed path LIST (each path drawn dashed), not by
- * tracing the mask's true edge. This matches the mask exactly for `replace` and
- * `add`, and reads correctly for `subtract` (the cut-out path's outline shows as
- * a hole) and `selectAll`/`invert` (a document-border path is included). It is an
- * approximation for `intersect` and for heavily overlapping compositions, where
- * the true selection outline is the boolean result rather than the union of the
- * source outlines — the ants may show interior source edges that the mask does
- * not. The exception is {@link SelectionState.replaceMask} (pixel-mask
- * replacement, e.g. a Select Object result), whose ants ARE traced from the
- * mask's true edge via {@link traceMaskOutlinePath}. The mask itself is always
- * exact.
+ * A `replace` strokes its own path. Every boolean op (`add` / `subtract` /
+ * `intersect`) re-traces the mask's true edge via {@link traceMaskOutlinePath},
+ * the same way {@link SelectionState.replaceMask} does, so the ants show the
+ * boolean result rather than the union of the source outlines. `selectAll` /
+ * `invert` keep their document-border path. When a trace yields nothing after
+ * an `add` (a raster stub with no readable pixels), the source paths are
+ * stroked instead; after `subtract` / `intersect` an empty trace means the mask
+ * is empty, and the selection is dropped.
*
* ## Emptiness
*
- * `hasSelection` is tracked structurally, not by scanning pixels (a scan is
- * unavailable on the node raster stub and costly on the DOM). Consequently,
- * `subtract`ing away the entire selection leaves `hasSelection` true until an
- * explicit deselect — a known, documented limitation of this phase.
+ * `hasSelection` is structural for `replace` / `add` (they cannot empty the
+ * mask) and pixel-derived for `subtract` / `intersect` through the same trace.
*
* Zero React, zero import-time side effects.
*/
@@ -348,7 +343,6 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =
? ensureMask(bounds)
: ensureMask(selectionBounds ?? bounds ?? { height: 0, width: 0, x: 0, y: 0 });
fillPath(surface, { x: maskRect!.x, y: maskRect!.y }, next.path, compositeForOp(next.op));
- commits.push(next);
switch (next.op) {
case 'add':
@@ -356,17 +350,49 @@ export const createSelectionState = (deps: SelectionStateDeps): SelectionState =
selected = selected || bounds !== null;
break;
case 'subtract':
- // Bounds can only shrink; without a pixel scan we keep the (over-approx)
- // prior bounds. `selected` stays true — see module docs.
+ // Bounds only shrink; they stay the prior over-approximation, and the
+ // trace below decides whether anything is left.
break;
case 'intersect':
selectionBounds = selectionBounds && bounds ? intersect(selectionBounds, bounds) : null;
selected = selectionBounds !== null;
break;
}
+
+ const outline = selected ? traceCurrentOutline() : null;
+ if (outline) {
+ commits = [{ bounds: selectionBounds ?? roundOut(next.bounds), op: 'replace', path: createPath2D(outline) }];
+ } else if (next.op === 'add') {
+ commits.push(next);
+ } else {
+ clear();
+ return;
+ }
changed();
};
+ /** The mask's true edge as path data, or null when it holds no pixels. */
+ const traceCurrentOutline = (): string | null => {
+ if (!mask || !maskRect || isEmpty(maskRect)) {
+ return null;
+ }
+ const pixels = mask.ctx.getImageData(0, 0, maskRect.width, maskRect.height);
+ // A subtract that emptied the mask is the common way to get here: one alpha
+ // scan settles it without paying for two full traces.
+ let hasAlpha = false;
+ for (let index = 3; index < pixels.data.length; index += 4) {
+ if (pixels.data[index] !== 0) {
+ hasAlpha = true;
+ break;
+ }
+ }
+ if (!hasAlpha) {
+ return null;
+ }
+ const source = { data: pixels.data, height: maskRect.height, width: maskRect.width };
+ return traceMaskOutlinePath(source, maskRect) || traceMaskOutlinePath(source, maskRect, 1) || null;
+ };
+
const selectAll = (domain: Rect): void => {
const rect = roundOut(domain);
const surface = resetMask(rect);
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 0ba251b71e..6c7aaf9788 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
@@ -31,6 +31,7 @@ const createHarness = () => {
dispatch: (action: WorkbenchAction) => dispatched.push(action),
invalidate: vi.fn(),
stores,
+ updateCursor: vi.fn(),
// 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 },
@@ -124,8 +125,7 @@ describe('lassoTool: cancel + guards', () => {
// These are all within 1px of each other → decimated away.
move(tool, ctx, pointer(0.5, 0));
move(tool, ctx, pointer(1, 0));
- const preview = stores.lassoPreview.get();
- expect(preview).toHaveLength(1);
+ expect(stores.lassoPreview.get()?.points).toHaveLength(1);
});
});
@@ -151,7 +151,7 @@ describe('lassoTool: polygon mode', () => {
click(tool, ctx, 40, 40, 2000);
expect(commits).toHaveLength(0);
- expect(stores.lassoPreview.get()).toHaveLength(3);
+ expect(stores.lassoPreview.get()?.points).toHaveLength(3);
});
it('shows a rubber-band segment to the cursor between clicks', () => {
@@ -162,10 +162,13 @@ describe('lassoTool: polygon mode', () => {
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 },
- ]);
+ expect(stores.lassoPreview.get()).toEqual({
+ closeArmed: false,
+ closeRadiusPx: null,
+ cursor: { x: 30, y: 10 },
+ kind: 'polygon',
+ points: [{ x: 0, y: 0 }],
+ });
});
it('closes and commits on Enter', () => {
@@ -182,6 +185,45 @@ describe('lassoTool: polygon mode', () => {
expect(stores.lassoPreview.get()).toBeNull();
});
+ it('arms the close cue and pointer cursor while the cursor hovers the first vertex', () => {
+ const tool = createLassoTool();
+ const { ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 40, 2000);
+ move(tool, ctx, pointer(30, 30));
+ expect(stores.lassoPreview.get()).toMatchObject({ closeArmed: false, kind: 'polygon' });
+ expect(tool.cursor?.(ctx)).toBe('crosshair');
+
+ move(tool, ctx, pointer(3, 2));
+ expect(stores.lassoPreview.get()).toMatchObject({ closeArmed: true, kind: 'polygon' });
+ expect(tool.cursor?.(ctx)).toBe('pointer');
+ expect(ctx.updateCursor).toHaveBeenCalled();
+ });
+
+ it('offers the close ring only once three vertices are placed', () => {
+ const tool = createLassoTool();
+ const { ctx, stores } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ expect(stores.lassoPreview.get()).toMatchObject({ closeRadiusPx: null });
+ click(tool, ctx, 40, 40, 2000);
+ expect(stores.lassoPreview.get()).toMatchObject({ closeRadiusPx: 8 });
+ });
+
+ it('commits nothing for a flat polygon (a double-click on the second vertex)', () => {
+ const tool = createLassoTool();
+ const { commits, ctx } = createPolygonHarness();
+
+ click(tool, ctx, 0, 0, 0);
+ click(tool, ctx, 40, 0, 1000);
+ click(tool, ctx, 40, 1, 1200);
+
+ expect(commits).toHaveLength(0);
+ });
+
it('closes on a click landing on the first vertex', () => {
const tool = createLassoTool();
const { commits, ctx } = createPolygonHarness();
@@ -205,7 +247,7 @@ describe('lassoTool: polygon mode', () => {
click(tool, ctx, 2, 0, 1000);
expect(commits).toHaveLength(0);
- expect(stores.lassoPreview.get()).toHaveLength(2);
+ expect(stores.lassoPreview.get()?.points).toHaveLength(2);
});
it('closes on a double-click', () => {
@@ -231,7 +273,7 @@ describe('lassoTool: polygon mode', () => {
click(tool, ctx, 40, 40, 9000);
expect(commits).toHaveLength(0);
- expect(stores.lassoPreview.get()).toHaveLength(4);
+ expect(stores.lassoPreview.get()?.points).toHaveLength(4);
});
it('drops the session on Escape without committing', () => {
@@ -254,7 +296,7 @@ describe('lassoTool: polygon mode', () => {
click(tool, ctx, 0, 0, 0);
click(tool, ctx, 40, 0, 1000);
tool.onDeactivate?.(ctx, { temporary: true });
- expect(stores.lassoPreview.get()).toHaveLength(2);
+ expect(stores.lassoPreview.get()?.points).toHaveLength(2);
tool.onActivate?.(ctx, { temporary: true });
click(tool, ctx, 40, 40, 2000);
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 a79c293912..eacbec7593 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/lassoTool.ts
@@ -66,6 +66,8 @@ interface PolygonSession {
points: Vec2[];
/** The rubber-band endpoint (the last cursor position), or `null` before any move. */
cursor: Vec2 | null;
+ /** Whether the cursor sits on the first vertex, where a click closes the polygon. */
+ closeArmed: boolean;
/** Screen position and time of the previous press, for double-click detection. */
lastPressScreen: Vec2;
lastPressAt: number;
@@ -89,20 +91,21 @@ export const createLassoTool = (): Tool => {
}
};
- /**
- * 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.
- */
+ /** Publishes the in-progress outline for the overlay. */
const publishPreview = (ctx: ToolContext): void => {
- if (!session) {
+ if (!session || session.points.length === 0) {
ctx.stores.lassoPreview.set(null);
- ctx.invalidate({ overlay: true });
- return;
+ } else if (session.kind === 'polygon') {
+ ctx.stores.lassoPreview.set({
+ closeArmed: session.closeArmed,
+ closeRadiusPx: session.points.length >= MIN_POLYGON_POINTS ? POLYGON_CLOSE_HIT_PX : null,
+ cursor: session.cursor,
+ kind: 'polygon',
+ points: session.points.slice(),
+ });
+ } else {
+ ctx.stores.lassoPreview.set({ kind: 'freehand', points: session.points.slice() });
}
- 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 });
};
@@ -113,11 +116,15 @@ export const createLassoTool = (): Tool => {
/** 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) {
+ const bounds = polygonBounds(polygon);
+ // A double-click's second press lands on the previous vertex, so count
+ // distinct points; and a flat polygon would select a line of nothing.
+ const distinct = polygon.filter((point, index) => index === 0 || distance(point, polygon[index - 1]!) >= 1);
+ if (distinct.length < MIN_POLYGON_POINTS || bounds.width < 1 || bounds.height < 1 || !ctx.commitSelection) {
return;
}
ctx.commitSelection({
- bounds: polygonBounds(polygon),
+ bounds,
op: selectionOpFor(modifiers, ctx.stores.lassoOptions.get().mode),
path: ctx.createPath2D(polygonToSvgPath(polygon)),
});
@@ -146,8 +153,9 @@ export const createLassoTool = (): Tool => {
};
return {
- cursor: () => 'crosshair',
+ cursor: () => (session?.kind === 'polygon' && session.closeArmed ? 'pointer' : 'crosshair'),
id: 'lasso',
+ usesAltKey: true,
onDeactivate: (ctx, opts) => {
if (opts?.temporary) {
// A modifier-hold switch (space → view to pan mid-polygon) must not
@@ -194,6 +202,7 @@ export const createLassoTool = (): Tool => {
if (!session) {
session = {
+ closeArmed: false,
cursor: null,
kind: 'polygon',
lastPressAt: input.timeStamp,
@@ -227,6 +236,11 @@ export const createLassoTool = (): Tool => {
}
if (session.kind === 'polygon') {
session.cursor = { x: input.documentPoint.x, y: input.documentPoint.y };
+ const closeArmed = isOnFirstVertex(ctx, session, input.screenPoint);
+ if (closeArmed !== session.closeArmed) {
+ session.closeArmed = closeArmed;
+ ctx.updateCursor();
+ }
} else {
for (const sample of batch) {
pushDecimated(session.points, sample.documentPoint);
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
index 3953429653..5becc1d459 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.test.ts
@@ -121,7 +121,52 @@ describe('marqueeTool: drag → commit', () => {
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', () => {
+ it('shapes with a modifier pressed mid-drag without changing the op', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(40, 30, { shift: true }));
+ up(tool, h.ctx, pointer(40, 30, { shift: true }));
+
+ expect(h.commits[0]!.op).toBe('replace');
+ expect(h.commits[0]!.bounds).toEqual({ height: 30, width: 30, x: 10, y: 10 });
+ });
+
+ it('adds with shift held before the press, without constraining the rect', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ drag(tool, h.ctx, pointer(10, 10, { shift: true }), pointer(40, 30, { shift: true }));
+
+ expect(h.commits[0]!.op).toBe('add');
+ expect(h.commits[0]!.bounds).toEqual({ height: 20, width: 30, x: 10, y: 10 });
+ });
+
+ it('lets an op key released mid-drag shape the rect when pressed again', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ down(tool, h.ctx, pointer(10, 10, { shift: true }));
+ move(tool, h.ctx, pointer(20, 15));
+ move(tool, h.ctx, pointer(40, 30, { shift: true }));
+ up(tool, h.ctx, pointer(40, 30, { shift: true }));
+
+ expect(h.commits[0]!.op).toBe('add');
+ expect(h.commits[0]!.bounds).toEqual({ height: 30, width: 30, x: 10, y: 10 });
+ });
+
+ it('subtracts with alt held before the press, without drawing from the center', () => {
+ const h = createHarness();
+ const tool = createMarqueeTool();
+
+ drag(tool, h.ctx, pointer(10, 10, { alt: true }), pointer(40, 30, { alt: true }));
+
+ expect(h.commits[0]!.op).toBe('subtract');
+ expect(h.commits[0]!.bounds).toEqual({ height: 20, width: 30, x: 10, y: 10 });
+ });
+
+ it('resolves the boolean op from the modifiers held at the press', () => {
const cases: [{ shift?: boolean; alt?: boolean }, string][] = [
[{ shift: true }, 'add'],
[{ alt: true }, 'subtract'],
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts
index 7bd36c0d5c..a827d43952 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/marqueeTool.ts
@@ -44,6 +44,13 @@ interface GestureState {
startDoc: Vec2;
startScreen: Vec2;
moved: boolean;
+ /**
+ * Shift/alt held at the press pick the boolean op (add/subtract); the same
+ * keys pressed mid-drag shape the rect instead (square / from centre).
+ */
+ opModifiers: { shift: boolean; alt: boolean };
+ /** Op keys let go during the drag: pressing one again shapes like any mid-drag press. */
+ released: { shift: boolean; alt: boolean };
}
/** How the drag modifiers shape the rect. */
@@ -84,11 +91,19 @@ export const marqueeRect = (start: Vec2, end: Vec2, constraints: MarqueeConstrai
};
};
-/** 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,
-});
+/** The shaping constraints: a key still held since it chose the op at the press does not also shape. */
+const constraintsFor = (modifiers: { shift: boolean; alt: boolean }, state: GestureState): MarqueeConstraints => {
+ if (state.opModifiers.shift && !modifiers.shift) {
+ state.released.shift = true;
+ }
+ if (state.opModifiers.alt && !modifiers.alt) {
+ state.released.alt = true;
+ }
+ return {
+ fromCenter: modifiers.alt && (!state.opModifiers.alt || state.released.alt),
+ square: modifiers.shift && (!state.opModifiers.shift || state.released.shift),
+ };
+};
/** Creates a fresh marquee tool with its own gesture state. */
export const createMarqueeTool = (): Tool => {
@@ -106,6 +121,7 @@ export const createMarqueeTool = (): Tool => {
return {
cursor: () => 'crosshair',
id: 'marquee',
+ usesAltKey: true,
onDeactivate: (ctx) => {
end();
clearPreview(ctx);
@@ -124,7 +140,13 @@ export const createMarqueeTool = (): Tool => {
if (state || (input.buttons & PRIMARY_BUTTON) === 0 || !ctx.getDocument()) {
return;
}
- state = { moved: false, startDoc: input.documentPoint, startScreen: input.screenPoint };
+ state = {
+ moved: false,
+ opModifiers: { alt: input.modifiers.alt, shift: input.modifiers.shift },
+ released: { alt: false, shift: false },
+ startDoc: input.documentPoint,
+ startScreen: input.screenPoint,
+ };
},
onPointerMove: (ctx, input) => {
if (!state) {
@@ -138,7 +160,7 @@ export const createMarqueeTool = (): Tool => {
}
state.moved = true;
}
- const rect = marqueeRect(state.startDoc, input.documentPoint, constraintsFor(input.modifiers));
+ const rect = marqueeRect(state.startDoc, input.documentPoint, constraintsFor(input.modifiers, state));
ctx.stores.marqueePreview.set({ kind: ctx.stores.marqueeOptions.get().kind, rect });
ctx.invalidate({ overlay: true });
},
@@ -153,14 +175,14 @@ export const createMarqueeTool = (): Tool => {
if (!current.moved || !ctx.commitSelection) {
return;
}
- const rect = marqueeRect(current.startDoc, input.documentPoint, constraintsFor(input.modifiers));
+ const rect = marqueeRect(current.startDoc, input.documentPoint, constraintsFor(input.modifiers, current));
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);
+ const op = selectionOpFor(current.opModifiers, ctx.stores.marqueeOptions.get().mode);
ctx.commitSelection({
bounds: rect,
op,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index f45a720ef2..4012923bf8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -279,4 +279,9 @@ export interface Tool {
onWheel?(ctx: ToolContext, deltaY: number, screenAnchor: { x: number; y: number }, modifiers: PointerModifiers): void;
/** The CSS cursor to show while this tool is active. */
cursor?(ctx: ToolContext): string;
+ /**
+ * Alt is one of this tool's gesture modifiers (selection ops), so the pointer
+ * pipeline must not turn an alt-hold into the temporary color picker.
+ */
+ readonly usesAltKey?: boolean;
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx
index 7a335778cc..0032844a05 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx
@@ -15,7 +15,8 @@ import { SelectionActions } from './SelectionOptionsRow';
interface CapturedButton {
children?: ReactNode;
- disabled?: boolean;
+ /** The row disables through `aria-disabled` so the reason tooltip and keyboard focus keep working. */
+ 'aria-disabled'?: boolean;
}
const { activeProject, buttons, hasSelection } = vi.hoisted(() => ({
@@ -27,7 +28,7 @@ const { activeProject, buttons, hasSelection } = vi.hoisted(() => ({
vi.mock('@platform/ui/Button', () => ({
Button: (props: CapturedButton) => {
buttons.set(String(props.children), props);
- return <button disabled={props.disabled}>{props.children}</button>;
+ return <button aria-disabled={props['aria-disabled']}>{props.children}</button>;
},
}));
vi.mock('@workbench/widgets/canvas/engineStoreHooks', () => ({
@@ -47,6 +48,7 @@ const engine = {
fillSelection: vi.fn(),
invertSelection: vi.fn(),
liftSelectionToLayer: vi.fn(),
+ selectAll: vi.fn(),
},
} as unknown as CanvasEngine;
@@ -75,6 +77,14 @@ beforeEach(() => {
hasSelection.current = true;
});
+describe('SelectionActions select all', () => {
+ it('stays available with no selection and no eligible layer', () => {
+ hasSelection.current = false;
+ const captured = renderRow(createControlLayer('Control', 'control-1', 'sd-1', null));
+ expect(captured.get('widgets.canvas.toolOptions.selectAll')?.['aria-disabled']).toBe(false);
+ });
+});
+
describe('SelectionActions pixel target eligibility', () => {
const rasterPaint = createEmptyPaintLayer('Raster', 'raster');
const controlPaint = createControlLayer('Control', 'control');
@@ -91,21 +101,21 @@ describe('SelectionActions pixel target eligibility', () => {
{ disabled: true, layer: rasterImage, scenario: 'raster image' },
])('sets Fill and Erase disabled=$disabled for $scenario', ({ disabled, 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);
+ expect(rendered.get('widgets.canvas.toolOptions.fillSelection')?.['aria-disabled']).toBe(disabled);
+ expect(rendered.get('widgets.canvas.toolOptions.eraseSelection')?.['aria-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);
+ expect(rendered.get(`widgets.canvas.toolOptions.${key}`)?.['aria-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);
+ expect(rendered.get('widgets.canvas.toolOptions.invertSelection')?.['aria-disabled']).toBe(false);
+ expect(rendered.get('widgets.canvas.toolOptions.deselect')?.['aria-disabled']).toBe(false);
});
});
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
index 0e7e09ff01..ec3da93d5b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx
@@ -79,9 +79,38 @@ export const SelectionOpModeButtons = ({
};
/**
- * Commands over the live selection. Fill, erase and lift need an eligible
- * (unlocked, visible) paint layer — the same rule the engine enforces; invert
- * and deselect need only a selection.
+ * A selection command; while unavailable, its tooltip says what is missing
+ * instead of going quiet. The button is aria-disabled rather than natively
+ * disabled so it still emits the pointer events the tooltip needs and stays
+ * reachable by keyboard, where the reason reads as its description.
+ */
+const SelectionAction = ({
+ disabledReason,
+ label,
+ onClick,
+}: {
+ disabledReason: string | null;
+ label: string;
+ onClick: () => void;
+}) => {
+ const guarded = useCallback(() => {
+ if (disabledReason === null) {
+ onClick();
+ }
+ }, [disabledReason, onClick]);
+ return (
+ <Tooltip content={disabledReason ?? ''} disabled={disabledReason === null}>
+ <Button aria-disabled={disabledReason !== null} size="xs" variant="ghost" onClick={guarded}>
+ {label}
+ </Button>
+ </Tooltip>
+ );
+};
+
+/**
+ * Commands over the live selection. Select all always works; fill, erase and
+ * lift need an eligible (unlocked, visible) paint layer — the same rule the
+ * engine enforces; invert and deselect need only a selection.
*/
export const SelectionActions = ({ engine }: ToolFormProps) => {
const { t } = useTranslation();
@@ -90,29 +119,43 @@ export const SelectionActions = ({ engine }: ToolFormProps) => {
const { document } = project.canvas;
return isLeafPixelEditEligible(lookupDocumentLeaf(document, document.selectedLayerId ?? ''));
});
+ const onSelectAll = useCallback(() => engine.selection.selectAll(), [engine]);
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 onLiftToLayer = useCallback(() => engine.selection.liftSelectionToLayer(), [engine]);
- const canEdit = hasSelection && canPaintTarget;
+ const needsSelection = hasSelection ? null : t('widgets.canvas.toolOptions.selectionNeedsSelection');
+ const needsPaintTarget =
+ needsSelection ?? (canPaintTarget ? null : t('widgets.canvas.toolOptions.selectionNeedsPaintLayer'));
return (
<HStack flexWrap="wrap" 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={!canEdit} size="xs" variant="ghost" onClick={onLiftToLayer}>
- {t('widgets.canvas.toolOptions.liftSelectionToLayer')}
- </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>
+ <SelectionAction disabledReason={null} label={t('widgets.canvas.toolOptions.selectAll')} onClick={onSelectAll} />
+ <SelectionAction
+ disabledReason={needsPaintTarget}
+ label={t('widgets.canvas.toolOptions.fillSelection')}
+ onClick={onFill}
+ />
+ <SelectionAction
+ disabledReason={needsPaintTarget}
+ label={t('widgets.canvas.toolOptions.eraseSelection')}
+ onClick={onErase}
+ />
+ <SelectionAction
+ disabledReason={needsPaintTarget}
+ label={t('widgets.canvas.toolOptions.liftSelectionToLayer')}
+ onClick={onLiftToLayer}
+ />
+ <SelectionAction
+ disabledReason={needsSelection}
+ label={t('widgets.canvas.toolOptions.invertSelection')}
+ onClick={onInvert}
+ />
+ <SelectionAction
+ disabledReason={needsSelection}
+ label={t('widgets.canvas.toolOptions.deselect')}
+ onClick={onDeselect}
+ />
</HStack>
);
};