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.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): add configurable workbench hotkeys
joshistoast2bcbd45da364
diff --git a/invokeai/frontend/webv2/src/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/WorkbenchApp.tsxindex 2959800623..401f05ebcb 100644--- a/invokeai/frontend/webv2/src/WorkbenchApp.tsx+++ b/invokeai/frontend/webv2/src/WorkbenchApp.tsx@@ -24,8 +24,10 @@ export const WorkbenchApp = () => {return (<WorkbenchProvider loadOptions={{ createNew: search.new, openProjectId: search.project }}><SessionExpiryGuard />+ <WorkbenchHotkeyRuntime /><WorkbenchRuntime /><WorkbenchSessionController search={search} />+ <WidgetHosts /><WorkbenchShell /></WorkbenchProvider>);diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.tsnew file mode 100644index 0000000000..4673a1f2df--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it, vi } from 'vitest';++import { commandApi } from './extensionApi';++describe('commandApi', () => {+ it('registers, executes, and disposes commands by id', async () => {+ const handler = vi.fn(() => 'ok');+ const dispose = commandApi.register({ handler, id: 'test.command', title: 'Test command' });++ await expect(commandApi.execute('test.command', 'arg')).resolves.toBe('ok');+ expect(handler).toHaveBeenCalledWith('arg');++ dispose();++ await expect(commandApi.execute('test.command')).resolves.toBeUndefined();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.tsindex 4c0975869a..70e919356a 100644--- a/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts+++ b/invokeai/frontend/webv2/src/workbench/extensions/extensionApi.ts@@ -17,20 +17,37 @@ const noopDispose = (): void => {};class ContributionStore<Contribution> {private readonly contributions = new Map<string, Contribution>();+ private readonly listeners = new Set<() => void>();register(contribution: Contribution, fallbackId: string): () => void {const id = fallbackId;this.contributions.set(id, contribution);+ this.notify();return () => {this.contributions.delete(id);+ this.notify();};}list(): Contribution[] {return [...this.contributions.values()];}++ subscribe(listener: () => void): () => void {+ this.listeners.add(listener);++ return () => {+ this.listeners.delete(listener);+ };+ }++ private notify(): void {+ for (const listener of this.listeners) {+ listener();+ }+ }}const commandStore = new ContributionStore<WidgetCommandContribution>();@@ -53,7 +70,7 @@ export const commandApi: WidgetCommandApi = {export const hotkeyApi: WidgetHotkeyApi = {register(hotkey) {- return hotkeyStore.register(hotkey, `${hotkey.commandId}:${hotkey.keybinding}`);+ return hotkeyStore.register(hotkey, hotkey.id);},};diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex 0d38bb78a3..15181ea84c 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -6,6 +6,10 @@ import type { WidgetRegion } from './types';import { useWorkbenchPreferences } from './settings/store';+let focusedRegionSnapshot: WidgetRegion | null = null;++export const getFocusedRegionSnapshot = (): WidgetRegion | null => focusedRegionSnapshot;+interface FocusRegionContextValue {focusedRegion: WidgetRegion | null;setFocusedRegion: (region: WidgetRegion | null) => void;@@ -27,15 +31,23 @@ const highlightStyles = {opacity: 0,pointerEvents: 'none',position: 'absolute',- transition: 'border-color 0.12s ease, opacity 0.12s ease',+ transition: 'border-color var(--wb-motion-duration-fast) ease, opacity var(--wb-motion-duration-fast) ease',zIndex: 2,},} as const;export const FocusRegionProvider = ({ children }: { children: ReactNode }) => {const [focusedRegion, setFocusedRegion] = useState<WidgetRegion | null>(null);+ const setFocusedRegionSnapshot = (region: WidgetRegion | null) => {+ focusedRegionSnapshot = region;+ setFocusedRegion(region);+ };- return <FocusRegionContext value={{ focusedRegion, setFocusedRegion }}>{children}</FocusRegionContext>;+ return (+ <FocusRegionContext value={{ focusedRegion, setFocusedRegion: setFocusedRegionSnapshot }}>+ {children}+ </FocusRegionContext>+ );};const useFocusRegionContext = () => {diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxnew file mode 100644index 0000000000..0719fb25f4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx@@ -0,0 +1,107 @@+import { commandApi } from '@workbench/extensions/extensionApi';+import { getFocusedRegionSnapshot } from '@workbench/focusRegions';+import { useWorkbenchPreferences } from '@workbench/settings/store';+import { useActiveProject } from '@workbench/WorkbenchContext';+import { useEffect, useEffectEvent, useMemo, useRef, useSyncExternalStore } from 'react';+import { tinykeys } from 'tinykeys';++import type { RegisteredHotkey } from './types';++import { firstPartyHotkeyCatalog } from './catalog';+import { useExtensionHotkeyDefinitions } from './extensionHotkeys';+import { useRegisterFirstPartyCommands } from './firstPartyCommands';+import { toTinykeysBinding } from './keys';+import { isHotkeyModalLayerActive, subscribeHotkeyModalLayers } from './modalLayer';+import { applyCustomHotkeys, resolveHotkey } from './resolve';+import { getHotkeyTargetWidget } from './targetWidget';++export const WorkbenchHotkeyRuntime = () => {+ useRegisterFirstPartyCommands();++ const preferences = useWorkbenchPreferences();+ const project = useActiveProject();+ const extensionHotkeys = useExtensionHotkeyDefinitions();+ const isModalLayerActive = useSyncExternalStore(+ subscribeHotkeyModalLayers,+ isHotkeyModalLayerActive,+ isHotkeyModalLayerActive+ );+ const projectRef = useRef(project);+ const registeredHotkeysRef = useRef<RegisteredHotkey[]>([]);++ projectRef.current = project;++ const registeredHotkeys = useMemo(() => {+ const customHotkeys = preferences.customHotkeys;+ const firstPartyHotkeys = firstPartyHotkeyCatalog.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys));+ const widgetHotkeys = extensionHotkeys.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys));++ return [...firstPartyHotkeys, ...widgetHotkeys];+ }, [extensionHotkeys, preferences.customHotkeys]);++ registeredHotkeysRef.current = registeredHotkeys;++ const keybindings = useMemo(() => {+ const bindings: Record<string, (event: KeyboardEvent) => void> = {};++ for (const hotkey of registeredHotkeys) {+ if (hotkey.implemented === false) {+ continue;+ }++ for (const key of hotkey.keys) {+ const tinykeysBinding = toTinykeysBinding(key);++ if (tinykeysBinding) {+ bindings[tinykeysBinding] = (event) => handleHotkey(event, key);+ }+ }+ }++ return bindings;+ }, [registeredHotkeys]);++ const executeHotkey = useEffectEvent((hotkey: RegisteredHotkey) => {+ void commandApi.execute(hotkey.commandId);+ });++ const handleHotkey = useEffectEvent((event: KeyboardEvent, matchedKey: string) => {+ if (event.isComposing || event.keyCode === 229) {+ return;+ }++ const focusedRegion = getFocusedRegionSnapshot();+ const targetWidget = getHotkeyTargetWidget(event.target);+ const activeRegion = focusedRegion ? projectRef.current.widgetRegions[focusedRegion] : null;+ const activeInstanceId = targetWidget?.instanceId ?? activeRegion?.activeInstanceId ?? null;+ const activeWidgetTypeId = activeInstanceId+ ? (targetWidget?.typeId ?? projectRef.current.widgetInstances[activeInstanceId]?.typeId ?? null)+ : null;+ const hotkey = resolveHotkey({+ context: { activeInstanceId, activeWidgetTypeId, focusedRegion, isModalLayerActive },+ event,+ hotkeys: registeredHotkeysRef.current,+ matchedKey,+ });++ if (!hotkey) {+ return;+ }++ if (hotkey.preventDefault) {+ event.preventDefault();+ }++ executeHotkey(hotkey);+ });++ useEffect(() => {+ if (Object.keys(keybindings).length === 0) {+ return;+ }++ return tinykeys(window, keybindings, { ignore: () => false });+ }, [keybindings]);++ return null;+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.tsnew file mode 100644index 0000000000..fe042d0207--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts@@ -0,0 +1,14 @@+import { describe, expect, it } from 'vitest';++import { firstPartyHotkeyCatalog } from './catalog';++describe('firstPartyHotkeyCatalog', () => {+ it('keeps legacy default hotkey parity', () => {+ expect(firstPartyHotkeyCatalog).toHaveLength(90);+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('app.invoke');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('canvas.mergeDown');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('workflows.copySelection');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.galleryNavLeft');+ expect(firstPartyHotkeyCatalog.map((hotkey) => hotkey.id)).toContain('gallery.remix');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.tsnew file mode 100644index 0000000000..57b997ed71--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts@@ -0,0 +1,174 @@+import type { HotkeyCategory, HotkeyDefinition } from './types';++const categoryScopes = {+ app: { kind: 'global' },+ canvas: { kind: 'widget', typeId: 'canvas' },+ gallery: { kind: 'widget', typeId: 'gallery' },+ viewer: { kind: 'widget', typeId: 'preview' },+ workflows: { kind: 'widget', typeId: 'workflow' },+} as const;++const implemented = new Set([+ 'app.cancelQueueItem',+ 'app.clearQueue',+ 'app.focusPrompt',+ 'app.invoke',+ 'app.invokeFront',+ 'app.resetPanelLayout',+ 'app.selectCanvasTab',+ 'app.selectGenerateTab',+ 'app.selectModelsTab',+ 'app.selectQueueTab',+ 'app.selectWorkflowsTab',+ 'app.toggleLeftPanel',+ 'app.togglePanels',+ 'app.toggleRightPanel',+ 'canvas.deleteSelected',+ 'canvas.nextEntity',+ 'canvas.prevEntity',+ 'canvas.redo',+ 'canvas.undo',+ 'gallery.clearSelection',+ 'gallery.deleteSelection',+ 'gallery.galleryNavDown',+ 'gallery.galleryNavDownAlt',+ 'gallery.galleryNavLeft',+ 'gallery.galleryNavLeftAlt',+ 'gallery.galleryNavRight',+ 'gallery.galleryNavRightAlt',+ 'gallery.galleryNavUp',+ 'gallery.galleryNavUpAlt',+ 'gallery.remix',+ 'gallery.selectAllOnPage',+ 'gallery.starImage',+ 'viewer.nextComparisonMode',+ 'viewer.recallAll',+ 'viewer.recallPrompts',+ 'viewer.recallSeed',+ 'viewer.remix',+ 'viewer.swapImages',+ 'viewer.toggleViewer',+ 'viewer.useSize',+ 'workflows.addNode',+ 'workflows.copySelection',+ 'workflows.deleteSelection',+ 'workflows.pasteSelection',+ 'workflows.pasteSelectionWithEdges',+ 'workflows.redo',+ 'workflows.selectAll',+ 'workflows.undo',+]);++const formatHotkeyTitle = (id: string): string =>+ id+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')+ .split(' ')+ .filter(Boolean)+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(' ');++const hotkey = (category: HotkeyCategory, id: string, defaultKeys: string[]): HotkeyDefinition => ({+ allowInEditable: category === 'app' && (id === 'invoke' || id === 'invokeFront'),+ category,+ commandId: `${category}.${id}`,+ defaultKeys,+ id: `${category}.${id}`,+ implemented: implemented.has(`${category}.${id}`),+ preventDefault: true,+ scope: categoryScopes[category],+ title: formatHotkeyTitle(id),+});++export const firstPartyHotkeyCatalog: HotkeyDefinition[] = [+ hotkey('app', 'invoke', ['mod+enter']),+ hotkey('app', 'invokeFront', ['mod+shift+enter']),+ hotkey('app', 'cancelQueueItem', ['shift+x']),+ hotkey('app', 'clearQueue', ['mod+shift+x']),+ hotkey('app', 'selectGenerateTab', ['1']),+ hotkey('app', 'selectCanvasTab', ['2']),+ hotkey('app', 'selectUpscalingTab', ['3']),+ hotkey('app', 'selectWorkflowsTab', ['4']),+ hotkey('app', 'selectModelsTab', ['5']),+ hotkey('app', 'selectQueueTab', ['6']),+ hotkey('app', 'promptHistoryPrev', ['alt+arrowup']),+ hotkey('app', 'promptHistoryNext', ['alt+arrowdown']),+ hotkey('app', 'promptWeightUp', ['ctrl+arrowup']),+ hotkey('app', 'promptWeightDown', ['ctrl+arrowdown']),+ hotkey('app', 'focusPrompt', ['alt+a']),+ hotkey('app', 'toggleLeftPanel', ['t', 'o']),+ hotkey('app', 'toggleRightPanel', ['g']),+ hotkey('app', 'resetPanelLayout', ['shift+r']),+ hotkey('app', 'togglePanels', ['f']),+ hotkey('canvas', 'selectBrushTool', ['b']),+ hotkey('canvas', 'selectBboxTool', ['c']),+ hotkey('canvas', 'decrementToolWidth', ['[']),+ hotkey('canvas', 'incrementToolWidth', [']']),+ hotkey('canvas', 'selectEraserTool', ['e']),+ hotkey('canvas', 'selectMoveTool', ['v']),+ hotkey('canvas', 'selectRectTool', ['u']),+ hotkey('canvas', 'selectLassoTool', ['l']),+ hotkey('canvas', 'selectViewTool', ['h']),+ hotkey('canvas', 'selectColorPickerTool', ['i']),+ 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', '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', 'filterSelected', ['shift+f']),+ hotkey('canvas', 'invertMask', ['shift+v']),+ hotkey('canvas', 'undo', ['mod+z']),+ hotkey('canvas', 'redo', ['mod+shift+z', 'mod+y']),+ hotkey('canvas', 'nextEntity', ['alt+]']),+ hotkey('canvas', 'prevEntity', ['alt+[']),+ hotkey('canvas', 'applyFilter', ['enter']),+ hotkey('canvas', 'cancelFilter', ['esc']),+ hotkey('canvas', 'applyTransform', ['enter']),+ hotkey('canvas', 'cancelTransform', ['esc']),+ hotkey('canvas', 'applySegmentAnything', ['enter']),+ hotkey('canvas', 'cancelSegmentAnything', ['esc']),+ hotkey('canvas', 'toggleNonRasterLayers', ['shift+h']),+ hotkey('canvas', 'fitBboxToMasks', ['shift+b']),+ hotkey('canvas', 'toggleBbox', ['shift+o']),+ hotkey('workflows', 'addNode', ['shift+a', 'space']),+ hotkey('workflows', 'copySelection', ['mod+c']),+ hotkey('workflows', 'pasteSelection', ['mod+v']),+ hotkey('workflows', 'pasteSelectionWithEdges', ['mod+shift+v']),+ hotkey('workflows', 'selectAll', ['mod+a']),+ hotkey('workflows', 'deleteSelection', ['delete', 'backspace']),+ hotkey('workflows', 'undo', ['mod+z']),+ hotkey('workflows', 'redo', ['mod+shift+z', 'mod+y']),+ hotkey('viewer', 'toggleViewer', ['z']),+ hotkey('viewer', 'swapImages', ['c']),+ hotkey('viewer', 'nextComparisonMode', ['m']),+ hotkey('viewer', 'loadWorkflow', ['w']),+ hotkey('viewer', 'recallAll', ['a']),+ hotkey('viewer', 'recallSeed', ['s']),+ hotkey('viewer', 'recallPrompts', ['p']),+ hotkey('viewer', 'remix', ['r']),+ hotkey('viewer', 'useSize', ['d']),+ hotkey('viewer', 'toggleMetadata', ['i']),+ hotkey('gallery', 'selectAllOnPage', ['mod+a']),+ hotkey('gallery', 'clearSelection', ['esc']),+ hotkey('gallery', 'galleryNavUp', ['up']),+ hotkey('gallery', 'galleryNavRight', ['right']),+ hotkey('gallery', 'galleryNavDown', ['down']),+ hotkey('gallery', 'galleryNavLeft', ['left']),+ hotkey('gallery', 'galleryNavUpAlt', ['alt+up']),+ hotkey('gallery', 'galleryNavRightAlt', ['alt+right']),+ hotkey('gallery', 'galleryNavDownAlt', ['alt+down']),+ hotkey('gallery', 'galleryNavLeftAlt', ['alt+left']),+ hotkey('gallery', 'deleteSelection', ['delete', 'backspace']),+ hotkey('gallery', 'remix', ['r']),+ hotkey('gallery', 'starImage', ['.']),+];diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.tsnew file mode 100644index 0000000000..6341b68ffc--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts@@ -0,0 +1,53 @@+import type { WidgetHotkeyContribution, WidgetRegion, WorkbenchRegion } from '@workbench/types';++import { extensionContributionStores } from '@workbench/extensions/extensionApi';+import { useEffect, useMemo, useState } from 'react';++import type { HotkeyDefinition } from './types';++const widgetRegions = new Set<WorkbenchRegion>(['bottom', 'center', 'left', 'right']);++const isWidgetRegion = (region: WorkbenchRegion | undefined): region is WidgetRegion =>+ region !== undefined && widgetRegions.has(region);++export const toExtensionHotkeyDefinition = (hotkey: WidgetHotkeyContribution): HotkeyDefinition | null => {+ const source = hotkey.source;+ const scope = hotkey.scope ?? 'widget';++ if (scope === 'global') {+ return { ...hotkey, category: 'app', implemented: true, scope: { kind: 'global' } };+ }++ if (scope === 'instance' && source) {+ return {+ ...hotkey,+ category: 'app',+ implemented: true,+ scope: { instanceId: source.instanceId, kind: 'instance' },+ };+ }++ if (scope === 'focused-region' && isWidgetRegion(source?.region)) {+ return { ...hotkey, category: 'app', implemented: true, scope: { kind: 'focused-region', region: source.region } };+ }++ if (source) {+ return { ...hotkey, category: 'app', implemented: true, scope: { kind: 'widget', typeId: source.typeId } };+ }++ return null;+};++export const useExtensionHotkeyDefinitions = (): HotkeyDefinition[] => {+ const [hotkeys, setHotkeys] = useState(() => extensionContributionStores.hotkeys.list());++ useEffect(+ () => extensionContributionStores.hotkeys.subscribe(() => setHotkeys(extensionContributionStores.hotkeys.list())),+ []+ );++ return useMemo(+ () => hotkeys.map(toExtensionHotkeyDefinition).filter((hotkey): hotkey is HotkeyDefinition => hotkey !== null),+ [hotkeys]+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.tsnew file mode 100644index 0000000000..215ad7989d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.test.ts@@ -0,0 +1,34 @@+import { describe, expect, it } from 'vitest';++import { firstPartyHotkeyCatalog } from './catalog';+import {+ FIRST_PARTY_APP_COMMAND_IDS,+ FIRST_PARTY_COMMAND_IDS,+ FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS,+} from './firstPartyCommands';++const centrallyOwnedCommandIds = new Set(FIRST_PARTY_COMMAND_IDS);++describe('first-party hotkey commands', () => {+ it('registers handlers for implemented app and shared image recall commands', () => {+ const sharedImageRecallCommands = new Set([+ 'gallery.remix',+ 'viewer.recallAll',+ 'viewer.recallPrompts',+ 'viewer.recallSeed',+ 'viewer.remix',+ 'viewer.useSize',+ ]);+ const expectedCentralCommands = new Set(+ firstPartyHotkeyCatalog+ .filter((hotkey) => hotkey.implemented !== false)+ .filter((hotkey) => hotkey.category === 'app' || sharedImageRecallCommands.has(hotkey.commandId))+ .map((hotkey) => hotkey.commandId)+ );++ expect(centrallyOwnedCommandIds).toEqual(expectedCentralCommands);+ expect(new Set(FIRST_PARTY_COMMAND_IDS).size).toBe(FIRST_PARTY_COMMAND_IDS.length);+ expect(new Set(FIRST_PARTY_APP_COMMAND_IDS).size).toBe(FIRST_PARTY_APP_COMMAND_IDS.length);+ expect(new Set(FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS).size).toBe(FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS.length);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.tsnew file mode 100644index 0000000000..5e56626694--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/firstPartyCommands.ts@@ -0,0 +1,231 @@+import { getConnectionStatus } from '@workbench/backend/connectionStore';+import { commandApi } from '@workbench/extensions/extensionApi';+import { cancelCurrentQueueItem } from '@workbench/generation/api';+import { executeImageRecall, getSelectedGalleryImage, type ImageRecallKind } from '@workbench/image-actions';+import { isInvocationRouteValid, resolveInvocationRoute } from '@workbench/invocation';+import { ensureModelsLoaded, useModelsSnapshot } from '@workbench/models/modelsStore';+import { openWidgetPlacement } from '@workbench/widgetPlacementCommands';+import { getWidgetsForRegion } from '@workbench/widgetRegistry';+import { focusPositivePrompt } from '@workbench/widgets/generate/promptFocus';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';+import { useEffect, useEffectEvent, useRef } from 'react';++const imageRecallCommands: Record<string, ImageRecallKind> = {+ 'gallery.remix': 'remix',+ 'viewer.recallAll': 'all',+ 'viewer.recallPrompts': 'prompts',+ 'viewer.recallSeed': 'seed',+ 'viewer.remix': 'remix',+ 'viewer.useSize': 'dimensions',+};++export const FIRST_PARTY_APP_COMMAND_IDS = [+ 'app.invoke',+ 'app.invokeFront',+ 'app.cancelQueueItem',+ 'app.clearQueue',+ 'app.selectGenerateTab',+ 'app.selectCanvasTab',+ 'app.selectWorkflowsTab',+ 'app.selectModelsTab',+ 'app.selectQueueTab',+ 'app.focusPrompt',+ 'app.toggleLeftPanel',+ 'app.toggleRightPanel',+ 'app.resetPanelLayout',+ 'app.togglePanels',+] as const;++export const FIRST_PARTY_IMAGE_RECALL_COMMAND_IDS = Object.keys(imageRecallCommands);++export const FIRST_PARTY_COMMAND_IDS = [...FIRST_PARTY_APP_COMMAND_IDS, ...Object.keys(imageRecallCommands)] as const;++export const useRegisterFirstPartyCommands = () => {+ const project = useActiveProject();+ const dispatch = useWorkbenchDispatch();+ const { models, status: modelsStatus } = useModelsSnapshot();+ const availabilityModels = modelsStatus === 'loaded' ? models : undefined;+ const projectRef = useRef(project);+ const modelsRef = useRef(availabilityModels);++ useInvocationTemplatesSnapshot();++ projectRef.current = project;+ modelsRef.current = availabilityModels;++ useEffect(() => {+ ensureModelsLoaded();+ }, []);++ const submitInvocation = useEffectEvent(() => {+ const activeProject = projectRef.current;+ const resolvedRoute = resolveInvocationRoute(activeProject, 'global', activeProject.invocation, modelsRef.current);+ const { status } = getConnectionStatus();++ if (!isInvocationRouteValid(resolvedRoute) || status !== 'connected') {+ return;+ }++ dispatch({+ backendSupportsCancellation: true,+ models: modelsRef.current,+ route: resolvedRoute,+ type: 'submitResolvedInvocationSnapshot',+ });+ });++ const recallSelectedImage = useEffectEvent(async (kind: ImageRecallKind) => {+ const activeProject = projectRef.current;+ const image = getSelectedGalleryImage(activeProject);++ if (!image) {+ dispatch({+ kind: 'info',+ message: 'Select an image in Gallery or Preview first.',+ title: 'No image selected',+ type: 'recordNotice',+ });+ return;+ }++ const didRecall = await executeImageRecall({+ dispatch,+ generateValues: getProjectWidgetValues(activeProject, 'generate'),+ image,+ kind,+ models: modelsRef.current ?? [],+ });++ if (didRecall) {+ openWidgetPlacement({+ dispatch,+ getWidgetsForRegion,+ options: { preferredRegions: ['left'] },+ typeId: 'generate',+ });+ }+ });++ useEffect(() => {+ const disposers = [+ commandApi.register({ handler: submitInvocation, id: 'app.invoke', title: 'Invoke' }),+ commandApi.register({ handler: submitInvocation, id: 'app.invokeFront', title: 'Invoke front' }),+ commandApi.register({+ handler: () => void cancelCurrentQueueItem().finally(() => dispatch({ type: 'refreshBackendData' })),+ id: 'app.cancelQueueItem',+ title: 'Cancel current queue item',+ }),+ commandApi.register({+ handler: () => dispatch({ projectId: projectRef.current.id, type: 'cancelAllQueueItems' }),+ id: 'app.clearQueue',+ title: 'Clear queue',+ }),+ commandApi.register({+ handler: () =>+ openWidgetPlacement({+ dispatch,+ getWidgetsForRegion,+ options: { preferredRegions: ['left'] },+ typeId: 'generate',+ }),+ id: 'app.selectGenerateTab',+ title: 'Select Generate tab',+ }),+ commandApi.register({+ handler: () =>+ openWidgetPlacement({+ dispatch,+ getWidgetsForRegion,+ options: { preferredRegions: ['center'], requireCenterView: true },+ typeId: 'canvas',+ }),+ id: 'app.selectCanvasTab',+ title: 'Select Canvas tab',+ }),+ commandApi.register({+ handler: () =>+ openWidgetPlacement({+ dispatch,+ getWidgetsForRegion,+ options: { preferredRegions: ['center'], requireCenterView: true },+ typeId: 'workflow',+ }),+ id: 'app.selectWorkflowsTab',+ title: 'Select Workflows tab',+ }),+ commandApi.register({+ handler: () => (window.location.hash = '#/models'),+ id: 'app.selectModelsTab',+ title: 'Select Models tab',+ }),+ commandApi.register({+ handler: () =>+ openWidgetPlacement({+ dispatch,+ getWidgetsForRegion,+ options: { preferredRegions: ['right', 'bottom'] },+ typeId: 'queue',+ }),+ id: 'app.selectQueueTab',+ title: 'Select Queue tab',+ }),+ commandApi.register({+ handler: () => {+ openWidgetPlacement({+ dispatch,+ getWidgetsForRegion,+ options: { preferredRegions: ['left'] },+ typeId: 'generate',+ });+ window.requestAnimationFrame(() => focusPositivePrompt());+ },+ id: 'app.focusPrompt',+ title: 'Focus prompt',+ }),+ commandApi.register({+ handler: () => {+ const region = projectRef.current.widgetRegions.left;++ dispatch({ isCollapsed: !region.isCollapsed, region: 'left', type: 'setRegionWidgetCollapsed' });+ },+ id: 'app.toggleLeftPanel',+ title: 'Toggle left panel',+ }),+ commandApi.register({+ handler: () => {+ const region = projectRef.current.widgetRegions.right;++ dispatch({ isCollapsed: !region.isCollapsed, region: 'right', type: 'setRegionWidgetCollapsed' });+ },+ id: 'app.toggleRightPanel',+ title: 'Toggle right panel',+ }),+ commandApi.register({+ handler: () => dispatch({ type: 'resetActiveLayout' }),+ id: 'app.resetPanelLayout',+ title: 'Reset panel layout',+ }),+ commandApi.register({+ handler: () => {+ const { bottom, left, right } = projectRef.current.widgetRegions;+ const shouldCollapse = !left.isCollapsed || !right.isCollapsed || !bottom.isCollapsed;++ dispatch({ isCollapsed: shouldCollapse, region: 'left', type: 'setRegionWidgetCollapsed' });+ dispatch({ isCollapsed: shouldCollapse, region: 'right', type: 'setRegionWidgetCollapsed' });+ dispatch({ isCollapsed: shouldCollapse, region: 'bottom', type: 'setRegionWidgetCollapsed' });+ },+ id: 'app.togglePanels',+ title: 'Toggle panels',+ }),+ ...Object.entries(imageRecallCommands).map(([id, kind]) =>+ commandApi.register({ handler: () => recallSelectedImage(kind), id, title: id })+ ),+ ];++ return () => {+ disposers.forEach((dispose) => dispose());+ };+ }, [dispatch]);+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/index.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/index.tsnew file mode 100644index 0000000000..7153873171--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/index.ts@@ -0,0 +1,7 @@+export * from './catalog';+export * from './extensionHotkeys';+export * from './keys';+export * from './modalLayer';+export * from './resolve';+export * from './targetWidget';+export * from './types';diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.tsnew file mode 100644index 0000000000..abfcfc07c4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it } from 'vitest';++import { eventToHotkeyString, normalizeHotkeyString, toTinykeysBinding } from './keys';++describe('hotkey keys', () => {+ it('normalizes modifier order and aliases', () => {+ expect(normalizeHotkeyString('Shift+Mod+Enter')).toBe('mod+shift+enter');+ expect(normalizeHotkeyString('escape')).toBe('esc');+ expect(normalizeHotkeyString('Alt+ArrowUp')).toBe('alt+arrowup');+ });++ it('converts normalized keys to tinykeys syntax', () => {+ expect(toTinykeysBinding('mod+enter')).toBe('$mod+Enter');+ expect(toTinykeysBinding('alt+]')).toBe('Alt+BracketRight');+ expect(toTinykeysBinding('.')).toBe('Period');+ });++ it('ignores IME composition events when recording hotkeys', () => {+ expect(eventToHotkeyString({ isComposing: true, key: 'a' } as KeyboardEvent)).toBe('');+ expect(eventToHotkeyString({ key: 'Process', keyCode: 229 } as KeyboardEvent)).toBe('');+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/keys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.tsnew file mode 100644index 0000000000..e74b9ad6d1--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/keys.ts@@ -0,0 +1,109 @@+const MODIFIER_ORDER = ['mod', 'ctrl', 'meta', 'shift', 'alt'] as const;++const KEY_ALIASES: Record<string, string> = {+ ' ': 'space',+ arrowdown: 'arrowdown',+ arrowleft: 'arrowleft',+ arrowright: 'arrowright',+ arrowup: 'arrowup',+ del: 'delete',+ escape: 'esc',+ return: 'enter',+};++const TINY_KEY_ALIASES: Record<string, string> = {+ '[': 'BracketLeft',+ ']': 'BracketRight',+ '.': 'Period',+ ',': 'Comma',+ '/': 'Slash',+ '\\': 'Backslash',+ '-': 'Minus',+ '=': 'Equal',+ arrowdown: 'ArrowDown',+ arrowleft: 'ArrowLeft',+ arrowright: 'ArrowRight',+ arrowup: 'ArrowUp',+ backspace: 'Backspace',+ delete: 'Delete',+ enter: 'Enter',+ esc: 'Escape',+ space: 'Space',+};++const TINY_MODIFIER_ALIASES: Record<string, string> = {+ alt: 'Alt',+ ctrl: 'Control',+ meta: 'Meta',+ mod: '$mod',+ shift: 'Shift',+};++export const IS_MAC_OS =+ typeof navigator !== 'undefined' &&+ (+ (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform ??+ navigator.platform ??+ ''+ )+ .toLowerCase()+ .includes('mac');++export const normalizeHotkeyString = (hotkey: string): string => {+ const parts = hotkey+ .split('+')+ .map((part) => part.trim().toLowerCase())+ .filter(Boolean)+ .map((part) => KEY_ALIASES[part] ?? part);+ const modifiers = parts+ .filter((part) => MODIFIER_ORDER.includes(part as (typeof MODIFIER_ORDER)[number]))+ .sort((left, right) => MODIFIER_ORDER.indexOf(left as never) - MODIFIER_ORDER.indexOf(right as never));+ const key = parts.find((part) => !MODIFIER_ORDER.includes(part as (typeof MODIFIER_ORDER)[number]));++ return key ? [...modifiers, key].join('+') : '';+};++export const eventToHotkeyString = (event: KeyboardEvent): string => {+ if (event.isComposing || event.keyCode === 229 || ['Alt', 'Control', 'Meta', 'Shift'].includes(event.key)) {+ return '';+ }++ const modifiers: string[] = [];++ if (event.metaKey || event.ctrlKey) {+ modifiers.push(IS_MAC_OS ? (event.metaKey ? 'mod' : 'ctrl') : event.ctrlKey ? 'mod' : 'meta');+ }+ if (event.shiftKey) {+ modifiers.push('shift');+ }+ if (event.altKey) {+ modifiers.push('alt');+ }++ return normalizeHotkeyString([...modifiers, event.key].join('+'));+};++export const toTinykeysBinding = (hotkey: string): string => {+ const normalized = normalizeHotkeyString(hotkey);+ const parts = normalized.split('+').filter(Boolean);++ return parts.map((part) => TINY_MODIFIER_ALIASES[part] ?? TINY_KEY_ALIASES[part] ?? part).join('+');+};++export const formatHotkeyForPlatform = (hotkey: string): string[] =>+ normalizeHotkeyString(hotkey)+ .split('+')+ .filter(Boolean)+ .map((part) => (IS_MAC_OS ? part.replace('mod', 'cmd').replace('alt', 'option') : part.replace('mod', 'ctrl')));++export const isEditableHotkeyTarget = (target: EventTarget | null): boolean => {+ if (typeof HTMLElement === 'undefined') {+ return false;+ }++ if (!(target instanceof HTMLElement)) {+ return false;+ }++ return Boolean(target.closest('input, textarea, select, [contenteditable="true"]'));+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.test.tsnew file mode 100644index 0000000000..1a780a7809--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.test.ts@@ -0,0 +1,17 @@+import { describe, expect, it } from 'vitest';++import { isHotkeyModalLayerActive, registerHotkeyModalLayer } from './modalLayer';++describe('hotkey modal layer registry', () => {+ it('is active only while a registered layer is mounted', () => {+ expect(isHotkeyModalLayerActive()).toBe(false);++ const unregister = registerHotkeyModalLayer('settings');++ expect(isHotkeyModalLayerActive()).toBe(true);++ unregister();++ expect(isHotkeyModalLayerActive()).toBe(false);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.tsnew file mode 100644index 0000000000..9c03a50180--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/modalLayer.ts@@ -0,0 +1,18 @@+import { createListenerChannel } from '@workbench/externalStore';++const channel = createListenerChannel();+const activeLayerIds = new Set<string>();++export const registerHotkeyModalLayer = (id: string): (() => void) => {+ activeLayerIds.add(id);+ channel.notify();++ return () => {+ activeLayerIds.delete(id);+ channel.notify();+ };+};++export const isHotkeyModalLayerActive = (): boolean => activeLayerIds.size > 0;++export const subscribeHotkeyModalLayers = channel.subscribe;diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.tsnew file mode 100644index 0000000000..73a51ad66c--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts@@ -0,0 +1,188 @@+import { describe, expect, it, vi } from 'vitest';++import type { RegisteredHotkey } from './types';++import { applyCustomHotkeys, resolveHotkey } from './resolve';++const event = { target: null } as KeyboardEvent;+const context = {+ activeInstanceId: null,+ activeWidgetTypeId: null,+ focusedRegion: null,+ isModalLayerActive: false,+} as const;++const base = {+ category: 'app',+ defaultKeys: ['x'] as string[],+ implemented: true,+ keys: ['x'] as string[],+ preventDefault: true,+} as const;++describe('resolveHotkey', () => {+ it('prefers active widget over global', () => {+ const globalHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'global',+ id: 'global',+ scope: { kind: 'global' },+ title: 'Global',+ };+ const widgetHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'widget',+ id: 'widget',+ scope: { kind: 'widget', typeId: 'gallery' },+ title: 'Widget',+ };++ expect(+ resolveHotkey({+ context: { ...context, activeInstanceId: 'gallery-1', activeWidgetTypeId: 'gallery', focusedRegion: 'left' },+ event,+ hotkeys: [globalHotkey, widgetHotkey],+ matchedKey: 'x',+ })?.commandId+ ).toBe('widget');+ });++ it('prefers active instance over widget', () => {+ const widgetHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'widget',+ id: 'widget',+ scope: { kind: 'widget', typeId: 'gallery' },+ title: 'Widget',+ };+ const instanceHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'instance',+ id: 'instance',+ scope: { instanceId: 'gallery-1', kind: 'instance' },+ title: 'Instance',+ };++ expect(+ resolveHotkey({+ context: { ...context, activeInstanceId: 'gallery-1', activeWidgetTypeId: 'gallery', focusedRegion: 'left' },+ event,+ hotkeys: [widgetHotkey, instanceHotkey],+ matchedKey: 'x',+ })?.commandId+ ).toBe('instance');+ });++ it('resolves by the matched canonical key instead of re-serializing the event', () => {+ const hotkey: RegisteredHotkey = {+ ...base,+ commandId: 'symbol',+ id: 'symbol',+ keys: ['shift+1'],+ scope: { kind: 'global' },+ title: 'Symbol',+ };++ expect(+ resolveHotkey({+ context,+ event: { ...event, key: '!' } as KeyboardEvent,+ hotkeys: [hotkey],+ matchedKey: 'shift+1',+ })?.commandId+ ).toBe('symbol');+ });++ it('does not match region-less focused-region hotkeys without a focused region', () => {+ const globalHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'global',+ id: 'global',+ scope: { kind: 'global' },+ title: 'Global',+ };+ const focusedHotkey: RegisteredHotkey = {+ ...base,+ commandId: 'focused',+ id: 'focused',+ scope: { kind: 'focused-region' },+ title: 'Focused',+ };++ expect(resolveHotkey({ context, event, hotkeys: [globalHotkey, focusedHotkey], matchedKey: 'x' })?.commandId).toBe(+ 'global'+ );+ expect(+ resolveHotkey({+ context: { ...context, focusedRegion: 'left' },+ event,+ hotkeys: [globalHotkey, focusedHotkey],+ matchedKey: 'x',+ })?.commandId+ ).toBe('focused');+ });++ it('suppresses editable targets unless allowed', () => {+ class FakeHTMLElement {+ closest(): FakeHTMLElement {+ return this;+ }+ }+ vi.stubGlobal('HTMLElement', FakeHTMLElement);+ const input = new FakeHTMLElement();+ const hotkey: RegisteredHotkey = {+ ...base,+ commandId: 'global',+ id: 'global',+ scope: { kind: 'global' },+ title: 'Global',+ };++ expect(+ resolveHotkey({+ context,+ event: { target: input } as unknown as KeyboardEvent,+ hotkeys: [hotkey],+ matchedKey: 'x',+ })+ ).toBeNull();+ });++ it('suppresses hotkeys while a modal layer is active unless allowed', () => {+ const hotkey: RegisteredHotkey = {+ ...base,+ commandId: 'global',+ id: 'global',+ scope: { kind: 'global' },+ title: 'Global',+ };+ const modalHotkey: RegisteredHotkey = {+ ...hotkey,+ allowInModal: true,+ commandId: 'modal',+ id: 'modal',+ title: 'Modal',+ };++ expect(+ resolveHotkey({+ context: { ...context, isModalLayerActive: true },+ event,+ hotkeys: [hotkey],+ matchedKey: 'x',+ })+ ).toBeNull();+ expect(+ resolveHotkey({+ context: { ...context, isModalLayerActive: true },+ event,+ hotkeys: [hotkey, modalHotkey],+ matchedKey: 'x',+ })?.commandId+ ).toBe('modal');+ });++ it('keeps an empty custom key array as a disabled hotkey', () => {+ expect(applyCustomHotkeys({ defaultKeys: ['x'], id: 'app.invoke' }, { 'app.invoke': [] }).keys).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.tsnew file mode 100644index 0000000000..ae8dfcab38--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts@@ -0,0 +1,54 @@+import type { HotkeyContext, RegisteredHotkey } from './types';++import { isEditableHotkeyTarget, normalizeHotkeyString } from './keys';++const getScopePriority = (hotkey: RegisteredHotkey, context: HotkeyContext): number => {+ const { scope } = hotkey;++ if (scope.kind === 'instance') {+ return scope.instanceId === context.activeInstanceId ? 400 : -1;+ }++ if (scope.kind === 'widget') {+ return scope.typeId === context.activeWidgetTypeId ? 300 : -1;+ }++ if (scope.kind === 'focused-region') {+ return context.focusedRegion && (!scope.region || scope.region === context.focusedRegion) ? 200 : -1;+ }++ return 100;+};++export const applyCustomHotkeys = <Hotkey extends { defaultKeys: string[]; id: string }>(+ hotkey: Hotkey,+ customHotkeys: Record<string, string[]>+): Hotkey & { keys: string[] } => ({+ ...hotkey,+ keys: (customHotkeys[hotkey.id] ?? hotkey.defaultKeys).map(normalizeHotkeyString).filter(Boolean),+});++export const resolveHotkey = ({+ context,+ event,+ hotkeys,+ matchedKey,+}: {+ context: HotkeyContext;+ event: KeyboardEvent;+ hotkeys: RegisteredHotkey[];+ matchedKey: string;+}): RegisteredHotkey | null => {+ const normalized = normalizeHotkeyString(matchedKey);+ const isEditable = isEditableHotkeyTarget(event.target);++ return (+ hotkeys+ .filter((hotkey) => hotkey.implemented !== false && hotkey.keys.includes(normalized))+ .filter((hotkey) => hotkey.allowInEditable || !isEditable)+ .filter((hotkey) => hotkey.allowInModal || !context.isModalLayerActive)+ .map((hotkey) => ({ hotkey, priority: getScopePriority(hotkey, context) }))+ .filter(({ priority }) => priority >= 0)+ .sort((left, right) => right.priority - left.priority)[0]?.hotkey ?? null+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.tsnew file mode 100644index 0000000000..4b419267d0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts@@ -0,0 +1,40 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { getHotkeyTargetWidget } from './targetWidget';++class FakeElement {+ constructor(private readonly attrs: Record<string, string> | null) {}++ closest(): FakeElement | null {+ return this.attrs ? this : null;+ }++ getAttribute(name: string): string | null {+ return this.attrs?.[name] ?? null;+ }+}++describe('getHotkeyTargetWidget', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('reads the nearest hotkey widget shell from the event target', () => {+ vi.stubGlobal('Element', FakeElement);++ expect(+ getHotkeyTargetWidget(+ new FakeElement({+ 'data-hotkey-widget-instance-id': 'preview',+ 'data-hotkey-widget-type-id': 'preview',+ }) as unknown as EventTarget+ )+ ).toEqual({ instanceId: 'preview', typeId: 'preview' });+ });++ it('ignores targets outside widget shells', () => {+ vi.stubGlobal('Element', FakeElement);++ expect(getHotkeyTargetWidget(new FakeElement(null) as unknown as EventTarget)).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.tsnew file mode 100644index 0000000000..ba08f7550f--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts@@ -0,0 +1,15 @@+import type { WidgetInstanceId, WidgetTypeId } from '@workbench/types';++export const getHotkeyTargetWidget = (+ target: EventTarget | null+): { instanceId: WidgetInstanceId; typeId: WidgetTypeId } | null => {+ if (!(target instanceof Element)) {+ return null;+ }++ const widgetElement = target.closest('[data-hotkey-widget-instance-id][data-hotkey-widget-type-id]');+ const instanceId = widgetElement?.getAttribute('data-hotkey-widget-instance-id');+ const typeId = widgetElement?.getAttribute('data-hotkey-widget-type-id');++ return instanceId && typeId ? { instanceId, typeId: typeId as WidgetTypeId } : null;+};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/types.tsnew file mode 100644index 0000000000..26723f7028--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts@@ -0,0 +1,37 @@+import type { WidgetInstanceId, WidgetRegion, WidgetTypeId } from '@workbench/types';++export type HotkeyCategory = 'app' | 'canvas' | 'gallery' | 'viewer' | 'workflows';++export type HotkeyScope =+ | { kind: 'global' }+ | { kind: 'focused-region'; region?: WidgetRegion }+ | { kind: 'widget'; typeId: WidgetTypeId }+ | { kind: 'instance'; instanceId: WidgetInstanceId };++export interface HotkeyDefinition {+ id: string;+ category: HotkeyCategory;+ commandId: string;+ defaultKeys: string[];+ title: string;+ description?: string;+ scope: HotkeyScope;+ preventDefault?: boolean;+ allowInEditable?: boolean;+ allowInModal?: boolean;+ unavailableReason?: string;+ implemented?: boolean;+}++export interface RegisteredHotkey extends HotkeyDefinition {+ keys: string[];+}++export interface HotkeyContext {+ focusedRegion: WidgetRegion | null;+ activeInstanceId: WidgetInstanceId | null;+ activeWidgetTypeId: WidgetTypeId | null;+ isModalLayerActive: boolean;+}++export type CustomHotkeys = Record<string, string[]>;diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsxnew file mode 100644index 0000000000..2767209ebf--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx@@ -0,0 +1,513 @@+import type { HotkeyCategory, HotkeyDefinition } from '@workbench/hotkeys';++import { Badge, Box, Flex, HStack, Icon, Input, InputGroup, Kbd, ScrollArea, Stack, Text } from '@chakra-ui/react';+import { useVirtualizer } from '@tanstack/react-virtual';+import { Button, IconButton } from '@workbench/components/ui';+import {+ firstPartyHotkeyCatalog,+ formatHotkeyForPlatform,+ normalizeHotkeyString,+ eventToHotkeyString,+ useExtensionHotkeyDefinitions,+} from '@workbench/hotkeys';+import { patchWorkbenchPreferences, useWorkbenchPreferences } from '@workbench/settings/store';+import { CheckIcon, PlusIcon, RotateCcwIcon, SearchIcon, Trash2Icon, XIcon } from 'lucide-react';+import { Fragment, useDeferredValue, useEffect, useMemo, useRef, useState } from 'react';++type HotkeyConflict = { hotkey: HotkeyDefinition; title: string };++type HotkeyRow =+ | { kind: 'category'; category: HotkeyCategory; title: string }+ | { kind: 'hotkey'; hotkey: HotkeyDefinition; effectiveKeys: string[]; isCustomized: boolean };++const CATEGORY_LABELS: Record<HotkeyCategory, string> = {+ app: 'App',+ canvas: 'Canvas',+ gallery: 'Gallery',+ viewer: 'Viewer',+ workflows: 'Workflows',+};++const CATEGORY_ORDER: HotkeyCategory[] = ['app', 'canvas', 'workflows', 'viewer', 'gallery'];++const normalizeKeys = (keys: string[]): string[] => keys.map(normalizeHotkeyString).filter(Boolean);++const titleFromId = (id: string): string =>+ id+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2')+ .replaceAll('.', ' ')+ .split(' ')+ .filter(Boolean)+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))+ .join(' ');++const getHotkeyTitle = (hotkey: HotkeyDefinition): string => hotkey.title || titleFromId(hotkey.id);++const getScopeRank = (hotkey: HotkeyDefinition): number => {+ if (hotkey.scope.kind === 'instance') {+ return 400;+ }++ if (hotkey.scope.kind === 'widget') {+ return 300;+ }++ if (hotkey.scope.kind === 'focused-region') {+ return 200;+ }++ return 100;+};++const canScopesOverlap = (left: HotkeyDefinition, right: HotkeyDefinition): boolean => {+ if (getScopeRank(left) !== getScopeRank(right)) {+ return false;+ }++ if (left.scope.kind === 'global' && right.scope.kind === 'global') {+ return true;+ }++ if (left.scope.kind === 'widget' && right.scope.kind === 'widget') {+ return left.scope.typeId === right.scope.typeId;+ }++ if (left.scope.kind === 'instance' && right.scope.kind === 'instance') {+ return left.scope.instanceId === right.scope.instanceId;+ }++ if (left.scope.kind === 'focused-region' && right.scope.kind === 'focused-region') {+ return !left.scope.region || !right.scope.region || left.scope.region === right.scope.region;+ }++ return false;+};++const buildConflictMap = (+ catalog: HotkeyDefinition[],+ customHotkeys: Record<string, string[]>+): Map<string, HotkeyConflict[]> => {+ const conflicts = new Map<string, HotkeyConflict[]>();++ for (const hotkey of catalog) {+ if (hotkey.implemented === false) {+ continue;+ }++ const effectiveKeys = normalizeKeys(customHotkeys[hotkey.id] ?? hotkey.defaultKeys);++ for (const key of effectiveKeys) {+ const entries = conflicts.get(key) ?? [];++ entries.push({ hotkey, title: getHotkeyTitle(hotkey) });+ conflicts.set(key, entries);+ }+ }++ return conflicts;+};++const isHotkeyCustomized = (hotkey: HotkeyDefinition, customHotkeys: Record<string, string[]>): boolean =>+ Object.prototype.hasOwnProperty.call(customHotkeys, hotkey.id);++const buildRows = ({+ catalog,+ customHotkeys,+ searchTerm,+}: {+ catalog: HotkeyDefinition[];+ customHotkeys: Record<string, string[]>;+ searchTerm: string;+}): HotkeyRow[] => {+ const needle = searchTerm.trim().toLowerCase();+ const rows: HotkeyRow[] = [];++ for (const category of CATEGORY_ORDER) {+ const hotkeys = catalog+ .filter((hotkey) => hotkey.category === category)+ .filter((hotkey) => {+ if (!needle) {+ return true;+ }++ const haystack = [getHotkeyTitle(hotkey), hotkey.description, hotkey.id, hotkey.defaultKeys.join(' ')]+ .filter(Boolean)+ .join(' ')+ .toLowerCase();++ return haystack.includes(needle);+ });++ if (hotkeys.length === 0) {+ continue;+ }++ rows.push({ category, kind: 'category', title: CATEGORY_LABELS[category] });++ for (const hotkey of hotkeys) {+ rows.push({+ effectiveKeys: normalizeKeys(customHotkeys[hotkey.id] ?? hotkey.defaultKeys),+ hotkey,+ isCustomized: isHotkeyCustomized(hotkey, customHotkeys),+ kind: 'hotkey',+ });+ }+ }++ return rows;+};++export const HotkeysSettingsSection = () => {+ const { customHotkeys } = useWorkbenchPreferences();+ const extensionHotkeys = useExtensionHotkeyDefinitions();+ const [searchTerm, setSearchTerm] = useState('');+ const deferredSearchTerm = useDeferredValue(searchTerm);+ const scrollRef = useRef<HTMLDivElement | null>(null);+ const catalog = useMemo(() => [...firstPartyHotkeyCatalog, ...extensionHotkeys], [extensionHotkeys]);+ const rows = useMemo(+ () => buildRows({ catalog, customHotkeys, searchTerm: deferredSearchTerm }),+ [catalog, customHotkeys, deferredSearchTerm]+ );+ const conflictMap = useMemo(() => buildConflictMap(catalog, customHotkeys), [catalog, customHotkeys]);+ const modifiedCount = Object.keys(customHotkeys).length;+ const virtualizer = useVirtualizer({+ count: rows.length,+ estimateSize: (index) => (rows[index]?.kind === 'category' ? 36 : 86),+ getScrollElement: () => scrollRef.current,+ measureElement: (element) => element.getBoundingClientRect().height,+ overscan: 8,+ });++ const saveHotkey = (hotkeyId: string, keys: string[]) => {+ void patchWorkbenchPreferences({ customHotkeys: { ...customHotkeys, [hotkeyId]: normalizeKeys(keys) } });+ };++ const resetHotkey = (hotkeyId: string) => {+ const next = { ...customHotkeys };++ delete next[hotkeyId];+ void patchWorkbenchPreferences({ customHotkeys: next });+ };++ const resetAll = () => {+ void patchWorkbenchPreferences({ customHotkeys: {} });+ };++ const virtualRows = virtualizer.getVirtualItems();++ return (+ <Stack h="full" minH="0">+ <HStack justify="space-between" gap="3">+ <Stack gap="0.5">+ <Text color="fg" fontSize="sm" fontWeight="600">+ Hotkeys+ </Text>+ <Text color="fg.subtle" fontSize="xs">+ Account-bound keybinds. Project-level overrides can layer on later without changing hotkey ids.+ </Text>+ </Stack>+ <Button disabled={modifiedCount === 0} size="xs" variant="outline" onClick={resetAll}>+ <RotateCcwIcon />+ Reset all+ </Button>+ </HStack>++ <InputGroup startElement={<Icon as={SearchIcon} boxSize="3.5" />}>+ <Input+ placeholder="Search hotkeys"+ size="xs"+ value={searchTerm}+ onChange={(event) => setSearchTerm(event.currentTarget.value)}+ />+ </InputGroup>++ <ScrollArea.Root flex="1" minH="0" rounded="md" size="xs" variant="hover" w="full">+ <ScrollArea.Viewport ref={scrollRef} aria-label="Hotkey bindings" h="full" w="full">+ <ScrollArea.Content w="full">+ <Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">+ {virtualRows.map((row) => {+ const item = rows[row.index];++ if (!item) {+ return null;+ }++ return (+ <Box+ key={row.key}+ ref={virtualizer.measureElement}+ data-index={row.index}+ position="absolute"+ top="0"+ transform={`translateY(${row.start}px)`}+ w="full"+ >+ {item.kind === 'category' ? (+ <CategoryRow title={item.title} />+ ) : (+ <HotkeyListRow+ conflictMap={conflictMap}+ effectiveKeys={item.effectiveKeys}+ hotkey={item.hotkey}+ isCustomized={item.isCustomized}+ onReset={() => resetHotkey(item.hotkey.id)}+ onSave={(keys) => saveHotkey(item.hotkey.id, keys)}+ />+ )}+ </Box>+ );+ })}+ </Box>+ </ScrollArea.Content>+ </ScrollArea.Viewport>+ <ScrollArea.Scrollbar>+ <ScrollArea.Thumb />+ </ScrollArea.Scrollbar>+ </ScrollArea.Root>+ </Stack>+ );+};++const CategoryRow = ({ title }: { title: string }) => (+ <Flex align="center" borderBottomWidth="1px" pb="2" pt="4">+ <Text color="fg.muted" fontSize="2xs" fontWeight="800" letterSpacing="0.08em" textTransform="uppercase">+ {title}+ </Text>+ </Flex>+);++const HotkeyListRow = ({+ conflictMap,+ effectiveKeys,+ hotkey,+ isCustomized,+ onReset,+ onSave,+}: {+ conflictMap: Map<string, HotkeyConflict[]>;+ effectiveKeys: string[];+ hotkey: HotkeyDefinition;+ isCustomized: boolean;+ onReset: () => void;+ onSave: (keys: string[]) => void;+}) => {+ const [draftKeys, setDraftKeys] = useState(effectiveKeys);+ const [editingIndex, setEditingIndex] = useState<number | null>(null);+ const isEditing = editingIndex !== null;+ const isDirty = draftKeys.join('\n') !== effectiveKeys.join('\n');+ const hasDuplicate = new Set(draftKeys).size !== draftKeys.length;+ const conflict =+ hotkey.implemented === false+ ? undefined+ : draftKeys+ .flatMap((key) => conflictMap.get(key) ?? [])+ .find((entry) => entry.hotkey.id !== hotkey.id && canScopesOverlap(hotkey, entry.hotkey));+ const canSave = !hasDuplicate && !conflict && (isDirty || isEditing);++ useEffect(() => {+ if (!isEditing) {+ setDraftKeys(effectiveKeys);+ }+ }, [effectiveKeys, isEditing]);++ const updateDraftKey = (index: number, key: string) => {+ setDraftKeys((current) => current.map((candidate, candidateIndex) => (candidateIndex === index ? key : candidate)));+ };++ const deleteDraftKey = (index: number) => {+ setDraftKeys((current) => current.filter((_key, candidateIndex) => candidateIndex !== index));+ setEditingIndex(null);+ };++ const addDraftKey = () => {+ setDraftKeys((current) => [...current, '']);+ setEditingIndex(draftKeys.length);+ };++ const cancelEdit = () => {+ setDraftKeys(effectiveKeys);+ setEditingIndex(null);+ };++ const saveEdit = () => {+ if (!canSave) {+ return;+ }++ onSave(draftKeys);+ setEditingIndex(null);+ };++ const disableHotkey = () => {+ onSave([]);+ setEditingIndex(null);+ };++ return (+ <Flex borderBottomWidth="1px" gap="3" py="2.5">+ <Stack flex="1" gap="1" minW="0">+ <HStack gap="2">+ <Text color="fg" fontSize="sm" fontWeight="600" truncate>+ {getHotkeyTitle(hotkey)}+ </Text>+ {hotkey.implemented === false ? (+ <Badge colorPalette="gray" size="xs" variant="surface">+ Pending+ </Badge>+ ) : null}+ {isCustomized ? (+ <Badge colorPalette="blue" size="xs" variant="surface">+ Custom+ </Badge>+ ) : null}+ </HStack>+ <Text color="fg.subtle" fontSize="2xs" truncate>+ {hotkey.description ?? hotkey.id}+ </Text>+ {conflict ? (+ <Text color="fg.error" fontSize="2xs">+ Conflicts with {conflict.title}+ </Text>+ ) : hasDuplicate ? (+ <Text color="fg.error" fontSize="2xs">+ Duplicate binding in this hotkey+ </Text>+ ) : null}+ </Stack>+ <Stack align="end" gap="1.5" maxW="58%">+ <HStack gap="1.5" justify="end" wrap="wrap">+ {draftKeys.length > 0 ? (+ draftKeys.map((key, index) => (+ <HotkeyChip+ key={`${index}:${key}`}+ editing={editingIndex === index}+ hotkey={key}+ onCancel={() => setEditingIndex(null)}+ onDelete={() => deleteDraftKey(index)}+ onEdit={() => setEditingIndex(index)}+ onRecord={(nextKey) => updateDraftKey(index, nextKey)}+ />+ ))+ ) : (+ <Text color="fg.subtle" fontSize="2xs">+ Disabled+ </Text>+ )}+ <IconButton aria-label="Add hotkey" size="xs" variant="ghost" onClick={addDraftKey}>+ <PlusIcon />+ </IconButton>+ </HStack>+ <HStack gap="1">+ {isEditing || isDirty ? (+ <>+ <IconButton aria-label="Cancel hotkey edit" size="xs" variant="ghost" onClick={cancelEdit}>+ <XIcon />+ </IconButton>+ <IconButton+ aria-label="Save hotkey edit"+ disabled={!canSave}+ size="xs"+ variant="ghost"+ onClick={saveEdit}+ >+ <CheckIcon />+ </IconButton>+ </>+ ) : null}+ {effectiveKeys.length > 0 ? (+ <Button size="xs" variant="ghost" onClick={disableHotkey}>+ Disable+ </Button>+ ) : null}+ {isCustomized ? (+ <IconButton aria-label="Reset hotkey" size="xs" variant="ghost" onClick={onReset}>+ <RotateCcwIcon />+ </IconButton>+ ) : null}+ </HStack>+ </Stack>+ </Flex>+ );+};++const HotkeyChip = ({+ editing,+ hotkey,+ onCancel,+ onDelete,+ onEdit,+ onRecord,+}: {+ editing: boolean;+ hotkey: string;+ onCancel: () => void;+ onDelete: () => void;+ onEdit: () => void;+ onRecord: (hotkey: string) => void;+}) => {+ useEffect(() => {+ if (!editing) {+ return;+ }++ const onKeyDown = (event: KeyboardEvent) => {+ event.preventDefault();+ event.stopPropagation();++ if (event.key === 'Escape') {+ onCancel();+ return;+ }++ const nextHotkey = eventToHotkeyString(event);++ if (nextHotkey) {+ onRecord(nextHotkey);+ onCancel();+ }+ };+ const blockKeyUp = (event: KeyboardEvent) => {+ event.preventDefault();+ event.stopPropagation();+ };++ window.addEventListener('keydown', onKeyDown, true);+ window.addEventListener('keyup', blockKeyUp, true);++ return () => {+ window.removeEventListener('keydown', onKeyDown, true);+ window.removeEventListener('keyup', blockKeyUp, true);+ };+ }, [editing, onCancel, onRecord]);++ if (editing) {+ return (+ <HStack borderColor="accent.solid" borderWidth="1px" gap="1" px="2" py="1" rounded="md">+ <Text color="accent.solid" fontSize="2xs" fontStyle="italic">+ Press keys+ </Text>+ <IconButton aria-label="Delete hotkey" colorPalette="red" size="2xs" variant="ghost" onClick={onDelete}>+ <Trash2Icon />+ </IconButton>+ </HStack>+ );+ }++ return (+ <Button type="button" onClick={onEdit} variant="outline" size="xs">+ {formatHotkeyForPlatform(hotkey).map((part, index, parts) => (+ <Fragment key={`${part}:${index}`}>+ <Kbd size="sm" textTransform="lowercase">+ {part}+ </Kbd>+ {index < parts.length - 1 ? (+ <Text color="fg.subtle" fontSize="2xs">+ ++ </Text>+ ) : null}+ </Fragment>+ ))}+ </Button>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsxindex cbd591a15a..28f3dac9b0 100644--- a/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/SettingsDialog.tsx@@ -29,6 +29,7 @@ import {import { themeCardRecipe } from '@theme/recipes';import { previewSwatches, THEMES, type ThemeDefinition } from '@theme/system';import { Button, CloseButton, IconButton, ConfirmDialog, Tabs, Tooltip } from '@workbench/components/ui';+import { registerHotkeyModalLayer } from '@workbench/hotkeys';import { syncedWorkbenchPersistence } from '@workbench/projects/syncedPersistence';import {useOptionalWorkbenchDispatch,@@ -40,6 +41,7 @@ import {Code2Icon,DatabaseIcon,FolderIcon,+ KeyboardIcon,PaletteIcon,RotateCcwIcon,SettingsIcon,@@ -48,7 +50,7 @@ import {WorkflowIcon,type LucideIcon,} from 'lucide-react';-import { useId, useState, type ReactNode } from 'react';+import { useEffect, useId, useState, type ReactNode } from 'react';import {closeWorkbenchSettings,@@ -98,25 +100,36 @@ export const SettingsButton = () => {);};-export const SettingsDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => (- <Dialog.Root- lazyMount- open={isOpen}- placement="center"- scrollBehavior="inside"- size="xl"- unmountOnExit- onOpenChange={(event) => {- if (!event.open) {- onClose();- }- }}- >- <SettingsDialogContent />- </Dialog.Root>-);+export const SettingsDialog = ({ isOpen, onClose }: { isOpen: boolean; onClose: () => void }) => {+ useEffect(() => {+ if (!isOpen) {+ return;+ }++ return registerHotkeyModalLayer('settings');+ }, [isOpen]);-const SettingsDialogContent = () => {+ return (+ <Dialog.Root+ closeOnInteractOutside={false}+ lazyMount+ open={isOpen}+ placement="center"+ scrollBehavior="inside"+ size="xl"+ unmountOnExit+ onOpenChange={(event) => {+ if (!event.open) {+ onClose();+ }+ }}+ >+ <SettingsDialogContent onClose={onClose} />+ </Dialog.Root>+ );+};++const SettingsDialogContent = ({ onClose }: { onClose: () => void }) => {const { error, scope, status } = useWorkbenchSettings();return (@@ -171,6 +184,12 @@ const SettingsTabs = () => {label: 'Behavior',value: 'behavior',},+ {+ children: <HotkeysSettingsSection />,+ icon: KeyboardIcon,+ label: 'Hotkeys',+ value: 'hotkeys',+ },{children: <ProjectSection />,condition: hasWorkbench,diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts b/invokeai/frontend/webv2/src/workbench/settings/store.test.tsindex e7c27d8449..8b386df270 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.test.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.test.ts@@ -159,6 +159,26 @@ describe('patchWorkbenchPreferences', () => {expect(readBackendPreferences().reduceMotion).toBe(true);expect(readBackendPreferences().themeId).toBe('forest');expect(store.getWorkbenchPreferences().reduceMotion).toBe(true);+ expect(store.getWorkbenchReduceMotion()).toBe(true);+ });++ it('persists account-bound custom hotkeys', async () => {+ seedBackendPreferences({ themeId: 'forest' });+ await store.loadWorkbenchSettings();++ await store.patchWorkbenchPreferences({ customHotkeys: { 'app.invoke': ['mod+shift+enter'] } });++ expect(readBackendPreferences().customHotkeys).toEqual({ 'app.invoke': ['mod+shift+enter'] });+ expect(store.getWorkbenchPreferences().customHotkeys).toEqual({ 'app.invoke': ['mod+shift+enter'] });+ });++ it('persists empty custom hotkeys as disabled bindings', async () => {+ await store.loadWorkbenchSettings();++ await store.patchWorkbenchPreferences({ customHotkeys: { 'app.invoke': [] } });++ expect(readBackendPreferences().customHotkeys).toEqual({ 'app.invoke': [] });+ expect(store.getWorkbenchPreferences().customHotkeys).toEqual({ 'app.invoke': [] });});it('replays an offline edit on the next load instead of reverting to the server copy', async () => {diff --git a/invokeai/frontend/webv2/src/workbench/settings/store.ts b/invokeai/frontend/webv2/src/workbench/settings/store.tsindex 7862a56425..8e58a9a955 100644--- a/invokeai/frontend/webv2/src/workbench/settings/store.ts+++ b/invokeai/frontend/webv2/src/workbench/settings/store.ts@@ -11,6 +11,7 @@ import { getUserStorageScope } from '@workbench/auth/session';import { createExternalStore } from '@workbench/externalStore';import { deleteClientStateValue, getClientStateValue, setClientStateValue } from '@workbench/projects/api';import { fetchSessionBlob } from '@workbench/projects/session';+import { useSyncExternalStore } from 'react';const SETTINGS_BASE_STORAGE_KEY = 'invokeai:v7:webv2:settings';const LEGACY_WORKBENCH_BASE_STORAGE_KEY = 'invokeai:v7:webv2:workbench';@@ -69,6 +70,7 @@ export const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {export const DEFAULT_PREFERENCES: WorkbenchPreferences = {confirmImageDeletion: true,+ customHotkeys: {},developerLogEnabled: true,developerLogLevel: 'debug',developerLogNamespaces: [...DEVELOPER_LOG_NAMESPACES],@@ -126,6 +128,23 @@ const normalizeDeveloperLogNamespaces = (values: unknown): DeveloperLogNamespacereturn DEVELOPER_LOG_NAMESPACES.filter((namespace) => enabled.has(namespace));};+const normalizeCustomHotkeys = (values: unknown): Record<string, string[]> => {+ if (!values || typeof values !== 'object' || Array.isArray(values)) {+ return {};+ }++ return Object.fromEntries(+ Object.entries(values)+ .filter(+ (entry): entry is [string, string[]] =>+ typeof entry[0] === 'string' &&+ Array.isArray(entry[1]) &&+ entry[1].every((hotkey) => typeof hotkey === 'string')+ )+ .map(([id, hotkeys]) => [id, hotkeys])+ );+};+export const normalizeProjectSettings = (settings?: Partial<ProjectSettings>): ProjectSettings => ({antialiasProgressImages:typeof settings?.antialiasProgressImages === 'boolean'@@ -155,6 +174,7 @@ export const normalizeWorkbenchPreferences = (preferences?: WorkbenchPreferencestypeof preferences?.confirmImageDeletion === 'boolean'? preferences.confirmImageDeletion: DEFAULT_PREFERENCES.confirmImageDeletion,+ customHotkeys: normalizeCustomHotkeys(preferences?.customHotkeys),developerLogEnabled:typeof preferences?.developerLogEnabled === 'boolean'? preferences.developerLogEnabled@@ -384,6 +404,11 @@ export const useWorkbenchPreferences = (): WorkbenchPreferences => store.useSnapexport const getWorkbenchPreferences = (): WorkbenchPreferences => store.getSnapshot().preferences;+export const getWorkbenchReduceMotion = (): boolean => store.getSnapshot().preferences.reduceMotion;++export const useWorkbenchReduceMotion = (): boolean =>+ useSyncExternalStore(store.subscribe, getWorkbenchReduceMotion, getWorkbenchReduceMotion);+export const patchWorkbenchPreferences = async (preferences: Partial<WorkbenchPreferences>): Promise<void> => {const next = normalizeWorkbenchPreferences({ ...store.getSnapshot().preferences, ...preferences });diff --git a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsxindex 9303f7862c..a8c76ceeb0 100644--- a/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/topbar/InvokeControl.tsx@@ -120,7 +120,6 @@ export const InvokeControl = () => {const isValid = isInvocationRouteValid(resolvedRoute) && isConnected;const routeLabel = isValid ? formatRoute(resolvedRoute) : (blockingReasons[0] ?? formatRoute(resolvedRoute));const resolvedRouteRef = useRef(resolvedRoute);- const isValidRef = useRef(isValid);const modelsRef = useRef(availabilityModels);resolvedRouteRef.current = resolvedRoute;@@ -131,33 +130,6 @@ export const InvokeControl = () => {ensureModelsLoaded();}, []);- useEffect(() => {- const onKeyDown = (event: KeyboardEvent) => {- if (!(event.metaKey || event.ctrlKey) || event.key !== 'Enter') {- return;- }-- event.preventDefault();-- if (!isValidRef.current) {- return;- }-- dispatch({- backendSupportsCancellation: true,- models: modelsRef.current,- route: resolvedRouteRef.current,- type: 'submitResolvedInvocationSnapshot',- });- };-- window.addEventListener('keydown', onKeyDown);-- return () => {- window.removeEventListener('keydown', onKeyDown);- };- }, [dispatch]);-const onInvoke = () => {if (!isValid) {return;@@ -201,7 +173,7 @@ export const InvokeControl = () => {<Text fontSize="sm" fontWeight="700" lineHeight="1">Invoke</Text>- <HStack gap="1" maxW="full">+ <HStack gap="1" maxW="full" mb="-0.5"><Text fontSize="2xs" fontWeight="600" lineHeight="1.1" opacity="0.85" truncate>{routeLabel}</Text>diff --git a/invokeai/frontend/webv2/src/workbench/types.ts b/invokeai/frontend/webv2/src/workbench/types.tsindex e04a82afd0..497fd9eb18 100644--- a/invokeai/frontend/webv2/src/workbench/types.ts+++ b/invokeai/frontend/webv2/src/workbench/types.ts@@ -131,6 +131,7 @@ export type WidgetView = ComponentType<WidgetViewProps>;export type WidgetHeaderActions = ComponentType<WidgetViewProps>;export type WidgetHeaderMenu = ComponentType<WidgetViewProps>;export type WidgetFooter = ComponentType<WidgetViewProps>;+export type WidgetHost = ComponentType;export interface WidgetLabelProps {region: WorkbenchRegion;@@ -182,9 +183,15 @@ export interface WidgetHotkeyApi {}export interface WidgetHotkeyContribution {+ id: string;commandId: string;- keybinding: string;- when?: string;+ defaultKeys: string[];+ title: string;+ description?: string;+ scope?: 'focused-region' | 'global' | 'instance' | 'widget';+ source?: { instanceId: WidgetInstanceId; region: WorkbenchRegion; typeId: WidgetTypeId };+ preventDefault?: boolean;+ allowInEditable?: boolean;}export interface WidgetMenuApi {@@ -250,7 +257,14 @@ export interface WidgetWorkbenchApi {}/** Sections of the workbench settings dialog, addressable via `openWorkbenchSettings`. */-export type SettingsSectionId = 'appearance' | 'behavior' | 'project' | 'workflow' | 'developer' | 'workspace';+export type SettingsSectionId =+ | 'appearance'+ | 'behavior'+ | 'hotkeys'+ | 'project'+ | 'workflow'+ | 'developer'+ | 'workspace';export interface WidgetManifest {/** Widget runtime API contract version. Defaults to 1 during registry normalization. */@@ -270,6 +284,12 @@ export interface WidgetManifest {header?: 'hidden' | 'visible';};view?: WidgetView;+ /**+ * Stable singleton UI owned by the widget but not by any widget instance.+ * Use for dialogs, file inputs, and other portals driven by widget-level+ * stores. Mounted once under WorkbenchProvider, independent of widget chrome.+ */+ host?: WidgetHost;headerActions?: WidgetHeaderActions;/*** Extra entries for the widget's shared header actions menu. Rendered inside@@ -648,6 +668,8 @@ export interface WorkbenchPreferences {workflowValidateConnections: boolean;/** Connection line rendering in the workflow editor. */workflowEdgeStyle: 'curved' | 'square';+ /** Account-bound overrides keyed by hotkey id (`app.invoke`, `gallery.galleryNavLeft`, etc.). */+ customHotkeys: Record<string, string[]>;}export interface AccountState {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 36dc74d461..0bdeef3417 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -1,12 +1,13 @@-import type { KeyboardEvent } from 'react';+import type { WidgetViewProps } from '@workbench/types';import { Box, Flex } from '@chakra-ui/react';import { useActiveProject, useWorkbenchDispatch } from '@workbench/WorkbenchContext';+import { useEffect, useEffectEvent } from 'react';import { CanvasDocumentFrame, CanvasPlaneImage, EmptyCanvasFrame, ToolScrubber } from './CanvasDocumentFrame';import { CanvasStagingControls, EmptyStagingControls } from './CanvasStagingControls';-export const CanvasWidgetView = () => {+export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const activeProject = useActiveProject();const dispatch = useWorkbenchDispatch();const { document, stagingArea } = activeProject.canvas;@@ -17,28 +18,37 @@ export const CanvasWidgetView = () => {const hasMultipleCandidates = stagingArea.pendingImages.length > 1;const renderedLayers = [...layers].reverse();const hasCanvasContent = renderedLayers.length > 0 || Boolean(selectedImage);- const onKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {- if (!hasStagedCandidates) {- return;- }-- if (event.key === 'ArrowLeft') {- event.preventDefault();+ const executeCanvasHotkey = useEffectEvent((commandId: string) => {+ if (commandId === 'canvas.prevEntity' && hasStagedCandidates) {dispatch({ direction: -1, type: 'cycleStagedImage' });- return;- }-- if (event.key === 'ArrowRight') {- event.preventDefault();+ } else if (commandId === 'canvas.nextEntity' && hasStagedCandidates) {dispatch({ direction: 1, type: 'cycleStagedImage' });- return;- }-- if (event.key === 'Delete' || event.key === 'Backspace') {- event.preventDefault();+ } else if (commandId === 'canvas.deleteSelected' && hasStagedCandidates) {dispatch({ type: 'discardSelectedStagedImage' });+ } else if (commandId === 'canvas.undo') {+ dispatch({ type: 'undoProjectChange' });+ } else if (commandId === 'canvas.redo') {+ dispatch({ type: 'redoProjectChange' });}- };+ });++ useEffect(() => {+ const hotkeys = [+ ['canvas.prevEntity', 'Previous canvas entity', ['alt+[', 'arrowleft']],+ ['canvas.nextEntity', 'Next canvas entity', ['alt+]', 'arrowright']],+ ['canvas.deleteSelected', 'Delete selected canvas item', ['delete', 'backspace']],+ ['canvas.undo', 'Undo canvas edit', ['mod+z']],+ ['canvas.redo', 'Redo canvas edit', ['mod+shift+z', 'mod+y']],+ ] as const;+ const disposers = hotkeys.flatMap(([id, title, defaultKeys]) => [+ runtime.commands.register({ handler: () => executeCanvasHotkey(id), id, title }),+ runtime.hotkeys.register({ commandId: id, defaultKeys: [...defaultKeys], id, title }),+ ]);++ return () => {+ disposers.forEach((dispose) => dispose());+ };+ }, [runtime.commands, runtime.hotkeys]);return (<Box@@ -51,7 +61,6 @@ export const CanvasWidgetView = () => {w="full"bgImage="radial-gradient({colors.fg.grid} 1.5px, transparent 1.5px)"bgSize="28px 28px"- onKeyDown={onKeyDown}><ToolScrubber /><Flex align="center" h="full" justify="center" p="12">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsxindex 9cd2e6454c..cd77d32ec7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryImageGrid.tsx@@ -38,7 +38,7 @@ type GridCell =| { kind: 'placeholder'; placeholder: GalleryQueuePlaceholder };export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) => {- const { actions, gallery, imageActions } = useGalleryWidget();+ const { actions, gallery, imageActions, runtime } = useGalleryWidget();const dispatch = useWorkbenchDispatch();const [contextMenuTarget, setContextMenuTarget] = useState<ImageContextMenuTarget | null>(null);const [isDropActive, setIsDropActive] = useState(false);@@ -209,7 +209,7 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>return [{ boardId: image.boardId, imageName: image.imageName }];};- const navigate = (direction: 'down' | 'left' | 'right' | 'up') => {+ const navigate = useEffectEvent((direction: 'down' | 'left' | 'right' | 'up') => {const imageCount = gallery.images.length;if (imageCount === 0) {@@ -227,7 +227,79 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>actions.selectImage(nextImage);virtualizer.scrollToIndex(Math.floor(getCellIndexForImage(nextIndex) / columnCount));}- };+ });++ const executeGalleryHotkey = useEffectEvent((commandId: string) => {+ if (commandId === 'gallery.selectAllOnPage') {+ const primaryImage = gallery.images[0];++ if (primaryImage) {+ actions.selectImageRange(+ gallery.images.map((image) => image.imageName),+ primaryImage+ );+ }+ return;+ }++ if (commandId === 'gallery.clearSelection') {+ dispatch({+ type: 'patchWidgetValues',+ values: { selectedImage: null, selectedImageName: null, selectedImageNames: [] },+ widgetId: 'gallery',+ });+ return;+ }++ if (commandId === 'gallery.deleteSelection' && gallery.selectedImageNames.length > 0) {+ void imageActions.deleteImages(gallery.selectedImageNames);+ return;+ }++ if (commandId === 'gallery.starImage') {+ const imageNames = gallery.selectedImageNames.length+ ? gallery.selectedImageNames+ : gallery.selectedImageName+ ? [gallery.selectedImageName]+ : [];+ const selectedImages = gallery.images.filter((image) => imageNames.includes(image.imageName));++ if (selectedImages.length > 0) {+ const shouldStar = selectedImages.some((image) => !image.starred);++ void imageActions.setImagesStarred(imageNames, shouldStar);+ }+ }+ });++ useEffect(() => {+ const directions = [+ ['gallery.selectAllOnPage', 'Select all gallery images on page', null, ['mod+a']],+ ['gallery.clearSelection', 'Clear gallery selection', null, ['esc']],+ ['gallery.galleryNavUp', 'Gallery navigation up', 'up', ['arrowup']],+ ['gallery.galleryNavRight', 'Gallery navigation right', 'right', ['arrowright']],+ ['gallery.galleryNavDown', 'Gallery navigation down', 'down', ['arrowdown']],+ ['gallery.galleryNavLeft', 'Gallery navigation left', 'left', ['arrowleft']],+ ['gallery.galleryNavUpAlt', 'Gallery navigation up', 'up', ['alt+arrowup']],+ ['gallery.galleryNavRightAlt', 'Gallery navigation right', 'right', ['alt+arrowright']],+ ['gallery.galleryNavDownAlt', 'Gallery navigation down', 'down', ['alt+arrowdown']],+ ['gallery.galleryNavLeftAlt', 'Gallery navigation left', 'left', ['alt+arrowleft']],+ ['gallery.deleteSelection', 'Delete gallery selection', null, ['delete', 'backspace']],+ ['gallery.starImage', 'Toggle gallery image star', null, ['.']],+ ] as const;+ const disposers = directions.flatMap(([id, title, direction, defaultKeys]) => [+ runtime.commands.register({+ handler: () => (direction ? navigate(direction) : executeGalleryHotkey(id)),+ id,+ title,+ }),+ runtime.hotkeys.register({ commandId: id, defaultKeys: [...defaultKeys], id, title }),+ ]);++ return () => {+ disposers.forEach((dispose) => dispose());+ };+ }, [runtime.commands, runtime.hotkeys]);return (<Box@@ -289,23 +361,6 @@ export const GalleryImageGrid = ({ layout }: { layout: 'stacked' | 'wide' }) =>role="listbox"tabIndex={0}w="full"- onKeyDown={(event) => {- const direction =- event.key === 'ArrowRight'- ? ('right' as const)- : event.key === 'ArrowLeft'- ? ('left' as const)- : event.key === 'ArrowDown'- ? ('down' as const)- : event.key === 'ArrowUp'- ? ('up' as const)- : null;-- if (direction) {- event.preventDefault();- navigate(direction);- }- }}><ScrollArea.Content><Box h={`${virtualizer.getTotalSize()}px`} position="relative" w="full">diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsxindex 964315e9d2..9451c0c098 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetContext.tsx@@ -1,6 +1,7 @@import type { GalleryImage, GalleryView } from '@workbench/gallery/api';import type { GallerySettings } from '@workbench/gallery/settings';import type { ImageActions } from '@workbench/image-actions';+import type { WidgetRuntimeApi } from '@workbench/types';import { createContext, use } from 'react';@@ -36,6 +37,7 @@ export interface GalleryWidgetContextValue {actions: GalleryActions;imageActions: ImageActions;projectName: string;+ runtime: WidgetRuntimeApi;}export const GalleryWidgetContext = createContext<GalleryWidgetContextValue | null>(null);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsxindex 412ce23466..490f90cc3c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/gallery/GalleryWidgetView.tsx@@ -25,7 +25,7 @@ import { GalleryWidgetContext, type GalleryWidgetContextValue } from './GalleryWimport { useGalleryActions } from './useGalleryActions';import { GALLERY_PAGE_SIZE, useGalleryData } from './useGalleryData';-export const GalleryWidgetView = ({ presentation, region }: WidgetViewProps) => {+export const GalleryWidgetView = ({ presentation, region, runtime }: WidgetViewProps) => {const activeProject = useActiveProject();const dispatch = useWorkbenchDispatch();const galleryValues = getProjectWidgetValues(activeProject, 'gallery');@@ -118,8 +118,8 @@ export const GalleryWidgetView = ({ presentation, region }: WidgetViewProps) =>selectedBoardId,});const contextValue = useMemo<GalleryWidgetContextValue>(- () => ({ actions, gallery, imageActions, projectName: activeProject.name }),- [actions, activeProject.name, gallery, imageActions]+ () => ({ actions, gallery, imageActions, projectName: activeProject.name, runtime }),+ [actions, activeProject.name, gallery, imageActions, runtime]);const isWidePlacement = region === 'center' || (region === 'bottom' && presentation === 'expanded');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsx b/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsxindex dc8166753f..2bd01b88fb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/GeneratePromptFields.tsx@@ -5,6 +5,8 @@ import { Stack, Textarea } from '@chakra-ui/react';import { Field } from '@workbench/components/ui';import { getPromptPolicy } from '@workbench/generation/baseGenerationPolicies';+import { registerPositivePromptElement } from './promptFocus';+interface GeneratePromptFieldsProps {settings: GenerateSettings;selectedModel: GenerateModelConfig | undefined;@@ -21,6 +23,7 @@ const PositivePromptField = ({ onChange, value }: PromptFieldProps) => (<Field label="Prompt"><Textareaaria-label="Positive prompt"+ ref={registerPositivePromptElement}minH="6rem"resize="vertical"size="xs"diff --git a/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFocus.ts b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFocus.tsnew file mode 100644index 0000000000..5385c8cb17--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/generate/promptFocus.ts@@ -0,0 +1,16 @@+let positivePromptElement: HTMLTextAreaElement | null = null;++export const registerPositivePromptElement = (element: HTMLTextAreaElement | null): void => {+ positivePromptElement = element;+};++export const focusPositivePrompt = (): boolean => {+ if (!positivePromptElement) {+ return false;+ }++ positivePromptElement.focus();+ positivePromptElement.select();++ return true;+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsxindex 30d0d11cf2..917a2a9b22 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewCompare.tsx@@ -1,9 +1,9 @@-import type { GeneratedImageContract } from '@workbench/types';+import type { GeneratedImageContract, WidgetRuntimeApi } from '@workbench/types';import { Badge, Box, Flex, HStack, Stack } from '@chakra-ui/react';import { Button } from '@workbench/components/ui';import { ArrowLeftRightIcon, Columns2Icon, XIcon } from 'lucide-react';-import { useRef, useState, type CSSProperties } from 'react';+import { useEffect, useEffectEvent, useRef, useState, type CSSProperties } from 'react';type CompareMode = 'slider' | 'side-by-side';@@ -34,16 +34,38 @@ export const PreviewCompare = ({compareImage,onExit,onSwap,+ runtime,}: {baseImage: GeneratedImageContract;compareImage: GeneratedImageContract;onExit: () => void;onSwap: () => void;+ runtime: WidgetRuntimeApi;}) => {const [mode, setMode] = useState<CompareMode>('slider');const [dividerPercent, setDividerPercent] = useState(50);const containerRef = useRef<HTMLDivElement | null>(null);const isDraggingRef = useRef(false);+ const nextMode = useEffectEvent(() => setMode((current) => (current === 'slider' ? 'side-by-side' : 'slider')));++ useEffect(() => {+ const command = runtime.commands.register({+ handler: nextMode,+ id: 'viewer.nextComparisonMode',+ title: 'Next comparison mode',+ });+ const hotkey = runtime.hotkeys.register({+ commandId: 'viewer.nextComparisonMode',+ defaultKeys: ['m'],+ id: 'viewer.nextComparisonMode',+ title: 'Next comparison mode',+ });++ return () => {+ command();+ hotkey();+ };+ }, [runtime.commands, runtime.hotkeys]);const updateDivider = (clientX: number) => {const rect = containerRef.current?.getBoundingClientRect();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsxindex 49417eb56f..bdcfd63aad 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/preview/PreviewWidgetView.tsx@@ -20,7 +20,7 @@ import {import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector, useWorkbenchDispatch } from '@workbench/WorkbenchContext';import { ChevronLeftIcon, ChevronRightIcon } from 'lucide-react';-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from 'react';import { PreviewCompare } from './PreviewCompare';@@ -96,7 +96,7 @@ const previewGridCss = {backgroundSize: '24px 24px',} as const;-export const PreviewWidgetView = ({ region }: WidgetViewProps) => {+export const PreviewWidgetView = ({ region, runtime }: WidgetViewProps) => {const galleryValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'gallery'));const generateValues = useActiveProjectSelector((project) => getProjectWidgetValues(project, 'generate'));const { antialiasProgressImages, showProgressImagesInViewer } = useActiveProjectSelector(@@ -264,6 +264,33 @@ export const PreviewWidgetView = ({ region }: WidgetViewProps) => {const isComparing =selectedImage !== null && compareImage !== null && compareImage.imageName !== selectedImage.imageName;const shouldShowProgressImage = showProgressImagesInViewer && progressImage !== null && !isComparing;+ const executeViewerHotkey = useEffectEvent((commandId: string) => {+ if (commandId === 'viewer.toggleViewer') {+ runtime.workbench.closeWidgetInstance(runtime.instanceId);+ return;+ }++ if (commandId === 'viewer.swapImages' && selectedImage && compareImage) {+ dispatch({ image: compareImage, type: 'selectGalleryImage' });+ dispatch({ image: selectedImage, type: 'setGalleryCompareImage' });+ return;+ }+ });++ useEffect(() => {+ const hotkeys = [+ ['viewer.toggleViewer', 'Toggle preview', ['z']],+ ['viewer.swapImages', 'Swap comparison images', ['c']],+ ] as const;+ const disposers = hotkeys.flatMap(([id, title, defaultKeys]) => [+ runtime.commands.register({ handler: () => executeViewerHotkey(id), id, title }),+ runtime.hotkeys.register({ commandId: id, defaultKeys: [...defaultKeys], id, title }),+ ]);++ return () => {+ disposers.forEach((dispose) => dispose());+ };+ }, [runtime.commands, runtime.hotkeys]);return (<Box p="2" h="full">@@ -273,6 +300,7 @@ export const PreviewWidgetView = ({ region }: WidgetViewProps) => {<PreviewComparebaseImage={selectedImage}compareImage={compareImage}+ runtime={runtime}onExit={() => dispatch({ image: null, type: 'setGalleryCompareImage' })}onSwap={() => {dispatch({ image: compareImage, type: 'selectGalleryImage' });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsxindex c20c3f7624..f49dc5032b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/WorkflowWidgetView.tsx@@ -33,14 +33,14 @@ const WorkflowStatusBarItem = () => {);};-export const WorkflowWidgetView = ({ presentation, region }: WidgetViewProps) => {+export const WorkflowWidgetView = ({ presentation, region, runtime }: WidgetViewProps) => {if (region === 'bottom') {- return presentation === 'expanded' ? <WorkflowEditorView /> : <WorkflowStatusBarItem />;+ return presentation === 'expanded' ? <WorkflowEditorView runtime={runtime} /> : <WorkflowStatusBarItem />;}if (region === 'left') {return <WorkflowLinearPanel />;}- return <WorkflowEditorView />;+ return <WorkflowEditorView runtime={runtime} />;};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsxindex 1a677c01b7..be930faf08 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/AddNodeDialog.tsx@@ -4,6 +4,7 @@ import type { InvocationTemplate } from '@workbench/workflows/types';import { Badge, Box, Dialog, HStack, Icon, Input, Portal, ScrollArea, Stack, Text } from '@chakra-ui/react';import { useVirtualizer } from '@tanstack/react-virtual';import { IconButton, Tooltip } from '@workbench/components/ui';+import { registerHotkeyModalLayer } from '@workbench/hotkeys';import { useInvocationTemplatesSnapshot } from '@workbench/workflows/templates';import { getCompatibleInputTemplate, getCompatibleOutputTemplate } from '@workbench/workflows/validation';import { ChevronDownIcon, ChevronsDownUpIcon, ChevronsUpDownIcon, HammerIcon } from 'lucide-react';@@ -186,7 +187,7 @@ const CategoryHeaderRow = ({color="fg.subtle"flexShrink={0}transform={isExpanded ? 'rotate(0deg)' : 'rotate(-90deg)'}- transition="transform 100ms ease-out"+ transition="transform var(--wb-motion-duration-fast) ease-out"/><Text flex="1" fontSize="xs" fontWeight="700">{group.label}@@ -215,30 +216,40 @@ export const AddNodeDialog = ({onAddNode: (template: InvocationTemplate) => void;onAddNote: () => void;onOpenChange: (isOpen: boolean) => void;-}) => (- <Dialog.Root- lazyMount- open={isOpen}- placement="center"- scrollBehavior="inside"- size="md"- unmountOnExit- onOpenChange={(event) => {- if (!event.open) {- onOpenChange(false);- }- }}- >- <AddNodeDialogContent- connectionFilter={connectionFilter}- onAddCurrentImage={onAddCurrentImage}- onAddConnector={onAddConnector}- onAddNode={onAddNode}- onAddNote={onAddNote}- onOpenChange={onOpenChange}- />- </Dialog.Root>-);+}) => {+ useEffect(() => {+ if (!isOpen) {+ return;+ }++ return registerHotkeyModalLayer('workflow-add-node');+ }, [isOpen]);++ return (+ <Dialog.Root+ lazyMount+ open={isOpen}+ placement="center"+ scrollBehavior="inside"+ size="md"+ unmountOnExit+ onOpenChange={(event) => {+ if (!event.open) {+ onOpenChange(false);+ }+ }}+ >+ <AddNodeDialogContent+ connectionFilter={connectionFilter}+ onAddCurrentImage={onAddCurrentImage}+ onAddConnector={onAddConnector}+ onAddNode={onAddNode}+ onAddNote={onAddNote}+ onOpenChange={onOpenChange}+ />+ </Dialog.Root>+ );+};const AddNodeDialogContent = ({connectionFilter,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsxindex 5756b2f88a..9855179715 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/workflow/editor/WorkflowEditorView.tsx@@ -1,3 +1,4 @@+import type { WidgetRuntimeApi } from '@workbench/types';import type { XYPosition } from '@workbench/workflows/types';import { Box, Flex, Stack, Text } from '@chakra-ui/react';@@ -35,11 +36,11 @@ import {import {useCallback,useEffect,+ useEffectEvent,useId,useMemo,useRef,useState,- type KeyboardEvent,type MouseEvent as ReactMouseEvent,} from 'react';@@ -99,9 +100,6 @@ const DELETE_KEY_CODES = ['Backspace', 'Delete'];const DEFAULT_EDGE_OPTIONS = { style: { strokeWidth: 2 } };-const isEditableTarget = (target: EventTarget | null): boolean =>- target instanceof HTMLElement && target.closest('input, textarea, select, [contenteditable="true"]') !== null;-const getEventClientPosition = (event: MouseEvent | TouchEvent): { x: number; y: number } | null => {if (event instanceof MouseEvent) {return { x: event.clientX, y: event.clientY };@@ -115,12 +113,18 @@ const getEventClientPosition = (event: MouseEvent | TouchEvent): { x: number; y:const getSelectedNodeIdSet = (nodes: WorkflowFlowNode[]): Set<string> =>new Set(nodes.filter((node) => node.selected).map((node) => node.id));-const WorkflowFlow = () => {+const WorkflowFlow = ({ runtime }: { runtime: WidgetRuntimeApi }) => {const projectGraph = useActiveProjectSelector((project) => project.projectGraph);const dispatch = useWorkbenchDispatch();const notify = useNotify();- const { themeId, workflowEdgeStyle, workflowShowMinimap, workflowSnapToGrid, workflowValidateConnections } =- useWorkbenchPreferences();+ const {+ reduceMotion,+ themeId,+ workflowEdgeStyle,+ workflowShowMinimap,+ workflowSnapToGrid,+ workflowValidateConnections,+ } = useWorkbenchPreferences();const templatesSnapshot = useInvocationTemplatesSnapshot();const invocationTemplates = templatesSnapshot.status === 'loaded' ? templatesSnapshot.templates : undefined;const edgeType: FlowEdgeType = workflowEdgeStyle === 'square' ? 'step' : 'default';@@ -128,7 +132,7 @@ const WorkflowFlow = () => {toFlowNodes(projectGraph, [], invocationTemplates));const [flowEdges, setFlowEdges] = useState<WorkflowFlowEdge[]>(() =>- toFlowEdges(projectGraph, [], edgeType, new Set<string>(), invocationTemplates)+ toFlowEdges(projectGraph, [], edgeType, new Set<string>(), invocationTemplates, reduceMotion));const [flowInstance, setFlowInstance] = useState<WorkflowFlowInstance | null>(null);const [tool, setTool] = useState<EditorTool>('pan');@@ -146,10 +150,12 @@ const WorkflowFlow = () => {const selectedNodeIdSet = new Set(nodeIds);setFlowNodes((current) => withNodeSelection(current, selectedNodeIdSet));- setFlowEdges((current) => toFlowEdges(projectGraph, current, edgeType, selectedNodeIdSet, invocationTemplates));+ setFlowEdges((current) =>+ toFlowEdges(projectGraph, current, edgeType, selectedNodeIdSet, invocationTemplates, reduceMotion)+ );reportNodeSelection(nodeIds);},- [edgeType, invocationTemplates, projectGraph]+ [edgeType, invocationTemplates, projectGraph, reduceMotion]);const { lassoHandlers, lassoOverlay } = useLasso({@@ -229,12 +235,12 @@ const WorkflowFlow = () => {selectNodes(selectionRequest.nodeIds);void flowInstance.fitView({- duration: 300,+ duration: reduceMotion ? 0 : 300,maxZoom: 1.25,nodes: selectionRequest.nodeIds.map((id) => ({ id })),});clearNodeSelectionRequest();- }, [flowInstance, selectNodes, selectionRequest]);+ }, [flowInstance, reduceMotion, selectNodes, selectionRequest]);/** The context-menu node acts alone unless it is part of the current selection. */const getActionNodeIds = useCallback(@@ -292,23 +298,83 @@ const WorkflowFlow = () => {dispatch({ action: { node: buildConnectorNode(position), type: 'addNode' }, type: 'applyProjectGraphAction' });};- const onEditorKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {- if (isEditableTarget(event.target) || !(event.ctrlKey || event.metaKey)) {- return;- }+ const selectAll = () => {+ selectNodes(projectGraph.nodes.map((node) => node.id));+ };- const key = event.key.toLowerCase();+ const deleteSelection = () => {+ const nodeIds = flowNodes.filter((node) => node.selected).map((node) => node.id);+ const edgeIds = flowEdges.filter((edge) => edge.selected).map((edge) => edge.id);- if (key === 'c') {- copyNodes();- } else if (key === 'v') {- pasteNodes();- } else if (key === 'd') {- event.preventDefault();- duplicateNodes();+ if (nodeIds.length > 0) {+ dispatch({ action: { nodeIds, type: 'removeNodes' }, type: 'applyProjectGraphAction' });+ }++ if (edgeIds.length > 0) {+ dispatch({ action: { edgeIds, type: 'removeEdges' }, type: 'applyProjectGraphAction' });}};+ const executeWorkflowHotkey = useEffectEvent((commandId: string) => {+ switch (commandId) {+ case 'workflows.addNode': {+ setAddNodeOpen(true);+ return;+ }+ case 'workflows.copySelection': {+ copyNodes();+ return;+ }+ case 'workflows.pasteSelection':+ case 'workflows.pasteSelectionWithEdges': {+ pasteNodes();+ return;+ }+ case 'workflows.duplicateSelection': {+ duplicateNodes();+ return;+ }+ case 'workflows.selectAll': {+ selectAll();+ return;+ }+ case 'workflows.deleteSelection': {+ deleteSelection();+ return;+ }+ case 'workflows.undo': {+ dispatch({ type: 'undoProjectChange' });+ return;+ }+ case 'workflows.redo': {+ dispatch({ type: 'redoProjectChange' });+ return;+ }+ }+ });++ useEffect(() => {+ const hotkeys = [+ ['workflows.addNode', 'Add workflow node', ['shift+a', 'space']],+ ['workflows.copySelection', 'Copy workflow selection', ['mod+c']],+ ['workflows.pasteSelection', 'Paste workflow selection', ['mod+v']],+ ['workflows.pasteSelectionWithEdges', 'Paste workflow selection with edges', ['mod+shift+v']],+ ['workflows.duplicateSelection', 'Duplicate workflow selection', ['mod+d']],+ ['workflows.selectAll', 'Select all workflow nodes', ['mod+a']],+ ['workflows.deleteSelection', 'Delete workflow selection', ['delete', 'backspace']],+ ['workflows.undo', 'Undo workflow edit', ['mod+z']],+ ['workflows.redo', 'Redo workflow edit', ['mod+shift+z', 'mod+y']],+ ] as const;+ const disposers = hotkeys.flatMap(([id, title, defaultKeys]) => [+ runtime.commands.register({ handler: () => executeWorkflowHotkey(id), id, title }),+ runtime.hotkeys.register({ commandId: id, defaultKeys: [...defaultKeys], id, title }),+ ]);++ return () => {+ disposers.forEach((dispose) => dispose());+ };+ }, [runtime.commands, runtime.hotkeys]);+const onNodesChange = useCallback((changes: NodeChange<WorkflowFlowNode>[]) => {const removedNodeIds = changes.flatMap((change) => (change.type === 'remove' ? [change.id] : []));@@ -561,14 +627,14 @@ const WorkflowFlow = () => {'& .react-flow__node': { opacity: nodeOpacity },'& .react-flow__edge .react-flow__edge-path': {opacity: 0.38,- transition: 'opacity 0.12s ease',+ transition: 'opacity var(--wb-motion-duration-fast) ease',},'& .react-flow__edge.selected .react-flow__edge-path, & .react-flow__edge.workflow-selected-node-edge .react-flow__edge-path, & .react-flow__edge:hover .react-flow__edge-path':{opacity: 1,},'& .react-flow__edge.workflow-selected-node-edge .react-flow__edge-path': {- animation: 'dashdraw 0.5s linear infinite',+ animation: 'dashdraw var(--wb-motion-duration-slow) linear var(--wb-motion-animation-iteration-count)',strokeDasharray: '5',},...(tool === 'eraser'@@ -587,7 +653,6 @@ const WorkflowFlow = () => {position="relative"w="full"onContextMenuCapture={onEditorContextMenuCapture}- onKeyDown={onEditorKeyDown}{...pointerToolHandlers}><ReactFlow<WorkflowFlowNode, WorkflowFlowEdge>@@ -722,7 +787,7 @@ const ReadinessBanner = () => {);};-export const WorkflowEditorView = () => {+export const WorkflowEditorView = ({ runtime }: { runtime: WidgetRuntimeApi }) => {useEffect(() => {ensureInvocationTemplatesLoaded();}, []);@@ -731,7 +796,7 @@ export const WorkflowEditorView = () => {<ReactFlowProvider><Flex direction="column" h="full" minH="0" w="full"><Box flex="1" minH="0" position="relative">- <WorkflowFlow />+ <WorkflowFlow runtime={runtime} /><ReadinessBanner /></Box></Flex>