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(webv2): make layer-panel selection authoritative on canvas

joshistoast2dca9c56bcf1
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 0cb6c3c7f8..c8571c9567 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -288,7 +288,12 @@ export interface CanvasDiagnosticsSnapshot {
}
export interface CanvasEngineToolCapability extends CanvasToolCapability {
- contextMenuLayerIdAt(screenPoint: Vec2): string | null;
+ /**
+ * Whether the canvas context menu may act on a layer. The menu targets the
+ * document's SELECTED layer (never the layer under the pointer); this reports
+ * only whether an in-progress gesture/session should suppress it.
+ */
+ canTargetLayerFromContextMenu(): boolean;
handleEscapePriority(options: { gestureWasActive: boolean }): void;
onStrokeCommitted(listener: (event: StrokeCommittedEvent) => void): () => void;
setInteractionLocked(locked: boolean): void;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts
index 758a9f178c..ce0a2519ff 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.test.ts
@@ -90,9 +90,86 @@ const spyCallbacks = () => ({
onDocumentReplaced: vi.fn<DocumentMirrorCallbacks['onDocumentReplaced']>(),
onLayerOrderChanged: vi.fn<DocumentMirrorCallbacks['onLayerOrderChanged']>(),
onLayersChanged: vi.fn<DocumentMirrorCallbacks['onLayersChanged']>(),
+ onSelectionChanged: vi.fn<NonNullable<DocumentMirrorCallbacks['onSelectionChanged']>>(),
onStagingChanged: vi.fn<DocumentMirrorCallbacks['onStagingChanged']>(),
});
+describe('createDocumentMirror: selection changes', () => {
+ const withSelection = (doc: CanvasDocumentContractV2, selectedLayerId: string | null): CanvasDocumentContractV2 => ({
+ ...doc,
+ selectedLayerId,
+ });
+
+ it('reports a selection-only change without reporting a layer change', () => {
+ // A selection-only edit produces a new `document` object that reuses the
+ // `layers` array reference — none of the other callbacks can see it.
+ const a = rasterLayer('a');
+ const b = rasterLayer('b');
+ const doc = makeDoc([a, b], { selectedLayerId: 'a' });
+ const canvas = makeCanvas(doc);
+ const store = createFakeStore([{ canvas, id: 'p1' }]);
+ const callbacks = spyCallbacks();
+ createDocumentMirror(store, 'p1', callbacks);
+
+ const nextDoc = withSelection(doc, 'b');
+ expect(nextDoc.layers).toBe(doc.layers);
+ store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });
+
+ expect(callbacks.onSelectionChanged).toHaveBeenCalledTimes(1);
+ expect(callbacks.onSelectionChanged).toHaveBeenCalledWith('b');
+ expect(callbacks.onLayersChanged).not.toHaveBeenCalled();
+ expect(callbacks.onLayerOrderChanged).not.toHaveBeenCalled();
+ expect(callbacks.onDocumentReplaced).not.toHaveBeenCalled();
+ expect(callbacks.onBboxChanged).not.toHaveBeenCalled();
+ });
+
+ it('stays silent when a layer edit leaves the selection alone', () => {
+ const a = rasterLayer('a');
+ const doc = makeDoc([a], { selectedLayerId: 'a' });
+ const canvas = makeCanvas(doc);
+ const store = createFakeStore([{ canvas, id: 'p1' }]);
+ const callbacks = spyCallbacks();
+ createDocumentMirror(store, 'p1', callbacks);
+
+ const nextDoc: CanvasDocumentContractV2 = { ...doc, layers: [{ ...a, opacity: 0.5 }] };
+ store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });
+
+ expect(callbacks.onLayersChanged).toHaveBeenCalledTimes(1);
+ expect(callbacks.onSelectionChanged).not.toHaveBeenCalled();
+ });
+
+ it('reports the cleared selection when the selected layer is removed', () => {
+ const a = rasterLayer('a');
+ const b = rasterLayer('b');
+ const doc = makeDoc([a, b], { selectedLayerId: 'a' });
+ const canvas = makeCanvas(doc);
+ const store = createFakeStore([{ canvas, id: 'p1' }]);
+ const callbacks = spyCallbacks();
+ createDocumentMirror(store, 'p1', callbacks);
+
+ const nextDoc: CanvasDocumentContractV2 = { ...doc, layers: [b], selectedLayerId: 'b' };
+ store.setState({ projects: [{ canvas: { ...canvas, document: nextDoc }, id: 'p1' }] });
+
+ expect(callbacks.onLayersChanged).toHaveBeenCalledTimes(1);
+ expect(callbacks.onSelectionChanged).toHaveBeenCalledWith('b');
+ });
+
+ it('reports a selection change carried by a wholesale document replacement', () => {
+ const a = rasterLayer('a');
+ const doc = makeDoc([a], { selectedLayerId: 'a' });
+ const canvas = makeCanvas(doc);
+ const store = createFakeStore([{ canvas, id: 'p1' }]);
+ const callbacks = spyCallbacks();
+ createDocumentMirror(store, 'p1', callbacks);
+
+ const nextDoc = makeDoc([rasterLayer('z')], { selectedLayerId: 'z' });
+ store.setState({ projects: [{ canvas: makeCanvas(nextDoc, 1), id: 'p1' }] });
+
+ expect(callbacks.onDocumentReplaced).toHaveBeenCalledTimes(1);
+ expect(callbacks.onSelectionChanged).toHaveBeenCalledWith('z');
+ });
+});
+
describe('createDocumentMirror', () => {
it('synchronously refreshes from authoritative state when normal notification was interrupted', () => {
const a = rasterLayer('a');
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
index 214bcd3aee..6079c181cb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/documentMirror.ts
@@ -34,6 +34,15 @@ export interface DocumentMirrorCallbacks {
onBboxChanged(): void;
/** The staging area changed. */
onStagingChanged(): void;
+ /**
+ * The document's `selectedLayerId` changed. A selection-only edit produces a
+ * new `document` object with the SAME `layers` reference and an equal `bbox`,
+ * so none of the other callbacks fire for it — this is the only signal. The
+ * engine uses it to repaint selection-derived chrome (the move-tool outline,
+ * the transform frame) and to close out per-layer transient sessions, since
+ * the layer panel is the sole authority on which layer is active.
+ */
+ onSelectionChanged?(selectedLayerId: string | null): void;
}
/** The imperative mirror handle. */
@@ -160,6 +169,7 @@ export const createDocumentMirror = (
if (doc !== lastDoc) {
const prevDoc = lastDoc;
const prevRevision = lastRevision;
+ const prevSelectedLayerId = prevDoc?.selectedLayerId ?? null;
lastDoc = doc;
lastRevision = revision;
@@ -188,6 +198,13 @@ export const createDocumentMirror = (
callbacks.onBboxChanged();
}
}
+
+ // Fired last, so an observer that tears down per-layer transient state
+ // (transform session, floating selection) sees the reconciled layer set.
+ const selectedLayerId = doc?.selectedLayerId ?? null;
+ if (selectedLayerId !== prevSelectedLayerId) {
+ callbacks.onSelectionChanged?.(selectedLayerId);
+ }
}
if (staging !== lastStaging) {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index be9365a850..178dd52229 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -7247,7 +7247,7 @@ describe('move tool: drag through the pipeline', () => {
engine.lifecycle.dispose();
});
- it('a click (no drag) dispatches a selection change and no transform update', () => {
+ it('a click (no drag) dispatches nothing — the layers panel owns selection', () => {
const raf = createControllableRaf();
vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
@@ -7271,7 +7271,7 @@ describe('move tool: drag through the pipeline', () => {
const actions = dispatch.mock.calls.map((call) => call[0] as EngineTestAction);
expect(actions.some((action) => action.type === 'updateCanvasLayer')).toBe(false);
- expect(actions.some((action) => action.type === 'setCanvasSelectedLayer')).toBe(true);
+ expect(actions.some((action) => action.type === 'setCanvasSelectedLayer')).toBe(false);
expect(engine.stores.canUndo.get()).toBe(false);
engine.lifecycle.dispose();
@@ -15005,63 +15005,49 @@ describe('text edit session', () => {
});
});
-describe('contextMenuLayerIdAt (canvas right-click target)', () => {
- const controlLayer = (id: string): CanvasLayerContract => ({
- adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },
- blendMode: 'normal',
- id,
- isEnabled: true,
- isLocked: false,
- name: id,
- opacity: 1,
- source: { image: { height: 10, imageName: id, width: 10 }, type: 'image' },
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- type: 'control',
- withTransparencyEffect: false,
- });
-
- // A raster at index 0 with a control layer above it, both covering [0,10]². At
- // the default viewport (zoom 1, no pan) a screen point maps 1:1 to document space.
- const stackedDoc = (): CanvasDocumentContractV2 => ({
+describe('canTargetLayerFromContextMenu (canvas right-click target)', () => {
+ // The menu acts on the document's SELECTED layer — the canvas never hit-tests
+ // to pick one, so this only reports whether an in-progress edit suppresses it.
+ const doc = (): CanvasDocumentContractV2 => ({
background: 'transparent',
bbox: { height: 100, width: 100, x: 0, y: 0 },
height: 100,
- layers: [rasterLayer('raster'), controlLayer('control')],
- selectedLayerId: null,
+ layers: [rasterLayer('raster')],
+ selectedLayerId: 'raster',
version: 2,
width: 100,
});
- const makeEngine = (doc: CanvasDocumentContractV2) => {
- const { store } = createFakeStore(doc);
- const engine = createCanvasEngine({
+ const makeEngine = (document: CanvasDocumentContractV2) => {
+ const { store } = createFakeStore(document);
+ return createCanvasEngine({
backend: createTestStubRasterBackend(),
imageResolver: () => Promise.resolve(new Blob()),
projectId: 'p1',
store,
});
- return engine;
};
- it('returns the composite-top layer at the point (control over raster, batch finding N1)', () => {
- const engine = makeEngine(stackedDoc());
- // The raster is earlier in the array but the control composites above it.
- expect(engine.tools.contextMenuLayerIdAt({ x: 5, y: 5 })).toBe('control');
+ it('allows a layer target with a document and no in-progress edit', () => {
+ const engine = makeEngine(doc());
+ expect(engine.tools.canTargetLayerFromContextMenu()).toBe(true);
engine.lifecycle.dispose();
});
- it('returns null on empty space', () => {
- const engine = makeEngine(stackedDoc());
- expect(engine.tools.contextMenuLayerIdAt({ x: 60, y: 60 })).toBeNull();
- engine.lifecycle.dispose();
- });
-
- it('returns null while a text-edit session is open (never opens over an in-progress edit)', () => {
- const engine = makeEngine(stackedDoc());
+ it('refuses while a text-edit session is open (never opens over an in-progress edit)', () => {
+ const engine = makeEngine(doc());
engine.tools.setTool('text');
engine.layers.openTextCreate({ x: 5, y: 5 });
expect(engine.stores.textEditSession.get()).not.toBeNull();
- expect(engine.tools.contextMenuLayerIdAt({ x: 5, y: 5 })).toBeNull();
+ expect(engine.tools.canTargetLayerFromContextMenu()).toBe(false);
+ engine.lifecycle.dispose();
+ });
+
+ it('refuses while a transform session is open', () => {
+ const engine = makeEngine(doc());
+ engine.tools.setTool('transform');
+ expect(engine.stores.transformSession.get()).not.toBeNull();
+ expect(engine.tools.canTargetLayerFromContextMenu()).toBe(false);
engine.lifecycle.dispose();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 5f91a72eb5..0013dff12b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -161,7 +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 { hittableLayerRect, layerOutlineCorners, topLayerAt } from '@workbench/canvas-engine/tools/moveHitTest';
+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';
import { createSamTool } from '@workbench/canvas-engine/tools/samTool';
@@ -318,7 +318,7 @@ export interface CanvasEngineOptions {
}
export interface CanvasEngineToolCapability extends CanvasToolCapability {
- contextMenuLayerIdAt(screenPoint: Vec2): string | null;
+ canTargetLayerFromContextMenu(): boolean;
handleEscapePriority(options: { gestureWasActive: boolean }): void;
onStrokeCommitted(listener: (event: StrokeCommittedEvent) => void): () => void;
setInteractionLocked(locked: boolean): void;
@@ -2044,6 +2044,30 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
cleanup.run(() => scheduler.invalidate({ layers: ids }));
cleanup.throwIfFailed();
},
+ /**
+ * The layers panel is the sole authority on which layer is active, so a
+ * panel selection has to retarget the engine's per-layer transient state.
+ * Nothing here dispatches — this only reconciles engine-side state.
+ *
+ * A selection-only document change reuses the `layers` array reference and
+ * leaves the bbox equal, so none of the other callbacks fire for it: without
+ * this the move-tool outline and the transform frame would keep framing the
+ * previously selected layer until some unrelated edit invalidated the overlay.
+ */
+ onSelectionChanged: (selectedLayerId) => {
+ const cleanup = createCleanupAccumulator();
+ const session = stores.transformSession.get();
+ if (session && session.layerId !== selectedLayerId) {
+ // The open session belongs to the layer that was just deselected; drop
+ // its preview rather than leaving a frame on an inactive layer.
+ cleanup.run(() => cancelTransform());
+ if (selectedLayerId !== null && interactionController.getActiveToolId() === 'transform') {
+ cleanup.run(() => beginTransformSession(selectedLayerId));
+ }
+ }
+ cleanup.run(() => scheduler.invalidate({ overlay: true }));
+ cleanup.throwIfFailed();
+ },
onStagingChanged: () => scheduler.invalidate({ overlay: true }),
});
@@ -2779,30 +2803,19 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
});
};
- const contextMenuLayerIdAt = (screenPoint: Vec2): string | null => {
- // Never open the menu over an in-progress edit: a live paint/drag gesture, or
- // an open transform / text-edit session. Right-click during those belongs to
- // the interaction, not to picking a layer. Mirrors the mid-gesture guards on
- // merge/nudge/undo above.
- if (pipeline.isGestureActive() || stores.transformSession.get() || stores.textEditSession.get()) {
- return null;
- }
- const doc = mirror.getDocument();
- if (!doc) {
- return null;
- }
- // Same screen→document conversion and group-rank-consistent, live-cache-aware
- // hit-test the move tool uses for click-selection, so right-clicking a layer
- // targets exactly the layer a left-click there would select.
- const documentPoint = viewport.screenToDocument(screenPoint);
- const hit = topLayerAt(
- doc,
- documentPoint,
- (layer) => layer.isEnabled,
- (layerId) => layerCache.get(layerId)?.rect
- );
- return hit?.id ?? null;
- };
+ /**
+ * Whether the canvas context menu may target a layer at all. It never picks a
+ * layer by hit-testing — the menu acts on the document's selected layer, since
+ * the layers panel is the sole authority on which layer is active. This only
+ * suppresses the menu during an in-progress edit: a live paint/drag gesture, or
+ * an open transform / text-edit session. Right-click during those belongs to
+ * the interaction. Mirrors the mid-gesture guards on merge/nudge/undo above.
+ */
+ const canTargetLayerFromContextMenu = (): boolean =>
+ !pipeline.isGestureActive() &&
+ !stores.transformSession.get() &&
+ !stores.textEditSession.get() &&
+ mirror.getDocument() !== null;
const undo = (): void => historyController.undo();
const redo = (): void => historyController.redo();
@@ -3237,7 +3250,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
};
const toolsCapability: CanvasEngineToolCapability = {
...interactionController.tools,
- contextMenuLayerIdAt,
+ canTargetLayerFromContextMenu,
handleEscapePriority,
onStrokeCommitted,
setInteractionLocked,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts
index b4a2fad706..befd78715e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.test.ts
@@ -3,7 +3,7 @@ import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/c
import { estimateTextExtent } from '@workbench/canvas-engine/render/rasterizers/textRasterizer';
import { describe, expect, it } from 'vitest';
-import { hitTestLayer, hittableLayerSize, layerOutlineCorners, topLayerAt } from './moveHitTest';
+import { hitTestLayer, hittableLayerSize, layerOutlineCorners } from './moveHitTest';
const shapeLayer = (id: string, width: number, height: number): CanvasLayerContract => ({
blendMode: 'normal',
@@ -81,27 +81,6 @@ const imageLayer = (
type: 'raster',
});
-/** A control layer (composite group rank 1) backed by an image source. */
-const controlLayer = (id: string, opts: { width?: number; height?: number } = {}): CanvasLayerContract => ({
- adapter: {
- beginEndStepPct: [0, 1],
- controlMode: 'balanced',
- kind: 'controlnet',
- model: null,
- weight: 1,
- },
- blendMode: 'normal',
- id,
- isEnabled: true,
- isLocked: false,
- name: id,
- opacity: 1,
- source: { image: { height: opts.height ?? 20, imageName: id, width: opts.width ?? 20 }, type: 'image' },
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- type: 'control',
- withTransparencyEffect: false,
-});
-
const paintLayer = (
id: string,
bitmap?: { width: number; height: number; offset?: { x: number; y: number } }
@@ -228,65 +207,6 @@ describe('hitTestLayer', () => {
});
});
-describe('topLayerAt', () => {
- it('returns the top-most (index 0) layer that passes the predicate and contains the point', () => {
- const top = imageLayer('top', { width: 50, height: 50 });
- const bottom = imageLayer('bottom', { width: 50, height: 50 });
- const d = doc([top, bottom]);
- expect(topLayerAt(d, { x: 10, y: 10 }, () => true)?.id).toBe('top');
- });
-
- it('skips layers the predicate rejects (e.g. locked/hidden)', () => {
- const top = imageLayer('top', { width: 50, height: 50, isLocked: true });
- const bottom = imageLayer('bottom', { width: 50, height: 50 });
- const d = doc([top, bottom]);
- // Drag predicate rejects locked → falls through to the bottom layer.
- expect(topLayerAt(d, { x: 10, y: 10 }, (l) => !l.isLocked)?.id).toBe('bottom');
- });
-
- it('returns null on empty space', () => {
- const layer = imageLayer('a', { x: 0, y: 0, width: 10, height: 10 });
- expect(topLayerAt(doc([layer]), { x: 80, y: 80 }, () => true)).toBeNull();
- });
-});
-
-describe('topLayerAt: composite-group ordering (batch finding N1)', () => {
- // The compositor draws by group rank (raster < control < regional < inpaint
- // mask), NOT by raw array index, so the hit-test must agree: a layer in a higher
- // group wins the hit over a lower-group layer that sits EARLIER in the array.
- it('a control layer wins the hit over an overlapping raster placed earlier in the array', () => {
- const raster = imageLayer('raster'); // global index 0 — would win under naive array order
- const control = controlLayer('control'); // index 1, but composites above the raster
- const d = doc([raster, control]);
- expect(topLayerAt(d, { x: 10, y: 10 }, () => true)?.id).toBe('control');
- });
-
- it('an inpaint mask (top group) wins over control and raster below it', () => {
- const raster = imageLayer('raster');
- const control = controlLayer('control');
- const mask = maskLayer('mask', { width: 20, height: 20 });
- // Array order deliberately does NOT match composite order.
- const d = doc([raster, mask, control]);
- expect(topLayerAt(d, { x: 10, y: 10 }, () => true)?.id).toBe('mask');
- });
-
- it('within a group, array order still decides (index 0 is top-most within the group)', () => {
- const top = controlLayer('top');
- const bottom = controlLayer('bottom');
- const raster = imageLayer('raster');
- const d = doc([top, bottom, raster]);
- expect(topLayerAt(d, { x: 10, y: 10 }, () => true)?.id).toBe('top');
- });
-
- it('falls through to a lower group when the predicate rejects the higher one', () => {
- const raster = imageLayer('raster');
- const control = controlLayer('control');
- const d = doc([raster, control]);
- // e.g. move-tool auto-select excluding controls → the raster below is grabbed.
- expect(topLayerAt(d, { x: 10, y: 10 }, (l) => l.type === 'raster')?.id).toBe('raster');
- });
-});
-
describe('layerOutlineCorners', () => {
it('returns the four document-space corners of the rendered rect', () => {
const layer = imageLayer('a', { x: 5, y: 5, width: 10, height: 10 });
@@ -328,15 +248,6 @@ describe('live cache rect (freshly-painted, not-yet-flushed content)', () => {
expect(hitTestLayer(layer, doc([layer]), { x: 5, y: 5 }, liveRect)).toBe(false);
});
- it('topLayerAt uses the liveRectOf resolver to grab unflushed content', () => {
- const layer = paintLayer('p');
- const d = doc([layer]);
- const liveRectOf = (id: string) => (id === 'p' ? { height: 40, width: 40, x: 20, y: 20 } : undefined);
- expect(topLayerAt(d, { x: 30, y: 30 }, () => true, liveRectOf)?.id).toBe('p');
- // Without the resolver the empty layer is ungrabbable.
- expect(topLayerAt(d, { x: 30, y: 30 }, () => true)).toBeNull();
- });
-
it('unions the live rect with persisted content (both contribute to the hit area)', () => {
const layer = paintLayer('p', { width: 10, height: 10 }); // persisted content [0,0,10,10]
const liveRect = { height: 10, width: 10, x: 40, y: 40 }; // grown region off to the side
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
index e10f36d1e9..883c88373a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveHitTest.ts
@@ -13,8 +13,13 @@
* (CANVAS_PLAN Phase 5: "param for parametric"), and MASK layers (inpaint /
* regional) by their alpha bitmap's content rect (legacy allows moving masks).
* An EMPTY layer (a brand-new / cleared paint or mask layer with no pixels)
- * returns `null`/`false` rather than throwing, so the move/transform tools can
- * scan a mixed stack safely.
+ * returns `null`/`false` rather than throwing, so callers can probe a mixed
+ * stack safely.
+ *
+ * There is deliberately no "top-most layer under the point" query here: the
+ * layers panel is the sole authority on which layer is active, so no tool picks
+ * a target by hit-testing the stack. These helpers answer "where is THIS layer",
+ * which is what the move outline and the transform frame need.
*
* Zero React, zero import-time side effects.
*/
@@ -26,25 +31,12 @@ import type {
} from '@workbench/canvas-engine/contracts';
import type { Rect, Vec2 } from '@workbench/canvas-engine/types';
-import {
- getSourceContentRect,
- LAYER_GROUP_COUNT,
- layerGroupRank,
- renderableSourceOf,
-} from '@workbench/canvas-engine/document/sources';
+import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';
import { applyToPoint, fromTRS, invert } from '@workbench/canvas-engine/math/mat2d';
import { isEmpty, union } from '@workbench/canvas-engine/math/rect';
type LayerTransform = CanvasLayerBaseContract['transform'];
-/**
- * Resolves a layer's LIVE cache rect (layer-local), or `undefined`. Threaded from
- * the engine so hit-testing covers freshly-painted content the debounced bitmap
- * flush hasn't yet written back to the persisted contract — mirrors how
- * `invertMask` unions the live cache rect. A pure caller (no engine) omits it.
- */
-export type LiveCacheRectOf = (layerId: string) => Rect | undefined;
-
/**
* A hit-testable layer's content rectangle in its LOCAL (untransformed) space —
* including its (possibly off-zero) origin for content-sized paint/mask layers —
@@ -111,38 +103,6 @@ export const hitTestLayer = (
return local.x >= rect.x && local.x <= rect.x + rect.width && local.y >= rect.y && local.y <= rect.y + rect.height;
};
-/**
- * The top-most layer that both satisfies `predicate` and contains `point`, or
- * `null`. "Top-most" follows the COMPOSITE order, not the raw array order: layers
- * are visited by group rank high→low (inpaint mask > regional guidance > control >
- * raster — see {@link layerGroupRank}), and WITHIN a group by array order (index 0
- * is top-most within its group). This matches what the compositor draws, so a
- * control layer painted visually over a raster wins the hit even when the raster
- * sits at a lower global index — keeping the move-tool auto-select and the canvas
- * context-menu target consistent with the pixels on screen (batch finding N1). The
- * predicate lets callers require visible/unlocked; `liveRectOf` (optional) supplies
- * each layer's live cache rect so freshly-painted, not-yet-flushed content is
- * hit-testable.
- */
-export const topLayerAt = (
- doc: CanvasDocumentContractV2,
- point: Vec2,
- predicate: (layer: CanvasLayerContract) => boolean,
- liveRectOf?: LiveCacheRectOf
-): CanvasLayerContract | null => {
- for (let rank = LAYER_GROUP_COUNT - 1; rank >= 0; rank--) {
- for (const layer of doc.layers) {
- if (layerGroupRank(layer) !== rank) {
- continue;
- }
- if (predicate(layer) && hitTestLayer(layer, doc, point, liveRectOf?.(layer.id))) {
- return layer;
- }
- }
- }
- return null;
-};
-
/**
* The four document-space corners of a layer's rendered rectangle (for the move
* overlay outline), or `null` when the layer has no hit-testable bounds.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
index 8dd5124224..55a19998c7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
@@ -122,8 +122,8 @@ describe('constrainDelta', () => {
});
});
-describe('move tool: click selection', () => {
- it('selects the top-most visible layer under the point (one dispatch, no commit)', () => {
+describe('move tool: the layers panel owns selection', () => {
+ it('does not select the layer under the pointer on click', () => {
const doc = makeDoc(
[imageLayer('top', { width: 50, height: 50 }), imageLayer('bottom', { width: 50, height: 50 })],
null
@@ -135,10 +135,10 @@ describe('move tool: click selection', () => {
up(tool, h.ctx, pointer(10, 10));
expect(h.commits).toHaveLength(0);
- expect(h.dispatched).toEqual([{ id: 'top', type: 'setCanvasSelectedLayer' }]);
+ expect(h.dispatched).toHaveLength(0);
});
- it('clears the selection when clicking empty space', () => {
+ it('does not clear the selection when clicking empty space', () => {
const doc = makeDoc([imageLayer('a', { width: 10, height: 10 })], 'a');
const h = createHarness(doc);
const tool = createMoveTool();
@@ -146,30 +146,23 @@ describe('move tool: click selection', () => {
down(tool, h.ctx, pointer(80, 80));
up(tool, h.ctx, pointer(80, 80));
- expect(h.dispatched).toEqual([{ id: null, type: 'setCanvasSelectedLayer' }]);
- });
-
- it('can click-select a locked layer', () => {
- const doc = makeDoc([imageLayer('locked', { width: 50, height: 50, isLocked: true })], null);
- const h = createHarness(doc);
- const tool = createMoveTool();
-
- down(tool, h.ctx, pointer(10, 10));
- up(tool, h.ctx, pointer(10, 10));
-
- expect(h.dispatched).toEqual([{ id: 'locked', type: 'setCanvasSelectedLayer' }]);
+ expect(h.dispatched).toHaveLength(0);
});
- it('does not click-select a hidden layer', () => {
- const doc = makeDoc([imageLayer('hidden', { width: 50, height: 50, isEnabled: false })], null);
+ it('does not steal the selection when pressing another layer above the selected one', () => {
+ // The exact complaint this contract exists to fix: 'bottom' is selected in
+ // the panel and 'top' covers the press point.
+ const doc = makeDoc(
+ [imageLayer('top', { width: 50, height: 50 }), imageLayer('bottom', { width: 50, height: 50 })],
+ 'bottom'
+ );
const h = createHarness(doc);
const tool = createMoveTool();
down(tool, h.ctx, pointer(10, 10));
up(tool, h.ctx, pointer(10, 10));
- // Hidden layer is not hit → empty-space clear.
- expect(h.dispatched).toEqual([{ id: null, type: 'setCanvasSelectedLayer' }]);
+ expect(h.dispatched).toHaveLength(0);
});
});
@@ -222,7 +215,9 @@ describe('move tool: drag', () => {
});
});
- it('auto-selects the pressed unlocked layer before committing the move', () => {
+ it('moves the SELECTED layer even when another layer covers the press point', () => {
+ // 'top' is composited over the press point, but 'bottom' is what the panel
+ // selected — the panel wins, and no selection dispatch is emitted.
const doc = makeDoc(
[imageLayer('top', { width: 50, height: 50 }), imageLayer('bottom', { width: 50, height: 50 })],
'bottom'
@@ -234,10 +229,9 @@ describe('move tool: drag', () => {
move(tool, h.ctx, pointer(30, 10));
up(tool, h.ctx, pointer(30, 10));
- // Selection switched to the pressed layer, then the move committed on it.
- expect(h.dispatched).toEqual([{ id: 'top', type: 'setCanvasSelectedLayer' }]);
+ expect(h.dispatched).toHaveLength(0);
expect(h.commits).toHaveLength(1);
- expect(h.commits[0]!.forward).toMatchObject({ id: 'top' });
+ expect(h.commits[0]!.forward).toMatchObject({ id: 'bottom' });
});
it('moves the selected layer when the press lands on empty space', () => {
@@ -258,8 +252,8 @@ describe('move tool: drag', () => {
});
});
- it('does not drag a locked layer (auto-select finds nothing, no selected fallback)', () => {
- const doc = makeDoc([imageLayer('locked', { width: 50, height: 50, isLocked: true })], null);
+ it('does not drag a locked selected layer', () => {
+ const doc = makeDoc([imageLayer('locked', { width: 50, height: 50, isLocked: true })], 'locked');
const h = createHarness(doc);
const tool = createMoveTool();
@@ -298,7 +292,21 @@ describe('move tool: drag', () => {
up(tool, h.ctx, pointer(11, 11));
expect(h.commits).toHaveLength(0);
- expect(h.dispatched).toEqual([{ id: 'a', type: 'setCanvasSelectedLayer' }]);
+ expect(h.dispatched).toHaveLength(0);
+ });
+
+ it('commits nothing on a zero-delta drag, only clearing the preview', () => {
+ const doc = makeDoc([imageLayer('a', { width: 50, height: 50 })], 'a');
+ const h = createHarness(doc);
+ const tool = createMoveTool();
+
+ down(tool, h.ctx, pointer(10, 10));
+ move(tool, h.ctx, pointer(20, 20)); // past the threshold
+ up(tool, h.ctx, pointer(10, 10)); // ...and back to the origin
+
+ expect(h.commits).toHaveLength(0);
+ expect(h.dispatched).toHaveLength(0);
+ expect(h.overrides.at(-1)).toEqual({ layerId: 'a', override: null });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
index e7ce55c4c7..1d5ff8dec1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.ts
@@ -1,20 +1,21 @@
/**
- * The move tool: click to select the top-most layer under the cursor, drag to
- * move a layer (auto-selecting the pressed unlocked layer, photo-editor style).
+ * The move tool: drag to move the SELECTED layer.
*
- * Interaction contract (see CANVAS_PLAN Phase 3):
- * - **Click** (press+release under the drag threshold): selects the top-most
- * VISIBLE layer whose rendered bounds contain the point (locked layers may be
- * click-selected); empty space clears the selection. One `setCanvasSelectedLayer`
- * dispatch, no history entry.
- * - **Drag**: moves a layer. The pressed point's top-most enabled+unlocked layer
- * becomes the target (auto-select); otherwise the currently-selected
- * enabled+unlocked layer is moved. Hidden/locked layers are never dragged.
+ * Interaction contract:
+ * - **The layers panel is the sole authority on which layer is active.** The move
+ * tool never hit-tests the stack to pick a target and never dispatches
+ * `setCanvasSelectedLayer`. Clicking canvas pixels that belong to some other
+ * layer does not steal the selection, and clicking empty space does not clear
+ * it — an editor where the pointer silently re-targets is the behaviour this
+ * contract exists to prevent.
+ * - **Click** (press+release under the drag threshold): a no-op.
+ * - **Drag**: moves the document's `selectedLayerId`, when that layer is enabled
+ * and unlocked. Hidden/locked layers are never dragged, and a press over empty
+ * space still drags the selected layer (the grab point is irrelevant).
* `shift` constrains motion to the dominant axis. Pointer-move only sets a
* transient transform override (live preview) — it never dispatches.
* - **Commit** (pointer-up after a real move): one `commitStructural` with the
- * new/old transform x/y (plus a selection dispatch when the target wasn't
- * already selected). A zero-delta drag commits nothing.
+ * new/old transform x/y. A zero-delta drag commits nothing.
* - **Cancel** (Esc / pointercancel): drops the override, no dispatch.
*
* Zero React, zero import-time side effects.
@@ -25,26 +26,12 @@ import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
import type { Tool, ToolContext } from './tool';
-import { type LiveCacheRectOf, topLayerAt } from './moveHitTest';
-
/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */
const PRIMARY_BUTTON = 1;
-/**
- * A live-cache-rect resolver over the tool's layer cache, so hit-testing grabs
- * freshly-painted content the debounced bitmap flush hasn't yet written back to
- * the persisted contract (a new layer + stroke is otherwise ungrabbable until the
- * ~1.5s flush lands).
- */
-const liveRectOf =
- (ctx: ToolContext): LiveCacheRectOf =>
- (layerId) =>
- ctx.layers.get(layerId)?.rect;
-
/** Screen-space distance (CSS px) the pointer must travel before a press becomes a drag. */
export const MOVE_DRAG_THRESHOLD_PX = 3;
-const isVisible = (layer: CanvasLayerContract): boolean => layer.isEnabled;
const isDraggable = (layer: CanvasLayerContract): boolean => layer.isEnabled && !layer.isLocked;
/** Applies the shift-to-dominant-axis constraint to a document-space delta. */
@@ -58,14 +45,10 @@ export const constrainDelta = (dx: number, dy: number, shift: boolean): Vec2 =>
interface GestureState {
startDoc: Vec2;
startScreen: Vec2;
- /** The layer being dragged (null when the press had nothing to move). */
+ /** The layer being dragged (null when the selected layer isn't movable). */
targetId: string | null;
/** The drag target's original transform x/y. */
origin: { x: number; y: number } | null;
- /** The top-most visible layer under the press, for click selection (lock allowed). */
- clickTargetId: string | null;
- /** The document's selected layer at press time. */
- selectedAtStart: string | null;
moved: boolean;
}
@@ -83,18 +66,14 @@ export const createMoveTool = (): Tool => {
state = null;
};
- const resolveDragTarget = (ctx: ToolContext, point: Vec2, selectedId: string | null): CanvasLayerContract | null => {
+ /**
+ * The drag target is the document's selected layer, and nothing else — the
+ * press point plays no part in choosing it.
+ */
+ const resolveDragTarget = (ctx: ToolContext): CanvasLayerContract | null => {
const doc = ctx.getDocument();
- if (!doc) {
- return null;
- }
- // Auto-select: the pressed point's top-most enabled+unlocked layer wins.
- const hit = topLayerAt(doc, point, isDraggable, liveRectOf(ctx));
- if (hit) {
- return hit;
- }
- // Otherwise fall back to moving the currently-selected layer (if movable).
- const selected = selectedId ? doc.layers.find((layer) => layer.id === selectedId) : undefined;
+ const selectedId = doc?.selectedLayerId;
+ const selected = doc && selectedId ? doc.layers.find((layer) => layer.id === selectedId) : undefined;
return selected && isDraggable(selected) ? selected : null;
};
@@ -130,13 +109,10 @@ export const createMoveTool = (): Tool => {
if (!doc) {
return;
}
- const clickTarget = topLayerAt(doc, input.documentPoint, isVisible, liveRectOf(ctx));
- const dragTarget = resolveDragTarget(ctx, input.documentPoint, doc.selectedLayerId);
+ const dragTarget = resolveDragTarget(ctx);
state = {
- clickTargetId: clickTarget?.id ?? null,
moved: false,
origin: dragTarget ? { x: dragTarget.transform.x, y: dragTarget.transform.y } : null,
- selectedAtStart: doc.selectedLayerId,
startDoc: input.documentPoint,
startScreen: input.screenPoint,
targetId: dragTarget?.id ?? null,
@@ -164,13 +140,12 @@ export const createMoveTool = (): Tool => {
endGesture();
if (!current.moved) {
- // A click: select the top-most visible layer, or clear on empty space.
- ctx.dispatch({ id: current.clickTargetId, type: 'setCanvasSelectedLayer' });
+ // A click never re-targets the layer selection — that is the panel's job.
return;
}
if (!current.targetId || !current.origin) {
- // Dragged over empty space with nothing to move — no-op.
+ // No movable layer is selected — nothing to commit.
return;
}
@@ -182,16 +157,11 @@ export const createMoveTool = (): Tool => {
const next = { x: current.origin.x + delta.x, y: current.origin.y + delta.y };
if (next.x === current.origin.x && next.y === current.origin.y) {
- // Zero-delta drag: behave like a click-select of the target, no commit.
+ // Zero-delta drag: drop the preview, commit nothing.
ctx.setLayerTransformOverride(current.targetId, null);
- ctx.dispatch({ id: current.targetId, type: 'setCanvasSelectedLayer' });
return;
}
- // Auto-select the dragged layer if it wasn't already selected (no history).
- if (current.targetId !== current.selectedAtStart) {
- ctx.dispatch({ id: current.targetId, type: 'setCanvasSelectedLayer' });
- }
ctx.commitStructural(
'Move layer',
{ id: current.targetId, patch: { transform: { x: next.x, y: next.y } }, type: 'updateCanvasLayer' },
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
index 7ccbd8a3cb..f4bc0ee051 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
@@ -199,14 +199,36 @@ describe('transform tool: session lifecycle', () => {
expect(h.session()).toBeNull();
});
- it('clicking a layer with no session starts a session (move gesture)', () => {
- const doc = makeDoc([imageLayer('a', { width: 100, height: 100 })], null);
+ it('pressing with no session opens one on the SELECTED layer (move gesture)', () => {
+ const doc = makeDoc([imageLayer('a', { width: 100, height: 100 })], 'a');
const h = createHarness(doc);
const tool = createTransformTool();
down(tool, h.ctx, pointer(50, 50));
expect(h.session()?.layerId).toBe('a');
});
+
+ it('opens no session when nothing is selected, however the press lands', () => {
+ const doc = makeDoc([imageLayer('a', { width: 100, height: 100 })], null);
+ const h = createHarness(doc);
+ const tool = createTransformTool();
+
+ down(tool, h.ctx, pointer(50, 50));
+ expect(h.session()).toBeNull();
+ });
+
+ it('does not adopt the layer under the pointer over the selected one', () => {
+ // 'top' covers the press point; 'bottom' is what the panel selected.
+ const doc = makeDoc(
+ [imageLayer('top', { width: 100, height: 100 }), imageLayer('bottom', { width: 100, height: 100 })],
+ 'bottom'
+ );
+ const h = createHarness(doc);
+ const tool = createTransformTool();
+
+ down(tool, h.ctx, pointer(50, 50));
+ expect(h.session()?.layerId).toBe('bottom');
+ });
});
describe('transform tool: gestures', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
index fb2f8c138f..7cb7ba962e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.ts
@@ -2,8 +2,10 @@
* The transform tool: an interactive scale/rotate/move SESSION on a single layer.
*
* Interaction contract (CANVAS_PLAN Phase 5):
- * - **Session**: selecting the tool with an eligible layer selected (or clicking a
- * layer) captures its committed transform and opens a session. The live preview
+ * - **Session**: selecting the tool with an eligible layer selected (or pressing
+ * the canvas with no session open) captures the SELECTED layer's committed
+ * transform and opens a session on it. A press never re-targets which layer is
+ * active — that is the layers panel's job. The live preview
* flows through the engine's transform-override channel; a `transformSession`
* store exposes the layer id + live transform so the numeric options bar can
* render and edit it. The session survives multiple gestures — drag handles,
@@ -42,7 +44,7 @@ import {
import type { Tool, ToolContext } from './tool';
-import { hittableLayerRect, topLayerAt } from './moveHitTest';
+import { hittableLayerRect } from './moveHitTest';
/** Bit for the primary (usually left) mouse button in `PointerEvent.buttons`. */
const PRIMARY_BUTTON = 1;
@@ -238,25 +240,30 @@ export const createTransformTool = (): Tool => {
}
}
- // 2) No session, or a press off the session frame: adopt the top-most eligible
- // layer under the pointer and start a move gesture on it. Empty space is a
- // no-op (the current session, if any, persists).
- const hit = topLayerAt(doc, input.documentPoint, (layer) => isEligible(layer, doc));
- if (!hit) {
+ // 2) No session yet: open one on the SELECTED layer (the layers panel is the
+ // sole authority on which layer is active — a press never re-targets it)
+ // and start a move gesture. A press off an existing session's frame is a
+ // no-op; the session persists.
+ if (session) {
+ return;
+ }
+ const selectedId = doc.selectedLayerId;
+ const selected = selectedId ? doc.layers.find((layer) => layer.id === selectedId) : undefined;
+ if (!selected || !isEligible(selected, doc)) {
return;
}
- const rect = hittableLayerRect(hit, doc);
+ const rect = hittableLayerRect(selected, doc);
if (!rect) {
return;
}
- ctx.beginTransformSession?.(hit.id);
+ ctx.beginTransformSession?.(selected.id);
gesture = {
cursor: 'move',
moved: false,
rect,
startPointerDoc: input.documentPoint,
startScreen: input.screenPoint,
- startTransform: hit.transform,
+ startTransform: selected.transform,
target: { kind: 'move' },
};
},
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 45a31ddfa7..38c7bbae12 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -173,26 +173,24 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
(event: ReactMouseEvent<HTMLDivElement>) => {
// Keep the native menu inside inline editors (the text tool's contenteditable
// overlay), consistent with the surface-focus INLINE_EDIT_SELECTOR.
- const rect = event.currentTarget.getBoundingClientRect();
+ //
+ // The menu targets the SELECTED layer, not the layer under the pointer, and
+ // never dispatches a selection — the layers panel is the sole authority on
+ // which layer is active.
const resolution = resolveCanvasContextMenu({
clientX: event.clientX,
clientY: event.clientY,
- hitTest: engine ? (point) => engine.tools.contextMenuLayerIdAt(point) : undefined,
isInlineEditor: event.target instanceof Element && !!event.target.closest(INLINE_EDIT_SELECTOR),
isInteractionLocked,
- surfaceLeft: rect.left,
- surfaceTop: rect.top,
+ selectedLayerId: engine?.tools.canTargetLayerFromContextMenu() ? canvas.document.selectedLayerId : null,
});
if (!resolution.preventDefault) {
return;
}
event.preventDefault();
- if (resolution.target?.layerId) {
- canvasDispatch({ id: resolution.target.layerId, type: 'setCanvasSelectedLayer' });
- }
setContextMenuTarget(resolution.target);
},
- [canvasDispatch, engine, isInteractionLocked]
+ [canvas.document.selectedLayerId, engine, isInteractionLocked]
);
const handleCanvasImageDrop = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
index a27b159dec..8937eb3db3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
@@ -1,4 +1,4 @@
-import { describe, expect, it, vi } from 'vitest';
+import { describe, expect, it } from 'vitest';
import { resolveCanvasContextMenu, resolveCanvasContextMenuBranch } from './canvasContextMenu';
@@ -7,49 +7,55 @@ const baseOptions = {
clientY: 160,
isInlineEditor: false,
isInteractionLocked: false,
- surfaceLeft: 40,
- surfaceTop: 20,
};
describe('resolveCanvasContextMenu', () => {
it('leaves inline editors to the native context menu', () => {
- const hitTest = vi.fn(() => 'layer-1');
-
- expect(resolveCanvasContextMenu({ ...baseOptions, hitTest, isInlineEditor: true })).toEqual({
+ expect(resolveCanvasContextMenu({ ...baseOptions, isInlineEditor: true, selectedLayerId: 'layer-1' })).toEqual({
preventDefault: false,
target: null,
});
- expect(hitTest).not.toHaveBeenCalled();
});
- it('opens the global menu without hit-testing while interaction is locked', () => {
- const hitTest = vi.fn(() => 'layer-1');
+ it('opens the global menu while interaction is locked, ignoring the selected layer', () => {
+ expect(resolveCanvasContextMenu({ ...baseOptions, isInteractionLocked: true, selectedLayerId: 'layer-1' })).toEqual(
+ {
+ preventDefault: true,
+ target: { layerId: null, x: 240, y: 160 },
+ }
+ );
+ });
- expect(resolveCanvasContextMenu({ ...baseOptions, hitTest, isInteractionLocked: true })).toEqual({
+ it('opens the layer menu at the pointer for the SELECTED layer', () => {
+ expect(resolveCanvasContextMenu({ ...baseOptions, selectedLayerId: 'layer-1' })).toEqual({
preventDefault: true,
- target: { layerId: null, x: 240, y: 160 },
+ target: { layerId: 'layer-1', x: 240, y: 160 },
});
- expect(hitTest).not.toHaveBeenCalled();
});
- it('opens the layer menu at the pointer for a hit layer', () => {
- const hitTest = vi.fn(() => 'layer-1');
-
- expect(resolveCanvasContextMenu({ ...baseOptions, hitTest })).toEqual({
- preventDefault: true,
- target: { layerId: 'layer-1', x: 240, y: 160 },
+ it('targets the selected layer regardless of where the pointer is', () => {
+ // The canvas never hit-tests for the menu: the layers panel is the sole
+ // authority on which layer is active, so the pointer position is irrelevant.
+ const overOneCorner = resolveCanvasContextMenu({ ...baseOptions, selectedLayerId: 'layer-7' });
+ const overAnother = resolveCanvasContextMenu({
+ ...baseOptions,
+ clientX: 900,
+ clientY: 900,
+ selectedLayerId: 'layer-7',
});
- expect(hitTest).toHaveBeenCalledWith({ x: 200, y: 140 });
+
+ expect(overOneCorner.target?.layerId).toBe('layer-7');
+ expect(overAnother.target?.layerId).toBe('layer-7');
});
- it('opens the global menu when the pointer is over empty canvas', () => {
- expect(resolveCanvasContextMenu({ ...baseOptions, hitTest: () => null })).toEqual({
+ it('opens the global menu when no layer is selected', () => {
+ expect(resolveCanvasContextMenu({ ...baseOptions, selectedLayerId: null })).toEqual({
preventDefault: true,
target: { layerId: null, x: 240, y: 160 },
});
});
- it('opens the global menu without a hit-test when the engine is unavailable', () => {
+ it('opens the global menu without a target when the engine is unavailable', () => {
const resolution = resolveCanvasContextMenu(baseOptions);
expect(resolution).toEqual({
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
index 707ce0e60f..25f15e7c86 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
@@ -7,11 +7,15 @@ export interface CanvasContextMenuTarget {
interface ResolveCanvasContextMenuOptions {
clientX: number;
clientY: number;
- hitTest?: (point: { x: number; y: number }) => string | null;
+ /**
+ * The document's selected layer — the menu's target. The canvas deliberately
+ * does NOT hit-test the pixel under the pointer: the layers panel is the sole
+ * authority on which layer is active, so right-clicking a layer's pixels must
+ * not silently re-target the menu (or the selection) to it.
+ */
+ selectedLayerId?: string | null;
isInlineEditor: boolean;
isInteractionLocked: boolean;
- surfaceLeft: number;
- surfaceTop: number;
}
interface CanvasContextMenuResolution {
@@ -35,19 +39,16 @@ export const resolveCanvasContextMenuBranch = (
export const resolveCanvasContextMenu = ({
clientX,
clientY,
- hitTest,
isInlineEditor,
isInteractionLocked,
- surfaceLeft,
- surfaceTop,
+ selectedLayerId,
}: ResolveCanvasContextMenuOptions): CanvasContextMenuResolution => {
if (isInlineEditor) {
return { preventDefault: false, target: null };
}
- const layerId = isInteractionLocked
- ? null
- : (hitTest?.({ x: clientX - surfaceLeft, y: clientY - surfaceTop }) ?? null);
+ // A locked surface offers only the global menu — there is nothing to act on.
+ const layerId = isInteractionLocked ? null : (selectedLayerId ?? null);
return {
preventDefault: true,