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): focus the widget a control opens
Josh Corbett087e12c9ccbf
diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsxindex ab1427c369..3b53b065c4 100644--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx@@ -18,6 +18,7 @@ import {} from '@platform/state/accountLifecycle';import { createProjectedExternalStore } from '@platform/state/projectedExternalStore';import { shallowEqual } from '@platform/state/selectors';+import { focusOpenedWidget } from '@workbench/focusRegions';import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';import { registerHotkeyModalLayer } from '@workbench/hotkeys';import {@@ -287,7 +288,11 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })project,registerModalHotkeyLayer: registerHotkeyModalLayer,widgets: {- open: (options) => commands.widgets.open(options),+ // Workflow opens widgets from its buttons: the opened widget takes focus and the region highlight.+ open: (options) => {+ commands.widgets.open(options);+ focusOpenedWidget(options.region, options.widgetId);+ },patchValues: (widgetId, values) => commands.widgets.patchValues(widgetId, values),},}),diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsxindex 89abdbe100..cb61ff405a 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx@@ -1,6 +1,6 @@import { Box, ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';-import { act } from 'react';+import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -9,7 +9,7 @@ vi.mock('./settings/store', () => ({selector({ showFocusRegionHighlight: true }),}));-import { FocusRegionProvider, useFocusRegionProps } from './focusRegions';+import { FocusRegionProvider, focusOpenedWidget, useFocusRegionProps } from './focusRegions';const FocusableRegion = () => <Box data-testid="focus-region" h="20" {...useFocusRegionProps('center')} />;@@ -50,3 +50,132 @@ describe('focus region highlight', () => {expect([highlight.top, highlight.right, highlight.bottom, highlight.left]).toEqual(['0px', '-1px', '0px', '-1px']);});});++/** A side panel whose button opens a widget in the center region, which mounts a little later as lazy widgets do. */+const OpeningHarness = ({ onOpen }: { onOpen: (open: () => void) => void }) => {+ const [isShown, setIsShown] = useState(false);+ const open = () => {+ window.setTimeout(() => setIsShown(true), 50);+ focusOpenedWidget('center', 'workflow');+ };++ return (+ <>+ <Box data-testid="left" {...useFocusRegionProps('left')}>+ <button type="button" onClick={() => onOpen(open)}>+ Open editor+ </button>+ <div data-hotkey-widget-type-id="gallery">Gallery</div>+ </Box>+ <Box data-testid="center" {...useFocusRegionProps('center')}>+ <button type="button">Center control</button>+ {isShown ? <div data-hotkey-widget-type-id="workflow">Workflow editor</div> : null}+ </Box>+ </>+ );+};++const frames = (count: number) =>+ act(async () => {+ for (let index = 0; index < count; index += 1) {+ await new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });+ }+ });++describe('focusOpenedWidget', () => {+ const renderHarness = async (onOpen: (open: () => void) => void = (open) => open()) => {+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <FocusRegionProvider>+ <OpeningHarness onOpen={onOpen} />+ </FocusRegionProvider>+ </ChakraProvider>+ );+ });+ return {+ center: host.querySelector<HTMLElement>('[data-testid="center"]')!,+ opener: [...host.querySelectorAll('button')].find((button) => button.textContent === 'Open editor')!,+ };+ };++ it('moves focus and the highlight to the region once the opened widget shows', async () => {+ const { center, opener } = await renderHarness();+ opener.focus();++ await act(() => opener.click());+ await act(+ () =>+ new Promise((resolve) => {+ window.setTimeout(resolve, 80);+ })+ );+ await frames(4);++ expect(center.contains(document.activeElement)).toBe(true);+ expect(center.getAttribute('data-highlighted')).toBe('true');+ });++ it('keeps the move when a closing menu hands focus back to the control that opened it', async () => {+ const { center, opener } = await renderHarness();+ // A menu item's menu restores focus to its trigger as it closes, after the move has landed.+ center.addEventListener('focusin', () => window.setTimeout(() => opener.focus(), 0), { once: true });+ opener.focus();++ await act(() => opener.click());+ await act(+ () =>+ new Promise((resolve) => {+ window.setTimeout(resolve, 80);+ })+ );+ await frames(6);++ expect(center.contains(document.activeElement)).toBe(true);+ });++ it('follows the last widget a control opens when it opens several', async () => {+ const { center, opener } = await renderHarness((open) => {+ open();+ focusOpenedWidget('left', 'gallery');+ });+ opener.focus();++ await act(() => opener.click());+ await act(+ () =>+ new Promise((resolve) => {+ window.setTimeout(resolve, 80);+ })+ );+ await frames(4);++ expect(center.contains(document.activeElement)).toBe(false);+ expect(document.activeElement).toBe(opener);+ });++ it('leaves focus where it is when it is already inside that region', async () => {+ const { center, opener } = await renderHarness((open) => {+ centerControl().focus();+ open();+ });+ const centerControl = () =>+ [...center.querySelectorAll('button')].find((button) => button.textContent === 'Center control')!;++ await act(() => opener.click());+ await act(+ () =>+ new Promise((resolve) => {+ window.setTimeout(resolve, 80);+ })+ );+ await frames(4);++ expect(document.activeElement).toBe(centerControl());+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex fd90e84eac..cb4cd6e579 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -86,9 +86,69 @@ export const useFocusRegionProps = (region: WidgetRegion) => {return {css: HIGHLIGHT_STYLES[region],+ 'data-focus-region': region,'data-highlighted': isHighlighted,onFocusCapture: (_event: FocusEvent<HTMLElement>) => setFocusedRegion(region),onPointerDownCapture: (_event: PointerEvent<HTMLElement>) => setFocusedRegion(region),position: 'relative' as const,};};++/** A lazy widget mounts within a few frames of opening; stop looking after about half a second. */+const OPENED_WIDGET_FRAME_BUDGET = 30;+/** Frames to keep the move after it lands: a closing menu or dialog hands focus back to its trigger on the way out. */+const OPENED_WIDGET_SETTLE_FRAMES = 30;+/** Only the latest open moves focus: a control that opens two widgets means the second one. */+let openedWidgetFocusRequest = 0;++/**+ * Moves keyboard focus into the region a control just opened a widget in, which also moves the region highlight there.+ * Leaves focus alone when it is already inside that region, and gives up if the widget never shows.+ */+export const focusOpenedWidget = (region: WidgetRegion, typeId: string): void => {+ // The control that opened the widget, where a closing menu or dialog would put focus back.+ const opener = document.activeElement;+ const request = ++openedWidgetFocusRequest;+ let frames = 0;++ const settle = (container: HTMLElement, remaining: number) => {+ if (request !== openedWidgetFocusRequest) {+ return;+ }++ const active = document.activeElement;++ if (!container.contains(active) && (active === opener || active === document.body || active === null)) {+ container.focus({ preventScroll: true });+ }+ if (remaining > 0) {+ requestAnimationFrame(() => settle(container, remaining - 1));+ }+ };++ const attempt = () => {+ if (request !== openedWidgetFocusRequest) {+ return;+ }++ const container = document.querySelector<HTMLElement>(`[data-focus-region="${region}"]`);+ const shown = container?.querySelector(`[data-hotkey-widget-type-id="${CSS.escape(typeId)}"]`);++ if (container && shown) {+ if (!container.contains(document.activeElement)) {+ if (!container.hasAttribute('tabindex')) {+ container.tabIndex = -1;+ }+ settle(container, OPENED_WIDGET_SETTLE_FRAMES);+ }+ return;+ }++ frames += 1;+ if (frames < OPENED_WIDGET_FRAME_BUDGET) {+ requestAnimationFrame(attempt);+ }+ };++ requestAnimationFrame(attempt);+};diff --git a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.tsindex 7706d1e32f..be9b411945 100644--- a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts+++ b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts@@ -5,6 +5,7 @@ import { useCallback } from 'react';import type { WorkbenchWidgetCommands } from './workbenchStore';+import { focusOpenedWidget } from './focusRegions';import { openWidgetPlacement } from './widgetPlacementCommands';import { useOptionalWorkbenchCommands, useWorkbenchCommands } from './WorkbenchContext';import { useOptionalWorkbenchWidgetRegistry, useWorkbenchWidgetRegistry } from './WorkbenchWidgetRegistryContext';@@ -22,13 +23,29 @@ export const openWorkbenchWidget = (return result.ok ? { ok: true, region: result.region as WidgetRegion } : { ok: false, reason: 'unavailable' };};+/** For controls the user acts on: the widget they open also takes focus (see `focusOpenedWidget`). */+const openAndFocus = (+ widgets: WorkbenchWidgetCommands,+ getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[],+ widgetId: WidgetTypeId,+ options?: OpenWorkbenchWidgetOptions+): OpenWorkbenchWidgetResult => {+ const result = openWorkbenchWidget(widgets, getWidgetsForRegion, widgetId, options);++ if (result.ok) {+ focusOpenedWidget(result.region, widgetId);+ }++ return result;+};+export const useOpenWorkbenchWidget = () => {const { widgets } = useWorkbenchCommands();const { getWidgetsForRegion } = useWorkbenchWidgetRegistry();return useCallback((widgetId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult =>- openWorkbenchWidget(widgets, getWidgetsForRegion, widgetId, options),+ openAndFocus(widgets, getWidgetsForRegion, widgetId, options),[getWidgetsForRegion, widgets]);};@@ -43,7 +60,7 @@ export const useOptionalOpenWorkbenchWidget = () => {return { ok: false, reason: 'unavailable' };}- return openWorkbenchWidget(commands.widgets, registry.getWidgetsForRegion, widgetId, options);+ return openAndFocus(commands.widgets, registry.getWidgetsForRegion, widgetId, options);},[commands, registry]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 6e58105bc7..583bd6059e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -32,6 +32,7 @@ import {renderableSourceOf,} from '@workbench/canvas-engine/api';import { getCanvasOperations } from '@workbench/canvas-operations/api';+import { focusOpenedWidget } from '@workbench/focusRegions';import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';import { useNotify } from '@workbench/useNotify';@@ -620,6 +621,7 @@ const LayerMenu = ({const handleOpenProperties = useCallback(() => {widgets.open({ region: 'right', widgetId: 'layers' });+ focusOpenedWidget('right', 'layers');requestLayerProperties(layer.id);}, [layer.id, widgets]);diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mtsindex 172256dd36..e92fb1d44f 100644--- a/invokeai/frontend/webv2/vite.config.mts+++ b/invokeai/frontend/webv2/vite.config.mts@@ -83,6 +83,8 @@ const ROUTE_SHARED_MODULES = [// Group dependencies shared by the editor shell and lazy widgets to reduce boot requests.const EDITOR_BOOT_SHARED_MODULES = [+ // Shell regions, their hotkeys and every control that opens a widget read it; alone it cost a boot request.+ '/workbench/focusRegions.tsx','/features/gallery/ui/GalleryItemSearch.tsx','/app/GalleryUiAdapter.tsx','/features/generation/core/prompt/ast.ts',