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): name the frame consistently and make layer actions reachable

Josh Corbett6c99c68899e8
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 3b39a11440..f3ff9a5630 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,15 +2,15 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 800593,
+ "brotliBytes": 800835,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 799703,
+ "gzipBytes": 800259,
"imageRawBytes": 44398,
- "initialRawBytes": 2061277,
+ "initialRawBytes": 2062881,
"largestAssetRawBytes": 752413,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 99011,
+ "ownedRawBytes": 99014,
"requestCount": 35,
"scriptRequestCount": 19,
"sourceOwners": [
@@ -349,15 +349,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1197162,
+ "brotliBytes": 1199599,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1190526,
+ "gzipBytes": 1192707,
"imageRawBytes": 44398,
- "initialRawBytes": 3293139,
+ "initialRawBytes": 3301853,
"largestAssetRawBytes": 752413,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 155635,
+ "ownedRawBytes": 156181,
"requestCount": 71,
"scriptRequestCount": 55,
"sourceOwners": [
@@ -1104,7 +1104,7 @@
"source": "src/app/WorkbenchApp.tsx"
}
},
- "capturedAt": "2026-10-18",
+ "capturedAt": "2026-10-20",
"developmentInvalidation": {
"platformUiBarrel": {
"specifier": "@platform/ui",
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 4c1b36ed33..42b0504fc6 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -162,9 +162,9 @@
"largestAssetRawBytes": 305523,
"otherRawBytes": 0,
"requestCount": 9,
- "scriptRawBytes": 518622,
+ "scriptRawBytes": 527661,
"scriptRequestCount": 9,
- "totalRawBytes": 518622
+ "totalRawBytes": 527661
},
"domContentLoadedMedianMs": 100.40000009536743,
"id": "editor-canvas",
@@ -200,9 +200,9 @@
"largestAssetRawBytes": 305523,
"otherRawBytes": 0,
"requestCount": 9,
- "scriptRawBytes": 518622,
+ "scriptRawBytes": 527661,
"scriptRequestCount": 9,
- "totalRawBytes": 518622
+ "totalRawBytes": 527661
},
"domContentLoadedMedianMs": 97.7000002861023,
"id": "editor-canvas",
@@ -2892,6 +2892,7 @@
"source:src/workbench/widgets/autosave-status/manifest.ts",
"source:src/workbench/widgets/canvas/CanvasBottomOverlay.tsx",
"source:src/workbench/widgets/canvas/CanvasCreateFromBboxSubmenu.tsx",
+ "source:src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx",
"source:src/workbench/widgets/canvas/CanvasEditRefusalNotices.tsx",
"source:src/workbench/widgets/canvas/CanvasFloatingBar.tsx",
"source:src/workbench/widgets/canvas/CanvasGlobalContextMenu.tsx",
@@ -2930,6 +2931,7 @@
"source:src/workbench/widgets/canvas/engineStoreHooks.ts",
"source:src/workbench/widgets/canvas/executeCanvasImageDropImport.ts",
"source:src/workbench/widgets/canvas/fitBbox.ts",
+ "source:src/workbench/widgets/canvas/frameIcons.ts",
"source:src/workbench/widgets/canvas/implementation.ts",
"source:src/workbench/widgets/canvas/invoke/canvasCompositing.ts",
"source:src/workbench/widgets/canvas/invoke/canvasScaling.ts",
@@ -3042,7 +3044,7 @@
"source:src/workbench/widgets/layers/runLayerWorkflow.ts",
"source:src/workbench/widgets/layers/selectedModel.ts",
"source:src/workbench/widgets/layers/useAddLayer.ts",
- "source:src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts",
+ "source:src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts",
"source:src/workbench/widgets/layers/useLayerSelectionCommands.ts",
"source:src/workbench/widgets/layers/useLayerStackActions.ts",
"source:src/workbench/widgets/layers/useSelectedMainModel.ts",
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
index 661cc95bd7..7bb01c4dd2 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.test.ts
@@ -468,13 +468,13 @@ describe('compileCanvasGraph', () => {
it('rejects a zero-area bbox', () => {
expect(() => compile(sd1Model, 'txt2img', { bbox: { height: 0, width: 512, x: 0, y: 0 } })).toThrow(
- 'Canvas bounding box must have a positive area.'
+ 'Canvas frame must have a positive area.'
);
});
it('rejects fractional bbox dimensions before emitting backend resize fields', () => {
expect(() => compile(flux2Model, 'txt2img', { bbox: { height: 888, width: 1024.5, x: 0, y: 0 } })).toThrow(
- 'Canvas bounding box dimensions must be whole pixels.'
+ 'Canvas frame dimensions must be whole pixels.'
);
});
diff --git a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
index 029ccde6d4..ed2bfe411c 100644
--- a/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
+++ b/invokeai/frontend/webv2/src/features/generation/core/canvas/compileCanvasGraph.ts
@@ -139,9 +139,9 @@ const getCanvasValidationReasons = (input: CompileCanvasGraphInput, processingSi
}
if (!Number.isFinite(bbox.width) || !Number.isFinite(bbox.height) || bbox.width <= 0 || bbox.height <= 0) {
- reasons.push('Canvas bounding box must have a positive area.');
+ reasons.push('Canvas frame must have a positive area.');
} else if (!Number.isInteger(bbox.width) || !Number.isInteger(bbox.height)) {
- reasons.push('Canvas bounding box dimensions must be whole pixels.');
+ reasons.push('Canvas frame dimensions must be whole pixels.');
}
if (isImageMode(mode)) {
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
index c8fe41f0db..931e64e621 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
@@ -11,7 +11,7 @@ import { toPlatformHotkey } from './resolve';
describe('firstPartyHotkeyCatalog', () => {
it('keeps legacy default hotkey parity', () => {
- expect(firstPartyHotkeyCatalog).toHaveLength(120);
+ expect(firstPartyHotkeyCatalog).toHaveLength(121);
expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.togglePreview');
expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');
expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.openCommandPalette');
@@ -49,6 +49,39 @@ describe('firstPartyHotkeyCatalog', () => {
expect(reset).toMatchObject({ defaultKeys: ['d'], implemented: true });
});
+ it('offers crop all layers to frame unbound, for a key the user chooses', () => {
+ const cropAll = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.cropAllLayersToFrame');
+
+ expect(cropAll).toMatchObject({ defaultKeys: [], implemented: true, title: 'Crop All Layers To Frame' });
+ });
+
+ it('binds transform to Shift+T only, leaving Mod+T to the browser', () => {
+ const transform = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.transformSelected');
+
+ expect(transform).toMatchObject({ defaultKeys: ['shift+t'], implemented: true, title: 'Transform Selected Layer' });
+ });
+
+ it.each([
+ ['canvas.setZoomTo100Percent', 'mod+1', 'Zoom to 100%'],
+ ['canvas.setZoomTo200Percent', 'mod+2', 'Zoom to 200%'],
+ ['canvas.setZoomTo400Percent', 'mod+3', 'Zoom to 400%'],
+ ['canvas.setZoomTo800Percent', 'mod+4', 'Zoom to 800%'],
+ ])('implements %s on %s, titled %s', (id, key, title) => {
+ const zoom = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === id);
+
+ expect(zoom).toMatchObject({ defaultKeys: [key], implemented: true, title });
+ });
+
+ // Ids keep "bbox" so saved custom bindings survive; only the visible titles say "Frame".
+ it('titles every frame command without the word bbox', () => {
+ const titles = firstPartyHotkeyCatalog.map((hotkey) => hotkey.title);
+
+ expect(titles.filter((title) => /bbox|bounding box/i.test(title))).toEqual([]);
+ expect(firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.fitBboxToMasks')?.title).toBe(
+ 'Fit Frame To Masks'
+ );
+ });
+
it('keeps layout saving explicit and out of editable controls', () => {
const saveLayout = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'app.saveLayoutPreset');
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index 9db3d0b247..2b3d717080 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -5,7 +5,7 @@ import { IS_MAC_OS } from './keys';
/**
* Only registered handlers intercept chords; handlerless catalog entries do not. App chords are global, other
* chords require widget focus, and editable fields are excluded unless explicitly allowed. Overrides include
- * print/search/settings, undo/redo, selection/clipboard, and Canvas merge/deselect/invert/transform;
+ * print/search/settings, undo/redo, selection/clipboard, and Canvas merge/deselect/invert;
* browser-reserved chords work only when delivered to the page.
*/
@@ -52,6 +52,7 @@ const implemented = new Set([
'app.togglePanels',
'app.togglePreview',
'app.toggleRightPanel',
+ 'canvas.cropAllLayersToFrame',
'canvas.deleteSelected',
'canvas.fitBboxToLayers',
'canvas.fitBboxToMasks',
@@ -59,11 +60,16 @@ const implemented = new Set([
'canvas.nextEntity',
'canvas.saveBboxToGallery',
'canvas.saveToGallery',
+ 'canvas.setZoomTo100Percent',
+ 'canvas.setZoomTo200Percent',
+ 'canvas.setZoomTo400Percent',
+ 'canvas.setZoomTo800Percent',
'canvas.prevEntity',
'canvas.quickSwitch',
'canvas.redo',
'canvas.setFillColorsToDefault',
'canvas.toggleFillColor',
+ 'canvas.transformSelected',
'canvas.undo',
'gallery.clearSelection',
'gallery.deleteSelection',
@@ -249,7 +255,7 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('app', 'togglePanels', ['f']),
hotkey('app', 'togglePreview', ['z']),
hotkey('canvas', 'selectBrushTool', ['b']),
- hotkey('canvas', 'selectBboxTool', ['c']),
+ hotkey('canvas', 'selectBboxTool', ['c'], { title: 'Select Frame Tool' }),
hotkey('canvas', 'decrementToolWidth', ['[']),
hotkey('canvas', 'incrementToolWidth', [']']),
hotkey('canvas', 'selectEraserTool', ['e']),
@@ -261,18 +267,18 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'setFillColorsToDefault', ['d']),
hotkey('canvas', 'toggleFillColor', ['x']),
hotkey('canvas', 'fitLayersToCanvas', ['mod+0']),
- hotkey('canvas', 'fitBboxToCanvas', ['mod+shift+0']),
- hotkey('canvas', 'fitBboxToLayers', ['shift+n']),
- hotkey('canvas', 'setZoomTo100Percent', ['mod+1']),
- hotkey('canvas', 'setZoomTo200Percent', ['mod+2']),
- hotkey('canvas', 'setZoomTo400Percent', ['mod+3']),
- hotkey('canvas', 'setZoomTo800Percent', ['mod+4']),
+ hotkey('canvas', 'fitBboxToCanvas', ['mod+shift+0'], { title: 'Fit Frame To Canvas' }),
+ hotkey('canvas', 'fitBboxToLayers', ['shift+n'], { title: 'Fit Frame To Layers' }),
+ hotkey('canvas', 'setZoomTo100Percent', ['mod+1'], { title: 'Zoom to 100%' }),
+ hotkey('canvas', 'setZoomTo200Percent', ['mod+2'], { title: 'Zoom to 200%' }),
+ hotkey('canvas', 'setZoomTo400Percent', ['mod+3'], { title: 'Zoom to 400%' }),
+ hotkey('canvas', 'setZoomTo800Percent', ['mod+4'], { title: 'Zoom to 800%' }),
hotkey('canvas', 'quickSwitch', ['q']),
hotkey('canvas', 'deleteSelected', ['delete', 'backspace']),
hotkey('canvas', 'resetSelected', ['shift+c']),
hotkey('canvas', 'mergeDown', ['mod+e']),
hotkey('canvas', 'mergeVisible', ['mod+shift+e']),
- hotkey('canvas', 'transformSelected', ['shift+t']),
+ hotkey('canvas', 'transformSelected', ['shift+t'], { title: 'Transform Selected Layer' }),
hotkey('canvas', 'filterSelected', ['shift+f']),
hotkey('canvas', 'invertMask', ['shift+v']),
hotkey('canvas', 'undo', ['mod+z']),
@@ -286,12 +292,13 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'applySegmentAnything', ['enter']),
hotkey('canvas', 'cancelSegmentAnything', ['esc']),
hotkey('canvas', 'toggleNonRasterLayers', ['shift+h']),
- hotkey('canvas', 'fitBboxToMasks', ['shift+b']),
- hotkey('canvas', 'toggleBbox', ['shift+o']),
- // New canvas session and the gallery saves: no default keys — assignable via the hotkeys settings.
+ hotkey('canvas', 'fitBboxToMasks', ['shift+b'], { title: 'Fit Frame To Masks' }),
+ hotkey('canvas', 'toggleBbox', ['shift+o'], { title: 'Toggle Frame' }),
+ // New canvas session, the gallery saves and crop all: no default keys — assignable via the hotkeys settings.
hotkey('canvas', 'newSession', []),
hotkey('canvas', 'saveToGallery', []),
- hotkey('canvas', 'saveBboxToGallery', []),
+ hotkey('canvas', 'saveBboxToGallery', [], { title: 'Save Frame To Gallery' }),
+ hotkey('canvas', 'cropAllLayersToFrame', []),
hotkey('workflows', 'addNode', ['shift+a', 'space']),
hotkey('workflows', 'copySelection', ['mod+c']),
hotkey('workflows', 'pasteSelection', ['mod+v']),
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/README.md b/invokeai/frontend/webv2/src/workbench/widget-frame/README.md
index dc4cce2b45..8057db70c5 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/README.md
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/README.md
@@ -38,7 +38,7 @@ Workbench focus is transient, never persisted. `WorkbenchFocusProvider` (`workbe
- **Recall is the one reveal that moves no focus.** Recall raises and expands its window but leaves keyboard focus, outline, and hotkey target where user had them; next press or focus change brings them back into agreement. Since focus inside active window does not re-raise, it cannot re-bury the window a recall just revealed.
- **Keys follow the outline.** A press inside a window moves keyboard focus into it when focus was elsewhere; a press on a docked region pulls focus out of a floating window. Floating layer renders windows in fixed DOM order and stacks them by z-index alone: raising a window never moves its node, which would drop the focus that raised it.
- **Focus follows placement:** into window after Float and after a marker or "Show window" reveal; into the region a docked rail tab shows in when it is selected, so keys stop going to a window that held them; into return region after Dock; after Remove from a marker's menu, into center when it gets its view back, else into the panel the window's own rail is showing, or center when that rail shows none (emptied by float or collapsed). Removing a window from a rail's enable menu moves no focus: that menu stays open and keeps it. A focus move targets region frame on screen (side regions keep earlier panels mounted but hidden), waits a bounded time for its widget to mount, and is abandoned if user presses elsewhere first. Every panel frame carries its instance's identity, including stand-in for a widget whose view cannot render, so a move into it lands.
-- **Hotkeys read the same target.** `HotkeyContext.focusedRegion` is `WidgetRegion | 'floating' | null`; persisted `WidgetRegion` unchanged. A key press is aimed at widget under event target first and, outside any widget's DOM, at active floating instance or focused region's active member (`resolveHotkeyTarget`). A region's active pointer counts only while it names a member, so a view that floated out of an emptied center answers as a window, not as center. Floating command source carries `region: 'floating'` and is never used to index `widgetRegions`. Generic `focused-region` shortcuts match under a window, shortcuts tied to a named docked region do not, and a floating widget's own `focused-region` contribution follows its window at the same priority it has when docked. A binding with a `targetSelector` (prompt weighting: an editable prompt whose model reads attention syntax) is a candidate only while the key press's target matches it; elsewhere the next candidate wins, or nothing claims the key and it keeps its browser behavior.
+- **Hotkeys read the same target.** `HotkeyContext.focusedRegion` is `WidgetRegion | 'floating' | null`; persisted `WidgetRegion` unchanged. A key press is aimed at widget under event target first and, outside any widget's DOM, at active floating instance or focused region's active member (`resolveHotkeyTarget`). A region's active pointer counts only while it names a member, so a view that floated out of an emptied center answers as a window, not as center. Floating command source carries `region: 'floating'` and is never used to index `widgetRegions`. Generic `focused-region` shortcuts match under a window, shortcuts tied to a named docked region do not, and a floating widget's own `focused-region` contribution follows its window at the same priority it has when docked. A binding with a `targetSelector` (prompt weighting: an editable prompt whose model reads attention syntax) is a candidate only while the key press's target matches it; elsewhere the next candidate wins, or nothing claims the key and it keeps its browser behavior. Canvas engine's own keys (Enter, Escape, C, and the Space and Alt holds) ask the same judge with the same inputs: the canvas surface maps the target to this canvas, a companion Layers widget, or elsewhere.
- **Modal dialogs suspend application shortcuts.** Every dialog is built on Platform `Dialog` root (`platform/ui/Dialog.tsx`; lint rejects Chakra's dialog and its drawer, which has no such root yet), which registers with `platform/ui/modalPresence` while its own open state holds, unless declared `modal={false}`. A dialog whose module is still loading uses `Dialog.Pending` as suspense fallback, so it is modal from keypress that opened it. While any registration stands, hotkey runtime runs only hotkeys marked `allowInModal` (command palette toggle), so invoke, global and widget shortcuts stay inactive wherever focus is, and keys the dialog handles itself (Enter, Escape, typing) keep browser behavior; Canvas engine's own key listener takes no key either. Both ask about the key press they are handling: a press that began under a modal still counts as aimed at it, because the Escape that dismisses a dialog releases its presence before the same press reaches bubble-phase listeners. Presence follows interactivity, not DOM: a closing dialog that stays mounted through its exit animation is inert and releases at close, so next press reaches application; reopening re-registers at once, an outer dialog stays registered while an inner one closes, and an unmount releases without a close. Media paste reads the same presence. Popovers and menus do not register.
## Contextual shortcut guidance
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx
new file mode 100644
index 0000000000..f192dfa7fc
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasCropAllLayersMenuItem.tsx
@@ -0,0 +1,34 @@
+import type { CanvasEngineLayerCapability } from '@workbench/canvas-engine/api';
+
+import { MenuActionItem } from '@platform/ui/Menu';
+import { useNotify } from '@workbench/useNotify';
+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
+import { CropIcon } from 'lucide-react';
+import { useCallback } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { cropAllLayersToFrame, hasCroppableLayers } from './canvasContextMenu';
+
+/** Canvas-menu action that crops every unlocked layer to the frame as one undo step and reports the count. */
+export const CanvasCropAllLayersMenuItem = ({
+ disabled,
+ layers,
+}: {
+ disabled: boolean;
+ layers: Pick<CanvasEngineLayerCapability, 'cropAllLayersToBbox'>;
+}) => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const hasCroppable = useActiveProjectSelector((project) => hasCroppableLayers(project.canvas.document));
+ const onSelect = useCallback(() => void cropAllLayersToFrame(layers, notify, t), [layers, notify, t]);
+
+ return (
+ <MenuActionItem
+ disabled={disabled || !hasCroppable}
+ icon={CropIcon}
+ label={t('widgets.canvas.contextMenu.cropAllLayersToBbox')}
+ value="crop-all-layers-to-bbox"
+ onSelect={onSelect}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
index 7f68f686a7..04662434f2 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.tsx
@@ -22,11 +22,10 @@ import {
ChevronDownIcon,
DatabaseIcon,
FilePlusIcon,
- FrameIcon,
+ FullscreenIcon,
MaximizeIcon,
Redo2Icon,
SaveIcon,
- SquareDashedBottomIcon,
Trash2Icon,
Undo2Icon,
} from 'lucide-react';
@@ -39,6 +38,7 @@ import type { ResolvedCanvasSettings } from './canvasSettings';
import { useModelGridSize } from './bboxGrid';
import {
applyFitBbox,
+ CANVAS_HEADER_HOTKEYS,
confirmNewCanvas as confirmNewCanvasDocument,
executeCanvasHeaderCommand,
zoomAtViewportCentre,
@@ -46,6 +46,8 @@ import {
import { CANVAS_SNAP_TO_GRID_KEY, canvasSettingsEqual, resolveCanvasSettings } from './canvasSettings';
import { useCanvasCanRedo, useCanvasCanUndo, useCanvasDocumentEditingLocked, useCanvasZoom } from './engineStoreHooks';
import { computeFitBboxToLayers, computeFitBboxToMasks } from './fitBbox';
+import { FitFrameToMasksIcon } from './frameIcons';
+import { readCanvasCompositingSettings } from './invoke/canvasCompositing';
import { useCanvasGallerySave } from './useCanvasGallerySave';
import { reportStructuralCommit } from './useStructuralCommit';
import { formatZoomPercent, zoomMenuOptions } from './zoomOptions';
@@ -68,6 +70,10 @@ const selectModelBase = (project: Project): string | null => {
return typeof values?.model?.base === 'string' ? values.model.base : null;
};
+/** The project's clamped compositing mask blur, which fit-to-masks clears so the feathered edge stays in frame. */
+const selectMaskBlur = (project: Project): number =>
+ readCanvasCompositingSettings(getProjectWidgetValues(project, 'canvas')).maskBlur;
+
const selectModelVariant = (project: Project): string | null => {
const values = getProjectWidgetValues(project, 'generate') as { model?: { variant?: unknown } } | undefined;
return typeof values?.model?.variant === 'string' ? values.model.variant : null;
@@ -96,6 +102,7 @@ const CanvasHeaderActionsInner = ({
const modelBase = useActiveProjectSelector(selectModelBase);
const modelVariant = useActiveProjectSelector(selectModelVariant);
const settings = useActiveProjectSelector(selectCanvasSettings, canvasSettingsEqual);
+ const maskBlur = useActiveProjectSelector(selectMaskBlur);
const [isNewCanvasOpen, setIsNewCanvasOpen] = useState(false);
const closeNewCanvas = useCallback(() => setIsNewCanvasOpen(false), []);
@@ -111,7 +118,10 @@ const CanvasHeaderActionsInner = ({
const modelGrid = useModelGridSize(modelBase, modelVariant);
const gridSize = settings[CANVAS_SNAP_TO_GRID_KEY] ? modelGrid : 1;
const fitLayersRect = useMemo(() => computeFitBboxToLayers(document, gridSize), [document, gridSize]);
- const fitMasksRect = useMemo(() => computeFitBboxToMasks(document, gridSize), [document, gridSize]);
+ const fitMasksRect = useMemo(
+ () => computeFitBboxToMasks(document, gridSize, maskBlur),
+ [document, gridSize, maskBlur]
+ );
const commandContext = (): CanvasHeaderCommandContext => ({
document,
@@ -139,18 +149,13 @@ const CanvasHeaderActionsInner = ({
);
useEffect(() => {
- const entries = [
- ['canvas.fitBboxToLayers', t('widgets.canvas.controls.fitBboxToLayers'), ['shift+n']],
- ['canvas.fitBboxToMasks', t('widgets.canvas.controls.fitBboxToMasks'), ['shift+b']],
- // No default keys — assignable through the hotkeys settings.
- ['canvas.saveToGallery', t('widgets.canvas.contextMenu.saveCanvasToGallery'), []],
- ['canvas.saveBboxToGallery', t('widgets.canvas.contextMenu.saveBboxToGallery'), []],
- ['canvas.newSession', t('widgets.canvas.controls.newSession'), []],
- ] as const;
- const disposers = entries.flatMap(([id, title, defaultKeys]) => [
- runtime.commands.register({ handler: () => executeHeaderCommand(id), id, title }),
- runtime.hotkeys.register({ allowInEditable: false, commandId: id, defaultKeys: [...defaultKeys], id, title }),
- ]);
+ const disposers = CANVAS_HEADER_HOTKEYS.flatMap(([id, titleKey, defaultKeys]) => {
+ const title = t(titleKey);
+ return [
+ runtime.commands.register({ handler: () => executeHeaderCommand(id), id, title }),
+ runtime.hotkeys.register({ allowInEditable: false, commandId: id, defaultKeys: [...defaultKeys], id, title }),
+ ];
+ });
return () => {
disposers.forEach((dispose) => dispose());
};
@@ -202,7 +207,7 @@ const CanvasHeaderActionsInner = ({
variant="ghost"
onClick={() => applyFit(fitLayersRect, true)}
>
- <FrameIcon />
+ <FullscreenIcon />
</IconButton>
</Tooltip>
@@ -215,7 +220,7 @@ const CanvasHeaderActionsInner = ({
variant="ghost"
onClick={() => applyFit(fitMasksRect, false)}
>
- <SquareDashedBottomIcon />
+ <FitFrameToMasksIcon />
</IconButton>
</Tooltip>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
index 9a95cf35cb..df5f8ae1c4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.browser.test.tsx
@@ -2,19 +2,43 @@ import type { CanvasStateContractV3 } from '@workbench/canvas-engine/contracts';
import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
import type { EngineDeps, EngineRegistry } from '@workbench/canvas-operations/engineRegistry';
import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';
+import type { ReactNode } from 'react';
import { ChakraProvider } from '@chakra-ui/react';
import { ResizeHandle } from '@platform/ui/ResizeHandle';
import { system } from '@theme/system';
import { createEngineRegistry } from '@workbench/canvas-operations/engineRegistry';
import { createEmptyCanvasState } from '@workbench/canvasMigration';
-import { act, StrictMode, useRef } from 'react';
+import { FocusRegionProvider, useFocusRegionProps } from '@workbench/focusRegions';
+import { createTestFocusController } from '@workbench/focusRegions.testing';
+import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { act, StrictMode, useRef, useState } from 'react';
import { createRoot } from 'react-dom/client';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { userEvent } from 'vitest/browser';
+/** The surface reads the workbench only for key ownership: the active project and its widget placement. */
+const workbench = vi.hoisted(() => ({ store: null as unknown as WorkbenchInternalStore }));
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof WorkbenchContextModule>()),
+ useWorkbenchInternalStore: () => workbench.store,
+ useWorkbenchQueries: () => workbench.store.queries,
+ useWorkbenchSubscription: () => workbench.store.subscribe,
+}));
+
import { CanvasSurface } from './CanvasSurface';
+workbench.store = createWorkbenchStore();
+
+/** Focus for the surface outside the workbench shell; ownership itself is covered under a real provider below. */
+const TestFocus = ({ children }: { children: ReactNode }) => {
+ const [controller] = useState(() => createTestFocusController());
+ return <FocusRegionProvider controller={controller}>{children}</FocusRegionProvider>;
+};
+
type Cleanup = () => void | Promise<void>;
const cleanupStack: Cleanup[] = [];
@@ -103,9 +127,11 @@ const nextFrame = (): Promise<void> =>
const StrictCanvasHarness = ({ engine }: { engine: CanvasEngine }) => (
<StrictMode>
<ChakraProvider value={system}>
- <div data-testid="surface-bounds" style={{ height: 120, width: 160 }}>
- <CanvasSurface engine={engine} />
- </div>
+ <TestFocus>
+ <div data-testid="surface-bounds" style={{ height: 120, width: 160 }}>
+ <CanvasSurface engine={engine} instanceId="canvas" />
+ </div>
+ </TestFocus>
</ChakraProvider>
</StrictMode>
);
@@ -220,22 +246,24 @@ const ResizeDragHarness = ({ engine, showCanvas = true }: { engine: CanvasEngine
return (
<ChakraProvider value={system}>
- <div style={{ display: 'flex' }}>
- <div ref={paneRef} style={{ width: 100 }} />
- <ResizeHandle
- label="Resize pane"
- max={300}
- min={50}
- orientation="vertical"
- pane="before"
- paneRef={paneRef}
- value={100}
- onCommit={ignoreCommit}
- />
- <div data-testid="surface-bounds" style={{ height: 120, width: 160 }}>
- {showCanvas ? <CanvasSurface engine={engine} /> : null}
+ <TestFocus>
+ <div style={{ display: 'flex' }}>
+ <div ref={paneRef} style={{ width: 100 }} />
+ <ResizeHandle
+ label="Resize pane"
+ max={300}
+ min={50}
+ orientation="vertical"
+ pane="before"
+ paneRef={paneRef}
+ value={100}
+ onCommit={ignoreCommit}
+ />
+ <div data-testid="surface-bounds" style={{ height: 120, width: 160 }}>
+ {showCanvas ? <CanvasSurface engine={engine} instanceId="canvas" /> : null}
+ </div>
</div>
- </div>
+ </TestFocus>
</ChakraProvider>
);
};
@@ -344,3 +372,149 @@ describe('CanvasSurface keyboard ownership', () => {
await userEvent.keyboard('{/Space}');
});
});
+
+/** The shell's layout in miniature: the canvas, the Generate panel and the Layers panel, each a focus region. */
+const WorkbenchHarness = ({ engine }: { engine: CanvasEngine }) => (
+ <ChakraProvider value={system}>
+ <WorkbenchFocusProvider>
+ <Region instanceId="canvas" region="center" typeId="canvas">
+ <div style={{ height: 120, width: 160 }}>
+ <CanvasSurface engine={engine} instanceId="canvas" />
+ </div>
+ </Region>
+ <Region instanceId="generate" region="left" typeId="generate">
+ <span>Model</span>
+ <input aria-label="Prompt" />
+ </Region>
+ <Region instanceId="layers" region="right" typeId="layers">
+ <div role="tree">
+ <div aria-selected="true" role="treeitem" tabIndex={0}>
+ Layer
+ </div>
+ </div>
+ </Region>
+ </WorkbenchFocusProvider>
+ </ChakraProvider>
+);
+
+const Region = ({
+ children,
+ instanceId,
+ region,
+ typeId,
+}: {
+ children: ReactNode;
+ instanceId: string;
+ region: 'center' | 'left' | 'right';
+ typeId: string;
+}) => (
+ <div
+ {...useFocusRegionProps(region)}
+ data-hotkey-widget-instance-id={instanceId}
+ data-hotkey-widget-region={region}
+ data-hotkey-widget-type-id={typeId}
+ >
+ {children}
+ </div>
+);
+
+describe('CanvasSurface key owner', () => {
+ const mount = async () => {
+ const registry = createTrackedRegistry(20);
+ const projectId = workbench.store.getSnapshot().activeProject.id;
+ const { engine } = acquireTrackedEngine(registry, projectId, createEngineDeps(createEmptyCanvasState(64, 64)));
+ const host = document.createElement('div');
+ document.body.append(host);
+ const { root } = createTrackedRoot(host);
+ await act(async () => {
+ root.render(<WorkbenchHarness engine={engine} />);
+ await nextFrame();
+ });
+ const overlay = host.querySelectorAll('canvas')[1]!;
+ return {
+ clickCanvas: () => userEvent.click(overlay, { position: { x: 4, y: 4 } }),
+ clickGenerate: () => userEvent.click(host.querySelector('span')!),
+ clickLayersRow: () => userEvent.click(host.querySelector('[role="treeitem"]')!),
+ engine,
+ hasSelection: () => engine.interaction.get('hasSelection'),
+ overlay,
+ prompt: host.querySelector('input')!,
+ tool: () => engine.interaction.get('activeTool'),
+ };
+ };
+
+ it('keeps Escape and C from the canvas after a click in another widget', async () => {
+ const view = await mount();
+ view.engine.tools.setTool('view');
+ view.engine.selection.selectAll();
+ await view.clickGenerate();
+
+ await userEvent.keyboard('{Escape}');
+ await userEvent.keyboard('c');
+ expect(view.hasSelection()).toBe(true);
+ expect(view.tool()).toBe('view');
+ });
+
+ it('lets Escape and C act from the canvas and from a Layers row', async () => {
+ const view = await mount();
+ view.engine.tools.setTool('view');
+ view.engine.selection.selectAll();
+ await view.clickLayersRow();
+
+ await userEvent.keyboard('{Escape}');
+ expect(view.hasSelection()).toBe(false);
+ // Away from the canvas, a C tap selects the frame tool.
+ await userEvent.keyboard('c');
+ expect(view.tool()).toBe('bbox');
+
+ view.engine.tools.setTool('view');
+ view.engine.selection.selectAll();
+ await view.clickCanvas();
+ await userEvent.keyboard('{Escape}');
+ expect(view.hasSelection()).toBe(false);
+ await userEvent.keyboard('{c>}');
+ expect(view.tool()).toBe('bbox');
+ await userEvent.keyboard('{/c}');
+ });
+
+ it('applies Enter only from the canvas itself', async () => {
+ const view = await mount();
+ view.engine.tools.setTool('lasso');
+ view.engine.interaction.set('lassoOptions', { ...view.engine.interaction.get('lassoOptions'), shape: 'polygon' });
+ for (const position of [
+ { x: 20, y: 20 },
+ { x: 120, y: 20 },
+ { x: 120, y: 100 },
+ ]) {
+ await userEvent.click(view.overlay, { position });
+ }
+
+ await view.clickLayersRow();
+ await userEvent.keyboard('{Enter}');
+ await view.clickGenerate();
+ await userEvent.keyboard('{Enter}');
+ expect(view.hasSelection()).toBe(false);
+
+ await userEvent.click(view.overlay, { position: { x: 20, y: 100 } });
+ await userEvent.keyboard('{Enter}');
+ expect(view.hasSelection()).toBe(true);
+ });
+
+ it('keeps the Space hold over the hovered canvas after a click elsewhere, and never takes typing', async () => {
+ const view = await mount();
+ view.engine.tools.setTool('brush');
+ await view.clickGenerate();
+
+ await userEvent.hover(view.overlay);
+ await userEvent.keyboard('{Space>}');
+ expect(view.tool()).toBe('view');
+ await userEvent.keyboard('{/Space}');
+ expect(view.tool()).toBe('brush');
+
+ await userEvent.click(view.prompt);
+ await userEvent.hover(view.overlay);
+ await userEvent.keyboard('c');
+ expect(view.prompt.value).toBe('c');
+ expect(view.tool()).toBe('brush');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
index be106f52fa..fe7e2dd7e4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasSurface.tsx
@@ -1,16 +1,21 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop -- the container ref callback is intentionally re-created when `engine` changes, so a project switch detaches the old engine and attaches the new one. */
+import type { CanvasKeyOwner } from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
import type { CSSProperties, PointerEvent as ReactPointerEvent } from 'react';
import { Box } from '@chakra-ui/react';
import { isResizeDragActive, subscribeResizeDrag } from '@platform/ui/ResizeHandle';
+import { useWorkbenchFocusTarget } from '@workbench/focusRegions';
+import { getHotkeyTargetWidget, resolveHotkeyTarget } from '@workbench/hotkeys/targetWidget';
+import { getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import { shouldFocusCanvasSurface } from '@workbench/widgets/canvas/surfaceFocus';
import { TextEditPortal } from '@workbench/widgets/canvas/TextEditPortal';
+import { useWorkbenchQueries } from '@workbench/WorkbenchContext';
import { useRef } from 'react';
export type CanvasSurfaceEngine = Pick<
CanvasEngineHandle,
- 'document' | 'interaction' | 'layers' | 'surface' | 'viewport'
+ 'document' | 'interaction' | 'layers' | 'projectId' | 'surface' | 'viewport'
>;
/**
@@ -27,9 +32,30 @@ const focusCanvasSurface = (event: ReactPointerEvent<HTMLDivElement>) => {
* Bind document/overlay canvases and ResizeObserver through an engine-keyed ref callback with cleanup. The engine
* owns input without React interaction renders.
*/
-export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {
+export const CanvasSurface = ({ engine, instanceId }: { engine: CanvasSurfaceEngine; instanceId: string }) => {
const screenRef = useRef<HTMLCanvasElement>(null);
const overlayRef = useRef<HTMLCanvasElement>(null);
+ const getFocusTarget = useWorkbenchFocusTarget();
+ const queries = useWorkbenchQueries();
+
+ // The engine's own keys ask the judge the hotkey runtime asks, with the same inputs, only on keydown: this canvas
+ // owns the key, the Layers widget acting on its layers is a companion, and any other widget keeps it.
+ const resolveKeyOwner = (event: KeyboardEvent): CanvasKeyOwner => {
+ const project = queries.getSnapshot().activeProject;
+ if (project.id !== engine.projectId) {
+ return 'elsewhere';
+ }
+ const target = resolveHotkeyTarget({
+ focusTarget: getFocusTarget(),
+ project: getWidgetPlacementProject(project),
+ targetWidget: getHotkeyTargetWidget(event.target),
+ });
+ return target.activeInstanceId === instanceId
+ ? 'surface'
+ : target.activeWidgetTypeId === 'layers'
+ ? 'companion'
+ : 'elsewhere';
+ };
const bindContainer = (container: HTMLDivElement) => {
const screen = screenRef.current;
@@ -38,7 +64,7 @@ export const CanvasSurface = ({ engine }: { engine: CanvasSurfaceEngine }) => {
return;
}
- engine.surface.attach(screen, overlay, container);
+ engine.surface.attach(screen, overlay, container, { resolveKeyOwner });
// A handle drag defers the resize and full recomposition to its release; pixel CSS sizes make the interim
// canvas crop or reveal rather than stretch.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index d8a0a47980..7e6ee6b9b8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -31,14 +31,21 @@ import { useModelGridSize } from './bboxGrid';
import { CanvasBottomOverlay } from './CanvasBottomOverlay';
import { copyBlobToClipboard, decodeImageBlob, readClipboardImage } from './canvasClipboard';
import {
+ cropAllLayersToFrame,
resolveCanvasContextMenu,
resolveCanvasContextMenuBranch,
type CanvasContextMenuTarget,
} from './canvasContextMenu';
import { CanvasCreateFromBboxSubmenu } from './CanvasCreateFromBboxSubmenu';
+import { CanvasCropAllLayersMenuItem } from './CanvasCropAllLayersMenuItem';
import { CanvasEditRefusalNotices } from './CanvasEditRefusalNotices';
import { CanvasGlobalContextMenu } from './CanvasGlobalContextMenu';
-import { executeCanvasHotkeyCommand } from './canvasHotkeyCommands';
+import {
+ CANVAS_COMPANION_HOTKEYS,
+ CANVAS_ONLY_HOTKEYS,
+ executeCanvasHotkeyCommand,
+ reportTransformRefusal,
+} from './canvasHotkeyCommands';
import { resolveCanvasImageDrop } from './canvasImageDnd';
import { CanvasImageDropOverlay } from './CanvasImageDropOverlay';
import { createCanvasInteractionLockReader, getCanvasInteractionCapabilities } from './canvasInteractionLock';
@@ -416,6 +423,11 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
const selectedLayerIds = readLayerPanelState(projectId, document.selectedLayerId).selectedIds;
executeCanvasHotkeyCommand(commandId, {
copySelection,
+ cropAllLayers: () => {
+ if (engine) {
+ void cropAllLayersToFrame(engine.layers, notify, t);
+ }
+ },
dispatch: canvasDispatch,
document,
engine,
@@ -426,6 +438,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),
pasteFromClipboard,
reportLayerOperation: (refusal) => reportLayerOperation(refusal, notify.error, t),
+ reportTransformRefusal: (refusal) => reportTransformRefusal(refusal, notify.error, t),
reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),
reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),
resetActiveColors: colorCommands.resetPair,
@@ -436,64 +449,14 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
});
useEffect(() => {
- const hotkeys = [
- // Staging keeps `alt+[` / `alt+]`; bare left/right are registered as layer nudges,
- // then intercepted above to cycle staging slots while any slot exists.
- ['canvas.prevEntity', t('widgets.canvas.commands.previousEntity'), ['alt+[']],
- ['canvas.nextEntity', t('widgets.canvas.commands.nextEntity'), ['alt+]']],
- ['canvas.quickSwitch', t('widgets.canvas.commands.quickSwitch'), ['q']],
- ['canvas.deleteSelected', t('widgets.canvas.commands.deleteSelected'), ['delete', 'backspace']],
- ['canvas.resetSelected', t('widgets.canvas.commands.resetSelected'), ['shift+c']],
- ['canvas.undo', t('widgets.canvas.commands.undo'), ['mod+z']],
- ['canvas.redo', t('widgets.canvas.commands.redo'), ['mod+shift+z', 'mod+y']],
- // Exclude editable targets so tool letters and size brackets do not intercept typing.
- ['canvas.tool.view', t('widgets.canvas.commands.selectViewTool'), ['h']],
- ['canvas.tool.move', t('widgets.canvas.commands.selectMoveTool'), ['v']],
- ['canvas.transformSelected', t('widgets.canvas.commands.selectTransformTool'), ['mod+t']],
- ['canvas.tool.bbox', t('widgets.canvas.commands.selectBboxTool'), []],
- ['canvas.tool.brush', t('widgets.canvas.commands.selectBrushTool'), ['b']],
- ['canvas.tool.eraser', t('widgets.canvas.commands.selectEraserTool'), ['e']],
- ['canvas.tool.lasso', t('widgets.canvas.commands.selectLassoTool'), ['l']],
- ['canvas.tool.marquee', t('widgets.canvas.commands.selectMarqueeTool'), ['u']],
- ['canvas.toggleNonRasterLayers', t('widgets.canvas.commands.toggleNonRasterLayers'), ['shift+h']],
- ['canvas.copySelection', t('widgets.canvas.commands.copySelection'), ['mod+c']],
- ['canvas.cutSelection', t('widgets.canvas.commands.cutSelection'), ['mod+x']],
- ['canvas.pasteImage', t('widgets.canvas.commands.pasteImage'), ['mod+v']],
- ['canvas.tool.shape', t('widgets.canvas.commands.selectShapeTool'), ['r']],
- ['canvas.tool.text', t('widgets.canvas.commands.selectTextTool'), ['t']],
- ['canvas.tool.gradient', t('widgets.canvas.commands.selectGradientTool'), ['g']],
- // Selection: select all / deselect / invert (engine-owned transient selection).
- ['canvas.selectAll', t('widgets.canvas.commands.selectAll'), ['mod+a']],
- ['canvas.deselect', t('widgets.canvas.commands.deselect'), ['mod+d']],
- ['canvas.invertSelection', t('widgets.canvas.commands.invertSelection'), ['mod+shift+i']],
- ['canvas.brushSizeDown', t('widgets.canvas.commands.decreaseBrushSize'), ['[']],
- ['canvas.brushSizeUp', t('widgets.canvas.commands.increaseBrushSize'), [']']],
- // The active color pair: X swaps, D resets to black/white.
- ['canvas.toggleFillColor', t('widgets.canvas.commands.swapColors'), ['x']],
- ['canvas.setFillColorsToDefault', t('widgets.canvas.commands.resetColors'), ['d']],
- // Move the selected layer: arrows nudge 1px, shift+arrows 10px.
- ['canvas.nudgeLeft', t('widgets.canvas.commands.nudgeLeft'), ['arrowleft']],
- ['canvas.nudgeRight', t('widgets.canvas.commands.nudgeRight'), ['arrowright']],
- ['canvas.nudgeUp', t('widgets.canvas.commands.nudgeUp'), ['arrowup']],
- ['canvas.nudgeDown', t('widgets.canvas.commands.nudgeDown'), ['arrowdown']],
- ['canvas.nudgeLeftLarge', t('widgets.canvas.commands.nudgeLeftLarge'), ['shift+arrowleft']],
- ['canvas.nudgeRightLarge', t('widgets.canvas.commands.nudgeRightLarge'), ['shift+arrowright']],
- ['canvas.nudgeUpLarge', t('widgets.canvas.commands.nudgeUpLarge'), ['shift+arrowup']],
- ['canvas.nudgeDownLarge', t('widgets.canvas.commands.nudgeDownLarge'), ['shift+arrowdown']],
- // Layer management.
- ['canvas.duplicateLayer', t('widgets.canvas.commands.duplicateLayer'), ['mod+j']],
- ['canvas.groupLayers', t('widgets.canvas.commands.groupLayers'), ['mod+g']],
- ['canvas.ungroupLayers', t('widgets.canvas.commands.ungroupLayers'), ['mod+shift+g']],
- ['canvas.mergeDown', t('widgets.canvas.commands.mergeDown'), ['mod+e']],
- ['canvas.layerForward', t('widgets.canvas.commands.layerForward'), ['mod+]']],
- ['canvas.layerBackward', t('widgets.canvas.commands.layerBackward'), ['mod+[']],
- ['canvas.layerToFront', t('widgets.canvas.commands.layerToFront'), ['mod+shift+]']],
- ['canvas.layerToBack', t('widgets.canvas.commands.layerToBack'), ['mod+shift+[']],
- ] as const;
- const disposers = hotkeys.flatMap(([id, title, defaultKeys]) => [
- runtime.commands.register({ handler: () => executeCanvasHotkey(id), id, title }),
- runtime.hotkeys.register({ allowInEditable: false, commandId: id, defaultKeys: [...defaultKeys], id, title }),
- ]);
+ // Exclude editable targets so tool letters and size brackets do not intercept typing.
+ const disposers = [...CANVAS_COMPANION_HOTKEYS, ...CANVAS_ONLY_HOTKEYS].flatMap(([id, titleKey, defaultKeys]) => {
+ const title = t(titleKey);
+ return [
+ runtime.commands.register({ handler: () => executeCanvasHotkey(id), id, title }),
+ runtime.hotkeys.register({ allowInEditable: false, commandId: id, defaultKeys: [...defaultKeys], id, title }),
+ ];
+ });
return () => {
disposers.forEach((dispose) => dispose());
@@ -518,16 +481,21 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
() => <CanvasCreateFromBboxSubmenu disabled={isCompositeMenuDisabled} onCreate={createFromBbox} />,
[createFromBbox, isCompositeMenuDisabled]
);
+ const isCropAllDisabled = isInteractionLocked || interactionCapabilities.isDocumentEditingLocked;
const compositeSubmenus = useMemo(
() => (
<>
{saveToGallerySubmenu}
{createFromBboxSubmenu}
+ {engine ? <CanvasCropAllLayersMenuItem disabled={isCropAllDisabled} layers={engine.layers} /> : null}
</>
),
- [createFromBboxSubmenu, saveToGallerySubmenu]
+ [createFromBboxSubmenu, engine, isCropAllDisabled, saveToGallerySubmenu]
+ );
+ const canvasSurface = useMemo(
+ () => (engine ? <CanvasSurface engine={engine} instanceId={instance.id} /> : null),
+ [engine, instance.id]
);
- const canvasSurface = useMemo(() => (engine ? <CanvasSurface engine={engine} /> : null), [engine]);
return (
<Box
@@ -564,7 +532,6 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
<ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />
<CanvasLayerContextMenu
beforeDangerItems={compositeSubmenus}
- dispatch={canvasDispatch}
engine={engine}
showGroupLabels
target={layerContextMenuTarget}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.browser.test.tsx
index 75a7ebc7c0..617ff12ee7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.browser.test.tsx
@@ -357,6 +357,52 @@ describe('tool strip family slots', () => {
}
});
+ /** Hover the slot fresh, so its tooltip opens with the current title. */
+ const hoverSlot = async (slot: HTMLElement) => {
+ await act(() => userEvent.unhover(slot));
+ await act(() => userEvent.hover(slot));
+ };
+ const tooltipText = () => document.querySelector('[role="tooltip"]')?.textContent ?? null;
+ const MARQUEE_HELP =
+ "Drag a rectangle or ellipse to select pixels on the active layer. Fill, erase, or move them to a new layer. Doesn't change the generation frame.";
+ const LASSO_HELP =
+ "Draw a freehand or polygon outline to select pixels on the active layer. Fill, erase, or move them to a new layer. Doesn't change the generation frame.";
+
+ it('titles the selection slot with the current tool’s effective key and its help line, remaps included', async () => {
+ accountLifecycle.activate('tool-strip-test');
+ await patchWorkbenchPreferences({ customHotkeys: { 'canvas.tool.lasso': ['k'] } });
+ const extensions = createExtensionRegistry();
+ const source = { instanceId: 'canvas', projectId: 'project-1', region: 'center', typeId: 'canvas' } as const;
+ for (const [id, key] of [
+ ['canvas.tool.marquee', 'u'],
+ ['canvas.tool.lasso', 'l'],
+ ] as const) {
+ extensions.hotkeys.register({ commandId: id, defaultKeys: [key], id, source, title: id });
+ }
+ workbench.extensions = extensions;
+
+ try {
+ await renderStrip();
+ const marquee = (await button('Marquee select').element()) as HTMLElement;
+ await hoverSlot(marquee);
+ await expect.poll(tooltipText).toBe(`Marquee select (U)${MARQUEE_HELP}`);
+
+ await openByContextMenu(marquee);
+ await act(() => userEvent.click(page.getByRole('menuitemradio', { name: /^Lasso select/ })));
+ // The lasso key was remapped from L to K; the title follows the effective binding.
+ await hoverSlot((await button('Lasso select').element()) as HTMLElement);
+ await expect.poll(tooltipText).toBe(`Lasso select (K)${LASSO_HELP}`);
+ } finally {
+ await patchWorkbenchPreferences({ customHotkeys: {} });
+ }
+ });
+
+ it('titles a slot without a binding by its label alone', async () => {
+ await renderStrip();
+ await hoverSlot((await button('Marquee select').element()) as HTMLElement);
+ await expect.poll(tooltipText).toBe(`Marquee select${MARQUEE_HELP}`);
+ });
+
it('remembers the last-used selection tool across tool switches', async () => {
const fake = await renderStrip();
await act(() => userEvent.click(button('Marquee select')));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
index 64a1729921..69f4b1b44d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx
@@ -16,14 +16,14 @@ import {
BrushIcon,
CircleIcon,
EraserIcon,
- FrameIcon,
HandIcon,
LassoIcon,
MousePointer2Icon,
PenLineIcon,
PentagonIcon,
Rotate3dIcon,
- SquareDashedIcon,
+ ScanIcon,
+ SquareDashedMousePointerIcon,
SquareIcon,
StarIcon,
TriangleIcon,
@@ -154,12 +154,14 @@ const SelectFamilyButton = ({
const items: ToolFlyoutItem[] = useMemo(
() => [
{
- icon: SquareDashedIcon,
+ description: t('widgets.canvas.tools.marqueeHelp'),
+ icon: SquareDashedMousePointerIcon,
id: 'marquee',
label: t('widgets.canvas.tools.marquee'),
hotkeys: toolHotkeys(hotkeyDefinitions, customHotkeys, 'canvas.tool.marquee'),
},
{
+ description: t('widgets.canvas.tools.lassoHelp'),
icon: LassoIcon,
id: 'lasso',
label: t('widgets.canvas.tools.lasso'),
@@ -180,7 +182,7 @@ const SelectFamilyButton = ({
<ToolFamilyButton
currentId={current}
disabled={!isCanvasToolEnabled(current, isInteractionLocked)}
- icon={current === 'lasso' ? LassoIcon : SquareDashedIcon}
+ icon={current === 'lasso' ? LassoIcon : SquareDashedMousePointerIcon}
isActive={activeTool === 'marquee' || activeTool === 'lasso'}
items={items}
label={t(current === 'lasso' ? 'widgets.canvas.tools.lasso' : 'widgets.canvas.tools.marquee')}
@@ -233,7 +235,7 @@ const ToolStripRoot = ({
/>
<ToolStripButton
engine={engine}
- icon={FrameIcon}
+ icon={ScanIcon}
isInteractionLocked={isInteractionLocked}
label={t('widgets.canvas.tools.bbox')}
toolId="bbox"
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx
index 134f458fea..3f8fdae47d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStripFlyout.tsx
@@ -1,13 +1,14 @@
import type { KeyboardEvent, MouseEvent as ReactMouseEvent, PointerEvent as ReactPointerEvent } from 'react';
-import { Box, Icon, Menu, Portal, useMenu } from '@chakra-ui/react';
+import { Box, Icon, Menu, Portal, Stack, Text, useMenu } from '@chakra-ui/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { IconButton } from '@platform/ui/Button';
import { MenuContent } from '@platform/ui/Menu';
import { Tooltip, useTooltipTriggerIds } from '@platform/ui/Tooltip';
import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';
-import { formatHotkeyForPlatform, isHotkeyPress } from '@workbench/hotkeys/keys';
-import { useCallback, useRef } from 'react';
+import { formatHotkeyForPlatform, formatHotkeyLabel, isHotkeyPress } from '@workbench/hotkeys/keys';
+import { useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
const HOLD_OPEN_MS = 350;
const TOOLTIP_POSITIONING = { placement: 'right' } as const;
@@ -21,6 +22,8 @@ export interface ToolFlyoutItem {
label: string;
/** The subtool's effective bindings, remaps included. The first shows as the entry's keycaps. */
hotkeys?: readonly string[];
+ /** One help line the slot's tooltip shows under its title while this subtool is current. */
+ description?: string;
}
const isOverElement = (element: Element, event: ReactPointerEvent): boolean => {
@@ -66,6 +69,7 @@ export const ToolFamilyButton = ({
}) => {
// The menu anchors to, and returns focus to, the element carrying the trigger id: the slot, through its tooltip.
// The slot is not a `Menu.Trigger`, whose click would open the menu instead of selecting the current subtool.
+ const { t } = useTranslation();
const ids = useTooltipTriggerIds();
const menuMachine = useMenu({ ids, positioning: MENU_POSITIONING });
const menu = menuMachine.api;
@@ -229,12 +233,34 @@ export const ToolFamilyButton = ({
[disabled, items, menu, onSelectSubtool]
);
+ // The title names the slot with the current subtool's first effective binding; its help line follows.
+ const current = items.find((item) => item.id === currentId);
+ const currentHotkey = current?.hotkeys?.[0];
+ const description = current?.description;
+ const title = currentHotkey
+ ? t('widgets.canvas.tools.withHotkey', { hotkey: formatHotkeyLabel(currentHotkey), label })
+ : label;
+ const tooltip = useMemo(
+ () =>
+ description ? (
+ <Stack gap="0.5" maxW="16rem">
+ <Text>{title}</Text>
+ <Text color="fg.muted" fontSize="sm">
+ {description}
+ </Text>
+ </Stack>
+ ) : (
+ title
+ ),
+ [description, title]
+ );
+
return (
<Menu.RootProvider lazyMount unmountOnExit value={menuMachine}>
{/* Forcing `open={false}` (not `disabled`) suppresses the tooltip while
the menu is open: the disabled path unwraps the trigger and remounts
the button, dropping pointer capture mid-hold. */}
- <Tooltip content={label} ids={ids} open={menu.open ? false : undefined} positioning={TOOLTIP_POSITIONING}>
+ <Tooltip content={tooltip} ids={ids} open={menu.open ? false : undefined} positioning={TOOLTIP_POSITIONING}>
<IconButton
aria-controls={menu.open ? menu.getContentProps().id : undefined}
aria-expanded={menu.open}
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 0650dd6295..99cd223b93 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.test.ts
@@ -1,6 +1,31 @@
-import { describe, expect, it } from 'vitest';
+import type { CanvasDocumentContractV3, CanvasNodeContract } from '@workbench/canvas-engine/api';
-import { resolveCanvasContextMenu, resolveCanvasContextMenuBranch } from './canvasContextMenu';
+import {
+ groupContract,
+ layerContract,
+ stacksFrom,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { createInstance } from 'i18next';
+import { describe, expect, it, vi } from 'vitest';
+
+import {
+ cropAllLayersToFrame,
+ hasCroppableLayers,
+ resolveCanvasContextMenu,
+ resolveCanvasContextMenuBranch,
+} from './canvasContextMenu';
+
+const englishCatalogModules = import.meta.glob('../../../../public/locales/en.json', {
+ eager: true,
+ import: 'default',
+});
+const i18n = createInstance();
+await i18n.init({
+ initAsync: false,
+ lng: 'en',
+ resources: { en: { translation: Object.values(englishCatalogModules)[0] as Record<string, unknown> } },
+});
const baseOptions = {
clientX: 240,
@@ -63,3 +88,69 @@ describe('resolveCanvasContextMenu', () => {
expect(resolveCanvasContextMenuBranch(resolution.target, false)).toBe('global');
});
});
+
+describe('hasCroppableLayers', () => {
+ const documentWith = (nodes: CanvasNodeContract[]): CanvasDocumentContractV3 => ({
+ ...createEmptyCanvasDocument(),
+ stacks: stacksFrom(nodes),
+ });
+
+ it('finds a croppable leaf in any stack, hidden or disabled ones included', () => {
+ expect(hasCroppableLayers(documentWith([layerContract('mask', 'inpaint_mask', { isEnabled: false })]))).toBe(true);
+ expect(hasCroppableLayers(documentWith([groupContract('G', [layerContract('region', 'regional_guidance')])]))).toBe(
+ true
+ );
+ });
+
+ it('has nothing to crop when every leaf is locked by itself or by a group above it', () => {
+ expect(hasCroppableLayers(documentWith([]))).toBe(false);
+ expect(
+ hasCroppableLayers(
+ documentWith([
+ layerContract('locked', 'raster', { isLocked: true }),
+ groupContract('G', [layerContract('inside', 'control')], { isLocked: true }),
+ ])
+ )
+ ).toBe(false);
+ });
+});
+
+describe('cropAllLayersToFrame', () => {
+ type CropResult = Awaited<ReturnType<Parameters<typeof cropAllLayersToFrame>[0]['cropAllLayersToBbox']>>;
+ const notices = async (result: CropResult | Error) => {
+ const notify = { error: vi.fn(), info: vi.fn(), success: vi.fn() };
+ const cropAllLayersToBbox = () => (result instanceof Error ? Promise.reject(result) : Promise.resolve(result));
+ await cropAllLayersToFrame({ cropAllLayersToBbox }, notify, i18n.t);
+ return {
+ error: notify.error.mock.calls,
+ info: notify.info.mock.calls,
+ success: notify.success.mock.calls,
+ };
+ };
+
+ it.each([
+ [{ cropped: 1, skippedLocked: 0 }, ['Cropped 1 layer to the frame', undefined]],
+ [{ cropped: 4, skippedLocked: 1 }, ['Cropped 4 layers to the frame', '1 locked layer skipped']],
+ [{ cropped: 2, skippedLocked: 3 }, ['Cropped 2 layers to the frame', '3 locked layers skipped']],
+ ])('reports %o as cropped, with the locked layers it skipped', async (counts, expected) => {
+ expect(await notices({ status: 'cropped', ...counts })).toEqual({ error: [], info: [], success: [expected] });
+ });
+
+ it('says nothing needed cropping, and that only unlocked layers were checked when some were skipped', async () => {
+ expect((await notices({ skippedLocked: 0, status: 'nothing' })).info).toEqual([
+ ['Every layer already fits the frame', undefined],
+ ]);
+ expect((await notices({ skippedLocked: 2, status: 'nothing' })).info).toEqual([
+ ['Every unlocked layer already fits the frame', '2 locked layers skipped'],
+ ]);
+ });
+
+ it('explains refusals and a rejected crop with the shared layer notice', async () => {
+ expect((await notices({ status: 'over-budget' })).error).toEqual([
+ [i18n.t('widgets.layers.actions.actionFailed'), i18n.t('widgets.layers.actions.overBudget')],
+ ]);
+ expect((await notices(new Error('rejected'))).error).toEqual([
+ [i18n.t('widgets.layers.actions.actionFailed'), i18n.t('widgets.layers.actions.operationFailed')],
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
index 316f9c0661..f4d56ac532 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasContextMenu.ts
@@ -1,3 +1,11 @@
+import type { CanvasDocumentContractV3, CanvasEngineLayerCapability } from '@workbench/canvas-engine/api';
+import type { Notify } from '@workbench/useNotify';
+import type { TFunction } from 'i18next';
+
+import { getDocumentIndex } from '@workbench/canvas-engine/api';
+
+import { reportLayerOperation } from './useStructuralCommit';
+
export interface CanvasContextMenuTarget {
x: number;
y: number;
@@ -50,3 +58,49 @@ export const resolveCanvasContextMenu = ({
target: { layerId, x: clientX, y: clientY },
};
};
+
+/** Whether Crop all layers to frame has a leaf to act on: one not locked by itself or a group above it. */
+export const hasCroppableLayers = (document: CanvasDocumentContractV3): boolean => {
+ const { byId, leaves } = getDocumentIndex(document);
+ return leaves.some((leaf) => !leaf.isLocked && !byId.get(leaf.id)?.ancestorsLocked);
+};
+
+/**
+ * Crops every unlocked layer to the frame as one undo step and says what happened: how many layers it cropped, how
+ * many locked ones it skipped, or that nothing needed cropping. The canvas menu and the command share it.
+ */
+export const cropAllLayersToFrame = async (
+ layers: Pick<CanvasEngineLayerCapability, 'cropAllLayersToBbox'>,
+ notify: Pick<Notify, 'error' | 'info' | 'success'>,
+ t: TFunction
+): Promise<void> => {
+ let result: Awaited<ReturnType<typeof layers.cropAllLayersToBbox>>;
+ try {
+ result = await layers.cropAllLayersToBbox();
+ } catch {
+ // The engine leaves every layer as it was when the transaction is rejected.
+ result = { status: 'failed' };
+ }
+ switch (result.status) {
+ case 'cropped':
+ case 'nothing': {
+ const skipped =
+ result.skippedLocked > 0
+ ? t('widgets.canvas.contextMenu.croppedAllLayersSkipped', { count: result.skippedLocked })
+ : undefined;
+ if (result.status === 'cropped') {
+ notify.success(t('widgets.canvas.contextMenu.croppedAllLayers', { count: result.cropped }), skipped);
+ } else {
+ notify.info(
+ t(
+ skipped ? 'widgets.canvas.contextMenu.cropAllNothingUnlocked' : 'widgets.canvas.contextMenu.cropAllNothing'
+ ),
+ skipped
+ );
+ }
+ return;
+ }
+ default:
+ reportLayerOperation(result.status, notify.error, t);
+ }
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
index f71fcf43f0..9163ebdfb1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.test.ts
@@ -179,6 +179,18 @@ describe('executeCanvasHeaderCommand', () => {
expect(saveToGallery).toHaveBeenCalledWith(region);
});
+ it.each([
+ ['canvas.setZoomTo100Percent', 1],
+ ['canvas.setZoomTo200Percent', 2],
+ ['canvas.setZoomTo400Percent', 4],
+ ['canvas.setZoomTo800Percent', 8],
+ ] as const)('%s zooms to %d× about the viewport centre', (commandId, scale) => {
+ const { engine, zoomAtPoint } = createEngine({ height: 600, width: 800 });
+ executeCanvasHeaderCommand(commandId, contextOf({ engine }));
+ expect(zoomAtPoint).toHaveBeenCalledExactlyOnceWith(scale, { x: 400, y: 300 });
+ expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ });
+
it('ignores an unknown command id', () => {
const openNewCanvas = vi.fn();
const { engine } = createEngine();
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
index db82842977..fd4a9fc66b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHeaderCommands.ts
@@ -80,9 +80,35 @@ export const confirmNewCanvas = (ctx: NewCanvasContext): void => {
ctx.engine.document.replaceDocument(createNewCanvasState(ctx.document.width, ctx.document.height).document);
};
+/** The header's commands as `[id, titleKey, defaultKeys]`; the header registers them while the Canvas is mounted. */
+export const CANVAS_HEADER_HOTKEYS = [
+ ['canvas.fitBboxToLayers', 'widgets.canvas.controls.fitBboxToLayers', ['shift+n']],
+ ['canvas.fitBboxToMasks', 'widgets.canvas.controls.fitBboxToMasks', ['shift+b']],
+ // No default keys — assignable through the hotkeys settings.
+ ['canvas.saveToGallery', 'widgets.canvas.contextMenu.saveCanvasToGallery', []],
+ ['canvas.saveBboxToGallery', 'widgets.canvas.contextMenu.saveBboxToGallery', []],
+ ['canvas.newSession', 'widgets.canvas.controls.newSession', []],
+ // Browsers reserve Mod+1…8 for tab switching; these act only where the browser delivers the chord.
+ ['canvas.setZoomTo100Percent', 'widgets.canvas.commands.zoomTo100', ['mod+1']],
+ ['canvas.setZoomTo200Percent', 'widgets.canvas.commands.zoomTo200', ['mod+2']],
+ ['canvas.setZoomTo400Percent', 'widgets.canvas.commands.zoomTo400', ['mod+3']],
+ ['canvas.setZoomTo800Percent', 'widgets.canvas.commands.zoomTo800', ['mod+4']],
+] as const satisfies readonly (readonly [id: string, titleKey: string, defaultKeys: readonly string[]])[];
+
+/** The zoom preset commands and the scale each sets about the viewport centre. */
+const ZOOM_PRESET_COMMANDS: Readonly<Record<string, number>> = {
+ 'canvas.setZoomTo100Percent': 1,
+ 'canvas.setZoomTo200Percent': 2,
+ 'canvas.setZoomTo400Percent': 4,
+ 'canvas.setZoomTo800Percent': 8,
+};
+
/** Route new-session commands through the button's confirmation dialog. */
export const executeCanvasHeaderCommand = (commandId: string, ctx: CanvasHeaderCommandContext): void => {
- if (commandId === 'canvas.fitBboxToLayers') {
+ const zoomPreset = ZOOM_PRESET_COMMANDS[commandId];
+ if (zoomPreset !== undefined) {
+ zoomAtViewportCentre(ctx.engine, zoomPreset);
+ } else if (commandId === 'canvas.fitBboxToLayers') {
applyFitBbox(ctx, ctx.fitLayersRect, true);
} else if (commandId === 'canvas.fitBboxToMasks') {
applyFitBbox(ctx, ctx.fitMasksRect, false);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
index 777d98baf1..0d378a5580 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -1,4 +1,5 @@
import type {
+ BeginTransformResult,
CanvasDocumentContractV3,
CanvasEngine,
CanvasInteractionState,
@@ -8,6 +9,7 @@ import type {
NewRasterLayerResult,
} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { TFunction } from 'i18next';
import { createDocumentModel } from '@workbench/canvas-engine/api';
import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
@@ -15,7 +17,15 @@ import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAncho
import { createControlLayer } from '@workbench/widgets/layers/layerOps';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
-import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
+import { CANVAS_HEADER_HOTKEYS } from './canvasHeaderCommands';
+import {
+ CANVAS_COMPANION_HOTKEYS,
+ CANVAS_ONLY_HOTKEYS,
+ executeCanvasHotkeyCommand,
+ executeCanvasToolCommand,
+ reportTransformRefusal,
+ type CanvasHotkeyContext,
+} from './canvasHotkeyCommands';
const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
({
@@ -78,6 +88,7 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {
status: 'duplicated',
})
),
+ beginTransform: vi.fn((): BeginTransformResult => 'started'),
mergeLayerDown: vi.fn((): MergeDownResult => 'merged'),
nudgeSelectedLayer: vi.fn(() => ({ status: 'committed' as const })),
},
@@ -99,8 +110,10 @@ let pasteFromClipboard: Mock<() => void>;
const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyContext => ({
copySelection,
+ cropAllLayers: vi.fn(),
dispatch,
reportLayerOperation: vi.fn(),
+ reportTransformRefusal: vi.fn(),
reportPreparedCommit: () => undefined,
reportStructuralCommit: () => undefined,
document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a'),
@@ -452,6 +465,18 @@ describe('clipboard', () => {
});
});
+describe('crop all layers to frame', () => {
+ it('runs the canvas menu action, but not while interaction is locked', () => {
+ const free = contextOf();
+ executeCanvasHotkeyCommand('canvas.cropAllLayersToFrame', free);
+ expect(free.cropAllLayers).toHaveBeenCalledOnce();
+
+ const locked = contextOf({ isInteractionLocked: true });
+ executeCanvasHotkeyCommand('canvas.cropAllLayersToFrame', locked);
+ expect(locked.cropAllLayers).not.toHaveBeenCalled();
+ });
+});
+
describe('tool selection', () => {
it.each([
['canvas.tool.view', 'view'],
@@ -462,12 +487,54 @@ describe('tool selection', () => {
['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('transform opens a session on the selected leaf at once, without a separate tool switch', () => {
+ const engine = run('canvas.transformSelected');
+ expect(engine.layers.beginTransform).toHaveBeenCalledExactlyOnceWith('a');
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ });
+
+ it('transform only picks the tool with no selection or a group selected', () => {
+ const none = run('canvas.transformSelected', { document: documentOf([rasterLayer('a')], null) });
+ expect(none.layers.beginTransform).not.toHaveBeenCalled();
+ expect(none.tools.setTool).toHaveBeenCalledWith('transform');
+ const group = run('canvas.transformSelected', {
+ document: { ...documentOf([], 'g'), stacks: stacksFrom([groupContract('g', [rasterLayer('a')])]) },
+ });
+ expect(group.layers.beginTransform).not.toHaveBeenCalled();
+ expect(group.tools.setTool).toHaveBeenCalledWith('transform');
+ });
+
+ it('transform explains a refusal and stays quiet mid-gesture', () => {
+ const report = (result: BeginTransformResult) => {
+ const engine = createEngine();
+ engine.layers.beginTransform.mockReturnValue(result);
+ const reportTransformRefusal = vi.fn();
+ executeCanvasHotkeyCommand('canvas.transformSelected', contextOf({ engine, reportTransformRefusal }));
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ return reportTransformRefusal.mock.calls;
+ };
+ expect(report('locked')).toEqual([['locked']]);
+ expect(report('ineligible')).toEqual([['ineligible']]);
+ expect(report('busy')).toEqual([]);
+ });
+
+ it("gives an ineligible layer Transform's own reason and other refusals the shared layer notice", () => {
+ const explain = (refusal: Exclude<BeginTransformResult, 'started'>) => {
+ const reportError = vi.fn();
+ reportTransformRefusal(refusal, reportError, ((key: string) => key) as unknown as TFunction);
+ return reportError.mock.calls;
+ };
+ expect(explain('ineligible')).toEqual([
+ ['widgets.layers.actions.actionFailed', 'widgets.layers.actions.transformIneligible'],
+ ]);
+ expect(explain('locked')).toEqual([['widgets.layers.actions.actionFailed', 'widgets.layers.actions.locked']]);
+ });
+
it('lasso selects the tool when not already active', () => {
const engine = run('canvas.tool.lasso');
expect(engine.tools.setTool).toHaveBeenCalledWith('lasso');
@@ -728,6 +795,24 @@ describe('group selection', () => {
expect.objectContaining({ forward: expect.objectContaining({ removeIds: ['g'] }) })
);
});
+
+ it('ungroup on leaves of one group moves them out above it, and does nothing for a top-level leaf', () => {
+ const document = nodeDocument([groupContract('g', [rasterLayer('a'), rasterLayer('b')]), rasterLayer('c')], 'a');
+ const lifted = run('canvas.ungroupLayers', { document, selectedLayerIds: ['b', 'a'] });
+ expect(lifted.layers.commitPrepared).toHaveBeenCalledExactlyOnceWith(
+ 'widgets.layers.actions.removeFromGroup',
+ expect.objectContaining({
+ forward: expect.objectContaining({
+ move: [{ anchor: expect.objectContaining({ beforeId: 'g', parentPath: [] }), ids: ['a', 'b'] }],
+ }),
+ })
+ );
+ const topLevel = run('canvas.ungroupLayers', {
+ document: { ...document, selectedLayerId: 'c' },
+ selectedLayerIds: ['c'],
+ });
+ expect(topLevel.layers.commitPrepared).not.toHaveBeenCalled();
+ });
});
describe('active color pair commands', () => {
@@ -745,3 +830,43 @@ describe('active color pair commands', () => {
}
});
});
+
+describe('registration tables', () => {
+ // Everything the mounted Canvas registers: its own keys, the companion keys and the header's commands. The
+ // companion widget registers a subset (history plus companion keys), so it is covered too.
+ const allEntries = [...CANVAS_COMPANION_HOTKEYS, ...CANVAS_ONLY_HOTKEYS, ...CANVAS_HEADER_HOTKEYS];
+
+ it('gives Transform Shift+T as its only default', () => {
+ expect(CANVAS_COMPANION_HOTKEYS.find(([id]) => id === 'canvas.transformSelected')?.[2]).toEqual(['shift+t']);
+ expect(allEntries.flatMap(([, , keys]) => keys)).not.toContain('mod+t');
+ });
+
+ it('never gives two entries the same id or default chord', () => {
+ const ids = allEntries.map(([id]) => id);
+ const chords = allEntries.flatMap(([, , keys]) => keys);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(chords.filter((chord, index) => chords.indexOf(chord) !== index)).toEqual([]);
+ expect(chords).toEqual(expect.arrayContaining(['mod+1', 'mod+2', 'mod+3', 'mod+4', 'mod+z', 'shift+t']));
+ });
+
+ it('shares every companion key with the companion runner and nothing else', () => {
+ const engine = createEngine();
+ const ctx = {
+ engine,
+ isInteractionLocked: false,
+ reportTransformRefusal: vi.fn(),
+ resetActiveColors: vi.fn(),
+ selectedLayerId: null,
+ swapActiveColors: vi.fn(),
+ };
+ for (const [id] of CANVAS_COMPANION_HOTKEYS) {
+ executeCanvasToolCommand(id, ctx);
+ }
+ // Every companion key reaches the engine or the color pair; bbox has no default key but still runs.
+ expect(engine.tools.setTool.mock.calls.length + engine.tools.stepBrushSize.mock.calls.length).toBe(
+ CANVAS_COMPANION_HOTKEYS.length - 2
+ );
+ expect(ctx.swapActiveColors).toHaveBeenCalledOnce();
+ expect(ctx.resetActiveColors).toHaveBeenCalledOnce();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 835f17437f..a01d77e305 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -1,10 +1,12 @@
import type {
+ BeginTransformResult,
CanvasDocumentContractV3,
CanvasEngine,
LayerStackMoveKind,
StructuralCommitResult,
} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
+import type { TFunction } from 'i18next';
import {
compileDocumentLeaves,
@@ -16,17 +18,224 @@ import {
import { publishLayerPanelSelection } from '@workbench/layerPanelState';
import {
commitPreparedEdit,
+ reportLayerOperation,
type LayerOperationRefusal,
type PreparedCommitOutcome,
} from '@workbench/widgets/canvas/useStructuralCommit';
import {
canGroupSelection,
+ canRemoveFromGroup,
canUngroupSelection,
groupLayers,
+ removeFromGroup,
ungroupLayers,
} from '@workbench/widgets/layers/layerGroupCommands';
import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
+type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];
+
+/**
+ * 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.
+ */
+export const CANVAS_COMPANION_HOTKEYS = [
+ ['canvas.tool.view', 'widgets.canvas.commands.selectViewTool', ['h']],
+ ['canvas.tool.move', 'widgets.canvas.commands.selectMoveTool', ['v']],
+ ['canvas.transformSelected', 'widgets.canvas.commands.selectTransformTool', ['shift+t']],
+ ['canvas.tool.bbox', 'widgets.canvas.commands.selectBboxTool', []],
+ ['canvas.tool.brush', 'widgets.canvas.commands.selectBrushTool', ['b']],
+ ['canvas.tool.eraser', 'widgets.canvas.commands.selectEraserTool', ['e']],
+ ['canvas.tool.lasso', 'widgets.canvas.commands.selectLassoTool', ['l']],
+ ['canvas.tool.marquee', 'widgets.canvas.commands.selectMarqueeTool', ['u']],
+ ['canvas.tool.shape', 'widgets.canvas.commands.selectShapeTool', ['r']],
+ ['canvas.tool.text', 'widgets.canvas.commands.selectTextTool', ['t']],
+ ['canvas.tool.gradient', 'widgets.canvas.commands.selectGradientTool', ['g']],
+ ['canvas.brushSizeDown', 'widgets.canvas.commands.decreaseBrushSize', ['[']],
+ ['canvas.brushSizeUp', 'widgets.canvas.commands.increaseBrushSize', [']']],
+ // The active color pair: X swaps, D resets to black/white.
+ ['canvas.toggleFillColor', 'widgets.canvas.commands.swapColors', ['x']],
+ ['canvas.setFillColorsToDefault', 'widgets.canvas.commands.resetColors', ['d']],
+] as const satisfies readonly HotkeyTableEntry[];
+
+/** Canvas history, which the Canvas and its companion widgets both bind. */
+export const CANVAS_HISTORY_HOTKEYS = [
+ ['canvas.undo', 'widgets.canvas.commands.undo', ['mod+z']],
+ ['canvas.redo', 'widgets.canvas.commands.redo', ['mod+shift+z', 'mod+y']],
+] as const satisfies readonly HotkeyTableEntry[];
+
+/** Keys that act only while the Canvas itself holds focus; rows and fields own them elsewhere. */
+export const CANVAS_ONLY_HOTKEYS = [
+ ...CANVAS_HISTORY_HOTKEYS,
+ // Staging keeps `alt+[` / `alt+]`; bare left/right are registered as layer nudges,
+ // then intercepted to cycle staging slots while any slot exists.
+ ['canvas.prevEntity', 'widgets.canvas.commands.previousEntity', ['alt+[']],
+ ['canvas.nextEntity', 'widgets.canvas.commands.nextEntity', ['alt+]']],
+ ['canvas.quickSwitch', 'widgets.canvas.commands.quickSwitch', ['q']],
+ ['canvas.deleteSelected', 'widgets.canvas.commands.deleteSelected', ['delete', 'backspace']],
+ ['canvas.resetSelected', 'widgets.canvas.commands.resetSelected', ['shift+c']],
+ ['canvas.toggleNonRasterLayers', 'widgets.canvas.commands.toggleNonRasterLayers', ['shift+h']],
+ ['canvas.copySelection', 'widgets.canvas.commands.copySelection', ['mod+c']],
+ ['canvas.cutSelection', 'widgets.canvas.commands.cutSelection', ['mod+x']],
+ ['canvas.pasteImage', 'widgets.canvas.commands.pasteImage', ['mod+v']],
+ // Selection: select all / deselect / invert (engine-owned transient selection).
+ ['canvas.selectAll', 'widgets.canvas.commands.selectAll', ['mod+a']],
+ ['canvas.deselect', 'widgets.canvas.commands.deselect', ['mod+d']],
+ ['canvas.invertSelection', 'widgets.canvas.commands.invertSelection', ['mod+shift+i']],
+ // Move the selected layer: arrows nudge 1px, shift+arrows 10px.
+ ['canvas.nudgeLeft', 'widgets.canvas.commands.nudgeLeft', ['arrowleft']],
+ ['canvas.nudgeRight', 'widgets.canvas.commands.nudgeRight', ['arrowright']],
+ ['canvas.nudgeUp', 'widgets.canvas.commands.nudgeUp', ['arrowup']],
+ ['canvas.nudgeDown', 'widgets.canvas.commands.nudgeDown', ['arrowdown']],
+ ['canvas.nudgeLeftLarge', 'widgets.canvas.commands.nudgeLeftLarge', ['shift+arrowleft']],
+ ['canvas.nudgeRightLarge', 'widgets.canvas.commands.nudgeRightLarge', ['shift+arrowright']],
+ ['canvas.nudgeUpLarge', 'widgets.canvas.commands.nudgeUpLarge', ['shift+arrowup']],
+ ['canvas.nudgeDownLarge', 'widgets.canvas.commands.nudgeDownLarge', ['shift+arrowdown']],
+ // Layer management.
+ ['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.layerForward', 'widgets.canvas.commands.layerForward', ['mod+]']],
+ ['canvas.layerBackward', 'widgets.canvas.commands.layerBackward', ['mod+[']],
+ ['canvas.layerToFront', 'widgets.canvas.commands.layerToFront', ['mod+shift+]']],
+ ['canvas.layerToBack', 'widgets.canvas.commands.layerToBack', ['mod+shift+[']],
+ // No default key — assignable through the hotkeys settings; the canvas menu offers the same action.
+ ['canvas.cropAllLayersToFrame', 'widgets.canvas.contextMenu.cropAllLayersToBbox', []],
+] as const satisfies readonly HotkeyTableEntry[];
+
+export type CanvasToolCommandId = (typeof CANVAS_COMPANION_HOTKEYS)[number][0];
+
+const CANVAS_TOOL_COMMAND_IDS: ReadonlySet<string> = new Set(CANVAS_COMPANION_HOTKEYS.map(([id]) => id));
+
+export const isCanvasToolCommand = (commandId: string): commandId is CanvasToolCommandId =>
+ CANVAS_TOOL_COMMAND_IDS.has(commandId);
+
+export type TransformRefusal = Exclude<BeginTransformResult, 'started'>;
+
+/** Explains a refused `beginTransform`; a layer Transform cannot act on gets Transform's own reason. */
+export const reportTransformRefusal = (
+ refusal: TransformRefusal,
+ reportError: (title: string, message: string) => void,
+ t: TFunction
+): void => {
+ if (refusal === 'ineligible') {
+ reportError(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.transformIneligible'));
+ } else {
+ reportLayerOperation(refusal, reportError, t);
+ }
+};
+
+/** What the companion keys need; the Canvas and the Layers widget each build it from their own state. */
+export interface CanvasToolCommandContext {
+ readonly engine: Pick<CanvasEngine, 'interaction' | 'layers' | 'tools'> | null;
+ readonly isInteractionLocked: boolean;
+ /** The selected leaf that Transform opens on; null when nothing or a group is selected. */
+ readonly selectedLayerId: string | null;
+ /** Swaps the project foreground/background pair — a preference, never a document edit. */
+ readonly swapActiveColors: () => void;
+ /** Resets the pair to the black-on-white default. */
+ readonly resetActiveColors: () => void;
+ readonly reportTransformRefusal: (refusal: TransformRefusal) => void;
+}
+
+/**
+ * Runs one companion key. The color pair is a preference, not a document edit, so X/D stay live while the surface
+ * is interaction-locked; of the rest only the view tool works then.
+ */
+export const executeCanvasToolCommand = (commandId: CanvasToolCommandId, ctx: CanvasToolCommandContext): void => {
+ const { engine } = ctx;
+ if (commandId === 'canvas.toggleFillColor') {
+ ctx.swapActiveColors();
+ return;
+ }
+ if (commandId === 'canvas.setFillColorsToDefault') {
+ ctx.resetActiveColors();
+ return;
+ }
+ if (ctx.isInteractionLocked && commandId !== 'canvas.tool.view') {
+ return;
+ }
+ if (!engine) {
+ return;
+ }
+ switch (commandId) {
+ case 'canvas.tool.view':
+ engine.tools.setTool('view');
+ return;
+ case 'canvas.tool.move':
+ engine.tools.setTool('move');
+ return;
+ case 'canvas.transformSelected': {
+ // A selected leaf opens its session at once, even with Transform already active; otherwise only the tool
+ // changes. Apply/Cancel (Enter/Escape) are handled engine-side.
+ if (ctx.selectedLayerId === null) {
+ engine.tools.setTool('transform');
+ return;
+ }
+ const result = engine.layers.beginTransform(ctx.selectedLayerId);
+ // A key pressed mid-gesture is dropped quietly; the gesture already says why.
+ if (result !== 'started' && result !== 'busy') {
+ ctx.reportTransformRefusal(result);
+ }
+ return;
+ }
+ case 'canvas.tool.bbox':
+ engine.tools.setTool('bbox');
+ return;
+ case 'canvas.tool.brush':
+ engine.tools.setTool('brush');
+ return;
+ case 'canvas.tool.eraser':
+ engine.tools.setTool('eraser');
+ return;
+ case 'canvas.tool.lasso':
+ // Repeating the active tool shortcut cycles its shape.
+ 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');
+ }
+ return;
+ case 'canvas.tool.marquee':
+ 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');
+ }
+ return;
+ case 'canvas.tool.shape':
+ if (engine.interaction.get('activeTool') === 'shape') {
+ // Repeat presses cycle the kind, like the marquee hotkey.
+ const shape = engine.interaction.get('shapeOptions');
+ const order = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'] as const;
+ const next = order[(order.indexOf(shape.kind) + 1) % order.length]!;
+ engine.interaction.set('shapeOptions', { ...shape, kind: next });
+ } else {
+ engine.tools.setTool('shape');
+ }
+ return;
+ case 'canvas.tool.text':
+ engine.tools.setTool('text');
+ return;
+ case 'canvas.tool.gradient':
+ engine.tools.setTool('gradient');
+ return;
+ case 'canvas.brushSizeDown':
+ engine.tools.stepBrushSize(-1);
+ return;
+ case 'canvas.brushSizeUp':
+ engine.tools.stepBrushSize(1);
+ }
+};
+
/** 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 },
@@ -86,26 +295,23 @@ const quickSwitchLayerId = (document: CanvasDocumentContractV3, engine: CanvasEn
};
/** Pass hotkey dependencies explicitly so dispatch can be tested without mounting React. */
-export interface CanvasHotkeyContext {
+export interface CanvasHotkeyContext extends Omit<CanvasToolCommandContext, 'engine' | 'selectedLayerId'> {
readonly document: CanvasDocumentContractV3;
readonly engine: CanvasEngine | null;
/** Any staging slot exists, so left/right cycle candidates instead of nudging. */
readonly hasStagingSlots: boolean;
+ readonly reportLayerOperation: (refusal: LayerOperationRefusal) => void;
/** A staged candidate is selected, so Delete discards it instead of touching layers. */
readonly hasSelectedStagedCandidate: boolean;
- readonly isInteractionLocked: boolean;
readonly selectedLayerIds: readonly string[];
readonly dispatch: CanvasProjectMutationDispatch;
readonly copySelection: (cut: boolean) => void;
- /** Swaps the project foreground/background pair — a preference, never a document edit. */
- readonly swapActiveColors: () => void;
- /** Resets the pair to the black-on-white default. */
- readonly resetActiveColors: () => void;
+ /** Crops every unlocked layer to the frame and reports the outcome, as the canvas menu does. */
+ readonly cropAllLayers: () => void;
readonly pasteFromClipboard: () => void;
readonly notifyLayerDuplicateFailed: () => void;
readonly reportStructuralCommit: (result: StructuralCommitResult) => void;
readonly reportPreparedCommit: (outcome: PreparedCommitOutcome) => void;
- readonly reportLayerOperation: (refusal: LayerOperationRefusal) => void;
readonly t: (key: string) => string;
}
@@ -113,9 +319,9 @@ export interface CanvasHotkeyContext {
* 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.
+ * cycling and staged-candidate discard win over layer commands, companion keys
+ * apply their own lock rule, the interaction lock then blocks everything else,
+ * and only after those do nudge, reorder, and the per-command table apply.
*/
export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyContext): void => {
const { dispatch, document, engine, t } = ctx;
@@ -140,22 +346,12 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
return;
}
- // The color pair is a preference, not a document edit, so X/D stay live even
- // while the surface is interaction-locked.
- if (commandId === 'canvas.toggleFillColor') {
- ctx.swapActiveColors();
- return;
- }
-
- if (commandId === 'canvas.setFillColorsToDefault') {
- ctx.resetActiveColors();
+ if (isCanvasToolCommand(commandId)) {
+ executeCanvasToolCommand(commandId, { ...ctx, selectedLayerId: selectedLayer?.id ?? null });
return;
}
if (ctx.isInteractionLocked) {
- if (commandId === 'canvas.tool.view') {
- engine?.tools.setTool('view');
- }
return;
}
@@ -211,6 +407,8 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
ctx.copySelection(commandId === 'canvas.cutSelection');
} else if (commandId === 'canvas.pasteImage') {
ctx.pasteFromClipboard();
+ } else if (commandId === 'canvas.cropAllLayersToFrame') {
+ ctx.cropAllLayers();
} else if (commandId === 'canvas.toggleNonRasterLayers') {
// Hide overlays without disabling generation content; showing restores individually hidden nodes too.
const overlays = index.nodes.filter((entry) => isOverlayStack(entry.stack));
@@ -241,71 +439,12 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
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) {
- // Repeating the active tool shortcut cycles its shape.
- 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') {
- if (engine) {
- if (engine.interaction.get('activeTool') === 'shape') {
- // Repeat presses cycle the kind, like the marquee hotkey.
- const shape = engine.interaction.get('shapeOptions');
- const order = ['rect', 'ellipse', 'triangle', 'star', 'polygon', 'freehand'] as const;
- const next = order[(order.indexOf(shape.kind) + 1) % order.length]!;
- engine.interaction.set('shapeOptions', { ...shape, kind: next });
- } else {
- 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.
@@ -348,8 +487,14 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
);
}
} else if (commandId === 'canvas.ungroupLayers') {
- if (engine && selected && canUngroupSelection(engine.document.model(), ctx.selectedLayerIds)) {
+ // Groups dissolve; a selection of leaves of one group moves out above it instead.
+ const model = engine?.document.model() ?? null;
+ if (engine && selected && canUngroupSelection(model, ctx.selectedLayerIds)) {
ctx.reportPreparedCommit(ungroupLayers(engine, ctx.selectedLayerIds, t('widgets.canvas.commands.ungroupLayers')));
+ } else if (engine && selected && canRemoveFromGroup(model, ctx.selectedLayerIds)) {
+ ctx.reportPreparedCommit(
+ removeFromGroup(engine, ctx.selectedLayerIds, t('widgets.layers.actions.removeFromGroup'))
+ );
}
} else if (commandId === 'canvas.mergeDown') {
// Share canMergeLayerDown with the layer menu so shortcuts respect identical eligibility.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx
new file mode 100644
index 0000000000..e3b73ace18
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx
@@ -0,0 +1,322 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { CanvasLayerContract, CanvasLayerSourceContract, ColorSamplePhase } from '@workbench/canvas-engine/api';
+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import type { Project } from '@workbench/projectContracts';
+import type * as workbenchContext from '@workbench/WorkbenchContext';
+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';
+
+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider } from 'react-i18next';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+
+/** The real workbench store the hooks under test read and write, standing in for the provider. */
+const harness = vi.hoisted(() => ({ store: null as WorkbenchInternalStore | null }));
+
+vi.mock('@workbench/WorkbenchContext', async (importOriginal) => {
+ const actual = await importOriginal<typeof workbenchContext>();
+ const { useExternalStoreSelector, shallowEqual } = await import('@platform/state/selectors');
+ const store = () => harness.store!;
+ return {
+ ...actual,
+ useActiveProjectSelector: <T,>(selector: (project: Project) => T, isEqual?: (a: T, b: T) => boolean) =>
+ useExternalStoreSelector(
+ store().subscribe,
+ store().getSnapshot,
+ (snapshot) => selector(snapshot.activeProject),
+ isEqual ?? shallowEqual
+ ),
+ useWorkbenchCommands: () => store().commands,
+ useWorkbenchQueries: () => store().queries,
+ };
+});
+
+import { CanvasColorFeed } from './CanvasColorFeed';
+import { armMaskTintTarget, clearMaskTintTarget } from './maskTintTarget';
+import { useMaskTintEditor, type MaskTintEditor } from './useMaskTintEditor';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const i18n = createInstance();
+beforeAll(async () => {
+ const translation = (await (await fetch('/locales/en.json')).json()) as Record<string, unknown>;
+ await i18n.init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+const TINT = '#e07575';
+const PICKED = '#3a7bd5';
+const SHAPE_SOURCE = {
+ fill: '#ff0000',
+ height: 10,
+ kind: 'rect',
+ stroke: '#00ff00',
+ strokeWidth: 2,
+ type: 'shape',
+ width: 10,
+} satisfies Extract<CanvasLayerSourceContract, { type: 'shape' }>;
+const TEXT_SOURCE = {
+ align: 'left',
+ color: '#123456',
+ content: 'Hello',
+ fontFamily: 'system-ui, sans-serif',
+ fontSize: 48,
+ fontWeight: 400,
+ lineHeight: 1.2,
+ type: 'text',
+} satisfies Extract<CanvasLayerSourceContract, { type: 'text' }>;
+
+type Router = (hex: string, phase: ColorSamplePhase) => boolean;
+
+/** The Color pane's tint editor, mounted beside the feed as the pane mounts it beside the canvas. */
+const TintEditorProbe = ({
+ engine,
+ onEditor,
+}: {
+ engine: CanvasEngine;
+ onEditor: (editor: MaskTintEditor | null) => void;
+}) => {
+ onEditor(useMaskTintEditor(engine));
+ return null;
+};
+
+const wait = (ms: number) =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, ms);
+ });
+
+const cleanups: (() => void | Promise<void>)[] = [];
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) {
+ await cleanup();
+ }
+ clearMaskTintTarget();
+ harness.store = null;
+});
+
+/**
+ * A real engine over a project holding a mask, a shape, a text layer and a paint layer, with `selected` selected. The feed's registered router is captured so tests drive picks the way the color-picker tool does.
+ */
+const setup = async (selected: 'm0' | 'shape' | 'text' | 'paint', { withTintEditor = false } = {}) => {
+ const store = createWorkbenchStore();
+ harness.store = store;
+ const projectId = store.getState().activeProjectId;
+ const layers: CanvasLayerContract[] = [
+ layerContract('shape', 'raster', { name: 'Shape', source: SHAPE_SOURCE }),
+ layerContract('text', 'raster', { name: 'Text', source: TEXT_SOURCE }),
+ layerContract('paint', 'raster', { name: 'Paint' }),
+ layerContract('m0', 'inpaint_mask', { name: 'Mask' }),
+ ];
+ store.commands.canvas.apply(projectId, {
+ document: { ...createEmptyCanvasDocument(), selectedLayerId: selected, stacks: stacksFrom(layers) },
+ type: 'replaceCanvasDocument',
+ });
+ const createEngine = (): CanvasEngine => {
+ const created = createCanvasEngine({
+ ensureProjectOnServer: () => Promise.resolve(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ mutationPort: createCanvasProjectMutationPort(store, projectId),
+ projectId,
+ reportError: () => undefined,
+ });
+ cleanups.push(() => created.lifecycle.dispose());
+ return created;
+ };
+ const engine = createEngine();
+ const [screen, overlay] = [document.createElement('canvas'), document.createElement('canvas')];
+ for (const canvas of [screen, overlay]) {
+ canvas.width = 64;
+ canvas.height = 64;
+ document.body.append(canvas);
+ cleanups.push(() => canvas.remove());
+ }
+ engine.surface.attach(screen, overlay);
+
+ let router: Router | null = null;
+ const setRouter = engine.tools.setColorSampleRouter.bind(engine.tools);
+ vi.spyOn(engine.tools, 'setColorSampleRouter').mockImplementation((next) => {
+ router = next;
+ return setRouter(next);
+ });
+
+ const host = document.createElement('div');
+ document.body.append(host);
+ const root: Root = createRoot(host);
+ cleanups.push(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ });
+ let tintEditor: MaskTintEditor | null = null;
+ const renderFeed = (feedEngine: CanvasEngine) =>
+ act(() => {
+ root.render(
+ <I18nextProvider i18n={i18n}>
+ <CanvasColorFeed engine={feedEngine} />
+ {withTintEditor ? <TintEditorProbe engine={feedEngine} onEditor={(editor) => (tintEditor = editor)} /> : null}
+ </I18nextProvider>
+ );
+ });
+ await renderFeed(engine);
+ expect(router).not.toBeNull();
+
+ const document_ = () => store.getState().projects.find((project) => project.id === projectId)!.canvas.document;
+ const layer = (id: string) => engine.document.model()!.getLayer(id)!;
+ const canvasValues = () =>
+ getProjectWidgetValues(
+ store.getState().projects.find((project) => project.id === projectId)!,
+ 'canvas'
+ );
+ /** One pick: previews each color, then ends with `end` carrying the last one, as the tool does. */
+ const pick = (colors: readonly string[], end: 'commit' | 'cancel') =>
+ act(() => {
+ for (const hex of colors) {
+ router!(hex, 'preview');
+ }
+ router!(colors.at(-1)!, end);
+ });
+ return {
+ canvasValues,
+ document: document_,
+ engine,
+ layer,
+ createEngine,
+ pick,
+ projectId,
+ renderFeed,
+ router: () => router!,
+ store,
+ tintEditor: () => tintEditor,
+ };
+};
+
+const tintOf = (layer: CanvasLayerContract) => (layer.type === 'inpaint_mask' ? layer.mask.fill.color : null);
+const sourceOf = (layer: CanvasLayerContract) => (layer.type === 'raster' ? layer.source : null);
+
+describe('CanvasColorFeed Alt-pick routing', () => {
+ it('writes the armed mask tint as one undoable edit and leaves the pair alone', async () => {
+ const view = await setup('m0');
+ armMaskTintTarget('m0');
+ const pairBefore = view.canvasValues().activeColors;
+
+ await act(() => view.router()('#101010', 'preview'));
+ // A preview shows live, on the next frame, without recording history.
+ await expect.poll(() => tintOf(view.layer('m0'))).toBe('#101010');
+ expect(view.engine.history.getEntries().past).toEqual([]);
+
+ await act(() => {
+ view.router()(PICKED, 'preview');
+ view.router()(PICKED, 'commit');
+ });
+ expect(tintOf(view.layer('m0'))).toBe(PICKED);
+ expect(view.engine.history.getEntries().past).toEqual(['Fill']);
+ expect(view.canvasValues().activeColors).toEqual(pairBefore);
+
+ await act(() => view.engine.history.undo());
+ expect(tintOf(view.layer('m0'))).toBe(TINT);
+ });
+
+ it('restores the tint from before the pick on cancel', async () => {
+ const view = await setup('m0');
+ armMaskTintTarget('m0');
+ await view.pick(['#101010', PICKED], 'cancel');
+ expect(tintOf(view.layer('m0'))).toBe(TINT);
+ expect(view.engine.history.getEntries().past).toEqual([]);
+ });
+
+ it('records a pending Color pane tint edit before an Alt-pick, so the pick lands last as its own step', async () => {
+ const view = await setup('m0', { withTintEditor: true });
+ await act(() => armMaskTintTarget('m0'));
+ // A pane edit waits out its settle delay before recording; the pick arrives inside that window.
+ await act(() => view.tintEditor()!.commit('#111111'));
+ await view.pick([PICKED], 'commit');
+ expect(tintOf(view.layer('m0'))).toBe(PICKED);
+ expect(view.engine.history.getEntries().past).toEqual(['Fill', 'Fill']);
+
+ // The pane's settle delay passing changes nothing more.
+ await act(() => wait(500));
+ expect(tintOf(view.layer('m0'))).toBe(PICKED);
+ expect(view.engine.history.getEntries().past).toEqual(['Fill', 'Fill']);
+
+ await act(() => view.engine.history.undo());
+ expect(tintOf(view.layer('m0'))).toBe('#111111');
+ });
+
+ it('keeps the pick on its target when the selection moves mid-pick', async () => {
+ const view = await setup('m0');
+ armMaskTintTarget('m0');
+ await act(() => view.router()('#101010', 'preview'));
+ await act(() => {
+ view.store.commands.canvas.apply(view.projectId, { id: 'paint', type: 'setCanvasSelectedLayer' });
+ });
+ await act(() => view.router()(PICKED, 'commit'));
+ expect(tintOf(view.layer('m0'))).toBe(PICKED);
+ expect(view.canvasValues().activeColors).toBeUndefined();
+ });
+
+ it.each([
+ ['foreground', 'fill'],
+ ['background', 'stroke'],
+ ] as const)('writes a selected shape’s %s-target color to its %s in one undo step', async (target, field) => {
+ const view = await setup('shape');
+ await act(() => view.store.commands.widgets.patchValues('canvas', { activeColorTarget: target }));
+ const pairBefore = view.canvasValues().activeColors;
+
+ await view.pick(['#101010', PICKED], 'commit');
+ expect(sourceOf(view.layer('shape'))).toMatchObject({ ...SHAPE_SOURCE, [field]: PICKED });
+ expect(view.engine.history.getEntries().past).toEqual(['Edit shape']);
+ expect(view.canvasValues().activeColors).toEqual(pairBefore);
+
+ await act(() => view.engine.history.undo());
+ expect(sourceOf(view.layer('shape'))).toEqual(SHAPE_SOURCE);
+ });
+
+ it('writes a selected text layer’s color in one undo step', async () => {
+ const view = await setup('text');
+ await view.pick([PICKED], 'commit');
+ expect(sourceOf(view.layer('text'))).toMatchObject({ color: PICKED });
+ expect(view.engine.history.getEntries().past).toEqual(['Edit text']);
+ });
+
+ it('writes the pair, with no history, when nothing is armed — the Gradient tool included', async () => {
+ const view = await setup('paint');
+ await act(() => view.engine.tools.setTool('gradient'));
+ await act(() => view.store.commands.widgets.patchValues('canvas', { activeColorTarget: 'background' }));
+
+ await act(() => view.router()('#101010', 'preview'));
+ // The pair follows every preview, as before.
+ expect(view.canvasValues().activeColors).toEqual({ background: '#101010', foreground: '#000000' });
+ await act(() => view.router()(PICKED, 'commit'));
+ expect(view.canvasValues().activeColors).toEqual({ background: PICKED, foreground: '#000000' });
+ expect(view.engine.history.getEntries().past).toEqual([]);
+ });
+
+ it('restores the pair color from before the pick on cancel', async () => {
+ const view = await setup('paint');
+ await view.pick(['#101010', PICKED], 'cancel');
+ expect(view.canvasValues().activeColors).toEqual({ background: '#ffffff', foreground: '#000000' });
+ });
+
+ it('registers its router again with a new engine instance for the same project', async () => {
+ const view = await setup('paint');
+ const replacement = view.createEngine();
+ const registered: Router[] = [];
+ const setRouter = replacement.tools.setColorSampleRouter.bind(replacement.tools);
+ vi.spyOn(replacement.tools, 'setColorSampleRouter').mockImplementation((next) => {
+ registered.push(next);
+ return setRouter(next);
+ });
+ expect(replacement.projectId).toBe(view.engine.projectId);
+
+ await view.renderFeed(replacement);
+
+ expect(registered).toHaveLength(1);
+ await act(() => registered[0]!('#101010', 'preview'));
+ expect(view.canvasValues().activeColors).toEqual({ background: '#ffffff', foreground: '#101010' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
index ac0f21c709..ed9bc6fe6d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
@@ -1,16 +1,67 @@
+import type { ColorSamplePhase } from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
-import { useEffect } from 'react';
+import { useMountEffect } from '@platform/react/useMountEffect';
+import { usePreparedCommit, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { useEffect, useEffectEvent, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+import type { ActiveColorTarget } from './colorPair';
+
+import { readActiveColorPair, readActiveColorTarget } from './colorPair';
+import { maskTintTargetStore, settlePendingMaskTint } from './maskTintTarget';
import { useActiveColorCommands, useActiveColorPair } from './useActiveColors';
+import {
+ armedMaskLayer,
+ isMaskLayer,
+ MASK_TINT_EDIT_LABEL_KEY,
+ maskTintPreview,
+ prepareMaskTintEdit,
+} from './useMaskTintEditor';
+
+/**
+ * What one eyedropper pick writes, fixed at its first sample so a selection change mid-pick cannot retarget it.
+ * Gradient stops have no armed state, so a pick on the Gradient tool writes the pair. A live text session is no
+ * target: its editor holds focus and keeps Alt, and leaving it commits the session.
+ */
+type PickTarget =
+ | { kind: 'mask-tint'; layerId: string }
+ | { kind: 'shape'; layerId: string; field: 'fill' | 'stroke' }
+ | { kind: 'text-layer'; layerId: string }
+ | { kind: 'pair'; target: ActiveColorTarget; before: string };
+
+/**
+ * Precedence: the armed mask tint while its mask is still selected; a selected shape (the foreground target writes
+ * its fill, the background its stroke); a selected text layer; otherwise the pair.
+ */
+const resolvePickTarget = (engine: CanvasEngineHandle, canvasValues: Record<string, unknown>): PickTarget => {
+ const model = engine.document.model();
+ const document = model?.document ?? null;
+ const pairTarget = readActiveColorTarget(canvasValues);
+ if (document) {
+ const tint = armedMaskLayer(document, maskTintTargetStore.getSnapshot().layerId);
+ if (tint) {
+ return { kind: 'mask-tint', layerId: tint.id };
+ }
+ }
+ const selected = document?.selectedLayerId ? (model?.getLayer(document.selectedLayerId) ?? null) : null;
+ if (selected?.type === 'raster' && selected.source.type === 'shape') {
+ return { field: pairTarget === 'foreground' ? 'fill' : 'stroke', kind: 'shape', layerId: selected.id };
+ }
+ if (selected?.type === 'raster' && selected.source.type === 'text') {
+ return { kind: 'text-layer', layerId: selected.id };
+ }
+ return { before: readActiveColorPair(canvasValues)[pairTarget], kind: 'pair', target: pairTarget };
+};
/**
* Isolate frequent color-pair updates in this null adapter. Mirror the pair into brush color, captured at stroke
- * start, and route unclaimed samples to the active pair target.
+ * start, and route eyedropper picks to the armed color target.
*/
export const CanvasColorFeed = ({ engine }: { engine: CanvasEngineHandle | null }) => {
const colorPair = useActiveColorPair();
- const colorCommands = useActiveColorCommands();
useEffect(() => {
if (!engine) {
@@ -31,15 +82,117 @@ export const CanvasColorFeed = ({ engine }: { engine: CanvasEngineHandle | null
engine.interaction.set('colorPair', { background: colorPair.background, foreground: colorPair.foreground });
}, [engine, colorPair.background, colorPair.foreground]);
- useEffect(() => {
- if (!engine) {
- return;
- }
- return engine.tools.setColorSampleRouter((hex) => {
- colorCommands.applySampledColor(hex);
- return true;
+ // Keyed by engine identity, so each engine instance (a project's engine recreated after disposal included) mounts
+ // its own routing and registers its router exactly once.
+ return engine ? <ColorSampleRouting key={engineKey(engine)} engine={engine} /> : null;
+};
+
+// Created on first use: a module-scope global constructor call would make this module side-effectful.
+let engineKeys: WeakMap<CanvasEngineHandle, string> | null = null;
+let nextEngineKey = 0;
+/** A stable React key per engine object; held weakly, so a disposed engine's entry goes with it. */
+const engineKey = (engine: CanvasEngineHandle): string => {
+ engineKeys ??= new WeakMap();
+ let key = engineKeys.get(engine);
+ if (key === undefined) {
+ nextEngineKey += 1;
+ key = `engine-${nextEngineKey}`;
+ engineKeys.set(engine, key);
+ }
+ return key;
+};
+
+/** Owns the engine's eyedropper router and the pick in progress. */
+const ColorSampleRouting = ({ engine }: { engine: CanvasEngineHandle }) => {
+ const { t } = useTranslation();
+ const colorCommands = useActiveColorCommands();
+ const queries = useWorkbenchQueries();
+ const tintPreview = useStructuralPreview(engine);
+ const commitPrepared = usePreparedCommit(engine);
+ const pickRef = useRef<PickTarget | null>(null);
+
+ /** Commits the shape's or text layer's color through the same edit and history label as its own picker. */
+ const commitSourceColor = (target: Extract<PickTarget, { kind: 'shape' | 'text-layer' }>, hex: string): void => {
+ const label =
+ target.kind === 'shape' ? t('widgets.canvas.toolOptions.shapeEdit') : t('widgets.canvas.toolOptions.textEdit');
+ commitPrepared(label, (model) => {
+ const layer = model.getLayer(target.layerId);
+ if (layer?.type !== 'raster') {
+ return { ids: [target.layerId], status: 'missing' };
+ }
+ if (target.kind === 'shape' && layer.source.type === 'shape') {
+ return model.prepare({ id: layer.id, source: { ...layer.source, [target.field]: hex }, type: 'patch-source' });
+ }
+ if (target.kind === 'text-layer' && layer.source.type === 'text') {
+ return model.prepare({ id: layer.id, source: { ...layer.source, color: hex }, type: 'patch-source' });
+ }
+ return { ids: [target.layerId], status: 'missing' };
});
- }, [colorCommands, engine]);
+ };
+
+ // Previews are live and unrecorded; the release records one edit, and a cancel restores the color from before the
+ // pick. Shape and text-layer colors live in the layer source, which has no live preview, so they change on release.
+ const routeSample = useEffectEvent((hex: string, phase: ColorSamplePhase): boolean => {
+ const startsPick = pickRef.current === null;
+ const target =
+ pickRef.current ??
+ resolvePickTarget(engine, getProjectWidgetValues(queries.getSnapshot().activeProject, 'canvas'));
+ pickRef.current = phase === 'preview' ? target : null;
+ switch (target.kind) {
+ case 'mask-tint': {
+ if (phase === 'cancel') {
+ tintPreview.cancel();
+ break;
+ }
+ if (phase === 'preview') {
+ // The pane's own tint gesture records first: the canvas holds one preview at a time.
+ if (startsPick) {
+ settlePendingMaskTint();
+ }
+ // The held layer, even if the selection moved mid-pick.
+ const layer = engine.document.model()?.getLayer(target.layerId) ?? null;
+ if (isMaskLayer(layer)) {
+ tintPreview.preview(maskTintPreview(layer, hex));
+ }
+ break;
+ }
+ tintPreview.commit(t(MASK_TINT_EDIT_LABEL_KEY), (model, baseline) =>
+ prepareMaskTintEdit(model, baseline, target.layerId, hex)
+ );
+ break;
+ }
+ case 'shape':
+ case 'text-layer':
+ if (phase === 'commit') {
+ commitSourceColor(target, hex);
+ }
+ break;
+ case 'pair':
+ colorCommands.setPairColor(target.target, phase === 'cancel' ? target.before : hex);
+ break;
+ }
+ return true;
+ });
+
+ /** A pick cut short by unmount records nothing. */
+ const abandonPick = useEffectEvent((): void => {
+ if (pickRef.current?.kind === 'mask-tint') {
+ tintPreview.cancel();
+ }
+ pickRef.current = null;
+ });
+
+ // The parent keys this component by engine, so the router registers once per engine instance.
+ // The linter cannot see useMountEffect as an effect, so it rejects calling the effect events from it.
+ /* eslint-disable react-hooks/rules-of-hooks -- useMountEffect is the repository's explicit useEffect wrapper */
+ useMountEffect(() => {
+ const dispose = engine.tools.setColorSampleRouter((hex, phase) => routeSample(hex, phase));
+ return () => {
+ dispose();
+ abandonPick();
+ };
+ });
+ /* eslint-enable react-hooks/rules-of-hooks */
return null;
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts
index 38d1b739f0..e4ec68aa62 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/maskTintTarget.ts
@@ -7,13 +7,38 @@ import { createExternalStore } from '@platform/state/externalStore';
*/
export const maskTintTargetStore = createExternalStore<{ layerId: string | null }>({ layerId: null });
+/**
+ * Records the Color pane's tint gesture that previews but has not yet recorded. The canvas allows one structural
+ * preview at a time, so an Alt-pick into the tint records this gesture before it starts its own; otherwise the
+ * pane's late settle would land after the pick and overwrite it.
+ */
+let pendingTintSettle: (() => void) | null = null;
+
registerAccountOwnedResource({
clear: () => {
maskTintTargetStore.setSnapshot({ layerId: null });
+ pendingTintSettle = null;
},
name: 'mask-tint-target',
});
+/** Registers `settle` as the gesture an Alt-pick must record first. */
+export const holdPendingMaskTint = (settle: () => void): void => {
+ pendingTintSettle = settle;
+};
+
+/** Forgets `settle` once its gesture recorded, leaving a newer gesture's registration in place. */
+export const releasePendingMaskTint = (settle: () => void): void => {
+ if (pendingTintSettle === settle) {
+ pendingTintSettle = null;
+ }
+};
+
+/** Records any pending pane tint gesture now, before another tint preview begins. */
+export const settlePendingMaskTint = (): void => {
+ pendingTintSettle?.();
+};
+
export const armMaskTintTarget = (layerId: string): void => {
maskTintTargetStore.setSnapshot({ layerId });
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts
index d6a65e5395..f92d4e46a6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useMaskTintEditor.ts
@@ -1,13 +1,25 @@
-import type { CanvasLayerContract, CanvasMaskFillContract } from '@workbench/canvas-engine/api';
+import type {
+ CanvasDocumentContractV3,
+ CanvasDocumentModel,
+ CanvasLayerContract,
+ CanvasLayerPreviewMutation,
+ CanvasMaskFillContract,
+ PrepareEditResult,
+} from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
import { getDocumentLayer } from '@workbench/canvas-engine/api';
import { baselineConfig, useStructuralPreview } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
-import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import { clearMaskTintTarget, useMaskTintTargetLayerId } from './maskTintTarget';
+import {
+ clearMaskTintTarget,
+ holdPendingMaskTint,
+ releasePendingMaskTint,
+ useMaskTintTargetLayerId,
+} from './maskTintTarget';
type MaskTintEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;
type MaskLayer = Extract<CanvasLayerContract, { type: 'inpaint_mask' | 'regional_guidance' }>;
@@ -35,7 +47,7 @@ interface TintGesture {
timer: ReturnType<typeof setTimeout> | null;
}
-const isMaskLayer = (layer: CanvasLayerContract | null): layer is MaskLayer =>
+export const isMaskLayer = (layer: CanvasLayerContract | null): layer is MaskLayer =>
layer?.type === 'inpaint_mask' || layer?.type === 'regional_guidance';
const configFor = (layer: MaskLayer, fill: CanvasMaskFillContract) =>
@@ -43,6 +55,40 @@ const configFor = (layer: MaskLayer, fill: CanvasMaskFillContract) =>
? ({ layerType: 'inpaint_mask', mask: { fill } } as const)
: ({ layerType: 'regional_guidance', mask: { fill } } as const);
+/** The history label every tint edit records under, whichever control or pick made it. */
+export const MASK_TINT_EDIT_LABEL_KEY = 'widgets.layers.maskFill.fill';
+
+/** The armed tint target's layer while it is still the selected mask; anything else disarms it. */
+export const armedMaskLayer = (document: CanvasDocumentContractV3, armedLayerId: string | null): MaskLayer | null => {
+ if (!armedLayerId || document.selectedLayerId !== armedLayerId) {
+ return null;
+ }
+ const node = getDocumentLayer(document, armedLayerId);
+ return node && isMaskLayer(node) ? node : null;
+};
+
+/** The un-recorded live preview of `layer` tinted `hex`. */
+export const maskTintPreview = (layer: MaskLayer, hex: string): CanvasLayerPreviewMutation => ({
+ config: configFor(layer, { ...layer.mask.fill, color: hex }),
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+});
+
+/** The recorded tint edit for the live layer, its `before` taken from what a preview gesture replaced. */
+export const prepareMaskTintEdit = (
+ model: CanvasDocumentModel,
+ baseline: CanvasLayerPreviewMutation | null,
+ layerId: string,
+ hex: string
+): PrepareEditResult => {
+ const live = model.getLayer(layerId);
+ if (!isMaskLayer(live)) {
+ return { ids: [layerId], status: 'missing' };
+ }
+ const config = configFor(live, { ...live.mask.fill, color: hex });
+ return model.prepare({ before: baselineConfig(baseline, config), config, id: live.id, type: 'patch-config' });
+};
+
/**
* Clear invalid/unselected mask targets and return to pair editing. Settle each pending preview into exactly one
* history entry on idle, disarm, or unmount.
@@ -51,35 +97,27 @@ export const useMaskTintEditor = (engine: MaskTintEngine | null): MaskTintEditor
const { t } = useTranslation();
const { commit: commitPrepared, preview: previewStructural } = useStructuralPreview(engine);
const armedLayerId = useMaskTintTargetLayerId();
- const layer = useActiveProjectSelector((project): MaskLayer | null => {
- if (!armedLayerId || project.canvas.document.selectedLayerId !== armedLayerId) {
- return null;
- }
- const node = getDocumentLayer(project.canvas.document, armedLayerId);
- return node && (node.type === 'inpaint_mask' || node.type === 'regional_guidance') ? node : null;
- });
+ const layer = useActiveProjectSelector((project) => armedMaskLayer(project.canvas.document, armedLayerId));
const gestureRef = useRef<TintGesture | null>(null);
+ const settleRef = useRef<() => void>(() => undefined);
+ // One stable identity for the shared pending-gesture slot, always running the latest settle.
+ const [settleLatest] = useState(() => () => settleRef.current());
const settle = useCallback(() => {
const gesture = gestureRef.current;
gestureRef.current = null;
if (!gesture) {
return;
}
+ releasePendingMaskTint(settleLatest);
if (gesture.timer !== null) {
clearTimeout(gesture.timer);
}
// A gesture ending on the color it started from prepares nothing, which drops its previews.
- commitPrepared(t('widgets.layers.maskFill.fill'), (model, baseline) => {
- const live = model.getLayer(gesture.layerId);
- if (!isMaskLayer(live)) {
- return { ids: [gesture.layerId], status: 'missing' };
- }
- const config = configFor(live, { ...live.mask.fill, color: gesture.latestHex });
- return model.prepare({ before: baselineConfig(baseline, config), config, id: live.id, type: 'patch-config' });
- });
- }, [commitPrepared, t]);
- const settleRef = useRef(settle);
+ commitPrepared(t(MASK_TINT_EDIT_LABEL_KEY), (model, baseline) =>
+ prepareMaskTintEdit(model, baseline, gesture.layerId, gesture.latestHex)
+ );
+ }, [commitPrepared, settleLatest, t]);
useEffect(() => {
settleRef.current = settle;
}, [settle]);
@@ -103,22 +141,17 @@ export const useMaskTintEditor = (engine: MaskTintEngine | null): MaskTintEditor
if (!layer) {
return;
}
- if (
- !previewStructural({
- config: configFor(layer, { ...layer.mask.fill, color: hex }),
- id: layer.id,
- type: 'updateCanvasLayerConfig',
- })
- ) {
+ if (!previewStructural(maskTintPreview(layer, hex))) {
return;
}
if (gestureRef.current === null) {
gestureRef.current = { latestHex: hex, layerId: layer.id, timer: null };
+ holdPendingMaskTint(settleLatest);
} else {
gestureRef.current.latestHex = hex;
}
},
- [previewStructural, layer]
+ [previewStructural, layer, settleLatest]
);
const commit = useCallback(
(hex: string) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index 0629fcae78..a8709facf8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -206,6 +206,10 @@ export const useBboxGrid = (engine: CanvasCoreStoreCapability): number => useCan
export const useTransformSession = (engine: CanvasCoreStoreCapability): TransformSession | null =>
useCanvasInteractionState(engine, 'transformSession');
+/** The layer a requested transform waits on until its stroke saves; null when nothing is waiting. */
+export const usePendingTransformLayerId = (engine: CanvasCoreStoreCapability): string | null =>
+ useCanvasInteractionState(engine, 'pendingTransformLayerId');
+
/** Whether a pixel selection currently exists (enables fill/erase/invert/deselect controls). */
export const useCanvasHasSelection = (engine: CanvasCoreStoreCapability): boolean =>
useCanvasInteractionState(engine, 'hasSelection');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts
index b894c22101..495d60a251 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts
@@ -118,21 +118,34 @@ describe('computeFitBboxToMasks', () => {
imageLayer('a', 0, 0, 500, 500), // ignored (not a mask)
inpaintMask('m', 100, 100, { height: 40, imageName: 'm-img', width: 40 }),
]);
- // mask bounds {100,100,40,40} → pad 8 → {92,92,56,56} → grid 8 → {96,96,48,48}.
- expect(computeFitBboxToMasks(doc, 8)).toEqual({ height: 48, width: 48, x: 96, y: 96 });
+ // mask bounds {100,100,40,40} → blur 0 pads 8 → {92,92,56,56} → grid 8 → {96,96,48,48}.
+ expect(computeFitBboxToMasks(doc, 8, 0)).toEqual({ height: 48, width: 48, x: 96, y: 96 });
+ });
+
+ it('pads by the mask blur plus 8 so the feathered edge stays inside the frame', () => {
+ const doc = docWith([inpaintMask('m', 200, 200, { height: 100, imageName: 'm-img', width: 100 })]);
+ // Default blur 16 pads 24: {176,176,148,148}. Blur 0 pads 8: {192,192,116,116}.
+ expect(computeFitBboxToMasks(doc, 1, 16)).toEqual({ height: 148, width: 148, x: 176, y: 176 });
+ expect(computeFitBboxToMasks(doc, 1, 0)).toEqual({ height: 116, width: 116, x: 192, y: 192 });
+ });
+
+ it('grid-snaps the blur-padded rect inward', () => {
+ const doc = docWith([inpaintMask('m', 100, 100, { height: 40, imageName: 'm-img', width: 40 })]);
+ // Blur 16 pads 24 → {76,76,88,88}; grid 8 moves the origin up to 80 (+4) and floors 84 to 80.
+ expect(computeFitBboxToMasks(doc, 8, 16)).toEqual({ height: 80, width: 80, x: 80, y: 80 });
});
it('excludes regional-guidance masks (legacy fits inpaint_mask only)', () => {
const regional = maskLayer('regional_guidance', 'rg', 400, 400, { height: 40, imageName: 'rg-img', width: 40 });
const doc = docWith([regional, inpaintMask('m', 100, 100, { height: 40, imageName: 'm-img', width: 40 })]);
// Identical to the inpaint-only fit above: the regional mask contributes nothing.
- expect(computeFitBboxToMasks(doc, 8)).toEqual({ height: 48, width: 48, x: 96, y: 96 });
+ expect(computeFitBboxToMasks(doc, 8, 0)).toEqual({ height: 48, width: 48, x: 96, y: 96 });
// Regional masks alone ⇒ nothing to fit.
- expect(computeFitBboxToMasks(docWith([regional]), 8)).toBeNull();
+ expect(computeFitBboxToMasks(docWith([regional]), 8, 0)).toBeNull();
});
it('returns null when there are no visible inpaint masks', () => {
- expect(computeFitBboxToMasks(docWith([imageLayer('a', 0, 0, 100, 100)]), 8)).toBeNull();
- expect(computeFitBboxToMasks(docWith([inpaintMask('empty', 0, 0, null)]), 8)).toBeNull();
+ expect(computeFitBboxToMasks(docWith([imageLayer('a', 0, 0, 100, 100)]), 8, 16)).toBeNull();
+ expect(computeFitBboxToMasks(docWith([inpaintMask('empty', 0, 0, null)]), 8, 16)).toBeNull();
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts
index e1bbaa9578..760d05101f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts
@@ -1,7 +1,7 @@
/**
* Union enabled, renderable, nonempty layer bounds in document space. Mask fitting includes only inpaint masks and
- * adds {@link MASK_FIT_PADDING}; snap inward with {@link fitRectToGrid}. Return null for no content or a collapsed
- * result.
+ * pads by the mask blur plus {@link MASK_FIT_MARGIN}; snap inward with {@link fitRectToGrid}. Return null for no
+ * content or a collapsed result.
*/
import {
@@ -15,8 +15,11 @@ import {
union,
} from '@workbench/canvas-engine/api';
-/** Fixed outward padding (document px) applied to the mask union before grid-fitting. */
-const MASK_FIT_PADDING = 8;
+/**
+ * Outward margin (document px) beyond the mask blur. The blur feathers the mask past its painted edge, so the frame
+ * has to clear the blur radius for the soft edge to land inside the generated region.
+ */
+const MASK_FIT_MARGIN = 8;
/**
* Snap inward: round origins up and sizes down. gridSize <= 1 uses integer rounding, matching legacy
@@ -61,16 +64,20 @@ export const computeFitBboxToLayers = (doc: CanvasDocumentContractV3, gridSize:
return isEmpty(fitted) ? null : fitted;
};
-/** The padded, grid-snapped bbox that fits the visible INPAINT masks (legacy parity), or `null` when there are none. */
+/**
+ * The grid-snapped frame that fits the visible INPAINT masks padded by `maskBlur` plus {@link MASK_FIT_MARGIN}, or
+ * `null` when there are none. `maskBlur` is the project's clamped compositing mask blur.
+ */
export const computeFitBboxToMasks = (
doc: CanvasDocumentContractV3,
gridSize: number,
- padding: number = MASK_FIT_PADDING
+ maskBlur: number
): Rect | null => {
const bounds = unionRenderableBounds(doc, (layer) => layer.type === 'inpaint_mask');
if (!bounds) {
return null;
}
+ const padding = maskBlur + MASK_FIT_MARGIN;
const expanded: Rect = {
height: bounds.height + padding * 2,
width: bounds.width + padding * 2,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/frameIcons.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/frameIcons.ts
new file mode 100644
index 0000000000..e882b05e40
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/frameIcons.ts
@@ -0,0 +1,17 @@
+import { createLucideIcon } from 'lucide-react';
+
+/**
+ * Fit frame to masks: the frame tool's viewfinder corners around a diamond, so it reads as the frame's own family and
+ * stays distinct from the inpaint-mask type icon. The corners are Lucide `Scan` 1.46.0's four paths, inlined because
+ * lucide-react exports no typed per-icon node; the icon inherits Lucide's sizing, stroke width and round joins.
+ */
+export const FitFrameToMasksIcon = createLucideIcon({
+ name: 'fit-frame-to-masks',
+ node: [
+ ['path', { d: 'M3 7V5a2 2 0 0 1 2-2h2', key: 'scan-top-left' }],
+ ['path', { d: 'M17 3h2a2 2 0 0 1 2 2v2', key: 'scan-top-right' }],
+ ['path', { d: 'M21 17v2a2 2 0 0 1-2 2h-2', key: 'scan-bottom-right' }],
+ ['path', { d: 'M7 21H5a2 2 0 0 1-2-2v-2', key: 'scan-bottom-left' }],
+ ['path', { d: 'M12 7.5 16.5 12 12 16.5 7.5 12Z', key: 'diamond' }],
+ ],
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
new file mode 100644
index 0000000000..b37dd726e6
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
@@ -0,0 +1,88 @@
+import type { CanvasInteractionState } from '@workbench/canvas-engine/api';
+import type { ToolFooterProps } from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { page } from 'vitest/browser';
+
+import { transformForm } from './geometryForm';
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const i18n = createInstance();
+let root: Root | null = null;
+let host: HTMLDivElement | null = null;
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ await i18n.use(initReactI18next).init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ root = null;
+ host = null;
+});
+
+/** The engine's interaction store as the footer reads it: a value per key and a listener set per key. */
+const createEngine = () => {
+ const state: Partial<CanvasInteractionState> = {
+ hasFloatingSelection: false,
+ pendingTransformLayerId: null,
+ transformSession: null,
+ };
+ const listeners = new Map<string, Set<() => void>>();
+ const engine = {
+ interaction: {
+ get: (key: keyof CanvasInteractionState) => state[key],
+ subscribe: (key: string, listener: () => void) => {
+ const keyListeners = listeners.get(key) ?? new Set();
+ keyListeners.add(listener);
+ listeners.set(key, keyListeners);
+ return () => keyListeners.delete(listener);
+ },
+ },
+ layers: { applyTransform: vi.fn(), cancelTransform: vi.fn() },
+ };
+ const setPending = (layerId: string | null) =>
+ act(() => {
+ state.pendingTransformLayerId = layerId;
+ listeners.get('pendingTransformLayerId')?.forEach((listener) => listener());
+ });
+ return { engine: engine as unknown as ToolFooterProps['engine'], setPending };
+};
+
+describe('Transform footer', () => {
+ it('says while a transform waits for its stroke to save, in a polite live region, and clears after', async () => {
+ const { engine, setPending } = createEngine();
+ const Footer = transformForm.footer!;
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Footer engine={engine} isExternalInteractionLocked={false} />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ const status = page.getByRole('status');
+ await expect.element(status).toBeInTheDocument();
+ await expect.element(status).toHaveTextContent('');
+
+ await setPending('layer-1');
+ await expect.element(status).toHaveTextContent('Waiting for the stroke to save…');
+ await expect.element(page.getByRole('button', { name: 'Apply' })).toBeDisabled();
+
+ await setPending(null);
+ await expect.element(status).toHaveTextContent('');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
index f1b1dfa739..507da527c9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
@@ -7,13 +7,14 @@ import type {
ToolPropertyGroup,
} from '@workbench/widgets/canvas/tool-presentation/toolFormContracts';
-import { Flex } from '@chakra-ui/react';
+import { Flex, Text } from '@chakra-ui/react';
import { AspectRatioLockButton, AspectRatioSelect } from '@features/generation/components';
import { ASPECT_RATIO_MAP, deriveAspectRatioId } from '@features/generation/settings';
import { constrainBboxToRatio, lookupDocumentLeaf } from '@workbench/canvas-engine/api';
import {
useCanvasActiveTool,
useCanvasHasFloatingSelection,
+ usePendingTransformLayerId,
useTransformSession,
} from '@workbench/widgets/canvas/engineStoreHooks';
import {
@@ -256,14 +257,23 @@ const FrameSizeSettings = ({ engine }: ToolFormProps) => {
* settled selected layer, matching the Transform pane.
*/
const TransformFooter = ({ engine, isExternalInteractionLocked }: ToolFooterProps) => {
+ const { t } = useTranslation();
const session = useTransformSession(engine);
const hasFloat = useCanvasHasFloatingSelection(engine);
+ const isPending = usePendingTransformLayerId(engine) !== null;
// The root sticky footer sits OUTSIDE the inert tool section, so the
// surface lock must be honored here, not inherited.
const disabled = isExternalInteractionLocked || (!session && !hasFloat);
const onApply = useCallback(() => engine.layers.applyTransform(), [engine]);
const onCancel = useCallback(() => engine.layers.cancelTransform(), [engine]);
- return <ApplyCancelBar applyDisabled={disabled} cancelDisabled={disabled} onApply={onApply} onCancel={onCancel} />;
+ return (
+ <ApplyCancelBar applyDisabled={disabled} cancelDisabled={disabled} onApply={onApply} onCancel={onCancel}>
+ {/* Always mounted, so screen readers hear the wait start and end as the live region's text changes. */}
+ <Text color="fg.muted" role="status" truncate>
+ {isPending ? t('widgets.canvas.transformPending') : null}
+ </Text>
+ </ApplyCancelBar>
+ );
};
/** Shared literal: the same object in every geometry form, so the rows' DOM survives tool switches. */
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsx
index 62c194b4f4..af7351e0b0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.browser.test.tsx
@@ -259,6 +259,8 @@ describe('CanvasEditRefusalNotices', () => {
it.each<[CanvasEditRefusal, string]>([
['over-budget', 'widgets.canvas.structural.overBudget'],
['busy', 'widgets.canvas.structural.busy'],
+ // A pending transform whose stroke failed to save ends with this refusal.
+ ['not-ready', 'widgets.canvas.structural.notReady'],
])('explains a %s refusal of an edit nobody else reports', (refusal, message) => {
const { emit, engine } = createRefusalEngine();
render(<CanvasEditRefusalNotices engine={engine} />);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index e08bd8e905..d5d08684e9 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -11,9 +11,8 @@ import type {
RegionalGuidanceReferenceImage,
} from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { LucideIcon } from 'lucide-react';
-import type { ComponentProps, Dispatch, ReactNode } from 'react';
+import type { ComponentProps, ReactNode } from 'react';
import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { galleryTransfers } from '@features/gallery';
@@ -37,6 +36,7 @@ import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
+import { reportTransformRefusal } from '@workbench/widgets/canvas/canvasHotkeyCommands';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
import {
useCanvasDocumentEditingLocked,
@@ -89,7 +89,7 @@ import {
getLayerContextMenuRenderEntries,
} from './layerContextMenuLayout';
import { copyLayerToClipboard, saveLayerToAssets } from './layerExportActions';
-import { canGroupSelection, groupLayers } from './layerGroupCommands';
+import { canGroupSelection, canRemoveFromGroup, groupLayers, removeFromGroup } from './layerGroupCommands';
import { resolveMenuTargetForRender } from './layerMenuState';
import {
DEFAULT_INPAINT_MASK_FILL,
@@ -178,7 +178,6 @@ const hasPureExportableLayerContent = (layer: CanvasLayerContract, document: Can
};
interface LayerMenuProps {
- dispatch: Dispatch<CanvasProjectMutation>;
engine: LayerContextMenuEngine | null;
layer: CanvasLayerContract;
/** Where the menu opens: the panel anchors to its trigger; the canvas uses a
@@ -212,7 +211,6 @@ interface LayerMenuProps {
* Keep dialogs outside the closing menu portal.
*/
const LayerMenu = ({
- dispatch,
engine,
layer,
positioning,
@@ -298,6 +296,13 @@ const LayerMenu = ({
)
);
});
+ const canMergeMasks = useCanvasEngineRead(
+ engine,
+ () => !!engine && targets.length > 1 && engine.layers.canMergeInpaintMasks(targets)
+ );
+ const canRemoveTargetsFromGroup = useCanvasEngineRead(engine, () =>
+ canRemoveFromGroup(engine?.document.model() ?? null, targets)
+ );
const canDeleteSelection = useCanvasEngineRead(
engine,
() => engine?.document.model()?.refusalFor({ ids: targets, type: 'remove' }) === null
@@ -309,7 +314,9 @@ const LayerMenu = ({
() => ({
canDeleteSelection,
canGroupSelection: canGroup,
+ canMergeMasks,
canMergeSelection: canMerge,
+ canRemoveFromGroup: canRemoveTargetsFromGroup,
hiddenByAncestor,
isQuickSwitchBookmark,
canRunWorkflow: workflowAvailability.canRunWorkflow,
@@ -329,6 +336,8 @@ const LayerMenu = ({
canDeleteSelection,
canGroup,
canMerge,
+ canMergeMasks,
+ canRemoveTargetsFromGroup,
document,
engine,
hasSupportedContent,
@@ -400,6 +409,25 @@ const LayerMenu = ({
}
}, [engine, layer, makeStatusError, projectId, selectedIds, t]);
+ const handleRemoveFromGroup = useCallback(() => {
+ const outcome = removeFromGroup(engine, actionTargets({ layer, selectedIds }), getActionLabel('remove-from-group'));
+ if (outcome.status === 'refused') {
+ throw makeStatusError(outcome.refusal.status === 'locked' ? 'locked' : 'unsupported');
+ }
+ }, [engine, getActionLabel, layer, makeStatusError, selectedIds]);
+
+ const handleMergeMasks = useCallback(async () => {
+ if (!engine) {
+ throw makeStatusError('not-ready');
+ }
+ const result = await engine.layers.mergeInpaintMasks(actionTargets({ layer, selectedIds }));
+ if (result.status === 'ineligible') {
+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.mergeMasksIneligible'));
+ } else if (result.status !== 'merged') {
+ reportLayerOperation(result.status, notify.error, t);
+ }
+ }, [engine, layer, makeStatusError, notify, selectedIds, t]);
+
const handleMergeSelected = useCallback(() => {
if (!engine) {
return;
@@ -592,9 +620,14 @@ const LayerMenu = ({
);
const handleTransform = useCallback(() => {
- dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });
- engine?.tools.setTool('transform');
- }, [dispatch, engine, layer.id]);
+ if (!engine) {
+ throw makeStatusError('not-ready');
+ }
+ const result = engine.layers.beginTransform(layer.id);
+ if (result !== 'started') {
+ reportTransformRefusal(result, notify.error, t);
+ }
+ }, [engine, layer.id, makeStatusError, notify, t]);
const handleFitToBbox = useCallback(() => {
const transform = fitLayerTransformToBbox(layer, bbox, documentRect);
@@ -876,6 +909,7 @@ const LayerMenu = ({
group: handleGroup,
fitToBbox: handleFitToBbox,
mergeDown: handleMerge,
+ mergeMasks: handleMergeMasks,
mergeSelected: handleMergeSelected,
openProperties: handleOpenProperties,
openRename,
@@ -884,6 +918,7 @@ const LayerMenu = ({
startFilter,
patchConfig: handleLayerConfigAction,
rasterize: handleRasterize,
+ removeFromGroup: handleRemoveFromGroup,
reorder: (kind, actionId) => reorder(kind, getActionLabel(actionId)),
saveToAssets: handleSaveToAssets,
setColorLabel: handleSetColorLabel,
@@ -909,11 +944,13 @@ const LayerMenu = ({
handleExtractMaskedArea,
handleFitToBbox,
handleGroup,
+ handleMergeMasks,
handleMergeSelected,
handleLayerConfigAction,
handleMerge,
handleOpenProperties,
handleRasterize,
+ handleRemoveFromGroup,
handleSaveToAssets,
handleSetColorLabel,
handleToggleLock,
@@ -1026,7 +1063,6 @@ const LayerMenu = ({
};
interface LayerRowMenuProps {
- dispatch: Dispatch<CanvasProjectMutation>;
engine: LayerContextMenuEngine | null;
layer: CanvasLayerContract;
}
@@ -1049,14 +1085,12 @@ export interface CanvasLayerContextMenuTarget {
*/
export const CanvasLayerContextMenu = ({
beforeDangerItems,
- dispatch,
engine,
target,
showGroupLabels,
onClose,
}: {
beforeDangerItems?: ReactNode;
- dispatch: Dispatch<CanvasProjectMutation>;
engine: LayerContextMenuEngine | null;
target: CanvasLayerContextMenuTarget | null;
showGroupLabels?: boolean;
@@ -1118,7 +1152,6 @@ export const CanvasLayerContextMenu = ({
<LayerMenu
key={renderTarget.layerId}
beforeDangerItems={beforeDangerItems}
- dispatch={dispatch}
dialogKind={dialogState?.isOpen ? dialogState.kind : null}
engine={engine}
layer={layer}
@@ -1319,6 +1352,7 @@ const LayerMenuActionItem = ({
return (
<LayerMenuItem
+ description={action.descriptionKey ? t(action.descriptionKey, { defaultValue: '' }) : undefined}
disabled={action.isDisabled}
hint={action.hint}
icon={action.icon}
@@ -1332,6 +1366,7 @@ const LayerMenuActionItem = ({
};
const LayerMenuItem = ({
+ description,
disabled,
hint,
icon,
@@ -1341,6 +1376,8 @@ const LayerMenuItem = ({
tone,
value,
}: {
+ /** A second line under the label. */
+ description?: string;
disabled?: boolean;
/** A raw hotkey string, formatted per platform and shown as trailing keycaps. */
hint?: string;
@@ -1359,6 +1396,7 @@ const LayerMenuItem = ({
return (
<MenuActionItem
disabled={disabled}
+ hint={description}
icon={icon}
iconColor={iconColor}
label={label}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
index e6cd9ddd1a..cb12387591 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.browser.test.tsx
@@ -104,7 +104,6 @@ const Harness = ({ ref }: { ref: Ref<OpenSurface> }) => {
return (
<LayerSurfaceHost
commands={rowCommands}
- dispatch={() => true}
document={mocks.project.canvas.document}
editingLocked={false}
engine={engine}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
index c3b15c1051..e90de71a5d 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerSurfaceHost.tsx
@@ -1,7 +1,5 @@
import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';
import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
-import type { Dispatch } from 'react';
import { getDocumentNode } from '@workbench/canvas-engine/api';
import { useCallback, useMemo } from 'react';
@@ -26,7 +24,6 @@ export type LayerSurfaceRequest =
interface LayerSurfaceHostProps {
commands: LayerRowCommands;
- dispatch: Dispatch<CanvasProjectMutation>;
document: CanvasDocumentContractV3;
editingLocked: boolean;
engine: LayerSurfaceEngine | null;
@@ -41,7 +38,6 @@ interface LayerSurfaceHostProps {
*/
export const LayerSurfaceHost = ({
commands,
- dispatch,
document,
editingLocked,
engine,
@@ -110,7 +106,7 @@ export const LayerSurfaceHost = ({
}
return (
<>
- <CanvasLayerContextMenu dispatch={dispatch} engine={engine} target={menuTarget} onClose={handleMenuClose} />
+ <CanvasLayerContextMenu engine={engine} target={menuTarget} onClose={handleMenuClose} />
{surface?.kind === 'menu' && node?.type === 'group' && engine ? (
<LayerGroupContextMenu
key={node.id}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
index 72febccb00..5d16b91a54 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
@@ -639,6 +639,7 @@ describe('LayersTree selection, surfaces and structure', () => {
hasSelectedStagedCandidate: false,
isInteractionLocked: false,
copySelection: vi.fn(),
+ cropAllLayers: vi.fn(),
swapActiveColors: vi.fn(),
resetActiveColors: vi.fn(),
pasteFromClipboard: vi.fn(),
@@ -646,6 +647,7 @@ describe('LayersTree selection, surfaces and structure', () => {
reportStructuralCommit: vi.fn(),
reportPreparedCommit: vi.fn(),
reportLayerOperation: vi.fn(),
+ reportTransformRefusal: vi.fn(),
t: (key) => key,
};
await act(() => executeCanvasHotkeyCommand('canvas.nextEntity', ctx));
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index 9c582193b8..416e925ab1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -1310,7 +1310,6 @@ export const LayersTree = ({
</Box>
<LayerSurfaceHost
commands={commands}
- dispatch={dispatch}
document={document}
editingLocked={editingLocked}
engine={engine}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index 26e717f22a..d1ecd723ae 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -33,7 +33,7 @@ import {
} from './panes/editorPaneLayout';
import { HistoryPane } from './panes/HistoryPane';
import { LayerColorPane, LayerEditorPanes } from './panes/LayerEditorPanes';
-import { useCanvasHistoryHotkeys } from './useCanvasHistoryHotkeys';
+import { useCanvasCompanionHotkeys } from './useCanvasCompanionHotkeys';
import { useLayerSelectionCommands } from './useLayerSelectionCommands';
const TREE_TABS_ID_BASE = 'layer-tree';
@@ -62,7 +62,7 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {
const degraded = nodeCount > LAYER_PANEL_DEGRADE_THRESHOLD;
const selectionCommands = useLayerSelectionCommands(engine, projectId, panel.selectedIds, editingLocked);
- useCanvasHistoryHotkeys(runtime, engine);
+ useCanvasCompanionHotkeys(runtime, engine);
const handleFilter = useCallback(
(filter: string) => setLayerPanelFilter(projectId, selectedLayerId, filter),
[projectId, selectedLayerId]
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index cf7b31915a..032cb7c271 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -1,11 +1,12 @@
import type {
CanvasDocumentContractV3,
CanvasLayerContract,
+ CanvasNodeContract,
CanvasRasterLayerContractV2,
} from '@workbench/canvas-engine/contracts';
import { seedArchitectureCapabilities } from '@features/generation/core/architectureCapabilities.testing';
-import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { describe, expect, it, vi } from 'vitest';
import {
@@ -58,7 +59,7 @@ const makeLayer = (type: CanvasLayerContract['type']): CanvasLayerContract => {
}
};
-const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({
+const makeDocument = (layers: CanvasNodeContract[]): CanvasDocumentContractV3 => ({
background: 'transparent',
bbox: { height: 512, width: 512, x: 0, y: 0 },
height: 512,
@@ -84,7 +85,9 @@ const makeState = (
interactionLocked: false,
canGroupSelection: true,
canDeleteSelection: true,
+ canMergeMasks: true,
canMergeSelection: true,
+ canRemoveFromGroup: true,
layer,
modelBase: null,
selectedIds: [layer.id],
@@ -108,6 +111,7 @@ const makeEffects = (): LayerContextActionEffects => ({
fitToBbox: vi.fn(),
group: vi.fn(),
mergeDown: vi.fn(),
+ mergeMasks: vi.fn(),
mergeSelected: vi.fn(),
openProperties: vi.fn(),
openRename: vi.fn(),
@@ -116,6 +120,7 @@ const makeEffects = (): LayerContextActionEffects => ({
startFilter: vi.fn(),
patchConfig: vi.fn(),
rasterize: vi.fn(),
+ removeFromGroup: vi.fn(),
reorder: vi.fn(),
setColorLabel: vi.fn(),
saveToAssets: vi.fn(() => Promise.resolve()),
@@ -143,7 +148,7 @@ const byId = (actions: readonly LayerContextAction[], id: LayerContextActionId):
const idsFor = (
layer: CanvasLayerContract,
- layers: readonly CanvasLayerContract[] = [layer],
+ layers: readonly CanvasNodeContract[] = [layer],
overrides: Partial<LayerContextActionState> = {}
): LayerContextActionId[] =>
getLayerContextActions(makeState(layer, { document: makeDocument([...layers]), ...overrides })).map(
@@ -178,7 +183,10 @@ describe('layer context action registry', () => {
it('has English translations for registry labels and action errors', () => {
const keys = [
- ...LAYER_CONTEXT_ACTION_DEFINITIONS.map((definition) => definition.labelKey),
+ ...LAYER_CONTEXT_ACTION_DEFINITIONS.flatMap((definition) => [
+ definition.labelKey,
+ ...(definition.descriptionKey ? [definition.descriptionKey] : []),
+ ]),
'widgets.layers.actions.enableTransparencyEffect',
'widgets.layers.actions.disableTransparencyEffect',
'widgets.layers.actions.enableAutoNegative',
@@ -196,6 +204,8 @@ describe('layer context action registry', () => {
'widgets.layers.actions.cropFailed',
'widgets.layers.actions.cropUnsupported',
'widgets.layers.actions.cropped',
+ 'widgets.layers.actions.mergeMasksIneligible',
+ 'widgets.layers.actions.transformIneligible',
'widgets.layers.rasterFilter.busy',
'widgets.layers.rasterFilter.cancel',
'widgets.layers.rasterFilter.commitFailure',
@@ -447,8 +457,10 @@ describe('getLayerContextActions', () => {
}),
makeState(nonEmptyControlLayer, { interactionLocked: true }),
makeState(inpaint, { interactionLocked: true }),
+ makeState(inpaint, { interactionLocked: true, selectedIds: [inpaint.id, 'interaction-mask-b'] }),
makeState(regional, { interactionLocked: true }),
makeState(text, { interactionLocked: true }),
+ makeState(raster, { document: makeDocument([groupContract('G', [raster])]), interactionLocked: true }),
];
const actions = contexts.flatMap((context) => getLayerContextActions(context));
const actionsById = new Map(actions.map((action) => [action.id, action]));
@@ -459,6 +471,7 @@ describe('getLayerContextActions', () => {
'move-to-back',
'duplicate',
'group',
+ 'remove-from-group',
'rename',
'transform',
'fit-to-bbox',
@@ -497,6 +510,7 @@ describe('getLayerContextActions', () => {
'add-denoise-limit',
'merge-down',
'merge-selected',
+ 'merge-masks',
'toggle-visibility',
'toggle-hidden',
'toggle-lock',
@@ -913,3 +927,76 @@ describe('toggle-hidden', () => {
expect(runtime.effects.toggleHidden).toHaveBeenCalledTimes(1);
});
});
+
+describe('add-regenerate-region description', () => {
+ it('gives only Add regenerate region a fixed description, and carries it onto the menu action', () => {
+ expect(
+ LAYER_CONTEXT_ACTION_DEFINITIONS.filter((definition) => definition.descriptionKey).map(
+ (definition) => definition.id
+ )
+ ).toEqual(['add-regenerate-region']);
+ const actions = getLayerContextActions(makeState(rasterLayer));
+ expect(byId(actions, 'add-regenerate-region').descriptionKey).toBe(
+ 'widgets.layers.actions.addRegenerateRegionDescription'
+ );
+ expect(byId(actions, 'add-regenerate-region').hint).toBeUndefined();
+ });
+});
+
+describe('remove-from-group', () => {
+ const r1 = paintLayer('r1');
+ const r2 = paintLayer('r2');
+ const r3 = paintLayer('r3');
+ const top = paintLayer('top');
+ const grouped = [top, groupContract('G', [r1, r2]), groupContract('H', [r3])];
+
+ it('is offered only when every target is a leaf of one group', () => {
+ expect(idsFor(r1, grouped)).toContain('remove-from-group');
+ expect(idsFor(r1, grouped, { selectedIds: ['r1', 'r2'] })).toContain('remove-from-group');
+ expect(idsFor(top, grouped)).not.toContain('remove-from-group');
+ expect(idsFor(r1, grouped, { selectedIds: ['r1', 'r3'] })).not.toContain('remove-from-group');
+ expect(idsFor(r1, grouped, { selectedIds: ['r1', 'H'] })).not.toContain('remove-from-group');
+ });
+
+ it("is enabled by the model's answer and routes to its effect", () => {
+ const document = makeDocument(grouped);
+ const refused = getLayerContextActions(makeState(r1, { canRemoveFromGroup: false, document }));
+ expect(byId(refused, 'remove-from-group').isDisabled).toBe(true);
+ const locked = getLayerContextActions(makeState(r1, { document, interactionLocked: true }));
+ expect(byId(locked, 'remove-from-group').isDisabled).toBe(true);
+
+ const runtime = makeRuntimeContext(r1, { document });
+ void getLayerContextActionDefinition('remove-from-group').handler(runtime);
+ expect(runtime.effects.removeFromGroup).toHaveBeenCalledOnce();
+ });
+});
+
+describe('merge-masks', () => {
+ const m1 = createInpaintMaskLayer('Mask 1', 'm1');
+ const m2 = createInpaintMaskLayer('Mask 2', 'm2');
+ const region = createRegionalGuidanceLayer('Region', 0, 'region');
+ const layers = [m1, groupContract('G', [m2]), region];
+
+ it('replaces raster merge for a selection of inpaint masks only', () => {
+ const masks = idsFor(m1, layers, { selectedIds: ['m1', 'm2'] });
+ expect(masks).toContain('merge-masks');
+ expect(masks).not.toContain('merge-selected');
+ expect(idsFor(m1, layers)).not.toContain('merge-masks');
+ const mixed = idsFor(m1, layers, { selectedIds: ['m1', 'region'] });
+ expect(mixed).not.toContain('merge-masks');
+ expect(mixed).toContain('merge-selected');
+ });
+
+ it("is enabled by the engine's eligibility and routes to its effect", () => {
+ const state = { document: makeDocument(layers), selectedIds: ['m1', 'm2'] };
+ expect(byId(getLayerContextActions(makeState(m1, state)), 'merge-masks').isDisabled).toBe(false);
+ expect(byId(getLayerContextActions(makeState(m1, state)), 'merge-masks').descriptionKey).toBeUndefined();
+ const ineligible = getLayerContextActions(makeState(m1, { ...state, canMergeMasks: false }));
+ expect(byId(ineligible, 'merge-masks').isDisabled).toBe(true);
+ expect(byId(ineligible, 'merge-masks').descriptionKey).toBe('widgets.layers.actions.mergeMasksIneligible');
+
+ const runtime = makeRuntimeContext(m1, state);
+ void getLayerContextActionDefinition('merge-masks').handler(runtime);
+ expect(runtime.effects.mergeMasks).toHaveBeenCalledOnce();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index eb1aa1fbfe..7593f25655 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -48,6 +48,7 @@ import {
SlidersVerticalIcon,
SplineIcon,
SunMediumIcon,
+ UngroupIcon,
WavesIcon,
SlidersHorizontalIcon,
Trash2Icon,
@@ -55,6 +56,7 @@ import {
} from 'lucide-react';
import { COLOR_LABEL_ITEMS } from './colorLabels';
+import { removeFromGroupCommand } from './layerGroupCommands';
import { canAddRegionalReferenceImage, canConvertRasterControl, canMergeLayerDown } from './layerOps';
export type LayerContextActionId =
@@ -70,12 +72,14 @@ export type LayerContextActionId =
| 'add-hue'
| 'add-invert'
| 'merge-selected'
+ | 'merge-masks'
| 'move-to-front'
| 'move-forward'
| 'move-backward'
| 'move-to-back'
| 'duplicate'
| 'group'
+ | 'remove-from-group'
| 'rename'
| 'transform'
| 'fit-to-bbox'
@@ -132,6 +136,10 @@ export interface LayerContextActionState {
canDeleteSelection: boolean;
/** Whether the whole multi-selection can merge into one raster, asked the same way. */
canMergeSelection: boolean;
+ /** Whether the engine would merge `actionTargets` into one inpaint mask. */
+ canMergeMasks: boolean;
+ /** The model's answer for lifting `actionTargets` out of their group. */
+ canRemoveFromGroup: boolean;
/** A group above the layer hides it on the canvas; the layer's own flag cannot override that. */
hiddenByAncestor: boolean;
/** Whether Q jumps to this layer: the engine's transient quick-switch bookmark names it. */
@@ -142,7 +150,9 @@ export interface LayerContextActionEffects {
reorder(kind: LayerStackMoveKind, actionId: LayerContextActionId): void;
duplicate(): void;
mergeSelected(): void;
+ mergeMasks(): void;
group(): void;
+ removeFromGroup(): void;
openRename(): void;
openRunWorkflow(): void;
startSelectObject(layerId: string): void;
@@ -191,6 +201,10 @@ export interface LayerContextActionDefinition {
tone?: 'danger';
/** A raw hotkey string (e.g. `mod+]`) shown as a trailing hint on the item. */
hint?: string;
+ /** A second line under the label explaining what the action does. */
+ descriptionKey?: string;
+ /** A second line that depends on the context, such as why the action is unavailable; wins over `descriptionKey`. */
+ getDescriptionKey?(context: LayerContextActionState): string | undefined;
isVisible(context: LayerContextActionState): boolean;
isEnabled(context: LayerContextActionState): boolean;
handler(context: LayerContextActionRuntimeContext): void | Promise<void>;
@@ -212,6 +226,7 @@ export interface LayerContextAction {
order: number;
tone?: 'danger';
hint?: string;
+ descriptionKey?: string;
isDisabled: boolean;
handler(context: LayerContextActionRuntimeContext): void | Promise<void>;
}
@@ -263,6 +278,8 @@ const allTargetsEnabled = (context: LayerContextActionState): boolean =>
targetNodes(context).every((node) => node.isEnabled);
const allTargetsLocked = (context: LayerContextActionState): boolean =>
targetNodes(context).every((node) => node.isLocked);
+const allTargetsInpaintMasks = (context: LayerContextActionState): boolean =>
+ targetNodes(context).every((node) => node.type === 'inpaint_mask');
/** Locked in its own right or by a group above it: content edits are refused either way. */
const isLayerFrozen = (context: LayerContextActionState): boolean =>
context.layer.isLocked || (layerEntry(context)?.ancestorsLocked ?? false);
@@ -424,6 +441,18 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
section: 'quick',
supportedLayerTypes: ALL_LAYER_TYPES,
},
+ {
+ defaultLabel: 'Remove from group',
+ handler: ({ effects }) => effects.removeFromGroup(),
+ icon: UngroupIcon,
+ id: 'remove-from-group',
+ isEnabled: (context) => isInteractionFree(context) && context.canRemoveFromGroup,
+ isVisible: (context) => removeFromGroupCommand(context.document, actionTargets(context)) !== null,
+ labelKey: 'widgets.layers.actions.removeFromGroup',
+ order: 21,
+ section: 'quick',
+ supportedLayerTypes: ALL_LAYER_TYPES,
+ },
{
defaultLabel: 'Transform',
handler: ({ effects }) => effects.transform(),
@@ -449,7 +478,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
supportedLayerTypes: ALL_LAYER_TYPES,
},
{
- defaultLabel: 'Fit to bbox',
+ defaultLabel: 'Fit to frame',
handler: ({ effects }) => effects.fitToBbox(),
icon: ImageIcon,
id: 'fit-to-bbox',
@@ -563,6 +592,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
},
{
defaultLabel: 'Add regenerate region',
+ descriptionKey: 'widgets.layers.actions.addRegenerateRegionDescription',
handler: ({ effects }) => effects.addLayerRegion(),
icon: WandSparklesIcon,
id: 'add-regenerate-region',
@@ -627,12 +657,27 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
icon: MergeIcon,
id: 'merge-selected',
isEnabled: (context) => isInteractionFree(context) && context.canMergeSelection,
- isVisible: isMultiTarget,
+ // A mask-only selection merges through Merge masks instead; raster merge never accepts masks.
+ isVisible: (context) => isMultiTarget(context) && !allTargetsInpaintMasks(context),
labelKey: 'widgets.layers.actions.mergeSelected',
order: 1,
section: 'operations',
supportedLayerTypes: ALL_LAYER_TYPES,
},
+ {
+ defaultLabel: 'Merge masks',
+ // The engine's eligibility has several reasons; name them rather than leave the item silently disabled.
+ getDescriptionKey: (context) => (context.canMergeMasks ? undefined : 'widgets.layers.actions.mergeMasksIneligible'),
+ handler: ({ effects }) => effects.mergeMasks(),
+ icon: MergeIcon,
+ id: 'merge-masks',
+ isEnabled: (context) => isInteractionFree(context) && context.canMergeMasks,
+ isVisible: (context) => isMultiTarget(context) && allTargetsInpaintMasks(context),
+ labelKey: 'widgets.layers.actions.mergeMasks',
+ order: 1,
+ section: 'operations',
+ supportedLayerTypes: INPAINT_ONLY,
+ },
{
defaultLabel: 'Intersect with layer below',
handler: ({ effects }) => effects.booleanMerge('intersect'),
@@ -816,7 +861,7 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
supportedLayerTypes: RASTER_ONLY,
},
{
- defaultLabel: 'Crop layer to bbox',
+ defaultLabel: 'Crop layer to frame',
handler: ({ effects }) => effects.cropToBbox(),
icon: CropIcon,
id: 'crop-to-bbox',
@@ -994,6 +1039,7 @@ export const getLayerContextActions = (context: LayerContextActionState): LayerC
(definition) => definition.supportedLayerTypes.includes(context.layer.type) && definition.isVisible(context)
).map((definition) => ({
defaultLabel: definition.getDefaultLabel?.(context) ?? definition.defaultLabel,
+ descriptionKey: definition.getDescriptionKey?.(context) ?? definition.descriptionKey,
handler: definition.handler,
hint: definition.hint,
icon: definition.getIcon?.(context) ?? definition.icon,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index 4c81e94fda..59f287f0be 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -51,7 +51,9 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerCont
selectedIds: [layer.id],
canGroupSelection: true,
canDeleteSelection: true,
+ canMergeMasks: true,
canMergeSelection: true,
+ canRemoveFromGroup: true,
layer,
modelBase: null,
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.test.ts
new file mode 100644
index 0000000000..197aec6b46
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.test.ts
@@ -0,0 +1,115 @@
+import type { CanvasDocumentContractV3, CanvasNodeContract, PreparedDocumentEdit } from '@workbench/canvas-engine/api';
+import type { Project } from '@workbench/projectContracts';
+import type { CanvasPreparedEngine } from '@workbench/widgets/canvas/useStructuralCommit';
+
+import { createDocumentModel, getDocumentIndex } from '@workbench/canvas-engine/api';
+import {
+ groupContract as group,
+ layerContract as layer,
+ stacksFrom,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { describe, expect, it } from 'vitest';
+
+import { canRemoveFromGroup, removeFromGroup } from './layerGroupCommands';
+
+const projectWith = (nodes: CanvasNodeContract[]): Project =>
+ applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
+ document: { ...createEmptyCanvasDocument(), selectedLayerId: null, stacks: stacksFrom(nodes) },
+ type: 'replaceCanvasDocument',
+ });
+
+/** Stacks top first, each node in preorder, indented by depth. */
+const outline = (document: CanvasDocumentContractV3): string[] =>
+ getDocumentIndex(document).nodes.map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);
+
+/** A prepared-edit engine over a real document model whose commits apply through the real reducer. */
+const createEngine = (initial: Project) => {
+ let project = initial;
+ const edits: PreparedDocumentEdit[] = [];
+ const engine: CanvasPreparedEngine = {
+ document: { model: () => createDocumentModel(project.canvas.document, { editRevision: 0, projectId: project.id }) },
+ layers: {
+ commitPrepared: (_label, edit) => {
+ edits.push(edit);
+ project = applyCanvasProjectMutation(project, edit.forward);
+ return { status: 'committed' };
+ },
+ endStructuralPreview: () => undefined,
+ },
+ };
+ return {
+ document: () => project.canvas.document,
+ edits,
+ engine,
+ undo: () => {
+ project = applyCanvasProjectMutation(project, edits.at(-1)!.inverse);
+ },
+ };
+};
+
+/** raster: r1, G[r2, H[r3, r4], r5], r6 */
+const tree = (overrides: { lockH?: boolean } = {}): CanvasNodeContract[] => [
+ layer('r1'),
+ group('G', [
+ layer('r2'),
+ group('H', [layer('r3'), layer('r4')], { isLocked: overrides.lockH ?? false }),
+ layer('r5'),
+ ]),
+ layer('r6'),
+];
+
+describe('removeFromGroup', () => {
+ it('moves a leaf directly above its group in the parent, and one undo puts it back', () => {
+ const harness = createEngine(projectWith(tree()));
+ const before = outline(harness.document());
+
+ expect(removeFromGroup(harness.engine, ['r5'], 'Remove from group')).toEqual({ status: 'committed' });
+
+ expect(outline(harness.document())).toEqual(['r1', 'r5', 'G', ' r2', ' H', ' r3', ' r4', 'r6']);
+ expect(harness.edits).toHaveLength(1);
+ harness.undo();
+ expect(outline(harness.document())).toEqual(before);
+ });
+
+ it('lifts several leaves of a nested group above it in document order, whatever the selection order', () => {
+ const harness = createEngine(projectWith(tree()));
+
+ removeFromGroup(harness.engine, ['r4', 'r3'], 'Remove from group');
+
+ expect(outline(harness.document())).toEqual(['r1', 'G', ' r2', ' r3', ' r4', ' H', ' r5', 'r6']);
+ });
+
+ it('refuses leaves inside a locked group and changes nothing', () => {
+ const harness = createEngine(projectWith(tree({ lockH: true })));
+ const before = outline(harness.document());
+
+ expect(canRemoveFromGroup(harness.engine.document.model(), ['r3'])).toBe(false);
+ expect(removeFromGroup(harness.engine, ['r3'], 'Remove from group')).toMatchObject({
+ refusal: { status: 'locked' },
+ status: 'refused',
+ });
+ expect(outline(harness.document())).toEqual(before);
+ });
+
+ it.each([
+ ['a top-level leaf', ['r1']],
+ ['leaves of different groups', ['r2', 'r3']],
+ ['a group', ['H']],
+ ['an absent id', ['r5', 'ghost']],
+ ])('is unavailable for %s', (_name, ids) => {
+ const harness = createEngine(projectWith(tree()));
+
+ expect(canRemoveFromGroup(harness.engine.document.model(), ids)).toBe(false);
+ expect(removeFromGroup(harness.engine, ids, 'Remove from group')).toEqual({ status: 'unchanged' });
+ expect(harness.edits).toHaveLength(0);
+ });
+
+ it('is available for leaves of one unlocked group', () => {
+ const harness = createEngine(projectWith(tree()));
+
+ expect(canRemoveFromGroup(harness.engine.document.model(), ['r2', 'r5'])).toBe(true);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts
index 65fd4aff4e..33a252ad11 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts
@@ -1,4 +1,4 @@
-import type { CanvasDocumentModel } from '@workbench/canvas-engine/api';
+import type { CanvasDocumentContractV3, CanvasDocumentModel, DocumentCommand } from '@workbench/canvas-engine/api';
import type { CanvasPreparedEngine, PreparedCommitOutcome } from '@workbench/widgets/canvas/useStructuralCommit';
import { getDocumentIndex, isGroupNode } from '@workbench/canvas-engine/api';
@@ -79,3 +79,46 @@ export const ungroupLayers = (
});
return groupIds.length === 0 ? { status: 'unchanged' } : model.prepare({ ids: groupIds, type: 'ungroup' });
});
+
+/**
+ * The reparent that lifts `ids` out of their shared parent group to sit directly above it, in document order; null
+ * unless every id is a leaf of the same group.
+ */
+export const removeFromGroupCommand = (
+ document: CanvasDocumentContractV3,
+ ids: readonly string[]
+): Extract<DocumentCommand, { type: 'reparent' }> | null => {
+ const index = getDocumentIndex(document);
+ const entries = ids.flatMap((id) => index.byId.get(id) ?? []);
+ const groupId = entries[0]?.parentId ?? null;
+ if (
+ groupId === null ||
+ entries.length !== ids.length ||
+ entries.some((entry) => isGroupNode(entry.node) || entry.parentId !== groupId)
+ ) {
+ return null;
+ }
+ return {
+ beforeId: groupId,
+ ids: [...entries].sort((a, b) => a.order - b.order).map((entry) => entry.node.id),
+ parentId: index.byId.get(groupId)!.parentId,
+ type: 'reparent',
+ };
+};
+
+/** Whether the model would accept lifting `ids` out of their group; the same check the command runs. */
+export const canRemoveFromGroup = (model: CanvasDocumentModel | null, ids: readonly string[]): boolean => {
+ const command = model ? removeFromGroupCommand(model.document, ids) : null;
+ return !!model && !!command && model.refusalFor(command) === null;
+};
+
+/** Moves leaves of one group directly above it as one edit; an ineligible selection is a quiet no-op. */
+export const removeFromGroup = (
+ engine: CanvasPreparedEngine | null,
+ ids: readonly string[],
+ label: string
+): PreparedCommitOutcome =>
+ commitPreparedEdit(engine, label, (model) => {
+ const command = removeFromGroupCommand(model.document, ids);
+ return command ? model.prepare(command) : { status: 'unchanged' };
+ });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx
index 3604b47054..49b335b5aa 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx
@@ -131,8 +131,9 @@ export const ColorPane = () => {
const hex = await engine.tools.requestColorSample();
if (hex) {
// Routed through the command so the target is read when the sample lands,
- // not when the pipette was armed. The pane's pipette is the mask tint's
- // editor-specific sampler; the standing router never writes the tint.
+ // not when the pipette was armed. This one-shot sample is claimed before
+ // the standing router (CanvasColorFeed), which routes Alt-picks to the
+ // same armed tint, a selected shape or text, or the pair.
settlePendingRecent(false);
if (maskTint) {
maskTint.commit(hex);
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
new file mode 100644
index 0000000000..bcbdbbe2b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.browser.test.tsx
@@ -0,0 +1,167 @@
+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 { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';
+import { useFocusRegionProps } from '@workbench/focusRegions';
+import { IS_MAC_OS } from '@workbench/hotkeys/keys';
+import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';
+import { readActiveColorPair } from '@workbench/widgets/canvas/color-system/colorPair';
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { act, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { useCanvasCompanionHotkeys, type CanvasCompanionEngine } from './useCanvasCompanionHotkeys';
+
+/**
+ * The companion keys under the real hotkey runtime, focus provider, store and extension registry: a key pressed
+ * with focus in the Layers widget reaches the canvas engine. Only context plumbing and first-party commands, which
+ * need the whole application, are replaced.
+ */
+const mocks = vi.hoisted(() => ({
+ extensions: null as unknown as ExtensionRegistry,
+ store: null as unknown as WorkbenchInternalStore,
+}));
+
+vi.mock('@workbench/WorkbenchContext', () => ({
+ useActiveProjectSelector: <Selected,>(selector: (project: Project) => Selected) =>
+ selector(mocks.store.getSnapshot().activeProject),
+ useOptionalWorkbenchCommands: () => mocks.store.commands,
+ useOptionalWorkbenchExtensions: () => mocks.extensions,
+ useWorkbenchCommands: () => mocks.store.commands,
+ useWorkbenchExtensions: () => mocks.extensions,
+ useWorkbenchInternalStore: () => mocks.store,
+ useWorkbenchQueries: () => mocks.store.queries,
+ useWorkbenchSubscription: () => mocks.store.subscribe,
+}));
+vi.mock('@workbench/hotkeys/firstPartyCommands', () => ({ useRegisterFirstPartyCommands: () => {} }));
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const createEngine = () => ({
+ document: { model: () => null },
+ history: { redo: vi.fn(), undo: vi.fn() },
+ interaction: { get: vi.fn(() => 'brush'), set: vi.fn() },
+ layers: { beginTransform: vi.fn(() => 'started') },
+ tools: { setTool: vi.fn(), stepBrushSize: vi.fn() },
+});
+
+/** The Layers widget's frame as the shell renders it, registering through a widget runtime bound to its source. */
+const LayersFrame = ({ engine }: { engine: ReturnType<typeof createEngine> }) => {
+ const [runtime] = useState(() => {
+ const source: WidgetContributionSource = {
+ instanceId: 'layers',
+ projectId: mocks.store.getSnapshot().activeProject.id,
+ region: 'right',
+ typeId: 'layers',
+ };
+ return {
+ commands: { register: (command) => mocks.extensions.commands.register({ ...command, source }) },
+ hotkeys: { register: (hotkey) => mocks.extensions.hotkeys.register({ ...hotkey, scope: 'widget', source }) },
+ } satisfies Parameters<typeof useCanvasCompanionHotkeys>[0];
+ });
+ useCanvasCompanionHotkeys(runtime, engine as unknown as CanvasCompanionEngine);
+
+ return (
+ <div
+ {...useFocusRegionProps('right')}
+ data-hotkey-widget-instance-id="layers"
+ data-hotkey-widget-region="right"
+ data-hotkey-widget-type-id="layers"
+ >
+ <div role="tree">
+ <div aria-selected="true" role="treeitem" tabIndex={0}>
+ Layer 1
+ </div>
+ </div>
+ <button type="button">Swatches</button>
+ <input aria-label="Hex" />
+ </div>
+ );
+};
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+let engine = createEngine();
+
+const colorPair = () => readActiveColorPair(getProjectWidgetValues(mocks.store.getSnapshot().activeProject, 'canvas'));
+
+beforeEach(async () => {
+ mocks.store = createWorkbenchStore();
+ mocks.extensions = createExtensionRegistry();
+ engine = createEngine();
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <WorkbenchFocusProvider>
+ <WorkbenchHotkeyRuntime />
+ <LayersFrame engine={engine} />
+ </WorkbenchFocusProvider>
+ )
+ );
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('useCanvasCompanionHotkeys', () => {
+ it('selects canvas tools from a clicked layer row without taking focus from it', async () => {
+ const row = host!.querySelector<HTMLElement>('[role="treeitem"]')!;
+ await userEvent.click(row);
+
+ await userEvent.keyboard('b');
+
+ expect(engine.tools.setTool).toHaveBeenCalledExactlyOnceWith('brush');
+ expect(document.activeElement).toBe(row);
+ });
+
+ it('swaps the color pair and steps the brush from a clicked control, and switches tools from it', async () => {
+ const before = colorPair();
+ await userEvent.click(host!.querySelector('button')!);
+
+ await userEvent.keyboard('x');
+ await userEvent.keyboard(']');
+ await userEvent.keyboard('e');
+
+ expect(colorPair()).toEqual({ background: before.foreground, foreground: before.background });
+ expect(engine.tools.stepBrushSize).toHaveBeenCalledExactlyOnceWith(1);
+ expect(engine.tools.setTool).toHaveBeenCalledExactlyOnceWith('eraser');
+ });
+
+ it('keeps undo and redo on the canvas history', async () => {
+ await userEvent.click(host!.querySelector('[role="treeitem"]')!);
+
+ await userEvent.keyboard(IS_MAC_OS ? '{Meta>}z{/Meta}' : '{Control>}z{/Control}');
+
+ expect(engine.history.undo).toHaveBeenCalledOnce();
+ });
+
+ it('leaves typing in a field alone', async () => {
+ const field = host!.querySelector('input')!;
+ await userEvent.click(field);
+
+ await userEvent.keyboard('b');
+
+ expect(field.value).toBe('b');
+ expect(engine.tools.setTool).not.toHaveBeenCalled();
+ });
+
+ it('withdraws every registration on unmount', async () => {
+ await act(() => root!.unmount());
+ root = null;
+
+ expect(mocks.extensions.stores.hotkeys.list()).toEqual([]);
+ expect(mocks.extensions.stores.commands.list()).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
new file mode 100644
index 0000000000..13eb879327
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts
@@ -0,0 +1,74 @@
+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
+import type { WidgetCommandApi, WidgetHotkeyApi } from '@workbench/widgetContracts';
+
+import { useNotify } from '@workbench/useNotify';
+import {
+ CANVAS_COMPANION_HOTKEYS,
+ CANVAS_HISTORY_HOTKEYS,
+ executeCanvasToolCommand,
+ reportTransformRefusal,
+ type CanvasToolCommandId,
+} from '@workbench/widgets/canvas/canvasHotkeyCommands';
+import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
+import { useActiveColorCommands } from '@workbench/widgets/canvas/color-system/useActiveColors';
+import { useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { useEffect, useEffectEvent } from 'react';
+import { useTranslation } from 'react-i18next';
+
+type CompanionCommandId = (typeof CANVAS_HISTORY_HOTKEYS)[number][0] | CanvasToolCommandId;
+
+export type CanvasCompanionEngine = Pick<
+ CanvasEngineHandle,
+ 'document' | 'history' | 'interaction' | 'layers' | 'tools'
+>;
+
+/**
+ * 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.
+ */
+export const useCanvasCompanionHotkeys = (
+ runtime: { commands: Pick<WidgetCommandApi, 'register'>; hotkeys: WidgetHotkeyApi },
+ engine: CanvasCompanionEngine | null
+): void => {
+ const { t } = useTranslation();
+ const notify = useNotify();
+ const queries = useWorkbenchQueries();
+ const colorCommands = useActiveColorCommands();
+ const run = useEffectEvent((commandId: CompanionCommandId) => {
+ if (commandId === 'canvas.undo') {
+ engine?.history.undo();
+ return;
+ }
+ if (commandId === 'canvas.redo') {
+ engine?.history.redo();
+ return;
+ }
+ const { canvas, queue } = queries.getSnapshot().activeProject;
+ const model = engine?.document.model() ?? null;
+ const selectedId = model?.document.selectedLayerId ?? null;
+ executeCanvasToolCommand(commandId, {
+ engine,
+ isInteractionLocked: isCanvasInteractionLocked(canvas, queue.items),
+ reportTransformRefusal: (refusal) => reportTransformRefusal(refusal, notify.error, t),
+ resetActiveColors: colorCommands.resetPair,
+ selectedLayerId: selectedId === null ? null : (model?.getLayer(selectedId)?.id ?? null),
+ swapActiveColors: colorCommands.swapPair,
+ });
+ });
+ 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(
+ ([id, titleKey, defaultKeys]) => {
+ const title = t(titleKey);
+ return [
+ runtime.commands.register({ handler: () => run(id), id, title }),
+ runtime.hotkeys.register({ allowInEditable: false, commandId: id, defaultKeys: [...defaultKeys], id, title }),
+ ];
+ }
+ );
+
+ return () => {
+ disposers.forEach((dispose) => dispose());
+ };
+ }, [runtime.commands, runtime.hotkeys, t]);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx
deleted file mode 100644
index 6cde36f9a2..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.browser.test.tsx
+++ /dev/null
@@ -1,98 +0,0 @@
-import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
-import type { WidgetCommandContribution, WidgetHotkeyContribution } from '@workbench/widgetContracts';
-
-import { act, createElement, type ReactElement } from 'react';
-import { createRoot, type Root } from 'react-dom/client';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-
-import { useCanvasHistoryHotkeys } from './useCanvasHistoryHotkeys';
-
-const translation = { t: (key: string) => key };
-vi.mock('react-i18next', () => ({ useTranslation: () => translation }));
-
-(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-
-const createRuntime = () => {
- const commands = new Map<string, WidgetCommandContribution>();
- const hotkeys = new Map<string, WidgetHotkeyContribution>();
- return {
- commands: {
- register: vi.fn((command: WidgetCommandContribution) => {
- commands.set(command.id, command);
- return () => commands.delete(command.id);
- }),
- },
- hotkeys: {
- register: vi.fn((hotkey: WidgetHotkeyContribution) => {
- hotkeys.set(hotkey.id, hotkey);
- return () => hotkeys.delete(hotkey.id);
- }),
- },
- registered: { commands, hotkeys },
- };
-};
-
-const Host = ({
- engine,
- runtime,
-}: {
- engine: Pick<CanvasEngineHandle, 'history'> | null;
- runtime: ReturnType<typeof createRuntime>;
-}) => {
- useCanvasHistoryHotkeys(runtime, engine);
- return null;
-};
-
-let root: Root | null = null;
-let host: HTMLDivElement | null = null;
-
-afterEach(() => {
- act(() => root?.unmount());
- host?.remove();
- root = null;
- host = null;
-});
-
-const mount = (element: ReactElement): void => {
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- act(() => root!.render(element));
-};
-
-describe('useCanvasHistoryHotkeys', () => {
- it('registers undo/redo outside editable fields and drives the current engine', () => {
- const runtime = createRuntime();
- const first = { history: { redo: vi.fn(), undo: vi.fn() } } as unknown as CanvasEngineHandle;
- const second = { history: { redo: vi.fn(), undo: vi.fn() } } as unknown as CanvasEngineHandle;
- mount(createElement(Host, { engine: first, runtime }));
-
- expect([...runtime.registered.hotkeys.values()]).toEqual([
- expect.objectContaining({ allowInEditable: false, commandId: 'canvas.undo', defaultKeys: ['mod+z'] }),
- expect.objectContaining({
- allowInEditable: false,
- commandId: 'canvas.redo',
- defaultKeys: ['mod+shift+z', 'mod+y'],
- }),
- ]);
- void runtime.registered.commands.get('canvas.undo')!.handler();
- expect(first.history.undo).toHaveBeenCalledOnce();
-
- // A new engine identity re-renders the host without re-registering.
- act(() => root!.render(createElement(Host, { engine: second, runtime })));
- void runtime.registered.commands.get('canvas.redo')!.handler();
- expect(second.history.redo).toHaveBeenCalledOnce();
- expect(first.history.redo).not.toHaveBeenCalled();
- expect(runtime.commands.register).toHaveBeenCalledTimes(2);
- });
-
- it('withdraws both registrations on unmount and tolerates a missing engine', () => {
- const runtime = createRuntime();
- mount(createElement(Host, { engine: null, runtime }));
- expect(() => runtime.registered.commands.get('canvas.undo')!.handler()).not.toThrow();
-
- act(() => root!.unmount());
- expect(runtime.registered.commands.size).toBe(0);
- expect(runtime.registered.hotkeys.size).toBe(0);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts
deleted file mode 100644
index 7a94d57ff3..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useCanvasHistoryHotkeys.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
-import type { WidgetCommandApi, WidgetHotkeyApi } from '@workbench/widgetContracts';
-
-import { useEffect, useEffectEvent } from 'react';
-import { useTranslation } from 'react-i18next';
-
-// The canvas history's undo/redo, reachable while a companion widget owns
-// focus: selecting a layer or editing its properties must not strand mod+Z.
-const HISTORY_HOTKEYS = [
- ['canvas.undo', 'widgets.canvas.commands.undo', ['mod+z']],
- ['canvas.redo', 'widgets.canvas.commands.redo', ['mod+shift+z', 'mod+y']],
-] as const;
-
-type HistoryCommandId = (typeof HISTORY_HOTKEYS)[number][0];
-
-/** Registers canvas undo/redo on `runtime` for as long as the caller is mounted. */
-export const useCanvasHistoryHotkeys = (
- runtime: { commands: Pick<WidgetCommandApi, 'register'>; hotkeys: WidgetHotkeyApi },
- engine: Pick<CanvasEngineHandle, 'history'> | null
-): void => {
- const { t } = useTranslation();
- const run = useEffectEvent((commandId: HistoryCommandId) => {
- if (commandId === 'canvas.undo') {
- engine?.history.undo();
- } else {
- engine?.history.redo();
- }
- });
- useEffect(() => {
- const disposers = HISTORY_HOTKEYS.flatMap(([id, titleKey, defaultKeys]) => [
- runtime.commands.register({ handler: () => run(id), id, title: t(titleKey) }),
- runtime.hotkeys.register({
- allowInEditable: false,
- commandId: id,
- defaultKeys: [...defaultKeys],
- id,
- title: t(titleKey),
- }),
- ]);
-
- return () => {
- disposers.forEach((dispose) => dispose());
- };
- }, [runtime.commands, runtime.hotkeys, t]);
-};
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 2b32173a43..eb9b08161f 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -267,9 +267,12 @@ const CANVAS_LAYER_SHARED_MODULES = [
'/workbench/canvas-operations/useCanvasEngine.ts',
'/workbench/canvasProjectMutationPort.ts',
'/workbench/useCanvasProjectMutationDispatch.ts',
+ '/workbench/widgets/canvas/canvasHotkeyCommands.ts',
'/workbench/widgets/canvas/canvasInteractionLock.ts',
'/workbench/widgets/canvas/color-system/colorPair.ts',
+ '/workbench/widgets/canvas/color-system/maskTintTarget.ts',
'/workbench/widgets/canvas/color-system/useActiveColors.ts',
+ '/workbench/widgets/canvas/color-system/useMaskTintEditor.ts',
'/workbench/widgets/canvas/engineStoreHooks.ts',
'/workbench/widgets/canvas/textFontStyle.tsx',
'/workbench/widgets/canvas/tool-presentation/FormControls.tsx',