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.

refactor(webv2): extract the canvas hotkey and header command dispatchers

joshistoast653c7103ccce
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index 4179c0b7fb..1363f1dfec 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -7,7 +7,6 @@ import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngi
import { Box, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { useModifierHeld } from '@platform/react/useModifierHeld';
import { ConfirmDialog, IconButton, MenuContent, Tooltip } from '@platform/ui';
-import { createNewCanvasStateV2 } from '@workbench/canvasMigration';
import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
@@ -28,9 +27,16 @@ import {
import { Fragment, useCallback, useEffect, useEffectEvent, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
+import type { CanvasHeaderCommandContext } from './canvasHeaderCommands';
import type { CanvasBooleanSetting, ResolvedCanvasSettings } from './canvasSettings';
import { gridSizeForModelBase } from './bboxGrid';
+import {
+ applyFitBbox,
+ confirmNewCanvas as confirmNewCanvasDocument,
+ executeCanvasHeaderCommand,
+ zoomAtViewportCentre,
+} from './canvasHeaderCommands';
import {
CANVAS_SETTING_SECTIONS,
CANVAS_SETTINGS,
@@ -98,61 +104,38 @@ const CanvasHeaderActionsInner = ({
}
}, [editingLocked]);
- const setZoom = (value: number) => {
- const viewport = engine.viewport.getViewport();
- const size = viewport.getViewportSize();
- viewport.zoomAtPoint(value, { x: size.width / 2, y: size.height / 2 });
- };
+ const setZoom = (value: number) => zoomAtViewportCentre(engine, value);
// Fit-bbox honors the snap-to-grid setting: snapping off ⇒ grid 1 (a plain round).
const gridSize = settings[CANVAS_SNAP_TO_GRID_KEY] ? gridSizeForModelBase(modelBase) : 1;
const fitLayersRect = useMemo(() => computeFitBboxToLayers(document, gridSize), [document, gridSize]);
const fitMasksRect = useMemo(() => computeFitBboxToMasks(document, gridSize), [document, gridSize]);
- // One undoable `setCanvasBbox` (inverse restores the current bbox) — exactly how a
- // manual bbox-tool edit commits. `refit` re-centers the view afterward (legacy
- // re-fits the stage after fit-to-layers, but not after fit-to-masks).
- const applyFit = (rect: Rect | null, refit: boolean) => {
- if (editingLocked || !rect) {
- return;
- }
- engine.layers.commitStructural(
- t('widgets.canvas.commands.fitBbox'),
- { bbox: rect, type: 'setCanvasBbox' },
- { bbox: document.bbox, type: 'setCanvasBbox' }
- );
- if (refit) {
- engine.viewport.fitToView();
- }
- };
+ const commandContext = (): CanvasHeaderCommandContext => ({
+ dispatch,
+ document,
+ editingLocked,
+ engine,
+ fitLayersRect,
+ fitMasksRect,
+ openNewCanvas,
+ t,
+ });
- const confirmNewCanvas = useCallback(() => {
- if (editingLocked) {
- return;
- }
- // A wholesale document replace (seeded with one empty inpaint mask, matching
- // Task 42's new-canvas init) at the current dimensions. The engine's mirror
- // treats this as a document swap and clears the canvas history by design, so
- // this is intentionally NOT undoable — the confirm dialog is the safety net.
- dispatch({
- document: createNewCanvasStateV2(document.width, document.height).document,
- type: 'replaceCanvasDocument',
- });
- }, [dispatch, document.height, document.width, editingLocked]);
+ const applyFit = (rect: Rect | null, refit: boolean) => applyFitBbox(commandContext(), rect, refit);
+
+ const confirmNewCanvas = useCallback(
+ () => confirmNewCanvasDocument({ dispatch, document, editingLocked }),
+ [dispatch, document, editingLocked]
+ );
// Commands (hotkey-assignable; catalog ids `canvas.fitBboxToLayers` /
// `canvas.fitBboxToMasks` / `canvas.newSession`). `useEffectEvent` reads the
// latest fit rects / dialog opener without re-registering per document change.
// The new-session command routes through the SAME confirm dialog as the button.
- const executeHeaderCommand = useEffectEvent((commandId: string) => {
- if (commandId === 'canvas.fitBboxToLayers') {
- applyFit(fitLayersRect, true);
- } else if (commandId === 'canvas.fitBboxToMasks') {
- applyFit(fitMasksRect, false);
- } else if (commandId === 'canvas.newSession') {
- openNewCanvas();
- }
- });
+ const executeHeaderCommand = useEffectEvent((commandId: string) =>
+ executeCanvasHeaderCommand(commandId, commandContext())
+ );
useEffect(() => {
const entries = [
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index 22f59e5705..c47115c81a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -4,22 +4,13 @@ import type { MouseEvent as ReactMouseEvent } from 'react';
import { Box } from '@chakra-ui/react';
import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';
import { useQueueItemProgressImage } from '@features/queue/react';
-import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';
import { getCanvasImportNotice } from '@workbench/canvas-operations/api';
-import {
- createLayerId,
- deleteLayerActions,
- duplicateLayerActions,
- type LayerReorderKind,
- reorderIdsForHotkey,
- reorderLayerActions,
-} from '@workbench/canvasLayerOps';
+import { createLayerId } from '@workbench/canvasLayerOps';
import { getCanvasStagingSlots } from '@workbench/canvasStagingView';
import { recordCanvasImportError } from '@workbench/image-actions/canvasImportError';
import { useWorkbenchSettingsSelector } from '@workbench/settings/store';
import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
import { CanvasLayerContextMenu } from '@workbench/widgets/layers/LayerContextMenu';
-import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useMemo, useState } from 'react';
@@ -36,6 +27,7 @@ import {
} from './canvasContextMenu';
import { CanvasCreateFromBboxSubmenu } from './CanvasCreateFromBboxSubmenu';
import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';
+import { executeCanvasHotkeyCommand } from './canvasHotkeyCommands';
import { resolveCanvasImageDrop } from './canvasImageDnd';
import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';
import { getCanvasInteractionCapabilities } from './canvasInteractionLock';
@@ -59,26 +51,6 @@ import { useCanvasEngine } from './useCanvasEngine';
import { useCanvasGallerySave } from './useCanvasGallerySave';
import { useCreateFromBbox } from './useCreateFromBbox';
-/** Command id → document-space nudge delta (shift variants are ×10). */
-const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {
- 'canvas.nudgeDown': { dx: 0, dy: 1 },
- 'canvas.nudgeDownLarge': { dx: 0, dy: 10 },
- 'canvas.nudgeLeft': { dx: -1, dy: 0 },
- 'canvas.nudgeLeftLarge': { dx: -10, dy: 0 },
- 'canvas.nudgeRight': { dx: 1, dy: 0 },
- 'canvas.nudgeRightLarge': { dx: 10, dy: 0 },
- 'canvas.nudgeUp': { dx: 0, dy: -1 },
- 'canvas.nudgeUpLarge': { dx: 0, dy: -10 },
-};
-
-/** Command id → z-reorder direction (index 0 = top-most; "forward" moves toward 0). */
-const REORDER_KINDS: Record<string, LayerReorderKind> = {
- 'canvas.layerBackward': 'backward',
- 'canvas.layerForward': 'forward',
- 'canvas.layerToBack': 'back',
- 'canvas.layerToFront': 'front',
-};
-
/**
* The canvas widget shell. The engine owns pixels and interaction and renders
* into {@link CanvasSurface}; this component only wires the reducer-backed
@@ -371,175 +343,18 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
}, [engine]);
const executeCanvasHotkey = useEffectEvent((commandId: string) => {
- const { layers, selectedLayerId } = document;
- const selectedIndex = selectedLayerId ? layers.findIndex((layer) => layer.id === selectedLayerId) : -1;
- const selectedLayer = selectedIndex >= 0 ? layers[selectedIndex] : undefined;
-
- if ((commandId === 'canvas.prevEntity' || commandId === 'canvas.nudgeLeft') && hasStagingSlots) {
- canvasDispatch({ direction: -1, type: 'cycleStagedImage' });
- return;
- }
-
- if ((commandId === 'canvas.nextEntity' || commandId === 'canvas.nudgeRight') && hasStagingSlots) {
- canvasDispatch({ direction: 1, type: 'cycleStagedImage' });
- return;
- }
-
- if (commandId === 'canvas.deleteSelected' && selectedCandidate) {
- canvasDispatch({ type: 'discardSelectedStagedImage' });
- return;
- }
-
- if (isInteractionLocked) {
- if (commandId === 'canvas.tool.view') {
- engine?.tools.setTool('view');
- }
- return;
- }
-
- // Arrow-key nudge: engine owns the bounds/lock logic (no-op with no/locked selection).
- const nudge = NUDGE_DELTAS[commandId];
- if (nudge) {
- engine?.layers.nudgeSelectedLayer(nudge.dx, nudge.dy);
- return;
- }
-
- // Layer z-reorder: same forward/inverse construction as the layers panel.
- const reorderKind = REORDER_KINDS[commandId];
- if (reorderKind) {
- if (!engine || selectedIndex < 0) {
- return;
- }
- const currentIds = layers.map((layer) => layer.id);
- const nextIds = reorderIdsForHotkey(currentIds, selectedIndex, reorderKind);
- if (!nextIds) {
- return;
- }
- const { forward, inverse } = reorderLayerActions(currentIds, nextIds);
- engine.layers.commitStructural(t('widgets.canvas.commands.reorderLayer'), forward, inverse);
- return;
- }
-
- if (commandId === 'canvas.deleteSelected') {
- // With a live pixel selection, Delete clears the selected PIXELS — the
- // Photoshop meaning. Only with no selection does it delete the layer.
- if (engine?.interaction.get('hasSelection')) {
- engine.selection.eraseSelection();
- } else if (engine && selectedLayer && selectedIndex >= 0) {
- const { forward, inverse } = deleteLayerActions(selectedLayer, selectedIndex);
- engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), forward, inverse);
- }
- } else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {
- copySelection(commandId === 'canvas.cutSelection');
- } else if (commandId === 'canvas.pasteImage') {
- pasteFromClipboard();
- } else if (commandId === 'canvas.toggleNonRasterLayers') {
- // Hide, never disable: this is the "get the overlays out of my way"
- // shortcut, and it must leave the generated image untouched.
- const hideable = layers.filter(isHideableLayer);
- if (engine && hideable.length > 0) {
- const nextHidden = hideable.every((layer) => !isLayerHidden(layer));
- engine.layers.commitStructural(
- t('widgets.canvas.commands.toggleNonRasterLayers'),
- {
- type: 'setCanvasLayersHidden',
- updates: hideable.map((layer) => ({ id: layer.id, isHidden: nextHidden })),
- },
- {
- type: 'setCanvasLayersHidden',
- updates: hideable.map((layer) => ({ id: layer.id, isHidden: isLayerHidden(layer) })),
- }
- );
- }
- } else if (commandId === 'canvas.resetSelected') {
- if (engine && selectedLayer) {
- engine.layers.clearMask(selectedLayer.id);
- }
- } else if (commandId === 'canvas.undo') {
- // Canvas undo/redo is engine-scoped: it drives the engine-owned pixel/
- // structural history, NOT project-level (reducer) undo. When the canvas
- // history is empty this is a no-op — it deliberately does not fall back to
- // `undoProjectChange` (project undo keeps its own commands/hotkeys, e.g.
- // the workflow editor's `workflows.undo`).
- engine?.history.undo();
- } else if (commandId === 'canvas.redo') {
- engine?.history.redo();
- } else if (commandId === 'canvas.tool.view') {
- engine?.tools.setTool('view');
- } else if (commandId === 'canvas.tool.move') {
- engine?.tools.setTool('move');
- } else if (commandId === 'canvas.transformSelected') {
- // Selecting the transform tool opens a session on the selected layer (if any
- // eligible one); Apply/Cancel (enter/esc) are handled engine-side.
- engine?.tools.setTool('transform');
- } else if (commandId === 'canvas.tool.bbox') {
- engine?.tools.setTool('bbox');
- } else if (commandId === 'canvas.tool.brush') {
- engine?.tools.setTool('brush');
- } else if (commandId === 'canvas.tool.eraser') {
- engine?.tools.setTool('eraser');
- } else if (commandId === 'canvas.tool.lasso') {
- if (engine) {
- // Pressing the shortcut while already on the tool cycles its shape
- // (Photoshop-style) rather than re-selecting the tool it is already on.
- if (engine.interaction.get('activeTool') === 'lasso') {
- const lasso = engine.interaction.get('lassoOptions');
- engine.interaction.set('lassoOptions', {
- ...lasso,
- shape: lasso.shape === 'freehand' ? 'polygon' : 'freehand',
- });
- } else {
- engine.tools.setTool('lasso');
- }
- }
- } else if (commandId === 'canvas.tool.marquee') {
- if (engine) {
- if (engine.interaction.get('activeTool') === 'marquee') {
- const marquee = engine.interaction.get('marqueeOptions');
- engine.interaction.set('marqueeOptions', {
- ...marquee,
- kind: marquee.kind === 'rect' ? 'ellipse' : 'rect',
- });
- } else {
- engine.tools.setTool('marquee');
- }
- }
- } else if (commandId === 'canvas.tool.shape') {
- engine?.tools.setTool('shape');
- } else if (commandId === 'canvas.tool.text') {
- engine?.tools.setTool('text');
- } else if (commandId === 'canvas.tool.gradient') {
- engine?.tools.setTool('gradient');
- } else if (commandId === 'canvas.selectAll') {
- engine?.selection.selectAll();
- } else if (commandId === 'canvas.deselect') {
- engine?.selection.deselect();
- } else if (commandId === 'canvas.invertSelection') {
- engine?.selection.invertSelection();
- } else if (commandId === 'canvas.brushSizeDown') {
- engine?.tools.stepBrushSize(-1);
- } else if (commandId === 'canvas.brushSizeUp') {
- engine?.tools.stepBrushSize(1);
- } else if (commandId === 'canvas.duplicateLayer') {
- // With a live pixel selection, mod+J is "layer via copy" — it lifts just
- // the selected pixels. With none, it duplicates the whole layer.
- if (engine?.interaction.get('hasSelection')) {
- engine.selection.liftSelectionToLayer();
- } else if (engine && selectedLayer) {
- const { forward, inverse } = duplicateLayerActions(selectedLayer.id, createLayerId());
- engine.layers.commitStructural(t('widgets.canvas.commands.duplicateLayer'), forward, inverse);
- }
- } else if (commandId === 'canvas.mergeDown') {
- // Gate on the SAME predicate the layers panel's context menu uses to
- // enable/disable its "Merge Down" item (`canMergeLayerDown`), so the hotkey
- // can never fire where the menu would refuse — e.g. a mask layer selected,
- // or a mask directly below the selection. `engine.layers.mergeLayerDown` also
- // guards this itself (defense in depth for callers other than this hotkey),
- // but checking here keeps the two surfaces visibly in lockstep.
- if (engine && selectedLayer && canMergeLayerDown(layers, selectedIndex, true)) {
- engine.layers.mergeLayerDown(selectedLayer.id);
- }
- }
+ executeCanvasHotkeyCommand(commandId, {
+ copySelection,
+ createLayerId,
+ dispatch: canvasDispatch,
+ document,
+ engine,
+ hasSelectedStagedCandidate: selectedCandidate !== undefined,
+ hasStagingSlots,
+ isInteractionLocked,
+ pasteFromClipboard,
+ t,
+ });
});
useEffect(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx
new file mode 100644
index 0000000000..faf632a657
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/TextEditPortal.browser.test.tsx
@@ -0,0 +1,209 @@
+import type { TextEditSession } from '@workbench/canvas-engine/api';
+
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { TextEditPortal } from './TextEditPortal';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const mounted: { root: Root; host: HTMLDivElement }[] = [];
+
+afterEach(() => {
+ while (mounted.length > 0) {
+ const entry = mounted.pop();
+ if (entry) {
+ act(() => entry.root.unmount());
+ entry.host.remove();
+ }
+ }
+});
+
+const session = (overrides: Partial<TextEditSession> = {}): TextEditSession =>
+ ({
+ id: 1,
+ layerId: 'layer-1',
+ mode: 'edit',
+ startSource: null,
+ source: {
+ align: 'left',
+ color: '#ff0000',
+ content: 'hello',
+ fontFamily: 'Inter',
+ fontSize: 24,
+ fontWeight: 400,
+ lineHeight: 1.2,
+ },
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 10, y: 20 },
+ ...overrides,
+ }) as unknown as TextEditSession;
+
+/**
+ * A minimal engine double: the portal only needs the interaction store to read
+ * the session, the layers commands it drives, and a viewport for positioning.
+ */
+const createEngine = (initialSession: TextEditSession | null) => {
+ let current = initialSession;
+ const listeners = new Set<() => void>();
+ const layers = {
+ cancelTextEdit: vi.fn(),
+ commitTextEdit: vi.fn(),
+ setTextEditContentReader: vi.fn(),
+ };
+ const viewport = {
+ documentToScreen: ({ x, y }: { x: number; y: number }) => ({ x, y }),
+ getState: () => ({ pan: { x: 0, y: 0 }, zoom: 1 }),
+ getZoom: () => 1,
+ subscribe: () => () => {},
+ };
+ const engine = {
+ interaction: {
+ get: (key: string) => (key === 'textEditSession' ? current : undefined),
+ subscribe: (_key: string, listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ },
+ layers,
+ viewport: { getViewport: () => viewport },
+ };
+ const setSession = (next: TextEditSession | null) => {
+ current = next;
+ listeners.forEach((listener) => listener());
+ };
+ return { engine: engine as unknown as Parameters<typeof TextEditPortal>[0]['engine'], layers, setSession };
+};
+
+const mount = (engine: Parameters<typeof TextEditPortal>[0]['engine']) => {
+ const host = window.document.createElement('div');
+ window.document.body.append(host);
+ const root = createRoot(host);
+ act(() => root.render(<TextEditPortal engine={engine} />));
+ mounted.push({ host, root });
+ return { host, root };
+};
+
+const editableIn = (host: HTMLElement): HTMLElement => {
+ const el = host.querySelector<HTMLElement>('[role="textbox"]');
+ if (!el) {
+ throw new Error('editable not rendered');
+ }
+ return el;
+};
+
+describe('TextEditPortal', () => {
+ it('renders nothing without an active session', () => {
+ const { engine } = createEngine(null);
+ const { host } = mount(engine);
+ expect(host.querySelector('[role="textbox"]')).toBeNull();
+ });
+
+ it('seeds the session content and focuses the editable exactly once', () => {
+ const { engine } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ expect(el.textContent).toBe('hello');
+ expect(window.document.activeElement).toBe(el);
+ expect(el.dataset.seeded).toBe('true');
+ });
+
+ it('places the caret at the end of the seeded content', () => {
+ const { engine } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ const selection = window.getSelection();
+ expect(selection?.isCollapsed).toBe(true);
+ expect(el.contains(selection?.anchorNode ?? null)).toBe(true);
+ expect(selection?.anchorOffset).toBe(el.childNodes.length);
+ });
+
+ it('registers a live content reader and clears it on unmount', () => {
+ const { engine, layers } = createEngine(session());
+ const { host, root } = mount(engine);
+ const el = editableIn(host);
+ const reader = layers.setTextEditContentReader.mock.calls.at(-1)?.[0] as () => string;
+ expect(typeof reader).toBe('function');
+
+ el.textContent = 'typed live';
+ expect(reader()).toBe('typed live');
+
+ act(() => root.unmount());
+ mounted.pop();
+ host.remove();
+ expect(layers.setTextEditContentReader).toHaveBeenLastCalledWith(null);
+ });
+
+ it('commits the current text on blur', () => {
+ const { engine, layers } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ el.textContent = 'edited';
+ // React maps `onBlur` to the bubbling `focusout`, so blur the element for real.
+ act(() => el.blur());
+ expect(layers.commitTextEdit).toHaveBeenCalledWith('edited');
+ });
+
+ it('commits on mod+enter and cancels on escape', () => {
+ const { engine, layers } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ el.textContent = 'committed';
+
+ act(() => {
+ el.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter', metaKey: true }));
+ });
+ expect(layers.commitTextEdit).toHaveBeenCalledWith('committed');
+
+ act(() => {
+ el.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' }));
+ });
+ expect(layers.cancelTextEdit).toHaveBeenCalled();
+ });
+
+ it('plain enter inserts a newline rather than committing', () => {
+ const { engine, layers } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ act(() => el.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Enter' })));
+ expect(layers.commitTextEdit).not.toHaveBeenCalled();
+ expect(layers.cancelTextEdit).not.toHaveBeenCalled();
+ });
+
+ it('stops every keystroke from escaping to canvas hotkeys', () => {
+ const { engine } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ const onWindowKeyDown = vi.fn();
+ window.addEventListener('keydown', onWindowKeyDown);
+ try {
+ for (const key of ['b', 'Escape', 'Delete', 'Enter']) {
+ act(() => el.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key })));
+ }
+ expect(onWindowKeyDown).not.toHaveBeenCalled();
+ } finally {
+ window.removeEventListener('keydown', onWindowKeyDown);
+ }
+ });
+
+ it('remounts and re-seeds when the session id changes', () => {
+ const { engine, setSession } = createEngine(session());
+ const { host } = mount(engine);
+ expect(editableIn(host).textContent).toBe('hello');
+
+ act(() => {
+ setSession(session({ id: 2, source: { ...session().source, content: 'second' } }));
+ });
+ expect(editableIn(host).textContent).toBe('second');
+ });
+
+ it('positions the editable from the session transform and document styles', () => {
+ const { engine } = createEngine(session());
+ const { host } = mount(engine);
+ const el = editableIn(host);
+ expect(el.style.transform).toContain('translate(10px, 20px)');
+ expect(el.style.fontSize).toBe('24px');
+ expect(el.style.whiteSpace).toBe('pre');
+ expect(el.style.color).toBe('rgb(255, 0, 0)');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
new file mode 100644
index 0000000000..670148b873
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
@@ -0,0 +1,178 @@
+import type { CanvasDocumentContractV2, Rect } from '@workbench/canvas-engine/api';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+
+import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
+
+import {
+ applyFitBbox,
+ confirmNewCanvas,
+ executeCanvasHeaderCommand,
+ zoomAtViewportCentre,
+ type CanvasHeaderCommandContext,
+} from './canvasHeaderCommands';
+
+const BBOX: Rect = { height: 64, width: 64, x: 0, y: 0 };
+const FIT_LAYERS: Rect = { height: 128, width: 256, x: 8, y: 16 };
+const FIT_MASKS: Rect = { height: 32, width: 32, x: 4, y: 4 };
+
+const documentOf = (): CanvasDocumentContractV2 =>
+ ({
+ background: { color: '#000000', type: 'transparent' },
+ bbox: BBOX,
+ height: 512,
+ layers: [],
+ selectedLayerId: null,
+ version: 2,
+ width: 768,
+ }) as unknown as CanvasDocumentContractV2;
+
+const createEngine = (viewportSize = { height: 600, width: 800 }) => {
+ const zoomAtPoint = vi.fn();
+ const engine = {
+ layers: { commitStructural: vi.fn(() => true) },
+ viewport: {
+ fitToView: vi.fn(),
+ getViewport: vi.fn(() => ({ getViewportSize: () => viewportSize, zoomAtPoint })),
+ },
+ };
+ return { engine, zoomAtPoint };
+};
+
+let dispatch: Mock<(mutation: CanvasProjectMutation) => boolean>;
+
+const contextOf = (overrides: Partial<CanvasHeaderCommandContext> = {}): CanvasHeaderCommandContext => ({
+ dispatch,
+ document: documentOf(),
+ editingLocked: false,
+ engine: createEngine().engine,
+ fitLayersRect: FIT_LAYERS,
+ fitMasksRect: FIT_MASKS,
+ openNewCanvas: vi.fn(),
+ t: (key) => key,
+ ...overrides,
+});
+
+beforeEach(() => {
+ dispatch = vi.fn(() => true);
+});
+
+describe('zoomAtViewportCentre', () => {
+ it('anchors the zoom at the viewport centre', () => {
+ const { engine, zoomAtPoint } = createEngine({ height: 600, width: 800 });
+ zoomAtViewportCentre(engine, 2.5);
+ expect(zoomAtPoint).toHaveBeenCalledWith(2.5, { x: 400, y: 300 });
+ });
+
+ it('re-reads the viewport size on every call', () => {
+ const { engine, zoomAtPoint } = createEngine({ height: 200, width: 100 });
+ zoomAtViewportCentre(engine, 1);
+ expect(zoomAtPoint).toHaveBeenCalledWith(1, { x: 50, y: 100 });
+ });
+});
+
+describe('applyFitBbox', () => {
+ it('commits one undoable setCanvasBbox whose inverse restores the current bbox', () => {
+ const { engine } = createEngine();
+ applyFitBbox(contextOf({ engine }), FIT_LAYERS, false);
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.fitBbox',
+ { bbox: FIT_LAYERS, type: 'setCanvasBbox' },
+ { bbox: BBOX, type: 'setCanvasBbox' }
+ );
+ });
+
+ it('re-fits the view only when asked', () => {
+ const withRefit = createEngine();
+ applyFitBbox(contextOf({ engine: withRefit.engine }), FIT_LAYERS, true);
+ expect(withRefit.engine.viewport.fitToView).toHaveBeenCalled();
+
+ const withoutRefit = createEngine();
+ applyFitBbox(contextOf({ engine: withoutRefit.engine }), FIT_LAYERS, false);
+ expect(withoutRefit.engine.viewport.fitToView).not.toHaveBeenCalled();
+ });
+
+ it('is inert with a null rect (nothing to fit to)', () => {
+ const { engine } = createEngine();
+ applyFitBbox(contextOf({ engine }), null, true);
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.viewport.fitToView).not.toHaveBeenCalled();
+ });
+
+ it('is inert while editing is locked, even with a valid rect', () => {
+ const { engine } = createEngine();
+ applyFitBbox(contextOf({ editingLocked: true, engine }), FIT_LAYERS, true);
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.viewport.fitToView).not.toHaveBeenCalled();
+ });
+});
+
+describe('confirmNewCanvas', () => {
+ it('replaces the document at the current dimensions', () => {
+ confirmNewCanvas({ dispatch, document: { height: 512, width: 768 }, editingLocked: false });
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ const mutation = dispatch.mock.calls[0]?.[0] as Extract<CanvasProjectMutation, { type: 'replaceCanvasDocument' }>;
+ expect(mutation.type).toBe('replaceCanvasDocument');
+ expect(mutation.document.width).toBe(768);
+ expect(mutation.document.height).toBe(512);
+ });
+
+ it('seeds exactly one empty inpaint mask', () => {
+ confirmNewCanvas({ dispatch, document: { height: 64, width: 64 }, editingLocked: false });
+ const mutation = dispatch.mock.calls[0]?.[0] as Extract<CanvasProjectMutation, { type: 'replaceCanvasDocument' }>;
+ expect(mutation.document.layers).toHaveLength(1);
+ expect(mutation.document.layers[0]?.type).toBe('inpaint_mask');
+ });
+
+ it('refuses while editing is locked — the second gate behind the confirm dialog', () => {
+ confirmNewCanvas({ dispatch, document: { height: 512, width: 768 }, editingLocked: true });
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
+
+describe('executeCanvasHeaderCommand', () => {
+ it('fitBboxToLayers commits the layers rect and re-fits', () => {
+ const { engine } = createEngine();
+ executeCanvasHeaderCommand('canvas.fitBboxToLayers', contextOf({ engine }));
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.fitBbox',
+ { bbox: FIT_LAYERS, type: 'setCanvasBbox' },
+ { bbox: BBOX, type: 'setCanvasBbox' }
+ );
+ expect(engine.viewport.fitToView).toHaveBeenCalled();
+ });
+
+ it('fitBboxToMasks commits the masks rect and does NOT re-fit', () => {
+ const { engine } = createEngine();
+ executeCanvasHeaderCommand('canvas.fitBboxToMasks', contextOf({ engine }));
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.fitBbox',
+ { bbox: FIT_MASKS, type: 'setCanvasBbox' },
+ { bbox: BBOX, type: 'setCanvasBbox' }
+ );
+ expect(engine.viewport.fitToView).not.toHaveBeenCalled();
+ });
+
+ it('newSession opens the confirm dialog instead of replacing directly', () => {
+ const openNewCanvas = vi.fn();
+ executeCanvasHeaderCommand('canvas.newSession', contextOf({ openNewCanvas }));
+ expect(openNewCanvas).toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('fit commands are inert with no rect to fit to', () => {
+ const { engine } = createEngine();
+ const ctx = contextOf({ engine, fitLayersRect: null, fitMasksRect: null });
+ executeCanvasHeaderCommand('canvas.fitBboxToLayers', ctx);
+ executeCanvasHeaderCommand('canvas.fitBboxToMasks', ctx);
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('ignores an unknown command id', () => {
+ const openNewCanvas = vi.fn();
+ const { engine } = createEngine();
+ executeCanvasHeaderCommand('canvas.nonexistent', contextOf({ engine, openNewCanvas }));
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(openNewCanvas).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
new file mode 100644
index 0000000000..467a54a314
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
@@ -0,0 +1,97 @@
+import type { CanvasDocumentContractV2, Rect } from '@workbench/canvas-engine/api';
+import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
+
+import { createNewCanvasStateV2 } from '@workbench/canvasMigration';
+
+/**
+ * The slice of the engine the header's actions drive. Structural rather than the
+ * full handle, so this module stays React-free and testable with a plain double.
+ */
+export interface CanvasHeaderCommandEngine {
+ readonly layers: {
+ commitStructural(label: string, forward: unknown, inverse: unknown): boolean;
+ };
+ readonly viewport: {
+ fitToView(): void;
+ getViewport(): {
+ getViewportSize(): { width: number; height: number };
+ zoomAtPoint(newZoom: number, screenAnchor: { x: number; y: number }): void;
+ };
+ };
+}
+
+/** The minimum the destructive replace needs — kept narrow so its memo deps stay tight. */
+export interface NewCanvasContext {
+ readonly document: Pick<CanvasDocumentContractV2, 'width' | 'height'>;
+ /** An in-flight operation owns the document; every mutating header action is inert. */
+ readonly editingLocked: boolean;
+ readonly dispatch: CanvasProjectMutationDispatch;
+}
+
+export interface CanvasHeaderCommandContext extends NewCanvasContext {
+ readonly engine: CanvasHeaderCommandEngine;
+ readonly document: CanvasDocumentContractV2;
+ readonly fitLayersRect: Rect | null;
+ readonly fitMasksRect: Rect | null;
+ /** Opens the confirm dialog. The destructive replace only runs from its confirm. */
+ readonly openNewCanvas: () => void;
+ readonly t: (key: string) => string;
+}
+
+/** Zooms about the viewport's centre, the anchor every header zoom control uses. */
+export const zoomAtViewportCentre = (engine: CanvasHeaderCommandEngine, value: number): void => {
+ const viewport = engine.viewport.getViewport();
+ const size = viewport.getViewportSize();
+ viewport.zoomAtPoint(value, { x: size.width / 2, y: size.height / 2 });
+};
+
+/**
+ * Commits a fit-bbox as one undoable `setCanvasBbox` whose inverse restores the
+ * current bbox — exactly how a manual bbox-tool edit commits. `refit` re-centres
+ * the view afterward (legacy re-fits the stage after fit-to-layers, but not after
+ * fit-to-masks). A null rect means nothing to fit to, and is a no-op.
+ */
+export const applyFitBbox = (ctx: CanvasHeaderCommandContext, rect: Rect | null, refit: boolean): void => {
+ if (ctx.editingLocked || !rect) {
+ return;
+ }
+ ctx.engine.layers.commitStructural(
+ ctx.t('widgets.canvas.commands.fitBbox'),
+ { bbox: rect, type: 'setCanvasBbox' },
+ { bbox: ctx.document.bbox, type: 'setCanvasBbox' }
+ );
+ if (refit) {
+ ctx.engine.viewport.fitToView();
+ }
+};
+
+/**
+ * Replaces the whole document (seeded with one empty inpaint mask) at the current
+ * dimensions. The engine's mirror treats this as a document swap and clears the
+ * canvas history by design, so this is intentionally NOT undoable — the confirm
+ * dialog is the safety net, and the editing lock is the second gate.
+ */
+export const confirmNewCanvas = (ctx: NewCanvasContext): void => {
+ if (ctx.editingLocked) {
+ return;
+ }
+ ctx.dispatch({
+ document: createNewCanvasStateV2(ctx.document.width, ctx.document.height).document,
+ type: 'replaceCanvasDocument',
+ });
+};
+
+/**
+ * Routes a header command id. `canvas.newSession` deliberately opens the confirm
+ * dialog rather than replacing directly, so the command and the button share one
+ * destructive path.
+ */
+export const executeCanvasHeaderCommand = (commandId: string, ctx: CanvasHeaderCommandContext): void => {
+ if (commandId === 'canvas.fitBboxToLayers') {
+ applyFitBbox(ctx, ctx.fitLayersRect, true);
+ } else if (commandId === 'canvas.fitBboxToMasks') {
+ applyFitBbox(ctx, ctx.fitMasksRect, false);
+ } else if (commandId === 'canvas.newSession') {
+ ctx.openNewCanvas();
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
new file mode 100644
index 0000000000..8d2ce786fe
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -0,0 +1,426 @@
+import type {
+ CanvasDocumentContractV2,
+ CanvasEngine,
+ CanvasInteractionState,
+ CanvasLayerContract,
+} from '@workbench/canvas-engine/api';
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+
+import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
+
+import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
+
+const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
+ ({
+ 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',
+ ...overrides,
+ }) as CanvasLayerContract;
+
+const documentOf = (layers: readonly CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 =>
+ ({
+ bbox: { height: 64, width: 64, x: 0, y: 0 },
+ height: 64,
+ layers,
+ selectedLayerId,
+ width: 64,
+ }) as CanvasDocumentContractV2;
+
+/**
+ * A recording engine double. Interaction state is a plain bag so tests can put
+ * the engine into "has a pixel selection" or "already on the lasso tool" without
+ * standing up the real store.
+ */
+const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {
+ const state: Record<string, unknown> = {
+ activeTool: 'brush',
+ hasSelection: false,
+ lassoOptions: { shape: 'freehand' },
+ marqueeOptions: { kind: 'rect' },
+ ...interaction,
+ };
+ const engine = {
+ history: { redo: vi.fn(), undo: vi.fn() },
+ interaction: {
+ get: vi.fn((key: string) => state[key]),
+ set: vi.fn((key: string, value: unknown) => {
+ state[key] = value;
+ }),
+ },
+ layers: {
+ clearMask: vi.fn(),
+ commitStructural: vi.fn(),
+ mergeLayerDown: vi.fn(),
+ nudgeSelectedLayer: vi.fn(),
+ },
+ selection: {
+ deselect: vi.fn(),
+ eraseSelection: vi.fn(),
+ invertSelection: vi.fn(),
+ liftSelectionToLayer: vi.fn(),
+ selectAll: vi.fn(),
+ },
+ tools: { setTool: vi.fn(), stepBrushSize: vi.fn() },
+ };
+ return engine as unknown as CanvasEngine & typeof engine;
+};
+
+let dispatch: Mock<(mutation: CanvasProjectMutation) => boolean>;
+let copySelection: Mock<(cut: boolean) => void>;
+let pasteFromClipboard: Mock<() => void>;
+
+const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyContext => ({
+ copySelection,
+ createLayerId: () => 'new-layer',
+ dispatch,
+ document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a'),
+ engine: createEngine(),
+ hasSelectedStagedCandidate: false,
+ hasStagingSlots: false,
+ isInteractionLocked: false,
+ pasteFromClipboard,
+ t: (key) => key,
+ ...overrides,
+});
+
+const run = (commandId: string, overrides: Partial<CanvasHotkeyContext> = {}) => {
+ const ctx = contextOf(overrides);
+ executeCanvasHotkeyCommand(commandId, ctx);
+ return ctx.engine as ReturnType<typeof createEngine>;
+};
+
+beforeEach(() => {
+ dispatch = vi.fn();
+ copySelection = vi.fn();
+ pasteFromClipboard = vi.fn();
+});
+
+describe('staging precedence', () => {
+ it.each([
+ ['canvas.prevEntity', -1],
+ ['canvas.nudgeLeft', -1],
+ ['canvas.nextEntity', 1],
+ ['canvas.nudgeRight', 1],
+ ] as const)('%s cycles staged images while slots exist', (commandId, direction) => {
+ const engine = run(commandId, { hasStagingSlots: true });
+ expect(dispatch).toHaveBeenCalledWith({ direction, type: 'cycleStagedImage' } satisfies CanvasProjectMutation);
+ expect(engine.layers.nudgeSelectedLayer).not.toHaveBeenCalled();
+ });
+
+ it('nudges instead of cycling when no staging slot exists', () => {
+ const engine = run('canvas.nudgeLeft');
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(engine.layers.nudgeSelectedLayer).toHaveBeenCalledWith(-1, 0);
+ });
+
+ it('delete discards the selected staged candidate before touching layers', () => {
+ const engine = run('canvas.deleteSelected', { hasSelectedStagedCandidate: true });
+ expect(dispatch).toHaveBeenCalledWith({ type: 'discardSelectedStagedImage' });
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
+ });
+
+ it('prevEntity does nothing at all without staging slots', () => {
+ const engine = run('canvas.prevEntity');
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ });
+});
+
+describe('interaction lock', () => {
+ it('allows only the view tool', () => {
+ const engine = run('canvas.tool.view', { isInteractionLocked: true });
+ expect(engine.tools.setTool).toHaveBeenCalledWith('view');
+ });
+
+ it.each([
+ 'canvas.tool.brush',
+ 'canvas.deleteSelected',
+ 'canvas.undo',
+ 'canvas.selectAll',
+ 'canvas.nudgeLeft',
+ 'canvas.layerToFront',
+ 'canvas.duplicateLayer',
+ 'canvas.mergeDown',
+ ])('blocks %s', (commandId) => {
+ const engine = run(commandId, { isInteractionLocked: true });
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.nudgeSelectedLayer).not.toHaveBeenCalled();
+ expect(engine.history.undo).not.toHaveBeenCalled();
+ expect(engine.selection.selectAll).not.toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it('still cycles staging while locked (staging is checked first)', () => {
+ run('canvas.nextEntity', { hasStagingSlots: true, isInteractionLocked: true });
+ expect(dispatch).toHaveBeenCalledWith({ direction: 1, type: 'cycleStagedImage' });
+ });
+});
+
+describe('nudge', () => {
+ it.each([
+ ['canvas.nudgeUp', 0, -1],
+ ['canvas.nudgeUpLarge', 0, -10],
+ ['canvas.nudgeDown', 0, 1],
+ ['canvas.nudgeDownLarge', 0, 10],
+ ['canvas.nudgeLeftLarge', -10, 0],
+ ['canvas.nudgeRightLarge', 10, 0],
+ ])('%s nudges by (%i, %i)', (commandId, dx, dy) => {
+ const engine = run(commandId);
+ expect(engine.layers.nudgeSelectedLayer).toHaveBeenCalledWith(dx, dy);
+ });
+
+ it('large nudges are unaffected by staging slots', () => {
+ const engine = run('canvas.nudgeRightLarge', { hasStagingSlots: true });
+ expect(engine.layers.nudgeSelectedLayer).toHaveBeenCalledWith(10, 0);
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+});
+
+describe('layer reorder', () => {
+ it.each(['canvas.layerForward', 'canvas.layerBackward', 'canvas.layerToFront', 'canvas.layerToBack'])(
+ '%s commits through the engine history',
+ (commandId) => {
+ const engine = run(commandId, {
+ document: documentOf([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')], 'b'),
+ });
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.reorderLayer',
+ expect.anything(),
+ expect.anything()
+ );
+ }
+ );
+
+ it('is a no-op at the edge of the stack', () => {
+ const engine = run('canvas.layerToFront', { document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a') });
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op with no selected layer', () => {
+ const engine = run('canvas.layerBackward', { document: documentOf([rasterLayer('a')], null) });
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('is a no-op without an engine', () => {
+ expect(() => executeCanvasHotkeyCommand('canvas.layerForward', contextOf({ engine: null }))).not.toThrow();
+ });
+});
+
+describe('delete: pixels vs layer', () => {
+ it('erases the pixel selection when one exists', () => {
+ const engine = run('canvas.deleteSelected', { engine: createEngine({ hasSelection: true }) });
+ expect(engine.selection.eraseSelection).toHaveBeenCalled();
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('deletes the selected layer when there is no pixel selection', () => {
+ const engine = run('canvas.deleteSelected');
+ expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.deleteLayer',
+ expect.anything(),
+ expect.anything()
+ );
+ });
+
+ it('does nothing with neither a selection nor a selected layer', () => {
+ const engine = run('canvas.deleteSelected', { document: documentOf([rasterLayer('a')], null) });
+ expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+});
+
+describe('duplicate: lift vs whole layer', () => {
+ it('lifts the pixel selection into a new layer when one exists', () => {
+ const engine = run('canvas.duplicateLayer', { engine: createEngine({ hasSelection: true }) });
+ expect(engine.selection.liftSelectionToLayer).toHaveBeenCalled();
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('duplicates the whole layer with no pixel selection, using the injected id', () => {
+ const engine = run('canvas.duplicateLayer');
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.duplicateLayer',
+ { newId: 'new-layer', sourceId: 'a', type: 'duplicateCanvasLayer' },
+ { ids: ['new-layer'], type: 'removeCanvasLayers' }
+ );
+ });
+});
+
+describe('clipboard', () => {
+ it('copies without cutting', () => {
+ run('canvas.copySelection');
+ expect(copySelection).toHaveBeenCalledWith(false);
+ });
+
+ it('cuts', () => {
+ run('canvas.cutSelection');
+ expect(copySelection).toHaveBeenCalledWith(true);
+ });
+
+ it('pastes', () => {
+ run('canvas.pasteImage');
+ expect(pasteFromClipboard).toHaveBeenCalled();
+ });
+});
+
+describe('tool selection', () => {
+ it.each([
+ ['canvas.tool.view', 'view'],
+ ['canvas.tool.move', 'move'],
+ ['canvas.tool.bbox', 'bbox'],
+ ['canvas.tool.brush', 'brush'],
+ ['canvas.tool.eraser', 'eraser'],
+ ['canvas.tool.shape', 'shape'],
+ ['canvas.tool.text', 'text'],
+ ['canvas.tool.gradient', 'gradient'],
+ ['canvas.transformSelected', 'transform'],
+ ])('%s selects the %s tool', (commandId, tool) => {
+ const engine = run(commandId);
+ expect(engine.tools.setTool).toHaveBeenCalledWith(tool);
+ });
+
+ it('lasso selects the tool when not already active', () => {
+ const engine = run('canvas.tool.lasso');
+ expect(engine.tools.setTool).toHaveBeenCalledWith('lasso');
+ expect(engine.interaction.set).not.toHaveBeenCalled();
+ });
+
+ it('lasso cycles freehand → polygon when already active', () => {
+ const engine = run('canvas.tool.lasso', {
+ engine: createEngine({ activeTool: 'lasso', lassoOptions: { shape: 'freehand' } as never }),
+ });
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ expect(engine.interaction.set).toHaveBeenCalledWith('lassoOptions', { shape: 'polygon' });
+ });
+
+ it('lasso cycles polygon → freehand', () => {
+ const engine = run('canvas.tool.lasso', {
+ engine: createEngine({ activeTool: 'lasso', lassoOptions: { shape: 'polygon' } as never }),
+ });
+ expect(engine.interaction.set).toHaveBeenCalledWith('lassoOptions', { shape: 'freehand' });
+ });
+
+ it('marquee cycles rect → ellipse when already active', () => {
+ const engine = run('canvas.tool.marquee', {
+ engine: createEngine({ activeTool: 'marquee', marqueeOptions: { kind: 'rect' } as never }),
+ });
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ expect(engine.interaction.set).toHaveBeenCalledWith('marqueeOptions', { kind: 'ellipse' });
+ });
+
+ it('marquee cycles ellipse → rect', () => {
+ const engine = run('canvas.tool.marquee', {
+ engine: createEngine({ activeTool: 'marquee', marqueeOptions: { kind: 'ellipse' } as never }),
+ });
+ expect(engine.interaction.set).toHaveBeenCalledWith('marqueeOptions', { kind: 'rect' });
+ });
+});
+
+describe('history, selection, and brush size', () => {
+ it('undo and redo drive the engine history, never the reducer', () => {
+ expect(run('canvas.undo').history.undo).toHaveBeenCalled();
+ expect(run('canvas.redo').history.redo).toHaveBeenCalled();
+ expect(dispatch).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['canvas.selectAll', 'selectAll'],
+ ['canvas.deselect', 'deselect'],
+ ['canvas.invertSelection', 'invertSelection'],
+ ] as const)('%s calls selection.%s', (commandId, method) => {
+ expect(run(commandId).selection[method]).toHaveBeenCalled();
+ });
+
+ it.each([
+ ['canvas.brushSizeDown', -1],
+ ['canvas.brushSizeUp', 1],
+ ])('%s steps the brush size by %i', (commandId, step) => {
+ expect(run(commandId).tools.stepBrushSize).toHaveBeenCalledWith(step);
+ });
+
+ it('resetSelected clears the selected layer mask', () => {
+ expect(run('canvas.resetSelected').layers.clearMask).toHaveBeenCalledWith('a');
+ });
+});
+
+describe('mergeDown', () => {
+ it('merges two mergeable rasters', () => {
+ const engine = run('canvas.mergeDown');
+ expect(engine.layers.mergeLayerDown).toHaveBeenCalledWith('a');
+ });
+
+ it('refuses when the selected layer is bottom-most', () => {
+ const engine = run('canvas.mergeDown', { document: documentOf([rasterLayer('a'), rasterLayer('b')], 'b') });
+ expect(engine.layers.mergeLayerDown).not.toHaveBeenCalled();
+ });
+
+ it('refuses with no selected layer', () => {
+ const engine = run('canvas.mergeDown', { document: documentOf([rasterLayer('a')], null) });
+ expect(engine.layers.mergeLayerDown).not.toHaveBeenCalled();
+ });
+});
+
+describe('toggleNonRasterLayers', () => {
+ it('does nothing when there are no hideable layers', () => {
+ const engine = run('canvas.toggleNonRasterLayers');
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('hides all hideable layers when all are visible, and restores prior state on undo', () => {
+ const mask = rasterLayer('m', { type: 'inpaint_mask' } as Partial<CanvasLayerContract>);
+ const engine = run('canvas.toggleNonRasterLayers', { document: documentOf([rasterLayer('a'), mask], 'a') });
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.toggleNonRasterLayers',
+ { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] },
+ { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: false }] }
+ );
+ });
+
+ it('reveals hideable layers when any is already hidden', () => {
+ const mask = rasterLayer('m', { isHidden: true, type: 'inpaint_mask' } as Partial<CanvasLayerContract>);
+ const engine = run('canvas.toggleNonRasterLayers', { document: documentOf([rasterLayer('a'), mask], 'a') });
+ expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ 'widgets.canvas.commands.toggleNonRasterLayers',
+ { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: false }] },
+ { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] }
+ );
+ });
+});
+
+describe('robustness', () => {
+ it('ignores an unknown command id', () => {
+ const engine = run('canvas.nonexistent');
+ expect(dispatch).not.toHaveBeenCalled();
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
+ it('never throws without an engine', () => {
+ for (const commandId of [
+ 'canvas.undo',
+ 'canvas.redo',
+ 'canvas.deleteSelected',
+ 'canvas.duplicateLayer',
+ 'canvas.mergeDown',
+ 'canvas.selectAll',
+ 'canvas.tool.lasso',
+ 'canvas.tool.marquee',
+ 'canvas.toggleNonRasterLayers',
+ 'canvas.resetSelected',
+ 'canvas.nudgeUp',
+ 'canvas.brushSizeUp',
+ ]) {
+ expect(() => executeCanvasHotkeyCommand(commandId, contextOf({ engine: null }))).not.toThrow();
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
new file mode 100644
index 0000000000..e1dad92827
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -0,0 +1,233 @@
+import type { CanvasDocumentContractV2, CanvasEngine } from '@workbench/canvas-engine/api';
+import type { LayerReorderKind } from '@workbench/canvasLayerOps';
+import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
+
+import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';
+import {
+ deleteLayerActions,
+ duplicateLayerActions,
+ reorderIdsForHotkey,
+ reorderLayerActions,
+} from '@workbench/canvasLayerOps';
+import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
+
+/** Command id → document-space nudge delta (shift variants are ×10). */
+const NUDGE_DELTAS: Record<string, { dx: number; dy: number }> = {
+ 'canvas.nudgeDown': { dx: 0, dy: 1 },
+ 'canvas.nudgeDownLarge': { dx: 0, dy: 10 },
+ 'canvas.nudgeLeft': { dx: -1, dy: 0 },
+ 'canvas.nudgeLeftLarge': { dx: -10, dy: 0 },
+ 'canvas.nudgeRight': { dx: 1, dy: 0 },
+ 'canvas.nudgeRightLarge': { dx: 10, dy: 0 },
+ 'canvas.nudgeUp': { dx: 0, dy: -1 },
+ 'canvas.nudgeUpLarge': { dx: 0, dy: -10 },
+};
+
+/** Command id → z-reorder direction (index 0 = top-most; "forward" moves toward 0). */
+const REORDER_KINDS: Record<string, LayerReorderKind> = {
+ 'canvas.layerBackward': 'backward',
+ 'canvas.layerForward': 'forward',
+ 'canvas.layerToBack': 'back',
+ 'canvas.layerToFront': 'front',
+};
+
+/**
+ * Everything the canvas hotkey dispatcher reads or drives. The widget supplies
+ * these from its render scope; keeping them as an explicit parameter is what
+ * makes the ~35-command dispatch table testable without mounting React.
+ */
+export interface CanvasHotkeyContext {
+ readonly document: CanvasDocumentContractV2;
+ readonly engine: CanvasEngine | null;
+ /** Any staging slot exists, so left/right cycle candidates instead of nudging. */
+ readonly hasStagingSlots: boolean;
+ /** A staged candidate is selected, so Delete discards it instead of touching layers. */
+ readonly hasSelectedStagedCandidate: boolean;
+ readonly isInteractionLocked: boolean;
+ readonly dispatch: CanvasProjectMutationDispatch;
+ readonly copySelection: (cut: boolean) => void;
+ readonly pasteFromClipboard: () => void;
+ readonly createLayerId: () => string;
+ readonly t: (key: string) => string;
+}
+
+/**
+ * Routes one canvas command id to its effect.
+ *
+ * Ordering is load-bearing and reads top-down as a precedence list: staging
+ * cycling and staged-candidate discard win over layer commands, the interaction
+ * lock then blocks everything except the view tool, and only after those do
+ * nudge, reorder, and the per-command table apply.
+ */
+export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyContext): void => {
+ const { createLayerId, dispatch, document, engine, t } = ctx;
+ const { layers, selectedLayerId } = document;
+ const selectedIndex = selectedLayerId ? layers.findIndex((layer) => layer.id === selectedLayerId) : -1;
+ const selectedLayer = selectedIndex >= 0 ? layers[selectedIndex] : undefined;
+
+ if ((commandId === 'canvas.prevEntity' || commandId === 'canvas.nudgeLeft') && ctx.hasStagingSlots) {
+ dispatch({ direction: -1, type: 'cycleStagedImage' });
+ return;
+ }
+
+ if ((commandId === 'canvas.nextEntity' || commandId === 'canvas.nudgeRight') && ctx.hasStagingSlots) {
+ dispatch({ direction: 1, type: 'cycleStagedImage' });
+ return;
+ }
+
+ if (commandId === 'canvas.deleteSelected' && ctx.hasSelectedStagedCandidate) {
+ dispatch({ type: 'discardSelectedStagedImage' });
+ return;
+ }
+
+ if (ctx.isInteractionLocked) {
+ if (commandId === 'canvas.tool.view') {
+ engine?.tools.setTool('view');
+ }
+ return;
+ }
+
+ // Arrow-key nudge: engine owns the bounds/lock logic (no-op with no/locked selection).
+ const nudge = NUDGE_DELTAS[commandId];
+ if (nudge) {
+ engine?.layers.nudgeSelectedLayer(nudge.dx, nudge.dy);
+ return;
+ }
+
+ // Layer z-reorder: same forward/inverse construction as the layers panel.
+ const reorderKind = REORDER_KINDS[commandId];
+ if (reorderKind) {
+ if (!engine || selectedIndex < 0) {
+ return;
+ }
+ const currentIds = layers.map((layer) => layer.id);
+ const nextIds = reorderIdsForHotkey(currentIds, selectedIndex, reorderKind);
+ if (!nextIds) {
+ return;
+ }
+ const { forward, inverse } = reorderLayerActions(currentIds, nextIds);
+ engine.layers.commitStructural(t('widgets.canvas.commands.reorderLayer'), forward, inverse);
+ return;
+ }
+
+ if (commandId === 'canvas.deleteSelected') {
+ // With a live pixel selection, Delete clears the selected PIXELS — the
+ // Photoshop meaning. Only with no selection does it delete the layer.
+ if (engine?.interaction.get('hasSelection')) {
+ engine.selection.eraseSelection();
+ } else if (engine && selectedLayer && selectedIndex >= 0) {
+ const { forward, inverse } = deleteLayerActions(selectedLayer, selectedIndex);
+ engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), forward, inverse);
+ }
+ } else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {
+ ctx.copySelection(commandId === 'canvas.cutSelection');
+ } else if (commandId === 'canvas.pasteImage') {
+ ctx.pasteFromClipboard();
+ } else if (commandId === 'canvas.toggleNonRasterLayers') {
+ // Hide, never disable: this is the "get the overlays out of my way"
+ // shortcut, and it must leave the generated image untouched.
+ const hideable = layers.filter(isHideableLayer);
+ if (engine && hideable.length > 0) {
+ const nextHidden = hideable.every((layer) => !isLayerHidden(layer));
+ engine.layers.commitStructural(
+ t('widgets.canvas.commands.toggleNonRasterLayers'),
+ {
+ type: 'setCanvasLayersHidden',
+ updates: hideable.map((layer) => ({ id: layer.id, isHidden: nextHidden })),
+ },
+ {
+ type: 'setCanvasLayersHidden',
+ updates: hideable.map((layer) => ({ id: layer.id, isHidden: isLayerHidden(layer) })),
+ }
+ );
+ }
+ } else if (commandId === 'canvas.resetSelected') {
+ if (engine && selectedLayer) {
+ engine.layers.clearMask(selectedLayer.id);
+ }
+ } else if (commandId === 'canvas.undo') {
+ // Canvas undo/redo is engine-scoped: it drives the engine-owned pixel/
+ // structural history, NOT project-level (reducer) undo. When the canvas
+ // history is empty this is a no-op — it deliberately does not fall back to
+ // `undoProjectChange` (project undo keeps its own commands/hotkeys, e.g.
+ // the workflow editor's `workflows.undo`).
+ engine?.history.undo();
+ } else if (commandId === 'canvas.redo') {
+ engine?.history.redo();
+ } else if (commandId === 'canvas.tool.view') {
+ engine?.tools.setTool('view');
+ } else if (commandId === 'canvas.tool.move') {
+ engine?.tools.setTool('move');
+ } else if (commandId === 'canvas.transformSelected') {
+ // Selecting the transform tool opens a session on the selected layer (if any
+ // eligible one); Apply/Cancel (enter/esc) are handled engine-side.
+ engine?.tools.setTool('transform');
+ } else if (commandId === 'canvas.tool.bbox') {
+ engine?.tools.setTool('bbox');
+ } else if (commandId === 'canvas.tool.brush') {
+ engine?.tools.setTool('brush');
+ } else if (commandId === 'canvas.tool.eraser') {
+ engine?.tools.setTool('eraser');
+ } else if (commandId === 'canvas.tool.lasso') {
+ if (engine) {
+ // Pressing the shortcut while already on the tool cycles its shape
+ // (Photoshop-style) rather than re-selecting the tool it is already on.
+ if (engine.interaction.get('activeTool') === 'lasso') {
+ const lasso = engine.interaction.get('lassoOptions');
+ engine.interaction.set('lassoOptions', {
+ ...lasso,
+ shape: lasso.shape === 'freehand' ? 'polygon' : 'freehand',
+ });
+ } else {
+ engine.tools.setTool('lasso');
+ }
+ }
+ } else if (commandId === 'canvas.tool.marquee') {
+ if (engine) {
+ if (engine.interaction.get('activeTool') === 'marquee') {
+ const marquee = engine.interaction.get('marqueeOptions');
+ engine.interaction.set('marqueeOptions', {
+ ...marquee,
+ kind: marquee.kind === 'rect' ? 'ellipse' : 'rect',
+ });
+ } else {
+ engine.tools.setTool('marquee');
+ }
+ }
+ } else if (commandId === 'canvas.tool.shape') {
+ engine?.tools.setTool('shape');
+ } else if (commandId === 'canvas.tool.text') {
+ engine?.tools.setTool('text');
+ } else if (commandId === 'canvas.tool.gradient') {
+ engine?.tools.setTool('gradient');
+ } else if (commandId === 'canvas.selectAll') {
+ engine?.selection.selectAll();
+ } else if (commandId === 'canvas.deselect') {
+ engine?.selection.deselect();
+ } else if (commandId === 'canvas.invertSelection') {
+ engine?.selection.invertSelection();
+ } else if (commandId === 'canvas.brushSizeDown') {
+ engine?.tools.stepBrushSize(-1);
+ } else if (commandId === 'canvas.brushSizeUp') {
+ engine?.tools.stepBrushSize(1);
+ } else if (commandId === 'canvas.duplicateLayer') {
+ // With a live pixel selection, mod+J is "layer via copy" — it lifts just
+ // the selected pixels. With none, it duplicates the whole layer.
+ if (engine?.interaction.get('hasSelection')) {
+ engine.selection.liftSelectionToLayer();
+ } else if (engine && selectedLayer) {
+ const { forward, inverse } = duplicateLayerActions(selectedLayer.id, createLayerId());
+ engine.layers.commitStructural(t('widgets.canvas.commands.duplicateLayer'), forward, inverse);
+ }
+ } else if (commandId === 'canvas.mergeDown') {
+ // Gate on the SAME predicate the layers panel's context menu uses to
+ // enable/disable its "Merge Down" item (`canMergeLayerDown`), so the hotkey
+ // can never fire where the menu would refuse — e.g. a mask layer selected,
+ // or a mask directly below the selection. `engine.layers.mergeLayerDown` also
+ // guards this itself (defense in depth for callers other than this hotkey),
+ // but checking here keeps the two surfaces visibly in lockstep.
+ if (engine && selectedLayer && canMergeLayerDown(layers, selectedIndex, true)) {
+ engine.layers.mergeLayerDown(selectedLayer.id);
+ }
+ }
+};