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.

feat(canvas): add assignable new raster layer command (#10325)

rnshine83611a6adfc8
diff --git a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
index f9d2f67ad3..18c3a6fbd4 100644
--- a/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
+++ b/docs/src/content/docs/Users Guide/07.Canvas/02.canvas-guide.mdx
@@ -242,6 +242,8 @@ These shortcuts work while the canvas has focus; then they take the key from a w
The tool keys, **Shift+T**, **[** and **]**, and **X** and **D** also work after you click in the Layers panel or its Color pane, so you can pick a layer or a color and switch tools without clicking back on the canvas. **Escape** and holding or tapping **C** work from the Layers panel too, but **Enter** applies a transform, text or filter only while the canvas has focus. None of these keys act while you type in a text field.
+To create a raster layer from the keyboard, assign a shortcut to **New raster layer** under **Settings → Keyboard shortcuts → Canvas**. It has no default binding, leaving browser-reserved shortcuts untouched. With the canvas focused, it adds and selects an empty raster layer using the same insertion and undo behavior as the Layers panel.
+
| Shortcut | Action |
|---|---|
| **H**, **V**, **Shift+T**, **C**, **B**, **E**, **U**, **S**, **G**, **T**, **M**, **L**, **I** | Select a tool (see [Tools](#tools)) |
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 92dc143cb1..119a20b7c0 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4474,6 +4474,7 @@
"deleteSelected": "Delete selected canvas item",
"deselect": "Deselect",
"duplicateLayer": "Duplicate layer",
+ "newRasterLayer": "New raster layer",
"fitBbox": "Fit generation frame",
"increaseBrushSize": "Increase brush/eraser size",
"invertSelection": "Invert selection",
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
index ddffc52fe3..42300e14b9 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
@@ -35,6 +35,32 @@ describe('firstPartyHotkeyCatalog', () => {
expect(openSettings).toMatchObject({ allowInEditable: true, defaultKeys: ['mod+,'] });
});
+ it('keeps new raster layer unbound until remapped, and limits it to Canvas focus outside modals', () => {
+ const definition = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.newRasterLayer')!;
+ const context = {
+ activeInstanceId: 'canvas',
+ activeWidgetTypeId: 'canvas',
+ focusedRegion: 'center',
+ isModalPresent: false,
+ projectId: 'project-1',
+ } as const;
+ const resolve = (customHotkeys: Record<string, string[]>, overrides = {}) =>
+ resolveHotkey({
+ context: { ...context, ...overrides },
+ event: { target: null } as KeyboardEvent,
+ hotkeys: firstPartyHotkeyCatalog.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys)),
+ matchedKey: 'alt+shift+n',
+ });
+
+ expect(definition.defaultKeys).toEqual([]);
+ expect(definition.allowInEditable).toBe(false);
+ expect(resolve({})).toBeNull();
+ const custom = { 'canvas.newRasterLayer': ['alt+shift+n'] };
+ expect(resolve(custom)?.commandId).toBe('canvas.newRasterLayer');
+ expect(resolve(custom, { activeWidgetTypeId: 'gallery' })).toBeNull();
+ expect(resolve(custom, { isModalPresent: true })).toBeNull();
+ });
+
it('binds transform to Shift+T only, leaving Mod+T to the browser', () => {
const transform = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.transformSelected');
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index 6aaa5b6b51..b86debde17 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -200,6 +200,7 @@ export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [
hotkey('canvas', 'nudgeRightLarge', ['shift+arrowright']),
hotkey('canvas', 'nudgeUpLarge', ['shift+arrowup']),
hotkey('canvas', 'nudgeDownLarge', ['shift+arrowdown']),
+ hotkey('canvas', 'newRasterLayer', [], { ignoreRepeat: true }),
hotkey('canvas', 'duplicateLayer', ['mod+j']),
hotkey('canvas', 'groupLayers', ['mod+g']),
hotkey('canvas', 'ungroupLayers', ['mod+shift+g']),
diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx
index a7de3d2d1d..44ec5755bd 100644
--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.browser.test.tsx
@@ -8,10 +8,10 @@ import { act } from 'react';
import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { page } from 'vitest/browser';
+import { page, userEvent } from 'vitest/browser';
import { HotkeysSettingsSection } from './HotkeysSettingsSection';
-import { DEFAULT_PREFERENCES, patchWorkbenchPreferences } from './store';
+import { DEFAULT_PREFERENCES, getWorkbenchPreferences, patchWorkbenchPreferences } from './store';
vi.mock('@workbench/projects/api', async (importOriginal) => ({
...(await importOriginal<typeof projectsApi>()),
@@ -63,6 +63,26 @@ afterEach(async () => {
});
describe('HotkeysSettingsSection conflicts', () => {
+ it('rejects the stock Shift+N collision and saves an available New Raster Layer shortcut', async () => {
+ await render();
+ await act(() => search().fill('new raster layer'));
+ await expect.element(page.getByText('New Raster Layer', { exact: true })).toBeVisible();
+ await act(() => page.getByRole('button', { name: i18n.t('hotkeys.addHotkey'), exact: true }).click());
+ await act(() => userEvent.keyboard('{Shift>}n{/Shift}'));
+ await expect.element(conflictText('Fit Frame To Layers')).toBeVisible();
+ const save = page.getByRole('button', { name: i18n.t('hotkeys.saveEdit'), exact: true });
+ await expect.element(save).toBeDisabled();
+ expect(getWorkbenchPreferences().customHotkeys['canvas.newRasterLayer']).toBeUndefined();
+
+ await act(() => page.getByRole('button', { name: i18n.t('hotkeys.cancelEdit'), exact: true }).click());
+ await act(() => page.getByRole('button', { name: i18n.t('hotkeys.addHotkey'), exact: true }).click());
+ await act(() => userEvent.keyboard('{Alt>}{Shift>}n{/Shift}{/Alt}'));
+ await expect.element(page.getByText(/^Conflicts with /)).not.toBeInTheDocument();
+ await expect.element(save).toBeEnabled();
+ await act(() => save.click());
+ expect(getWorkbenchPreferences().customHotkeys['canvas.newRasterLayer']).toEqual(['shift+alt+n']);
+ });
+
// Recall Seed answers in Preview and Gallery. A Gallery binding on its key meets it through the second of those
// widget types; a Canvas binding on the same key meets neither.
it('flags a binding that shares its key with a multi-widget shortcut on any of that shortcut’s widgets', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
index 37e3326958..a89e945d7f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetContracts.ts
@@ -195,6 +195,7 @@ export interface WidgetHotkeyContribution {
source?: WidgetContributionSource;
preventDefault?: boolean;
allowInEditable?: boolean;
+ ignoreRepeat?: boolean;
}
export interface WidgetCommandPaletteApi {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx
index 59dad5d973..857d6c676b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.browser.test.tsx
@@ -10,14 +10,17 @@ import type {
import type { CanvasStagingCandidateContract } from '@workbench/canvas-engine/contracts';
import type * as CanvasOperationsApi from '@workbench/canvas-operations/api';
import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import type { ExtensionRegistry } from '@workbench/extensions/extensionRegistry';
import type { Project } from '@workbench/projectContracts';
+import type * as ProjectsApi from '@workbench/projects/api';
import type { WorkbenchQueueItem as QueueItem } from '@workbench/queueHistoryContracts';
-import type { WidgetViewProps } from '@workbench/widgetContracts';
+import type { WidgetHotkeyContribution, WidgetCommandContribution, WidgetViewProps } from '@workbench/widgetContracts';
import type * as WorkbenchContextModule from '@workbench/WorkbenchContext';
-import { ChakraProvider } from '@chakra-ui/react';
+import { Box, ChakraProvider } from '@chakra-ui/react';
import { auditAccessibility } from '@platform/browser/auditAccessibility.testing';
import { TINY_PNG_BASE64 } from '@platform/browser/nativeDrag.testing';
+import { accountLifecycle } from '@platform/state/accountLifecycle';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { system } from '@theme/system';
import { createControlLayer, createVectorLayer } from '@workbench/canvas-engine/api';
@@ -28,11 +31,15 @@ import { getCanvasOperations } from '@workbench/canvas-operations/api';
import { createControlDetectionStatusStore } from '@workbench/canvas-operations/controlDetectionStatusStore';
import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';
+import { WorkbenchHotkeyRuntime } from '@workbench/hotkeys/WorkbenchHotkeyRuntime';
+import { DEFAULT_PREFERENCES, patchWorkbenchPreferences } from '@workbench/settings/store';
import { runNotificationUndo } from '@workbench/shell/notifications/undoRegistry';
+import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { createWorkbenchStore } from '@workbench/workbenchStore';
import { createInstance } from 'i18next';
-import { act } from 'react';
+import { act, useSyncExternalStore } 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';
@@ -42,6 +49,7 @@ import type * as EngineStoreHooks from './engineStoreHooks';
const harness = vi.hoisted(() => ({
dragData: null as unknown,
+ extensions: null as ExtensionRegistry | null,
engine: null as CanvasEngine | null,
isEngineLive: true,
operation: null as unknown,
@@ -76,7 +84,12 @@ vi.mock('@workbench/canvas-operations/api', async (importOriginal) => ({
vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
...(await importOriginal<typeof WorkbenchContextModule>()),
useActiveProjectId: () => activeProject().id,
- useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(activeProject()),
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => {
+ const project = useSyncExternalStore(harness.store!.subscribe, activeProject, activeProject);
+ return selector(project);
+ },
+ useWorkbenchExtensions: () => harness.extensions,
+ useOptionalWorkbenchExtensions: () => harness.extensions,
useWidgetValuesSelector: (widgetId: string, selector: (values: Record<string, unknown>) => unknown) =>
selector(
Object.values(activeProject().widgetInstances).find((instance) => instance.typeId === widgetId)?.state.values ??
@@ -87,6 +100,11 @@ vi.mock('@workbench/WorkbenchContext', async (importOriginal) => ({
useWorkbenchQueries: () => harness.store!.queries,
useWorkbenchSubscription: () => harness.store!.subscribe,
}));
+vi.mock('@workbench/hotkeys/firstPartyCommands', () => ({ useRegisterFirstPartyCommands: () => {} }));
+vi.mock('@workbench/projects/api', async (importOriginal) => ({
+ ...(await importOriginal<typeof ProjectsApi>()),
+ setClientStateValue: async () => {},
+}));
vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({
useCanvasProjectMutationDispatch: () => () => undefined,
}));
@@ -132,9 +150,21 @@ beforeAll(async () => {
afterEach(async () => {
await act(() => root?.unmount());
+ await act(() => i18n.changeLanguage('en'));
host?.remove();
harness.engine?.lifecycle.dispose();
- Object.assign(harness, { dragData: null, engine: null, isEngineLive: true, operation: null, store: null });
+ if (harness.extensions) {
+ await patchWorkbenchPreferences(DEFAULT_PREFERENCES);
+ accountLifecycle.invalidate();
+ }
+ Object.assign(harness, {
+ dragData: null,
+ engine: null,
+ extensions: null,
+ isEngineLive: true,
+ operation: null,
+ store: null,
+ });
harness.uploadImage.mockReset();
root = null;
host = null;
@@ -158,6 +188,7 @@ const renderView = async (
beforeRender,
domRaster = false,
hostWidth = 1000,
+ hotkeys = false,
nodes,
selectedLayer,
staged = true,
@@ -165,6 +196,7 @@ const renderView = async (
beforeRender?: (engine: CanvasEngine) => void;
domRaster?: boolean;
hostWidth?: number;
+ hotkeys?: boolean;
nodes?: CanvasNodeContract[];
selectedLayer?: CanvasLayerContract;
staged?: boolean;
@@ -222,31 +254,169 @@ const renderView = async (
document.body.append(host);
root = createRoot(host);
const commandHandlers = new Map<string, () => void>();
- const runtime = {
+ const extensions = hotkeys ? createExtensionRegistry() : null;
+ harness.extensions = extensions;
+ const source = { instanceId: 'canvas', projectId, region: 'center', typeId: 'canvas' } as const;
+ const createRuntime = (extensions: ExtensionRegistry | null) => ({
commands: {
- register: ({ handler, id }: { handler: () => void; id: string }) => {
- commandHandlers.set(id, handler);
- return () => commandHandlers.delete(id);
+ register: (command: WidgetCommandContribution) => {
+ commandHandlers.set(command.id, command.handler);
+ const dispose = extensions?.commands.register({ ...command, source });
+ return () => {
+ commandHandlers.delete(command.id);
+ dispose?.();
+ };
},
},
- hotkeys: { register: () => () => undefined },
+ hotkeys: {
+ register: (hotkey: WidgetHotkeyContribution) =>
+ extensions?.hotkeys.register({ ...hotkey, source }) ?? (() => undefined),
+ },
+ });
+ const queryClient = new QueryClient();
+ const render = (extensions: ExtensionRegistry | null) => {
+ const runtime = createRuntime(extensions);
+ return act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <QueryClientProvider client={queryClient}>
+ <WorkbenchFocusProvider>
+ {hotkeys ? <WorkbenchHotkeyRuntime /> : null}
+ <Box
+ h="full"
+ data-hotkey-widget-instance-id="canvas"
+ data-hotkey-widget-region="center"
+ data-hotkey-widget-type-id="canvas"
+ >
+ <CanvasWidgetView
+ {...({ instance: activeProject().widgetInstances.canvas, runtime } as unknown as WidgetViewProps)}
+ />
+ </Box>
+ </WorkbenchFocusProvider>
+ </QueryClientProvider>
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ };
+ await render(extensions);
+ return {
+ commandHandlers,
+ extensions,
+ projectId,
+ store,
+ replaceRuntime: async () => {
+ const next = createExtensionRegistry();
+ harness.extensions = next;
+ await render(next);
+ return next;
+ },
};
- await act(() =>
- root!.render(
- <I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>
- <QueryClientProvider client={new QueryClient()}>
- <CanvasWidgetView
- {...({ instance: activeProject().widgetInstances.canvas, runtime } as unknown as WidgetViewProps)}
- />
- </QueryClientProvider>
- </ChakraProvider>
- </I18nextProvider>
- )
- );
- return { commandHandlers, projectId, store };
};
+describe('mounted Canvas hotkeys', () => {
+ it('creates one layer and undo step per press, suppresses held repeats, and keeps nudges repeating', async () => {
+ accountLifecycle.activate('canvas-hotkeys-test');
+ await patchWorkbenchPreferences({
+ customHotkeys: { 'canvas.newRasterLayer': ['alt+shift+n'] },
+ });
+ await renderView('completed', { hotkeys: true, staged: false });
+ const engine = harness.engine!;
+ const target = host!.querySelector<HTMLElement>('[data-hotkey-widget-instance-id="canvas"]')!;
+ const document = () => engine.document.model()!.document;
+ const layerCount = () => document().stacks.raster.length;
+ const initialCount = layerCount();
+ const press = (repeat = false) =>
+ act(() => {
+ target.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ altKey: true,
+ bubbles: true,
+ cancelable: true,
+ code: 'KeyN',
+ shiftKey: true,
+ key: 'N',
+ repeat,
+ })
+ );
+ });
+
+ await press();
+ expect(layerCount()).toBe(initialCount + 1);
+ expect(engine.history.getEntries().past).toEqual(['Raster layer']);
+ await press(true);
+ await press(true);
+ expect(layerCount()).toBe(initialCount + 1);
+ expect(engine.history.getEntries().past).toEqual(['Raster layer']);
+ await act(() => {
+ target.dispatchEvent(
+ new KeyboardEvent('keyup', { altKey: true, bubbles: true, code: 'KeyN', key: 'N', shiftKey: true })
+ );
+ });
+ await press();
+ expect(layerCount()).toBe(initialCount + 2);
+ expect(engine.history.getEntries().past).toEqual(['Raster layer', 'Raster layer']);
+
+ await act(() => engine.history.undo());
+ expect(layerCount()).toBe(initialCount + 1);
+ await act(() => engine.history.redo());
+ expect(layerCount()).toBe(initialCount + 2);
+ const selected = document().stacks.raster.find((layer) => layer.id === document().selectedLayerId)!;
+ if (selected.type !== 'raster') {
+ throw new Error('Expected the new raster layer to be selected');
+ }
+ const initialX = selected.transform.x;
+ for (const repeat of [false, true, true]) {
+ await act(() =>
+ target.dispatchEvent(
+ new KeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ code: 'ArrowRight',
+ key: 'ArrowRight',
+ repeat,
+ })
+ )
+ );
+ }
+ expect(document().stacks.raster.find((layer) => layer.id === selected.id)).toMatchObject({
+ transform: { x: initialX + 3 },
+ });
+ });
+});
+
+describe('Canvas hotkey registration lifetime', () => {
+ it('releases and refreshes locale and runtime registrations without discarding Canvas history', async () => {
+ accountLifecycle.activate('canvas-hotkey-lifetime-test');
+ const { commandHandlers, extensions, replaceRuntime } = await renderView('completed', {
+ hotkeys: true,
+ staged: false,
+ });
+ const engine = harness.engine!;
+ await act(() => commandHandlers.get('canvas.newRasterLayer')!());
+ expect(engine.history.getEntries().past).toEqual(['Raster layer']);
+ const hotkey = (registry: ExtensionRegistry) =>
+ registry.stores.hotkeys.list().find(({ id }) => id === 'canvas.newRasterLayer');
+ expect(hotkey(extensions!)?.title).toBe('New raster layer');
+ i18n.addResource('en-GB', 'translation', 'widgets.canvas.commands.newRasterLayer', 'Create Raster Layer');
+ await act(() => i18n.changeLanguage('en-GB'));
+ await expect.poll(() => hotkey(extensions!)?.title).toBe('Create Raster Layer');
+ expect(extensions!.stores.hotkeys.list().filter(({ id }) => id === 'canvas.newRasterLayer')).toHaveLength(1);
+
+ const next = await replaceRuntime();
+ expect(extensions!.stores.commands.list()).toEqual([]);
+ expect(extensions!.stores.hotkeys.list()).toEqual([]);
+ expect(hotkey(next)).toMatchObject({ ignoreRepeat: true, title: 'Create Raster Layer' });
+ expect(harness.engine).toBe(engine);
+ expect(engine.history.getEntries().past).toEqual(['Raster layer']);
+ await act(() => root!.unmount());
+ root = null;
+ expect(next.stores.commands.list()).toEqual([]);
+ expect(next.stores.hotkeys.list()).toEqual([]);
+ });
+});
+
describe('Canvas spline context menu', () => {
const renderSpline = async (selectPath = true) => {
const layer = createVectorLayer({ id: 'vector', name: 'Guides' });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index e3b6fcd533..9df68688e3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -1,4 +1,5 @@
-import type { WidgetViewProps } from '@workbench/widgetContracts';
+import type { WidgetRuntimeApi, WidgetViewProps } from '@workbench/widgetContracts';
+import type { TFunction } from 'i18next';
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
import { Box } from '@chakra-ui/react';
@@ -64,6 +65,7 @@ import { CanvasSurface } from './CanvasSurface';
import { CanvasSurfaceContextLayout } from './CanvasSurfaceContextLayout';
import {
CANVAS_COMPANION_HOTKEYS,
+ type HotkeyTableEntry,
reportMergeDownRefusal,
reportTransformRefusal,
showCanvasRefusalNotice,
@@ -109,6 +111,50 @@ const CanvasShortcutHintRegistration = ({
return null;
};
+// Reset only the registration lease when its APIs or translator change, leaving Canvas state mounted.
+let hotkeyRegistrationKeys: WeakMap<object, number> | null = null;
+let nextHotkeyRegistrationKey = 0;
+const hotkeyRegistrationKey = (identity: object): number => {
+ hotkeyRegistrationKeys ??= new WeakMap();
+ let key = hotkeyRegistrationKeys.get(identity);
+ if (key === undefined) {
+ key = ++nextHotkeyRegistrationKey;
+ hotkeyRegistrationKeys.set(identity, key);
+ }
+ return key;
+};
+
+const CanvasHotkeyRegistration = ({
+ commands,
+ hotkeys,
+ execute,
+ t,
+}: Pick<WidgetRuntimeApi, 'commands' | 'hotkeys'> & { execute: (commandId: string) => void; t: TFunction }) => {
+ const executeCommand = useEffectEvent(execute);
+ // useMountEffect is the repository's mount/unmount effect boundary.
+ /* eslint-disable react-hooks/rules-of-hooks */
+ useMountEffect(() => {
+ const entries: readonly HotkeyTableEntry[] = [...CANVAS_COMPANION_HOTKEYS, ...CANVAS_ONLY_HOTKEYS];
+ const disposers = entries.flatMap(([id, titleKey, defaultKeys, options]) => {
+ const title = t(titleKey);
+ return [
+ commands.register({ handler: () => executeCommand(id), id, title }),
+ hotkeys.register({
+ allowInEditable: false,
+ commandId: id,
+ defaultKeys: [...defaultKeys],
+ id,
+ title,
+ ...options,
+ }),
+ ];
+ });
+ return () => disposers.forEach((dispose) => dispose());
+ });
+ /* eslint-enable react-hooks/rules-of-hooks */
+ return null;
+};
+
/** Wire reducer chrome, commands, settings, and staging around the pixel/input engine. */
export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
const { t } = useTranslation();
@@ -344,26 +390,29 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
);
/** The engine produces selected pixels; widget code owns system clipboard writes and optional cutting. */
- const copySelection = useEffectEvent((cut: boolean) => {
- const mountedEngine = engine;
- if (!mountedEngine) {
- return;
- }
- void (async () => {
- try {
- await copyCanvasSelection(mountedEngine.selection, cut, copyImage);
- } catch (error) {
- notifications.add({
- kind: 'error',
- message: error instanceof ClipboardUnavailableError ? t('common.copyUnavailable') : undefined,
- title: t('widgets.canvas.clipboard.copyFailed'),
- });
+ const copySelection = useCallback(
+ (cut: boolean) => {
+ const mountedEngine = engine;
+ if (!mountedEngine) {
+ return;
}
- })();
- });
+ void (async () => {
+ try {
+ await copyCanvasSelection(mountedEngine.selection, cut, copyImage);
+ } catch (error) {
+ notifications.add({
+ kind: 'error',
+ message: error instanceof ClipboardUnavailableError ? t('common.copyUnavailable') : undefined,
+ title: t('widgets.canvas.clipboard.copyFailed'),
+ });
+ }
+ })();
+ },
+ [engine, notifications, t]
+ );
/** Pastes an image off the system clipboard as a new layer over the bbox. */
- const pasteFromClipboard = useEffectEvent(() => {
+ const pasteFromClipboard = useCallback(() => {
const mountedEngine = engine;
if (!mountedEngine) {
return;
@@ -394,7 +443,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
reportLayerOperation(result.status, notify.error, t);
}
})();
- });
+ }, [engine, notifications, notify.error, t]);
useDndMonitor({ onDragEnd: handleCanvasImageDrop });
@@ -515,53 +564,52 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
return () => engine?.previews.setStagedPreview(null);
}, [engine]);
- const executeCanvasHotkey = useEffectEvent((commandId: string) => {
- const selectedLayerIds = readLayerPanelState(projectId, document.selectedLayerId).selectedIds;
- executeCanvasHotkeyCommand(commandId, {
+ const executeCanvasHotkey = useCallback(
+ (commandId: string) => {
+ const selectedLayerIds = readLayerPanelState(projectId, document.selectedLayerId).selectedIds;
+ executeCanvasHotkeyCommand(commandId, {
+ copySelection,
+ cropAllLayers: () => {
+ if (engine) {
+ void cropAllLayersToFrame(engine.layers, notify, t);
+ }
+ },
+ dispatch: canvasDispatch,
+ document,
+ engine,
+ hasMultipleStagingSlots,
+ layerCommands: { engine, reportError: notify.error, t },
+ pasteFromClipboard,
+ reportLayerOperation: (refusal) => reportLayerOperation(refusal, notify.error, t),
+ reportMergeDownRefusal: (refusal) => reportMergeDownRefusal(document, refusal, showCanvasRefusalNotice, t),
+ reportTransformRefusal: (refusal, layerId) =>
+ reportTransformRefusal(
+ refusal,
+ { id: layerId, name: getDocumentNode(document, layerId)?.name ?? '' },
+ { error: notify.error, notice: showCanvasRefusalNotice },
+ t
+ ),
+ reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),
+ reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),
+ resetActiveColors: colorCommands.resetPair,
+ selectedLayerIds,
+ swapActiveColors: colorCommands.swapPair,
+ t,
+ });
+ },
+ [
+ canvasDispatch,
+ colorCommands,
copySelection,
- cropAllLayers: () => {
- if (engine) {
- void cropAllLayersToFrame(engine.layers, notify, t);
- }
- },
- dispatch: canvasDispatch,
document,
engine,
hasMultipleStagingSlots,
- layerCommands: { engine, reportError: notify.error, t },
+ notify,
pasteFromClipboard,
- reportLayerOperation: (refusal) => reportLayerOperation(refusal, notify.error, t),
- reportMergeDownRefusal: (refusal) => reportMergeDownRefusal(document, refusal, showCanvasRefusalNotice, t),
- reportTransformRefusal: (refusal, layerId) =>
- reportTransformRefusal(
- refusal,
- { id: layerId, name: getDocumentNode(document, layerId)?.name ?? '' },
- { error: notify.error, notice: showCanvasRefusalNotice },
- t
- ),
- reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),
- reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),
- resetActiveColors: colorCommands.resetPair,
- selectedLayerIds,
- swapActiveColors: colorCommands.swapPair,
+ projectId,
t,
- });
- });
-
- useEffect(() => {
- // 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());
- };
- }, [runtime.commands, runtime.hotkeys, t]);
+ ]
+ );
const layerContextMenuTarget = useMemo(
() =>
@@ -609,6 +657,13 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
w="full"
{...fileDragHandlers}
>
+ <CanvasHotkeyRegistration
+ key={[runtime.commands, runtime.hotkeys, t].map(hotkeyRegistrationKey).join(':')}
+ commands={runtime.commands}
+ hotkeys={runtime.hotkeys}
+ execute={executeCanvasHotkey}
+ t={t}
+ />
{engine ? (
<CanvasShortcutHintRegistration
key={`${projectId}:${instance.id}`}
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 9a29156702..32af7edb90 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -15,8 +15,10 @@ import type { TFunction } from 'i18next';
import { createControlLayer, createDocumentModel } from '@workbench/canvas-engine/api';
import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
import { deleteLayers, duplicateLayers, groupLayers, ungroupLayers } from '@workbench/widgets/layers/layerCommands';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
// The layer commands own their eligibility, labels and feedback (see layerCommands tests); here only routing counts.
@@ -30,7 +32,7 @@ vi.mock('@workbench/widgets/layers/layerCommands', async (importOriginal) => ({
import { CANVAS_HEADER_HOTKEYS } from './canvasHeaderCommands';
import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
-import { CANVAS_COMPANION_HOTKEYS, reportMergeDownRefusal } from './canvasToolCommands';
+import { CANVAS_COMPANION_HOTKEYS, type HotkeyTableEntry, reportMergeDownRefusal } from './canvasToolCommands';
const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}): CanvasLayerContract =>
({
@@ -431,16 +433,58 @@ describe('group selection', () => {
});
});
+describe('new raster layer', () => {
+ it('inserts and selects a layer above a group child with a reversible prepared edit', () => {
+ const project = { ...createInitialWorkbenchState().projects[0]!, id: 'project' };
+ const before = applyCanvasProjectMutation(project, {
+ document: {
+ ...documentOf([], 'paint'),
+ stacks: stacksFrom([groupContract('group', [rasterLayer('paint')])]),
+ },
+ type: 'replaceCanvasDocument',
+ });
+ const engine = run('canvas.newRasterLayer', { document: before.canvas.document });
+ const commit = engine.layers.commitPrepared as Mock<CanvasEngine['layers']['commitPrepared']>;
+ expect(commit).toHaveBeenCalledOnce();
+ const [label, edit] = commit.mock.calls[0]!;
+ expect(label).toBe('widgets.layers.actions.addRasterLayer');
+
+ const after = applyCanvasProjectMutation(before, edit.forward);
+ const group = after.canvas.document.stacks.raster[0]!;
+ expect(group.type).toBe('group');
+ if (group.type !== 'group') {
+ throw new Error('Expected the existing group');
+ }
+ expect(group.children).toHaveLength(2);
+ expect(group.children[0]).toMatchObject({
+ id: after.canvas.document.selectedLayerId,
+ name: 'Layer 1',
+ source: { bitmap: null, type: 'paint' },
+ type: 'raster',
+ });
+ expect(group.children[1]!.id).toBe('paint');
+
+ const restored = applyCanvasProjectMutation(after, edit.inverse);
+ expect(restored.canvas.document).toEqual(before.canvas.document);
+ expect(applyCanvasProjectMutation(restored, edit.forward).canvas.document).toEqual(after.canvas.document);
+ });
+});
+
describe('registration tables', () => {
const allEntries = [...CANVAS_COMPANION_HOTKEYS, ...CANVAS_ONLY_HOTKEYS, ...CANVAS_HEADER_HOTKEYS];
- it('mirrors every registered key in the hotkey catalog with the same defaults, under Canvas', () => {
+ it('mirrors registered defaults and repeat policy in the Canvas catalog', () => {
const catalogDefaults = Object.fromEntries(
firstPartyHotkeyCatalog
.filter((hotkey) => hotkey.category === 'canvas')
- .map((hotkey) => [hotkey.id, hotkey.defaultKeys])
+ .map((hotkey) => [hotkey.id, { defaultKeys: hotkey.defaultKeys, ignoreRepeat: hotkey.ignoreRepeat }])
+ );
+ const registeredDefaults = Object.fromEntries(
+ (allEntries as readonly HotkeyTableEntry[]).map(([id, , keys, options]) => [
+ id,
+ { defaultKeys: [...keys], ignoreRepeat: options?.ignoreRepeat },
+ ])
);
- const registeredDefaults = Object.fromEntries(allEntries.map(([id, , keys]) => [id, [...keys]]));
expect(registeredDefaults).toEqual(catalogDefaults);
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index ff692f8fc9..35c6e670e1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -37,6 +37,7 @@ import {
deleteLayers,
duplicateLayers,
groupLayers,
+ prepareNewRasterLayer,
ungroupLayers,
type LayerCommandDeps,
} from '@workbench/widgets/layers/layerCommands';
@@ -67,6 +68,8 @@ export const CANVAS_ONLY_HOTKEYS = [
['canvas.nudgeRightLarge', 'widgets.canvas.commands.nudgeRightLarge', ['shift+arrowright']],
['canvas.nudgeUpLarge', 'widgets.canvas.commands.nudgeUpLarge', ['shift+arrowup']],
['canvas.nudgeDownLarge', 'widgets.canvas.commands.nudgeDownLarge', ['shift+arrowdown']],
+ // Mod+Shift+N is reserved by browsers; creation stays unbound until customized.
+ ['canvas.newRasterLayer', 'widgets.canvas.commands.newRasterLayer', [], { ignoreRepeat: true }],
['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']],
@@ -246,6 +249,10 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
ctx.copySelection(commandId === 'canvas.cutSelection');
} else if (commandId === 'canvas.pasteImage') {
ctx.pasteFromClipboard();
+ } else if (commandId === 'canvas.newRasterLayer') {
+ ctx.reportPreparedCommit(
+ commitPreparedEdit(engine, t('widgets.layers.actions.addRasterLayer'), prepareNewRasterLayer)
+ );
} else if (commandId === 'canvas.cropAllLayersToFrame') {
ctx.cropAllLayers();
} else if (commandId === 'canvas.flipHorizontal' || commandId === 'canvas.flipVertical') {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
index b9fe4fe7a8..8f0e969453 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasToolCommands.ts
@@ -7,6 +7,7 @@ import type {
LayerUnreadable,
ShapeToolKind,
} from '@workbench/canvas-engine/api';
+import type { WidgetHotkeyContribution } from '@workbench/widgetContracts';
import type { TFunction } from 'i18next';
import type { ElementType } from 'react';
@@ -30,7 +31,12 @@ export const showCanvasRefusalNotice = (key: string, title: string, message: str
export type CanvasRefusalNotice = typeof showCanvasRefusalNotice;
-export type HotkeyTableEntry = readonly [id: string, titleKey: string, defaultKeys: readonly string[]];
+export type HotkeyTableEntry = readonly [
+ id: string,
+ titleKey: string,
+ defaultKeys: readonly string[],
+ options?: Pick<WidgetHotkeyContribution, 'ignoreRepeat'>,
+];
/** The same layer operation is available from the Canvas and the Layers widget. */
export const CANVAS_MERGE_DOWN_HOTKEY = ['canvas.mergeDown', 'widgets.canvas.commands.mergeDown', ['mod+e']] as const;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts
index aeed86b3f7..af72ebcee0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts
@@ -5,11 +5,13 @@ import type {
CanvasDocumentModel,
CanvasEngineLayerCapability,
DocumentCommand,
+ PrepareEditResult,
StructuralCommitResult,
} from '@workbench/canvas-engine/api';
import type { TFunction } from 'i18next';
import { getDocumentIndex, isGroupNode, outermostNodes } from '@workbench/canvas-engine/api';
+import { nextLayerName } from '@workbench/canvasProjectMutations';
import { publishLayerPanelSelection, readLayerPanelState, setLayerGroupExpanded } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { useCanvasDocumentRead } from '@workbench/widgets/canvas/engineStoreHooks';
@@ -17,7 +19,17 @@ import { reportLayerOperation, reportStructuralCommit } from '@workbench/widgets
import { useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { createLayerId, nextGroupName } from './layerOps';
+import { createEmptyPaintLayer, createLayerId, nextGroupName } from './layerOps';
+
+export const prepareNewRasterLayer = (model: CanvasDocumentModel): PrepareEditResult => {
+ const { document } = model;
+ const layerNames = getDocumentIndex(document).nodes.map(({ node }) => node.name);
+ return model.prepare({
+ aboveId: document.selectedLayerId,
+ nodes: [createEmptyPaintLayer(nextLayerName(layerNames))],
+ type: 'insert',
+ });
+};
/**
* The structural commands every layer surface offers: the Canvas hotkeys, the panel footer, the row and group menus,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
index 96ae9abf9f..940aabac66 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
@@ -10,15 +10,14 @@ import { useCanvasEngine } from '@workbench/canvas-operations/react';
import { setLayerGroupExpanded } from '@workbench/layerPanelState';
import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
-import { nextLayerName } from '@workbench/workbenchState';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import type { AddLayerItemId } from './addLayerMenu';
import { isAddLayerItemAvailable } from './addLayerMenu';
+import { prepareNewRasterLayer } from './layerCommands';
import {
- createEmptyPaintLayer,
createInpaintMaskLayer,
createLayerId,
createRegionalGuidanceLayer,
@@ -103,8 +102,7 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
return;
}
case 'raster': {
- const layer = createEmptyPaintLayer(nextLayerName(layerNames));
- add(t('widgets.layers.actions.addRasterLayer'), layer);
+ commitPrepared(t('widgets.layers.actions.addRasterLayer'), prepareNewRasterLayer);
return;
}
case 'control': {