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): enable merge down shortcut in layers (#10150)

Valeri Che89aaeff8c65f
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index a35120dea0..27ce98b236 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -18,8 +18,10 @@ import {
import { publishLayerPanelSelection } from '@workbench/layerPanelState';
import {
CANVAS_HISTORY_HOTKEYS,
+ CANVAS_MERGE_DOWN_HOTKEY,
executeCanvasToolCommand,
isCanvasToolCommand,
+ mergeSelectedLayerDown,
type CanvasToolCommandContext,
type HotkeyTableEntry,
} from '@workbench/widgets/canvas/canvasToolCommands';
@@ -36,7 +38,6 @@ import {
removeFromGroup,
ungroupLayers,
} from '@workbench/widgets/layers/layerGroupCommands';
-import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
/** Keys that act only while the Canvas itself holds focus; rows and fields own them elsewhere. */
export const CANVAS_ONLY_HOTKEYS = [
@@ -69,7 +70,7 @@ export const CANVAS_ONLY_HOTKEYS = [
['canvas.duplicateLayer', 'widgets.canvas.commands.duplicateLayer', ['mod+j']],
['canvas.groupLayers', 'widgets.canvas.commands.groupLayers', ['mod+g']],
['canvas.ungroupLayers', 'widgets.canvas.commands.ungroupLayers', ['mod+shift+g']],
- ['canvas.mergeDown', 'widgets.canvas.commands.mergeDown', ['mod+e']],
+ CANVAS_MERGE_DOWN_HOTKEY,
['canvas.layerForward', 'widgets.canvas.commands.layerForward', ['mod+]']],
['canvas.layerBackward', 'widgets.canvas.commands.layerBackward', ['mod+[']],
['canvas.layerToFront', 'widgets.canvas.commands.layerToFront', ['mod+shift+]']],
@@ -323,16 +324,6 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
);
}
} else if (commandId === 'canvas.mergeDown') {
- // Share canMergeLayerDown with the layer menu so shortcuts respect identical eligibility.
- if (engine && selectedLayer && canMergeLayerDown(document, selectedLayer.id, true)) {
- void engine.layers.mergeLayerDown(selectedLayer.id).then(
- (result) => {
- if (result !== 'merged') {
- ctx.reportLayerOperation(result);
- }
- },
- () => ctx.reportLayerOperation('failed')
- );
- }
+ mergeSelectedLayerDown(engine, document, ctx.reportLayerOperation);
}
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
index af7041a6eb..62b041eb2d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
@@ -1,11 +1,40 @@
-import type { BeginTransformResult, CanvasEngine } from '@workbench/canvas-engine/api';
+import type {
+ AdjustmentRefusal,
+ BeginTransformResult,
+ CanvasDocumentContractV3,
+ CanvasEngine,
+ LayerUnreadable,
+} from '@workbench/canvas-engine/api';
import type { TFunction } from 'i18next';
-import { reportLayerOperation } from '@workbench/widgets/canvas/useStructuralCommit';
+import { mergeDownEligibility } from '@workbench/canvas-engine/api';
+import { reportLayerOperation, type LayerOperationRefusal } from '@workbench/widgets/canvas/useStructuralCommit';
/** One hotkey row: its command id, title key and default keys. */
export type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];
+/** The same layer operation is available from the Canvas and the Layers widget. */
+export const CANVAS_MERGE_DOWN_HOTKEY = ['canvas.mergeDown', 'widgets.canvas.commands.mergeDown', ['mod+e']] as const;
+
+export const mergeSelectedLayerDown = (
+ engine: Pick<CanvasEngine, 'layers'> | null,
+ document: CanvasDocumentContractV3,
+ report: (refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable) => void
+): void => {
+ const id = document.selectedLayerId;
+ if (!engine || !id || mergeDownEligibility(document, id).status !== 'eligible') {
+ return;
+ }
+ void engine.layers.mergeLayerDown(id).then(
+ (result) => {
+ if (result !== 'merged') {
+ report(result);
+ }
+ },
+ () => report('failed')
+ );
+};
+
/**
* Canvas keys that also act while a companion widget (Layers, with its Color pane) holds focus: tools, the
* transform session, brush size and the color pair. The Canvas and the companion both register from this table;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.browser.test.tsx
index c1042fd45c..3526d45377 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.browser.test.tsx
@@ -1,8 +1,11 @@
+import type { CanvasDocumentContractV3, CanvasLayerContract } from '@workbench/canvas-engine/api';
import type { ExtensionRegistry } from '@workbench/extensions/extensionRegistry';
import type { Project } from '@workbench/projectContracts';
import type { WidgetContributionSource } from '@workbench/widgetContracts';
import type { WorkbenchInternalStore } from '@workbench/workbenchStore';
+import { createDocumentModel } from '@workbench/canvas-engine/api';
+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';
import { useFocusRegionProps } from '@workbench/focusRegions';
import { IS_MAC_OS } from '@workbench/hotkeys/keys';
@@ -46,10 +49,10 @@ vi.mock('@workbench/hotkeys/firstPartyCommands', () => ({ useRegisterFirstPartyC
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const createEngine = () => ({
- document: { model: () => null },
+ document: { model: vi.fn(() => null as ReturnType<CanvasCompanionEngine['document']['model']> | null) },
history: { redo: vi.fn(), undo: vi.fn() },
interaction: { get: vi.fn(() => 'brush'), set: vi.fn() },
- layers: { beginTransform: vi.fn(() => 'started') },
+ layers: { beginTransform: vi.fn(() => 'started'), mergeLayerDown: vi.fn(() => Promise.resolve('merged' as const)) },
tools: { setTool: vi.fn(), stepBrushSize: vi.fn() },
});
@@ -149,6 +152,46 @@ describe('useCanvasCompanionHotkeys', () => {
expect(engine.history.undo).toHaveBeenCalledOnce();
});
+ it('merges the selected raster down from a focused layer row and prevents the browser shortcut', async () => {
+ const raster = (id: string) =>
+ ({
+ blendMode: 'normal',
+ id,
+ isEnabled: true,
+ isLocked: false,
+ name: id,
+ opacity: 1,
+ source: { bitmap: null, type: 'paint' },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
+ type: 'raster',
+ }) as CanvasLayerContract;
+ const canvasDocument = {
+ bbox: { height: 64, width: 64, x: 0, y: 0 },
+ height: 64,
+ stacks: stacksFrom([raster('upper'), raster('lower')]),
+ selectedLayerId: 'upper',
+ width: 64,
+ } as CanvasDocumentContractV3;
+ engine.document.model.mockReturnValue(
+ createDocumentModel(canvasDocument, { editRevision: 0, projectId: 'project' })
+ );
+ const row = host!.querySelector<HTMLElement>('[role="treeitem"]')!;
+ await userEvent.click(row);
+
+ const event = new KeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ code: 'KeyE',
+ key: 'e',
+ ...(IS_MAC_OS ? { metaKey: true } : { ctrlKey: true }),
+ });
+ await act(() => row.dispatchEvent(event));
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(engine.layers.mergeLayerDown).toHaveBeenCalledExactlyOnceWith('upper');
+ expect(document.activeElement).toBe(row);
+ });
+
it('leaves typing in a field alone', async () => {
const field = host!.querySelector('input')!;
await userEvent.click(field);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
index c11b70e0f2..b5bd68a959 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
@@ -5,15 +5,18 @@ import { useNotify } from '@workbench/useNotify';
import {
CANVAS_COMPANION_HOTKEYS,
CANVAS_HISTORY_HOTKEYS,
+ CANVAS_MERGE_DOWN_HOTKEY,
executeCanvasToolCommand,
+ mergeSelectedLayerDown,
reportTransformRefusal,
type CanvasToolCommandId,
} from '@workbench/widgets/canvas/canvasToolCommands';
import { useActiveColorCommands } from '@workbench/widgets/canvas/color-system/useActiveColors';
+import { reportLayerOperation } from '@workbench/widgets/canvas/useStructuralCommit';
import { useEffect, useEffectEvent } from 'react';
import { useTranslation } from 'react-i18next';
-type CompanionCommandId = (typeof CANVAS_HISTORY_HOTKEYS)[number][0] | CanvasToolCommandId;
+type CompanionCommandId = (typeof CANVAS_HISTORY_HOTKEYS)[number][0] | CanvasToolCommandId | 'canvas.mergeDown';
export type CanvasCompanionEngine = Pick<
CanvasEngineHandle,
@@ -22,7 +25,7 @@ export type CanvasCompanionEngine = Pick<
/**
* Registers the canvas keys that stay live while a companion widget (Layers and its Color pane) holds focus:
- * undo/redo and the shared tool, brush-size and color table. Rows keep arrows, Delete and selection.
+ * undo/redo, merge down, and the shared tool, brush-size and color table. Rows keep arrows, Delete and selection.
*/
export const useCanvasCompanionHotkeys = (
runtime: { commands: Pick<WidgetCommandApi, 'register'>; hotkeys: WidgetHotkeyApi },
@@ -41,6 +44,12 @@ export const useCanvasCompanionHotkeys = (
return;
}
const model = engine?.document.model() ?? null;
+ if (commandId === 'canvas.mergeDown') {
+ if (model) {
+ mergeSelectedLayerDown(engine, model.document, (refusal) => reportLayerOperation(refusal, notify.error, t));
+ }
+ return;
+ }
const selectedId = model?.document.selectedLayerId ?? null;
executeCanvasToolCommand(commandId, {
engine,
@@ -52,7 +61,7 @@ export const useCanvasCompanionHotkeys = (
});
useEffect(() => {
// Undo/redo stay reachable while a companion owns focus: selecting a layer or editing it must not strand mod+Z.
- const disposers = [...CANVAS_HISTORY_HOTKEYS, ...CANVAS_COMPANION_HOTKEYS].flatMap(
+ const disposers = [...CANVAS_HISTORY_HOTKEYS, ...CANVAS_COMPANION_HOTKEYS, CANVAS_MERGE_DOWN_HOTKEY].flatMap(
([id, titleKey, defaultKeys]) => {
const title = t(titleKey);
return [