Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

feat(webv2): give floating windows workbench focus and hotkeys

Josh Corbettec375001492c
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 4b5530a936..f330eef32e 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -115,6 +115,17 @@ A project places each widget instance in regions (`widgetRegions`) or in a float
The rails subscribe to placement only (`getWidgetPlacementProject` projects `floatingPlacements`), so a window's geometry, mode, and stacking change without re-rendering them. A marker is not a tab: it stays out of the sortable list, activating it raises and expands its window, and Dock and Remove live in its context menu. Marker UI exists only on the left and right rails.
+### Focus
+
+Workbench focus is transient and never persisted. `WorkbenchFocusProvider` (`workbench/WorkbenchRuntime.tsx`) owns one controller (`workbench/focusRegions.tsx`) above the UI ports, the hotkey runtime, and the shell; there is no module-level focus state. The target is a docked region or one floating instance.
+
+- Pointer-down and keyboard focus activate a region or window; hover does not. The active window carries the same accent outline, under the same preference, as a focused region, and no region is outlined while a window is active.
+- The target is fenced to the project and account it was set under and is cleared — with any focus move still waiting for its widget to mount — when the active project changes, the account changes, or the workbench unmounts. A window passes its own project id when it activates, so a late event from a project that has left the screen is refused before it can raise anything.
+- Activating a window raises it through the reducer, which is a no-op for the topmost window: focus returning from a closing dialog or popover writes nothing. Ordinary focus leaves a shaded window shaded; the explicit reveal (marker, center "Show window", recall) expands it.
+- A press inside a window also moves keyboard focus into it when focus was elsewhere, so the keys follow the outline. The floating layer renders windows in a fixed DOM order and stacks them by z-index alone: raising a window never moves its node, which would drop the focus that raised it.
+- Focus follows placement: into the window after Float and after a marker or "Show window" reveal, into the return region after Dock, and into the center when Remove gives it its view back. A focus move targets the region frame that is on screen; side regions keep earlier panels mounted but hidden.
+- Hotkeys read the same target. `HotkeyContext.focusedRegion` is `WidgetRegion | 'floating' | null`; the persisted `WidgetRegion` is unchanged. A key press is aimed at the widget under the event target first and, outside any widget's DOM, at the active floating instance or the focused region's active instance (`resolveHotkeyTarget`). A floating command source carries `region: 'floating'` and is never used to index `widgetRegions`. Generic `focused-region` shortcuts match under a window, shortcuts tied to a named docked region do not, and a floating widget's own `focused-region` contribution binds to its instance.
+
## Settings contributions
Settings are declared by their owners and presented by Workbench. Platform UI owns domain-neutral field metadata and controls; it does not own setting values or persistence. A widget manifest exposes a `settings` contribution containing localized field metadata, an ordered `quick` subset, and a deferred field binding loader. The full dialog includes every declared field. Bindings retain the owner's normalization and command path, including Gallery's size/density conversion and project/instance fencing.
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index a29d506dad..5d4d0ef1f9 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -952,16 +952,31 @@ const runFloatingWindowJourney = async (browser) => {
};
const focusedRegion = () =>
page.evaluate(() => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region'));
+ // Focus, the accent outline, and the top of the stack all name the same window.
+ const waitForActiveWindow = () =>
+ page.waitForFunction(() => {
+ const active = document.activeElement?.closest('[data-floating-window]');
+
+ return active !== null && active !== undefined && active.getAttribute('data-highlighted') === 'true';
+ });
+ const waitForFocusedRegion = (region) =>
+ page.waitForFunction(
+ (expected) =>
+ document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region') === expected,
+ region
+ );
await floatPreviewFromRail();
+ await waitForActiveWindow();
await center.getByText('Preview is in a floating window', { exact: true }).waitFor();
await waitForSettledDocument(page);
await assertNoAxeViolations(page, `${id}:floating`);
- // The marker is a keyboard stop with a visible focus ring, and it shows the window rather than docking it.
+ // The marker is a keyboard stop, and it shows the window rather than docking it.
await marker.focus();
await page.keyboard.press('Enter');
assert.equal(await floatingWindow.count(), 1, 'Activating the marker must keep the window floating.');
+ await waitForActiveWindow();
await marker.click({ button: 'right' });
assert.deepEqual(await page.getByRole('menuitem').allInnerTexts(), ['Dock to right panel', 'Remove Preview']);
@@ -969,19 +984,25 @@ const runFloatingWindowJourney = async (browser) => {
await centerViewTrigger(page, 'Preview').waitFor();
await floatingWindow.waitFor({ state: 'detached' });
assert.equal(await marker.count(), 0, 'Removing the window must free its rail slot.');
- await page.waitForFunction(
- () => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region') === 'center'
- );
+ await waitForFocusedRegion('center');
await floatPreviewFromRail();
+ await waitForActiveWindow();
await center.getByRole('button', { exact: true, name: 'Dock to right panel' }).click();
await centerViewTrigger(page, 'Preview').waitFor();
await floatingWindow.waitFor({ state: 'detached' });
await rail.getByRole('button', { exact: true, name: 'Preview' }).waitFor();
- await page.waitForFunction(
- () => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region') === 'center'
- );
+ await waitForFocusedRegion('center');
assert.equal(await focusedRegion(), 'center');
+
+ // Docking brought Preview to the front of the right panel. Float it again: docking from the window's own
+ // control returns focus to that panel.
+ await page.getByRole('button', { exact: true, name: 'Float Window' }).click();
+ await floatingWindow.waitFor();
+ await waitForActiveWindow();
+ await floatingWindow.getByRole('button', { exact: true, name: 'Dock to right panel' }).click();
+ await floatingWindow.waitFor({ state: 'detached' });
+ await waitForFocusedRegion('right');
await waitForSettledDocument(page);
await assertNoAxeViolations(page, `${id}:docked`);
diff --git a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
index a7a2d4e8ca..468355c40e 100644
--- a/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkbenchApp.tsx
@@ -10,7 +10,7 @@ import { WorkbenchShell } from '@workbench/shell';
import { WidgetHosts } from '@workbench/widget-frame/WidgetHosts';
import { getWidgetById, getWidgetsForRegion } from '@workbench/widgetRegistry';
import { WorkbenchProvider } from '@workbench/WorkbenchContext';
-import { WorkbenchRuntime } from '@workbench/WorkbenchRuntime';
+import { WorkbenchFocusProvider, WorkbenchRuntime } from '@workbench/WorkbenchRuntime';
import { WorkbenchSessionController } from '@workbench/WorkbenchSessionController';
import { WorkbenchWidgetRegistryProvider } from '@workbench/WorkbenchWidgetRegistryContext';
import { useMemo } from 'react';
@@ -43,16 +43,19 @@ export const WorkbenchApp = () => {
<GenerateWidgetSyncRuntime />
<LLMTaskProgressRuntime />
<RecallParametersRuntime />
- <WorkbenchUiPorts>
- <WorkbenchHotkeyRuntime />
- <WorkbenchCommandPalette />
- <QueueRuntimeAdapter />
- <GalleryRealtimeRuntime />
- <WorkbenchRuntime />
- <WorkbenchSessionController search={search} />
- <WidgetHosts />
- <WorkbenchShell />
- </WorkbenchUiPorts>
+ {/* Above the UI ports, the hotkey runtime, and the shell: they all read and move the same focus. */}
+ <WorkbenchFocusProvider>
+ <WorkbenchUiPorts>
+ <WorkbenchHotkeyRuntime />
+ <WorkbenchCommandPalette />
+ <QueueRuntimeAdapter />
+ <GalleryRealtimeRuntime />
+ <WorkbenchRuntime />
+ <WorkbenchSessionController search={search} />
+ <WidgetHosts />
+ <WorkbenchShell />
+ </WorkbenchUiPorts>
+ </WorkbenchFocusProvider>
</WorkbenchWidgetRegistryProvider>
</WorkbenchProvider>
);
diff --git a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
index 9e7a2ef798..2b094a3f1f 100644
--- a/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
+++ b/invokeai/frontend/webv2/src/app/WorkflowUiAdapter.tsx
@@ -18,7 +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 { useWorkbenchFocus } from '@workbench/focusRegions';
import { resolveAndSubmitGraphPreviewInvocation } from '@workbench/graphPreviewInvocation';
import { registerHotkeyModalLayer } from '@workbench/hotkeys';
import { useFindGalleryItem } from '@workbench/image-actions/useFindGalleryItem';
@@ -192,6 +192,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
const commands = useWorkbenchCommands();
const queries = useWorkbenchQueries();
const notify = useNotify();
+ const { focusRegion } = useWorkbenchFocus();
useMountEffect(() => {
void ensureModelsLoaded();
@@ -296,7 +297,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
// 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);
+ focusRegion(options.region, options.widgetId);
},
patchValues: (widgetId, values) => commands.widgets.patchValues(widgetId, values),
},
@@ -305,6 +306,7 @@ export const WorkflowUiAdapterProvider = ({ children }: { children: ReactNode })
capabilities,
commands,
findInGallery,
+ focusRegion,
notify.error,
notify.info,
notify.success,
diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
index 5910b5fda5..973994dc8c 100644
--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx
@@ -1,6 +1,11 @@
+import type { ReactNode } from 'react';
+
import { useMountEffect } from '@platform/react/useMountEffect';
+import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
+import { useState } from 'react';
import { createCanvasDimsSync } from './canvasDimsSync';
+import { createWorkbenchFocusController, FocusRegionProvider } from './focusRegions';
import { useWorkbenchInternalStore } from './WorkbenchContext';
/** Workbench-owned lifecycle adapter for aggregate-local synchronization. Cross-module adapters are constructed by App. */
@@ -17,3 +22,34 @@ export const WorkbenchRuntime = () => {
return null;
};
+
+/**
+ * Owns workbench focus for everything below it — the shell and the hotkey runtime read the same target. Focus is
+ * transient: it is forgotten, along with any focus move still in flight, when the project on screen changes, the
+ * account changes, or the workbench unmounts.
+ */
+export const WorkbenchFocusProvider = ({ children }: { children: ReactNode }) => {
+ const store = useWorkbenchInternalStore();
+ const [controller] = useState(() => createWorkbenchFocusController(() => store.getSnapshot().activeProject.id));
+
+ useMountEffect(() => {
+ let projectId = store.getSnapshot().activeProject.id;
+ const unsubscribe = store.subscribe(() => {
+ const nextProjectId = store.getSnapshot().activeProject.id;
+
+ if (nextProjectId !== projectId) {
+ projectId = nextProjectId;
+ controller.clear();
+ }
+ });
+ const unregister = registerAccountOwnedResource({ clear: controller.clear, name: 'workbench-focus' });
+
+ return () => {
+ unsubscribe();
+ unregister();
+ controller.clear();
+ };
+ });
+
+ return <FocusRegionProvider controller={controller}>{children}</FocusRegionProvider>;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx
index cb61ff405a..d796989015 100644
--- a/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx
@@ -9,7 +9,14 @@ vi.mock('./settings/store', () => ({
selector({ showFocusRegionHighlight: true }),
}));
-import { FocusRegionProvider, focusOpenedWidget, useFocusRegionProps } from './focusRegions';
+import {
+ createWorkbenchFocusController,
+ FocusRegionProvider,
+ useFloatingWindowFocus,
+ useFocusRegionProps,
+ useWorkbenchFocus,
+ type WorkbenchFocusController,
+} from './focusRegions';
const FocusableRegion = () => <Box data-testid="focus-region" h="20" {...useFocusRegionProps('center')} />;
@@ -52,17 +59,20 @@ describe('focus region highlight', () => {
});
/** 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 }) => {
+type FocusRegion = WorkbenchFocusController['focusRegion'];
+
+const OpeningHarness = ({ onOpen }: { onOpen: (open: () => void, focusRegion: FocusRegion) => void }) => {
const [isShown, setIsShown] = useState(false);
+ const { focusRegion } = useWorkbenchFocus();
const open = () => {
window.setTimeout(() => setIsShown(true), 50);
- focusOpenedWidget('center', 'workflow');
+ focusRegion('center', 'workflow');
};
return (
<>
<Box data-testid="left" {...useFocusRegionProps('left')}>
- <button type="button" onClick={() => onOpen(open)}>
+ <button type="button" onClick={() => onOpen(open, focusRegion)}>
Open editor
</button>
<div data-hotkey-widget-type-id="gallery">Gallery</div>
@@ -84,8 +94,8 @@ const frames = (count: number) =>
}
});
-describe('focusOpenedWidget', () => {
- const renderHarness = async (onOpen: (open: () => void) => void = (open) => open()) => {
+describe('focusRegion', () => {
+ const renderHarness = async (onOpen: (open: () => void, focusRegion: FocusRegion) => void = (open) => open()) => {
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -140,9 +150,9 @@ describe('focusOpenedWidget', () => {
});
it('follows the last widget a control opens when it opens several', async () => {
- const { center, opener } = await renderHarness((open) => {
+ const { center, opener } = await renderHarness((open, focusRegion) => {
open();
- focusOpenedWidget('left', 'gallery');
+ focusRegion('left', 'gallery');
});
opener.focus();
@@ -179,3 +189,182 @@ describe('focusOpenedWidget', () => {
expect(document.activeElement).toBe(centerControl());
});
});
+
+/** A side region as the shell renders it: the panel shown before stays mounted but hidden beside the current one. */
+const KeptPanelsHarness = () => {
+ const { focusRegion } = useWorkbenchFocus();
+ const hiddenPanel = useFocusRegionProps('right');
+ const shownPanel = useFocusRegionProps('right');
+
+ return (
+ <>
+ <button type="button" onClick={() => focusRegion('right', 'layers')}>
+ Open layers
+ </button>
+ <Box data-testid="hidden-panel" display="none" {...hiddenPanel}>
+ <div data-hotkey-widget-type-id="gallery">Gallery</div>
+ </Box>
+ <Box data-testid="shown-panel" {...shownPanel}>
+ <div data-hotkey-widget-type-id="layers">Layers</div>
+ </Box>
+ </>
+ );
+};
+
+describe('focusRegion with kept-alive panels', () => {
+ it('moves focus into the panel on screen, not a hidden one kept mounted in the same region', async () => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <FocusRegionProvider>
+ <KeptPanelsHarness />
+ </FocusRegionProvider>
+ </ChakraProvider>
+ );
+ });
+ const opener = host.querySelector('button')!;
+ opener.focus();
+
+ await act(() => opener.click());
+ await frames(3);
+
+ expect(document.activeElement).toBe(host.querySelector('[data-testid="shown-panel"]'));
+ });
+});
+
+/** A docked region beside a floating window that shows a little later, as a lazily loaded window does. */
+const WindowHarness = ({ isWindowShown, windowProjectId }: { isWindowShown: boolean; windowProjectId: string }) => (
+ <>
+ <Box data-testid="region" {...useFocusRegionProps('left')}>
+ <button type="button">Region control</button>
+ </Box>
+ {isWindowShown ? <WindowStub projectId={windowProjectId} /> : null}
+ </>
+);
+
+const WindowStub = ({ projectId }: { projectId: string }) => {
+ const { activate, isHighlighted } = useFloatingWindowFocus('map', projectId);
+
+ return (
+ <Box
+ data-floating-window="map"
+ data-highlighted={isHighlighted}
+ data-testid="window"
+ onFocusCapture={activate}
+ onPointerDownCapture={activate}
+ >
+ <button type="button">Window control</button>
+ </Box>
+ );
+};
+
+describe('workbench focus across regions and floating windows', () => {
+ let projectId = 'project-1';
+ let controller: WorkbenchFocusController;
+
+ const renderWindowHarness = async (isWindowShown = true) => {
+ projectId = 'project-1';
+ controller = createWorkbenchFocusController(() => projectId);
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ await rerender(isWindowShown);
+ };
+ const rerender = (isWindowShown: boolean, windowProjectId = 'project-1') =>
+ act(() => {
+ root?.render(
+ <ChakraProvider value={system}>
+ <FocusRegionProvider controller={controller}>
+ <WindowHarness isWindowShown={isWindowShown} windowProjectId={windowProjectId} />
+ </FocusRegionProvider>
+ </ChakraProvider>
+ );
+ });
+ const region = () => host!.querySelector<HTMLElement>('[data-testid="region"]')!;
+ const floatingWindow = () => host!.querySelector<HTMLElement>('[data-testid="window"]');
+ const highlighted = () => ({
+ region: region().getAttribute('data-highlighted'),
+ window: floatingWindow()?.getAttribute('data-highlighted'),
+ });
+
+ it('gives the outline to whichever of a region or a window was last pressed or focused, never to both', async () => {
+ await renderWindowHarness();
+
+ await act(() => region().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+ expect(highlighted()).toEqual({ region: 'true', window: 'false' });
+
+ await act(() => floatingWindow()!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+ expect(highlighted()).toEqual({ region: 'false', window: 'true' });
+ expect(controller.getTarget()).toEqual({ instanceId: 'map', kind: 'floating' });
+
+ // Keyboard focus moves it just as a press does.
+ await act(() => region().querySelector('button')!.focus());
+ expect(highlighted()).toEqual({ region: 'true', window: 'false' });
+ await act(() => floatingWindow()!.querySelector('button')!.focus());
+ expect(highlighted()).toEqual({ region: 'false', window: 'true' });
+ });
+
+ it('does not activate a window that is only hovered', async () => {
+ await renderWindowHarness();
+ await act(() => region().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+
+ await act(() => {
+ for (const type of ['pointerover', 'pointerenter', 'pointermove', 'mouseover']) {
+ floatingWindow()!.dispatchEvent(new PointerEvent(type, { bubbles: true }));
+ }
+ });
+
+ expect(highlighted()).toEqual({ region: 'true', window: 'false' });
+ });
+
+ it('moves keyboard focus into a window once it shows, which activates it', async () => {
+ await renderWindowHarness(false);
+ const opener = region().querySelector('button')!;
+ opener.focus();
+
+ controller.focusFloating('map');
+ await frames(2);
+ await rerender(true);
+ await frames(3);
+
+ expect(floatingWindow()!.contains(document.activeElement)).toBe(true);
+ expect(highlighted()).toEqual({ region: 'false', window: 'true' });
+ });
+
+ it('refuses activation from a window of a project that has left the screen', async () => {
+ await renderWindowHarness();
+ await act(() => region().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+ projectId = 'project-2';
+ // The stale window still renders for the project it was mounted under.
+ await rerender(true, 'project-1');
+ await act(() => region().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+
+ await act(() => floatingWindow()!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+
+ expect(controller.getTarget()).toEqual({ kind: 'region', region: 'left' });
+ expect(controller.activate({ instanceId: 'map', kind: 'floating' }, 'project-1')).toBe(false);
+ });
+
+ it('forgets the target and abandons a pending focus move when the project changes', async () => {
+ await renderWindowHarness(false);
+ await act(() => region().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+ const opener = region().querySelector('button')!;
+ opener.focus();
+ controller.focusFloating('map');
+
+ // The project switches before the window ever shows. Returning to it must not resurrect the old focus.
+ projectId = 'project-2';
+ expect(controller.getTarget()).toBeNull();
+ await act(() => controller.clear());
+ projectId = 'project-1';
+ await rerender(true);
+ await frames(4);
+
+ expect(controller.getTarget()).toBeNull();
+ expect(highlighted()).toEqual({ region: 'false', window: 'false' });
+ expect(document.activeElement).toBe(opener);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx
index cb4cd6e579..8dd138e8bd 100644
--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx
@@ -1,21 +1,159 @@
import type { WidgetRegion } from '@workbench/layoutContracts';
+import type { WidgetInstanceId } from '@workbench/widgetContracts';
/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
import type { FocusEvent, PointerEvent, ReactNode } from 'react';
-import { createContext, use, useState } from 'react';
+import { captureAccountScope, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';
+import { createContext, use, useCallback, useState, useSyncExternalStore } from 'react';
import { useWorkbenchPreferenceSelector } from './settings/store';
-let focusedRegionSnapshot: WidgetRegion | null = null;
+/** What holds workbench focus: a docked region, or one floating window. */
+export type WorkbenchFocusTarget =
+ | { kind: 'region'; region: WidgetRegion }
+ | { instanceId: WidgetInstanceId; kind: 'floating' };
-export const getFocusedRegionSnapshot = (): WidgetRegion | null => focusedRegionSnapshot;
-
-interface FocusRegionContextValue {
- focusedRegion: WidgetRegion | null;
- setFocusedRegion: (region: WidgetRegion | null) => void;
+/**
+ * Transient workbench focus, owned by one provider above the shell and the hotkey runtime. It is never persisted:
+ * the outline, the hotkey target, and focus moves all read it, and it is fenced to the project and account it was
+ * set under.
+ */
+export interface WorkbenchFocusController {
+ /** Record what the user focused. Returns false for an event from a project that is no longer on screen. */
+ activate(target: WorkbenchFocusTarget, projectId?: string): boolean;
+ /** Forget the target and abandon any focus move still waiting for its widget to show. */
+ clear(): void;
+ /** Move keyboard focus into a floating window once it shows; focus arriving there activates it. */
+ focusFloating(instanceId: WidgetInstanceId): void;
+ /** Move keyboard focus into the region a control just opened a widget in, once that widget shows. */
+ focusRegion(region: WidgetRegion, typeId: string): void;
+ /** The focus target, or null once the project or account it was set under is no longer the current one. */
+ getTarget(): WorkbenchFocusTarget | null;
+ subscribe(listener: () => void): () => void;
}
-const FocusRegionContext = createContext<FocusRegionContextValue | null>(null);
+/** A lazy widget mounts within a few frames of opening; stop looking after about half a second. */
+const FOCUS_MOVE_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 FOCUS_MOVE_SETTLE_FRAMES = 30;
+
+const isSameTarget = (left: WorkbenchFocusTarget | null, right: WorkbenchFocusTarget): boolean =>
+ left !== null &&
+ (left.kind === 'region'
+ ? right.kind === 'region' && left.region === right.region
+ : right.kind === 'floating' && left.instanceId === right.instanceId);
+
+export const createWorkbenchFocusController = (getProjectId: () => string): WorkbenchFocusController => {
+ let entry: { owner: AccountScope; projectId: string; target: WorkbenchFocusTarget } | null = null;
+ // Only the latest move runs: a control that opens two widgets means the second one.
+ let focusMove = 0;
+ const listeners = new Set<() => void>();
+ const notify = () => {
+ for (const listener of listeners) {
+ listener();
+ }
+ };
+ const getTarget = (): WorkbenchFocusTarget | null =>
+ entry && entry.projectId === getProjectId() && isAccountScopeCurrent(entry.owner) ? entry.target : null;
+
+ /**
+ * Leaves focus alone when it is already inside the container, and gives up if the container never shows or the
+ * project or account changes first.
+ */
+ const moveFocus = (findContainer: () => HTMLElement | null): void => {
+ // The control that asked, where a closing menu or dialog would put focus back.
+ const opener = document.activeElement;
+ const move = ++focusMove;
+ const projectId = getProjectId();
+ const owner = captureAccountScope();
+ const isCurrent = () => move === focusMove && projectId === getProjectId() && isAccountScopeCurrent(owner);
+ let frames = 0;
+
+ const settle = (container: HTMLElement, remaining: number) => {
+ if (!isCurrent() || !container.isConnected) {
+ 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 (!isCurrent()) {
+ return;
+ }
+
+ const container = findContainer();
+
+ if (container) {
+ if (!container.contains(document.activeElement)) {
+ if (!container.hasAttribute('tabindex')) {
+ container.tabIndex = -1;
+ }
+ settle(container, FOCUS_MOVE_SETTLE_FRAMES);
+ }
+ return;
+ }
+
+ frames += 1;
+ if (frames < FOCUS_MOVE_FRAME_BUDGET) {
+ requestAnimationFrame(attempt);
+ }
+ };
+
+ requestAnimationFrame(attempt);
+ };
+
+ return {
+ activate: (target, projectId = getProjectId()) => {
+ if (projectId !== getProjectId()) {
+ return false;
+ }
+ if (!isSameTarget(getTarget(), target)) {
+ entry = { owner: captureAccountScope(), projectId, target };
+ notify();
+ }
+ return true;
+ },
+ clear: () => {
+ focusMove += 1;
+ if (entry) {
+ entry = null;
+ notify();
+ }
+ },
+ focusFloating: (instanceId) =>
+ moveFocus(() => document.querySelector<HTMLElement>(`[data-floating-window="${CSS.escape(instanceId)}"]`)),
+ focusRegion: (region, typeId) =>
+ moveFocus(() => {
+ // A side region keeps the panels it showed before mounted but hidden, each in its own region frame; only
+ // the frame on screen can take focus.
+ for (const container of document.querySelectorAll<HTMLElement>(`[data-focus-region="${region}"]`)) {
+ if (
+ container.getClientRects().length > 0 &&
+ container.querySelector(`[data-hotkey-widget-type-id="${CSS.escape(typeId)}"]`)
+ ) {
+ return container;
+ }
+ }
+
+ return null;
+ }),
+ getTarget,
+ subscribe: (listener) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ },
+ };
+};
+
+const FocusRegionContext = createContext<WorkbenchFocusController | null>(null);
const highlightBase = {
border: '1px solid',
@@ -44,111 +182,102 @@ const HIGHLIGHT_STYLES = {
right: regionHighlight('0 -1px 0 0'),
} satisfies Record<WidgetRegion, unknown>;
-export const FocusRegionProvider = ({ children }: { children: ReactNode }) => {
- const [focusedRegion, setFocusedRegion] = useState<WidgetRegion | null>(null);
- const setFocusedRegionSnapshot = (region: WidgetRegion | null) => {
- focusedRegionSnapshot = region;
- setFocusedRegion(region);
- };
+/**
+ * Provides workbench focus to everything below it. The workbench passes the controller it owns (see
+ * `WorkbenchFocusProvider`); without one the provider keeps its own, which is all an isolated subtree needs.
+ */
+export const FocusRegionProvider = ({
+ children,
+ controller,
+}: {
+ children: ReactNode;
+ controller?: WorkbenchFocusController;
+}) => {
+ const [ownController] = useState(() => controller ?? createWorkbenchFocusController(() => ''));
- return (
- <FocusRegionContext value={{ focusedRegion, setFocusedRegion: setFocusedRegionSnapshot }}>
- {children}
- </FocusRegionContext>
- );
+ return <FocusRegionContext value={controller ?? ownController}>{children}</FocusRegionContext>;
};
-const useFocusRegionContext = () => {
- const context = use(FocusRegionContext);
+const NO_FOCUS_TARGET = (): null => null;
+const subscribeToNothing = (): (() => void) => () => {};
- if (!context) {
- throw new Error('useFocusRegionProps must be used within a FocusRegionProvider.');
- }
+const useFocusTarget = (): WorkbenchFocusTarget | null => {
+ const controller = use(FocusRegionContext);
+
+ return useSyncExternalStore(
+ controller?.subscribe ?? subscribeToNothing,
+ controller?.getTarget ?? NO_FOCUS_TARGET,
+ controller?.getTarget ?? NO_FOCUS_TARGET
+ );
+};
+
+const useShowsFocusHighlight = (): boolean =>
+ useWorkbenchPreferenceSelector((preferences) => preferences.showFocusRegionHighlight);
- return context;
+const NO_FOCUS_MOVES: Pick<WorkbenchFocusController, 'focusFloating' | 'focusRegion' | 'getTarget'> = {
+ focusFloating: () => {},
+ focusRegion: () => {},
+ getTarget: NO_FOCUS_TARGET,
};
+/**
+ * Focus moves and the current target, for controls that open, float, or dock a widget and for the hotkey runtime.
+ * Outside a provider there is nothing to move focus between, so the moves do nothing.
+ */
+export const useWorkbenchFocus = (): Pick<WorkbenchFocusController, 'focusFloating' | 'focusRegion' | 'getTarget'> =>
+ use(FocusRegionContext) ?? NO_FOCUS_MOVES;
+
/**
* The region whose outline is showing, if any. Borders the outline is drawn over hide while it shows, so a shared
- * edge draws one line at any display scale.
+ * edge draws one line at any display scale. No region is outlined while a floating window holds focus.
*/
export const useHighlightedRegion = (): WidgetRegion | null => {
- const focusedRegion = use(FocusRegionContext)?.focusedRegion ?? null;
- const showFocusRegionHighlight = useWorkbenchPreferenceSelector(
- (preferences) => preferences.showFocusRegionHighlight
- );
- return showFocusRegionHighlight ? focusedRegion : null;
+ const target = useFocusTarget();
+ const showsHighlight = useShowsFocusHighlight();
+
+ return showsHighlight && target?.kind === 'region' ? target.region : null;
};
export const useFocusRegionProps = (region: WidgetRegion) => {
- const { setFocusedRegion } = useFocusRegionContext();
+ const controller = use(FocusRegionContext);
+
+ if (!controller) {
+ throw new Error('useFocusRegionProps must be used within a FocusRegionProvider.');
+ }
+
const isHighlighted = useHighlightedRegion() === region;
+ const activate = () => controller.activate({ kind: 'region', region });
return {
css: HIGHLIGHT_STYLES[region],
'data-focus-region': region,
'data-highlighted': isHighlighted,
- onFocusCapture: (_event: FocusEvent<HTMLElement>) => setFocusedRegion(region),
- onPointerDownCapture: (_event: PointerEvent<HTMLElement>) => setFocusedRegion(region),
+ onFocusCapture: (_event: FocusEvent<HTMLElement>) => activate(),
+ onPointerDownCapture: (_event: PointerEvent<HTMLElement>) => activate(),
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.
+ * Focus for one floating window. Pointer-down and keyboard focus activate it — hover does not — and `activate`
+ * reports whether the window still belongs to the project on screen, so a late event cannot raise a stale one.
*/
-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;
- }
+export const useFloatingWindowFocus = (
+ instanceId: WidgetInstanceId,
+ projectId: string
+): { activate: () => boolean; isActive: boolean; isHighlighted: boolean } => {
+ const controller = use(FocusRegionContext);
+ const target = useFocusTarget();
+ const showsHighlight = useShowsFocusHighlight();
+ const isActive = target?.kind === 'floating' && target.instanceId === instanceId;
+ const activate = useCallback(
+ () => controller?.activate({ instanceId, kind: 'floating' }, projectId) ?? true,
+ [controller, instanceId, projectId]
+ );
- frames += 1;
- if (frames < OPENED_WIDGET_FRAME_BUDGET) {
- requestAnimationFrame(attempt);
- }
+ return {
+ activate,
+ isActive,
+ isHighlighted: isActive && showsHighlight,
};
-
- requestAnimationFrame(attempt);
};
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx
index 95b53a5a9d..56927b1b63 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx
@@ -1,6 +1,6 @@
import type { WidgetContributionSource } from '@workbench/widgetContracts';
-import { getFocusedRegionSnapshot } from '@workbench/focusRegions';
+import { useWorkbenchFocus } from '@workbench/focusRegions';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import { useActiveProjectSelector, useWorkbenchExtensions } from '@workbench/WorkbenchContext';
@@ -15,7 +15,7 @@ import { useRegisterFirstPartyCommands } from './firstPartyCommands';
import { toTinykeysBinding } from './keys';
import { useIsHotkeyModalLayerActive } from './modalLayer';
import { applyCustomHotkeys, resolveHotkey } from './resolve';
-import { getHotkeyTargetWidget } from './targetWidget';
+import { getHotkeyTargetWidget, resolveHotkeyTarget } from './targetWidget';
export const getHotkeyExecutionSource = (
hotkey: Pick<RegisteredHotkey, 'scope' | 'source'>,
@@ -37,6 +37,7 @@ export const WorkbenchHotkeyRuntime = () => {
const project = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);
const extensionHotkeys = useExtensionHotkeyDefinitions();
const isModalLayerActive = useIsHotkeyModalLayerActive();
+ const focus = useWorkbenchFocus();
const registeredHotkeys = useMemo(() => {
const firstPartyHotkeys = firstPartyHotkeyCatalog.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys));
@@ -54,30 +55,13 @@ export const WorkbenchHotkeyRuntime = () => {
return;
}
- const focusedRegion = getFocusedRegionSnapshot();
- const targetWidget = getHotkeyTargetWidget(event.target);
- const activeRegion = focusedRegion ? project.widgetRegions[focusedRegion] : null;
- const activeInstanceId = targetWidget?.instanceId ?? activeRegion?.activeInstanceId ?? null;
- const activeWidgetTypeId = activeInstanceId
- ? (targetWidget?.typeId ?? project.widgetInstances[activeInstanceId]?.typeId ?? null)
- : null;
- const commandSource: WidgetContributionSource | null =
- activeInstanceId && activeWidgetTypeId && (targetWidget?.region || focusedRegion)
- ? {
- instanceId: activeInstanceId,
- projectId: project.projectId ?? '',
- region: (targetWidget?.region ?? focusedRegion)!,
- typeId: activeWidgetTypeId,
- }
- : null;
+ const { source, ...target } = resolveHotkeyTarget({
+ focusTarget: focus.getTarget(),
+ project,
+ targetWidget: getHotkeyTargetWidget(event.target),
+ });
const hotkey = resolveHotkey({
- context: {
- activeInstanceId,
- activeWidgetTypeId,
- focusedRegion,
- isModalLayerActive,
- projectId: project.projectId ?? '',
- },
+ context: { ...target, isModalLayerActive, projectId: project.projectId ?? '' },
event,
hotkeys: registeredHotkeys,
matchedKey,
@@ -91,7 +75,7 @@ export const WorkbenchHotkeyRuntime = () => {
event.preventDefault();
}
- executeHotkey(hotkey, commandSource);
+ executeHotkey(hotkey, source);
});
useEffect(() => {
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts
index badaa42210..ace48ffea7 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts
@@ -1,3 +1,5 @@
+import type { WidgetHotkeyContribution } from '@workbench/widgetContracts';
+
import { describe, expect, it } from 'vitest';
import { toExtensionHotkeyDefinition } from './extensionHotkeys';
@@ -17,4 +19,26 @@ describe('toExtensionHotkeyDefinition', () => {
})
).toMatchObject({ source });
});
+
+ it('scopes a focused-region shortcut to its docked region, or to its own window when it floats', () => {
+ const contribution: WidgetHotkeyContribution = {
+ commandId: 'test.command',
+ defaultKeys: ['mod+x'],
+ id: 'test.hotkey',
+ scope: 'focused-region',
+ title: 'Test hotkey',
+ };
+ const docked = { instanceId: 'alpha', projectId: 'project-1', region: 'right', typeId: 'test-widget' } as const;
+ const floating = { ...docked, region: 'floating' } as const;
+
+ expect(toExtensionHotkeyDefinition({ ...contribution, source: docked })?.scope).toEqual({
+ kind: 'focused-region',
+ region: 'right',
+ });
+ // A window is not a region other widgets share, so the shortcut follows this instance.
+ expect(toExtensionHotkeyDefinition({ ...contribution, source: floating })?.scope).toEqual({
+ instanceId: 'alpha',
+ kind: 'instance',
+ });
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts
index 76983df6fa..8a5fb42540 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts
@@ -35,6 +35,16 @@ export const toExtensionHotkeyDefinition = (hotkey: WidgetHotkeyContribution): H
return { ...hotkey, category: 'app', implemented: true, scope: { kind: 'focused-region', region: source.region } };
}
+ // A floating window is not a region other widgets share: "while my region is focused" means "while my window is".
+ if (scope === 'focused-region' && source?.region === 'floating') {
+ return {
+ ...hotkey,
+ category: 'app',
+ implemented: true,
+ scope: { instanceId: source.instanceId, kind: 'instance' },
+ };
+ }
+
if (source) {
return { ...hotkey, category: 'app', implemented: true, scope: { kind: 'widget', typeId: source.typeId } };
}
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts
index b01b4a9ba0..0222fe63a2 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts
@@ -123,6 +123,45 @@ describe('resolveHotkey', () => {
).toBe('focused');
});
+ it('keeps every scope working under a floating window, except shortcuts tied to a named docked region', () => {
+ const hotkey = (id: string, scope: RegisteredHotkey['scope']): RegisteredHotkey => ({
+ ...base,
+ commandId: id,
+ id,
+ scope,
+ title: id,
+ });
+ const floating = {
+ ...context,
+ activeInstanceId: 'map-1',
+ activeWidgetTypeId: 'image-map',
+ focusedRegion: 'floating',
+ } as const;
+ const global = hotkey('global', { kind: 'global' });
+ const anyRegion = hotkey('any-region', { kind: 'focused-region' });
+ const rightOnly = hotkey('right-only', { kind: 'focused-region', region: 'right' });
+ const widget = hotkey('widget', { kind: 'widget', typeId: 'image-map' });
+ const instance = hotkey('instance', { instanceId: 'map-1', kind: 'instance' });
+ const resolve = (hotkeys: RegisteredHotkey[]) =>
+ resolveHotkey({ context: floating, event, hotkeys, matchedKey: 'x' })?.commandId;
+
+ // The dock-specific shortcut never matches; the rest keep their priority order.
+ expect(resolve([global, rightOnly])).toBe('global');
+ expect(resolve([global, rightOnly, anyRegion])).toBe('any-region');
+ expect(resolve([global, rightOnly, anyRegion, widget])).toBe('widget');
+ expect(resolve([global, rightOnly, anyRegion, widget, instance])).toBe('instance');
+ expect(resolve([rightOnly])).toBeUndefined();
+ // Modal suppression is unchanged by where focus is.
+ expect(
+ resolveHotkey({
+ context: { ...floating, isModalLayerActive: true },
+ event,
+ hotkeys: [global, anyRegion, widget, instance],
+ matchedKey: 'x',
+ })
+ ).toBeNull();
+ });
+
it('does not resolve hotkeys contributed by another project source', () => {
const staleProjectHotkey: RegisteredHotkey = {
...base,
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts
index a4b245fe7a..92b073d40a 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts
@@ -1,6 +1,8 @@
+import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands';
+
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { getHotkeyTargetWidget } from './targetWidget';
+import { getHotkeyTargetWidget, resolveHotkeyTarget } from './targetWidget';
class FakeElement {
constructor(private readonly attrs: Record<string, string> | null) {}
@@ -39,3 +41,91 @@ describe('getHotkeyTargetWidget', () => {
expect(getHotkeyTargetWidget(new FakeElement(null) as unknown as EventTarget)).toBeNull();
});
});
+
+describe('resolveHotkeyTarget', () => {
+ const region = (activeInstanceId: string, instanceIds: string[] = activeInstanceId ? [activeInstanceId] : []) => ({
+ activeInstanceId,
+ instanceIds,
+ });
+ const project: WidgetPlacementProject = {
+ floatingPlacements: { map: { returnIndex: 1, returnRegion: 'right' } },
+ projectId: 'project-1',
+ widgetInstances: {
+ canvas: { id: 'canvas', typeId: 'canvas' },
+ gallery: { id: 'gallery', typeId: 'gallery' },
+ map: { id: 'map', typeId: 'image-map' },
+ },
+ // No `floating` entry exists here, so indexing the regions with a floating target would throw.
+ widgetRegions: { bottom: region(''), center: region('canvas'), left: region(''), right: region('gallery') },
+ };
+
+ it('aims at the active floating window when the key press lands outside any widget', () => {
+ expect(
+ resolveHotkeyTarget({ focusTarget: { instanceId: 'map', kind: 'floating' }, project, targetWidget: null })
+ ).toEqual({
+ activeInstanceId: 'map',
+ activeWidgetTypeId: 'image-map',
+ focusedRegion: 'floating',
+ source: { instanceId: 'map', projectId: 'project-1', region: 'floating', typeId: 'image-map' },
+ });
+ });
+
+ it('aims at the focused docked region’s active instance when the key press lands outside any widget', () => {
+ expect(
+ resolveHotkeyTarget({ focusTarget: { kind: 'region', region: 'right' }, project, targetWidget: null })
+ ).toEqual({
+ activeInstanceId: 'gallery',
+ activeWidgetTypeId: 'gallery',
+ focusedRegion: 'right',
+ source: { instanceId: 'gallery', projectId: 'project-1', region: 'right', typeId: 'gallery' },
+ });
+ });
+
+ it('prefers the widget under the event target over whatever holds focus', () => {
+ const target = resolveHotkeyTarget({
+ focusTarget: { instanceId: 'map', kind: 'floating' },
+ project,
+ targetWidget: { instanceId: 'canvas', region: 'center', typeId: 'canvas' },
+ });
+
+ expect(target).toMatchObject({
+ activeInstanceId: 'canvas',
+ activeWidgetTypeId: 'canvas',
+ source: { instanceId: 'canvas', region: 'center' },
+ });
+ });
+
+ it('gives a key press inside a floating window a floating source', () => {
+ const target = resolveHotkeyTarget({
+ focusTarget: { instanceId: 'map', kind: 'floating' },
+ project,
+ targetWidget: { instanceId: 'map', region: 'floating', typeId: 'image-map' },
+ });
+
+ expect(target.focusedRegion).toBe('floating');
+ expect(target.source).toEqual({
+ instanceId: 'map',
+ projectId: 'project-1',
+ region: 'floating',
+ typeId: 'image-map',
+ });
+ });
+
+ it('ignores a floating focus whose instance no longer floats in this project', () => {
+ expect(
+ resolveHotkeyTarget({ focusTarget: { instanceId: 'gallery', kind: 'floating' }, project, targetWidget: null })
+ ).toEqual({ activeInstanceId: null, activeWidgetTypeId: null, focusedRegion: null, source: null });
+ });
+
+ it('has no widget target for a focused region that is empty, or when nothing holds focus', () => {
+ expect(
+ resolveHotkeyTarget({ focusTarget: { kind: 'region', region: 'left' }, project, targetWidget: null })
+ ).toEqual({ activeInstanceId: null, activeWidgetTypeId: null, focusedRegion: 'left', source: null });
+ expect(resolveHotkeyTarget({ focusTarget: null, project, targetWidget: null })).toEqual({
+ activeInstanceId: null,
+ activeWidgetTypeId: null,
+ focusedRegion: null,
+ source: null,
+ });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts
index 23c7ec0133..361bcd74c3 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts
@@ -1,4 +1,12 @@
-import type { WidgetInstanceId, WidgetTypeId, WorkbenchRegion } from '@workbench/widgetContracts';
+import type { WorkbenchFocusTarget } from '@workbench/focusRegions';
+import type { WidgetRegion } from '@workbench/layoutContracts';
+import type {
+ WidgetContributionSource,
+ WidgetInstanceId,
+ WidgetTypeId,
+ WorkbenchRegion,
+} from '@workbench/widgetContracts';
+import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands';
export const getHotkeyTargetWidget = (
target: EventTarget | null
@@ -16,3 +24,52 @@ export const getHotkeyTargetWidget = (
? { instanceId, region: region as WorkbenchRegion | null, typeId: typeId as WidgetTypeId }
: null;
};
+
+export interface HotkeyTarget {
+ activeInstanceId: WidgetInstanceId | null;
+ activeWidgetTypeId: WidgetTypeId | null;
+ focusedRegion: WidgetRegion | 'floating' | null;
+ /** The widget a scoped command runs against; a floating window's source carries `region: 'floating'`. */
+ source: WidgetContributionSource | null;
+}
+
+/**
+ * What a key press is aimed at. The widget under the event target wins; outside any widget's DOM the press falls
+ * back to whatever holds workbench focus — the active floating window, or the active instance of the focused
+ * docked region. A floating target is never used to index `widgetRegions`, and is ignored once its instance no
+ * longer floats in this project.
+ */
+export const resolveHotkeyTarget = ({
+ focusTarget,
+ project,
+ targetWidget,
+}: {
+ focusTarget: WorkbenchFocusTarget | null;
+ project: WidgetPlacementProject;
+ targetWidget: ReturnType<typeof getHotkeyTargetWidget>;
+}): HotkeyTarget => {
+ const focus =
+ focusTarget?.kind === 'floating' && !project.floatingPlacements?.[focusTarget.instanceId] ? null : focusTarget;
+ const focusedRegion = focus === null ? null : focus.kind === 'floating' ? 'floating' : focus.region;
+ const focusedInstanceId =
+ focus === null
+ ? null
+ : focus.kind === 'floating'
+ ? focus.instanceId
+ : project.widgetRegions[focus.region].activeInstanceId;
+ const activeInstanceId = targetWidget?.instanceId ?? (focusedInstanceId || null);
+ const activeWidgetTypeId = activeInstanceId
+ ? (targetWidget?.typeId ?? project.widgetInstances[activeInstanceId]?.typeId ?? null)
+ : null;
+ const region = targetWidget?.region ?? focusedRegion;
+
+ return {
+ activeInstanceId,
+ activeWidgetTypeId,
+ focusedRegion,
+ source:
+ activeInstanceId && activeWidgetTypeId && region
+ ? { instanceId: activeInstanceId, projectId: project.projectId ?? '', region, typeId: activeWidgetTypeId }
+ : null,
+ };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts
index edeb9fe0b8..6e43fe3680 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts
@@ -30,7 +30,8 @@ export interface RegisteredHotkey extends HotkeyDefinition {
}
export interface HotkeyContext {
- focusedRegion: WidgetRegion | null;
+ /** The docked region holding focus, or `'floating'` while a floating window does. Never persisted. */
+ focusedRegion: WidgetRegion | 'floating' | null;
activeInstanceId: WidgetInstanceId | null;
activeWidgetTypeId: WidgetTypeId | null;
isModalLayerActive: boolean;
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
index 88054d008f..50b07f0be5 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
@@ -57,7 +57,14 @@ const centerAreaMocks = vi.hoisted(() => {
},
};
- return { activeItem, dockFloating: vi.fn(), focusOpenedWidget: vi.fn(), project, revealFloating: vi.fn() };
+ return {
+ activeItem,
+ dockFloating: vi.fn(),
+ focusFloating: vi.fn(),
+ focusRegion: vi.fn(),
+ project,
+ revealFloating: vi.fn(),
+ };
});
vi.mock('@features/models', () => ({ useModelLoads: () => [] }));
@@ -66,9 +73,13 @@ vi.mock('@features/queue/contracts', () => ({
}));
vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));
vi.mock('@workbench/focusRegions', () => ({
- focusOpenedWidget: centerAreaMocks.focusOpenedWidget,
useFocusRegionProps: () => ({}),
useHighlightedRegion: () => null,
+ useWorkbenchFocus: () => ({
+ focusFloating: centerAreaMocks.focusFloating,
+ focusRegion: centerAreaMocks.focusRegion,
+ getTarget: () => null,
+ }),
}));
vi.mock('@workbench/widgetRegionViewModel', () => ({
// The center's placed views are exactly its docked members.
@@ -198,7 +209,8 @@ describe('CenterArea with its last view floating', () => {
centerAreaMocks.project.widgetInstances = {};
centerAreaMocks.project.widgetRegions.center = dockedCenter;
centerAreaMocks.dockFloating.mockClear();
- centerAreaMocks.focusOpenedWidget.mockClear();
+ centerAreaMocks.focusFloating.mockClear();
+ centerAreaMocks.focusRegion.mockClear();
centerAreaMocks.revealFloating.mockClear();
});
@@ -226,6 +238,8 @@ describe('CenterArea with its last view floating', () => {
});
expect(centerAreaMocks.revealFloating).toHaveBeenCalledWith('preview-instance');
+ // Showing the window also moves focus into it.
+ expect(centerAreaMocks.focusFloating).toHaveBeenCalledWith('preview-instance');
expect(centerAreaMocks.dockFloating).not.toHaveBeenCalled();
await act(async () => {
@@ -235,7 +249,7 @@ describe('CenterArea with its last view floating', () => {
expect(centerAreaMocks.dockFloating).toHaveBeenCalledWith('preview-instance');
// Docking from here restores the center view, so focus follows it.
- expect(centerAreaMocks.focusOpenedWidget).toHaveBeenCalledWith('center', 'preview');
+ expect(centerAreaMocks.focusRegion).toHaveBeenCalledWith('center', 'preview');
});
it('still reports an empty center whose view is not floating as unavailable', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
index 2aff2959ec..51f49913b5 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
@@ -9,7 +9,7 @@ import type {
import { Box, Flex, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
import { Button, IconButton, MenuContent } from '@platform/ui';
-import { focusOpenedWidget, useFocusRegionProps } from '@workbench/focusRegions';
+import { useFocusRegionProps, useWorkbenchFocus } from '@workbench/focusRegions';
import { WidgetIcon } from '@workbench/iconResolver';
import {
WidgetChromeSlotById,
@@ -446,15 +446,19 @@ const FloatedCenterView = ({
}) => {
const { t } = useTranslation();
const { widgets } = useWorkbenchCommands();
+ const { focusFloating, focusRegion } = useWorkbenchFocus();
const widget = getWidgetById(typeId);
const label = widget ? resolveWidgetInstanceLabel({ title }, widget.manifest, t) : (title ?? instanceId);
- const handleShow = useCallback(() => widgets.revealFloating(instanceId), [instanceId, widgets]);
+ const handleShow = useCallback(() => {
+ widgets.revealFloating(instanceId);
+ focusFloating(instanceId);
+ }, [focusFloating, instanceId, widgets]);
// Docking from here always gives the center its view back, so focus follows it.
const handleDock = useCallback(() => {
flushWorkbenchDrafts();
widgets.dockFloating(instanceId);
- focusOpenedWidget('center', typeId);
- }, [instanceId, typeId, widgets]);
+ focusRegion('center', typeId);
+ }, [focusRegion, instanceId, typeId, widgets]);
return (
<Flex align="center" direction="column" gap="3" h="full" justify="center" px="6" textAlign="center" w="full">
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
index 6ded587231..800f1bfdd6 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
@@ -148,9 +148,9 @@ vi.mock('@features/workflow/react', async (importOriginal) => {
};
});
vi.mock('@workbench/focusRegions', () => ({
- focusOpenedWidget: () => {},
useFocusRegionProps: () => ({}),
useHighlightedRegion: () => null,
+ useWorkbenchFocus: () => ({ focusFloating: () => {}, focusRegion: () => {}, getTarget: () => null }),
}));
vi.mock('@workbench/widgetRegionViewModel', () => ({
createWidgetRegionViewModelFromState: ({ regionState }: { regionState: { instanceIds: string[] } }) => ({
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
index ea550a5ac0..33984289b0 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
@@ -12,7 +12,7 @@ import { restrictToWindowEdges } from '@dnd-kit/modifiers';
import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
import { GalleryDragCursor, GalleryDragScope } from '@features/gallery/utility';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { focusOpenedWidget, FocusRegionProvider } from '@workbench/focusRegions';
+import { useWorkbenchFocus } from '@workbench/focusRegions';
import { WidgetIcon } from '@workbench/iconResolver';
import { PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';
import { WidgetBar, type WidgetBarGroup } from '@workbench/widget-frame';
@@ -63,6 +63,7 @@ const DND_MODIFIERS = [restrictToWindowEdges];
export const WorkbenchShell = () => {
const { notifications, widgets } = useWorkbenchCommands();
+ const { focusFloating, focusRegion } = useWorkbenchFocus();
const { t } = useTranslation();
const panels = useActiveProjectSelector((project) => project.layout.panels);
const projectName = useActiveProjectSelector((project) => project.name);
@@ -188,27 +189,36 @@ export const WorkbenchShell = () => {
[placementProject, widgets]
);
const handleDragCancel = useCallback(() => setActiveDrag(null), []);
+ // Focus follows each of these: into the window a marker shows, into the region a window docks to, and into a
+ // center that gets its view back when the window is removed.
const handleSelect = useCallback(
(region: WidgetBarGroup['region'], instanceId: string) => {
- activateRailPlacement({ instanceId, project: placementProject, region, widgets });
+ if (activateRailPlacement({ instanceId, project: placementProject, region, widgets }) === 'window') {
+ focusFloating(instanceId);
+ }
},
- [placementProject, widgets]
+ [focusFloating, placementProject, widgets]
);
const handleDock = useCallback(
(instanceId: string) => {
- dockFloatingPlacement({ instanceId, project: placementProject, widgets });
+ const typeId = placementProject.widgetInstances[instanceId]?.typeId;
+ const returnRegion = dockFloatingPlacement({ instanceId, project: placementProject, widgets });
+
+ if (returnRegion && typeId) {
+ focusRegion(returnRegion, typeId);
+ }
},
- [placementProject, widgets]
+ [focusRegion, placementProject, widgets]
);
const closeFloating = useCallback(
(instanceId: string) => {
const typeId = placementProject.widgetInstances[instanceId]?.typeId;
if (removeFloatingPlacement({ instanceId, project: placementProject, widgets })?.restoresCenter && typeId) {
- focusOpenedWidget('center', typeId);
+ focusRegion('center', typeId);
}
},
- [placementProject, widgets]
+ [focusRegion, placementProject, widgets]
);
const handleToggleLeft = useCallback(
(item: (typeof leftMenuItems)[number]) =>
@@ -274,77 +284,75 @@ export const WorkbenchShell = () => {
);
return (
- <FocusRegionProvider>
- <DndContext
- autoScroll={workbenchAutoScroll}
- collisionDetection={widgetCollisionDetection}
- modifiers={DND_MODIFIERS}
- sensors={sensors}
- onDragCancel={handleDragCancel}
- onDragEnd={handleDragEnd}
- onDragStart={handleDragStart}
- >
- <GalleryDragScope value>
- <Flex direction="column" h="100vh" w="100vw">
- <WorkbenchNotificationToaster />
- <DocumentTitleProgress />
- <TopBar />
- <ProjectConflictBanner />
- <QueueRecoveryBanner />
+ <DndContext
+ autoScroll={workbenchAutoScroll}
+ collisionDetection={widgetCollisionDetection}
+ modifiers={DND_MODIFIERS}
+ sensors={sensors}
+ onDragCancel={handleDragCancel}
+ onDragEnd={handleDragEnd}
+ onDragStart={handleDragStart}
+ >
+ <GalleryDragScope value>
+ <Flex direction="column" h="100vh" w="100vw">
+ <WorkbenchNotificationToaster />
+ <DocumentTitleProgress />
+ <TopBar />
+ <ProjectConflictBanner />
+ <QueueRecoveryBanner />
- <Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden">
- <VisuallyHidden as="h1" id="workbench-project-heading">
- {projectName}
- </VisuallyHidden>
- {/* Use a named content region: the project switcher is no longer a tablist. */}
- <Flex
- aria-labelledby="workbench-project-heading"
- flex="1"
- id={PROJECT_CONTENT_PANEL_ID}
- minH="0"
- overflow="hidden"
- role="region"
- >
- <WidgetBar
- edgeRegion={isLeftPanelShown ? 'left' : 'center'}
- groups={leftRailGroups}
- menuItems={leftMenuItems}
- side="left"
- onDock={handleDock}
- onSelect={handleSelect}
- onToggle={handleToggleLeft}
- />
- {isLeftPanelShown ? <LeftPanel instanceId={leftRegion.activeInstanceId} /> : null}
- <CenterArea />
- {isRightPanelShown ? <RightPanel instanceId={rightRegion.activeInstanceId} /> : null}
- <WidgetBar
- edgeRegion={isRightPanelShown ? 'right' : 'center'}
- groups={rightRailGroups}
- menuItems={rightMenuItems}
- side="right"
- onDock={handleDock}
- onSelect={handleSelect}
- onToggle={handleToggleRight}
- />
- </Flex>
+ <Flex aria-labelledby="workbench-project-heading" as="main" flex="1" minH="0" overflow="hidden">
+ <VisuallyHidden as="h1" id="workbench-project-heading">
+ {projectName}
+ </VisuallyHidden>
+ {/* Use a named content region: the project switcher is no longer a tablist. */}
+ <Flex
+ aria-labelledby="workbench-project-heading"
+ flex="1"
+ id={PROJECT_CONTENT_PANEL_ID}
+ minH="0"
+ overflow="hidden"
+ role="region"
+ >
+ <WidgetBar
+ edgeRegion={isLeftPanelShown ? 'left' : 'center'}
+ groups={leftRailGroups}
+ menuItems={leftMenuItems}
+ side="left"
+ onDock={handleDock}
+ onSelect={handleSelect}
+ onToggle={handleToggleLeft}
+ />
+ {isLeftPanelShown ? <LeftPanel instanceId={leftRegion.activeInstanceId} /> : null}
+ <CenterArea />
+ {isRightPanelShown ? <RightPanel instanceId={rightRegion.activeInstanceId} /> : null}
+ <WidgetBar
+ edgeRegion={isRightPanelShown ? 'right' : 'center'}
+ groups={rightRailGroups}
+ menuItems={rightMenuItems}
+ side="right"
+ onDock={handleDock}
+ onSelect={handleSelect}
+ onToggle={handleToggleRight}
+ />
</Flex>
-
- <BottomPanel />
- <StatusBar dropState={bottomDropState} />
</Flex>
- <FloatingWidgetLayer />
- <GalleryDragCursor />
- <PasteMediaRuntime />
- {/*
- * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch
- * handlers.
- */}
- <DragOverlay style={DRAG_OVERLAY_STYLE}>
- {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}
- </DragOverlay>
- </GalleryDragScope>
- </DndContext>
- </FocusRegionProvider>
+
+ <BottomPanel />
+ <StatusBar dropState={bottomDropState} />
+ </Flex>
+ <FloatingWidgetLayer />
+ <GalleryDragCursor />
+ <PasteMediaRuntime />
+ {/*
+ * Allow pointer events through the full-size drag overlay so another finger can reach Preview pinch
+ * handlers.
+ */}
+ <DragOverlay style={DRAG_OVERLAY_STYLE}>
+ {activeDrag ? <WidgetDragPreview activeDrag={activeDrag} /> : null}
+ </DragOverlay>
+ </GalleryDragScope>
+ </DndContext>
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts
index be9b411945..d0e95765df 100644
--- a/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts
+++ b/invokeai/frontend/webv2/src/workbench/useOpenWorkbenchWidget.ts
@@ -5,7 +5,7 @@ import { useCallback } from 'react';
import type { WorkbenchWidgetCommands } from './workbenchStore';
-import { focusOpenedWidget } from './focusRegions';
+import { useWorkbenchFocus } from './focusRegions';
import { openWidgetPlacement } from './widgetPlacementCommands';
import { useOptionalWorkbenchCommands, useWorkbenchCommands } from './WorkbenchContext';
import { useOptionalWorkbenchWidgetRegistry, useWorkbenchWidgetRegistry } from './WorkbenchWidgetRegistryContext';
@@ -23,17 +23,20 @@ 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`). */
+type FocusRegion = ReturnType<typeof useWorkbenchFocus>['focusRegion'];
+
+/** For controls the user acts on: the widget they open also takes focus (see `focusRegion`). */
const openAndFocus = (
widgets: WorkbenchWidgetCommands,
getWidgetsForRegion: (region: WidgetRegion) => RegisteredWidget[],
+ focusRegion: FocusRegion,
widgetId: WidgetTypeId,
options?: OpenWorkbenchWidgetOptions
): OpenWorkbenchWidgetResult => {
const result = openWorkbenchWidget(widgets, getWidgetsForRegion, widgetId, options);
if (result.ok) {
- focusOpenedWidget(result.region, widgetId);
+ focusRegion(result.region, widgetId);
}
return result;
@@ -42,17 +45,19 @@ const openAndFocus = (
export const useOpenWorkbenchWidget = () => {
const { widgets } = useWorkbenchCommands();
const { getWidgetsForRegion } = useWorkbenchWidgetRegistry();
+ const { focusRegion } = useWorkbenchFocus();
return useCallback(
(widgetId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult =>
- openAndFocus(widgets, getWidgetsForRegion, widgetId, options),
- [getWidgetsForRegion, widgets]
+ openAndFocus(widgets, getWidgetsForRegion, focusRegion, widgetId, options),
+ [focusRegion, getWidgetsForRegion, widgets]
);
};
export const useOptionalOpenWorkbenchWidget = () => {
const commands = useOptionalWorkbenchCommands();
const registry = useOptionalWorkbenchWidgetRegistry();
+ const { focusRegion } = useWorkbenchFocus();
return useCallback(
(widgetId: WidgetTypeId, options?: OpenWorkbenchWidgetOptions): OpenWorkbenchWidgetResult => {
@@ -60,8 +65,8 @@ export const useOptionalOpenWorkbenchWidget = () => {
return { ok: false, reason: 'unavailable' };
}
- return openAndFocus(commands.widgets, registry.getWidgetsForRegion, widgetId, options);
+ return openAndFocus(commands.widgets, registry.getWidgetsForRegion, focusRegion, widgetId, options);
},
- [commands, registry]
+ [commands, focusRegion, registry]
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.browser.test.tsx
new file mode 100644
index 0000000000..79b19e1885
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.browser.test.tsx
@@ -0,0 +1,99 @@
+import type { FloatingWidgetState } from '@workbench/layoutContracts';
+
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Raising a window changes how the layer stacks it. It must not change where the window sits in the DOM: moving
+ * a node drops keyboard focus from it, and focus arriving in a window is exactly what raises it.
+ */
+
+const layerMocks = vi.hoisted(() => ({
+ project: { floatingWidgets: {} as Record<string, FloatingWidgetState>, id: 'project-1' },
+}));
+
+vi.mock('@workbench/WorkbenchContext', () => ({
+ shallowEqual: Object.is,
+ useActiveProjectSelector: (selector: (project: typeof layerMocks.project) => unknown) => selector(layerMocks.project),
+}));
+
+vi.mock('./FloatingWidgetWindow', () => ({
+ FloatingWidgetWindow: ({ instanceId, stackRank }: { instanceId: string; stackRank: number }) => (
+ <button data-rank={stackRank} data-window={instanceId} type="button">
+ {instanceId}
+ </button>
+ ),
+}));
+
+import { FloatingWidgetLayer } from './FloatingWidgetLayer';
+
+const windowState = (stackOrder: number): FloatingWidgetState => ({
+ heightPx: 300,
+ mode: 'windowed',
+ returnIndex: 0,
+ returnRegion: 'right',
+ stackOrder,
+ widthPx: 300,
+ x: 0,
+ y: 0,
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const render = async (floatingWidgets: Record<string, FloatingWidgetState>) => {
+ layerMocks.project = { ...layerMocks.project, floatingWidgets };
+ await act(() => {
+ root?.render(<FloatingWidgetLayer />);
+ });
+ // The window chunk is lazy: let its import settle and the suspended layer commit.
+ await vi.waitFor(async () => {
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(host!.querySelector('[data-window]')).not.toBeNull();
+ });
+};
+const windows = () =>
+ [...host!.querySelectorAll<HTMLElement>('[data-window]')].map((element) => [
+ element.dataset.window,
+ element.dataset.rank,
+ ]);
+
+beforeEach(() => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('FloatingWidgetLayer', () => {
+ it('restacks a raised window without moving it in the DOM, so it keeps keyboard focus', async () => {
+ await render({ gallery: windowState(2), queue: windowState(1) });
+
+ expect(windows()).toEqual([
+ ['gallery', '1'],
+ ['queue', '0'],
+ ]);
+
+ const queue = host!.querySelector<HTMLElement>('[data-window="queue"]')!;
+ queue.focus();
+ // Focus arriving in the lower window raises it.
+ await render({ gallery: windowState(1), queue: windowState(2) });
+
+ expect(windows()).toEqual([
+ ['gallery', '0'],
+ ['queue', '1'],
+ ]);
+ expect(host!.querySelector('[data-window="queue"]')).toBe(queue);
+ expect(document.activeElement).toBe(queue);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx
index c3d030d2ac..a2994d27a7 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx
@@ -14,23 +14,35 @@ const EMPTY_FLOATING: Record<WidgetInstanceId, FloatingWidgetState> = {};
/**
* Render floating windows with z-order derived from stackOrder rank, keeping persisted ordering within UI layer
- * bounds.
+ * bounds. The windows render in a fixed order and stack by z-index alone: raising one must not move its DOM node,
+ * which would drop keyboard focus from the very window that focus just raised.
*/
export const FloatingWidgetLayer = () => {
const floatingWidgets = useActiveProjectSelector(
(project) => project.floatingWidgets ?? EMPTY_FLOATING,
shallowEqual
);
- const entries = Object.entries(floatingWidgets).sort(([, left], [, right]) => left.stackOrder - right.stackOrder);
+ const instanceIds = Object.keys(floatingWidgets).sort();
- if (entries.length === 0) {
+ if (instanceIds.length === 0) {
return null;
}
+ const stackRanks = new Map(
+ [...instanceIds]
+ .sort((left, right) => floatingWidgets[left].stackOrder - floatingWidgets[right].stackOrder)
+ .map((instanceId, stackRank) => [instanceId, stackRank])
+ );
+
return (
<Suspense fallback={null}>
- {entries.map(([instanceId, state], stackRank) => (
- <FloatingWidgetWindow key={instanceId} instanceId={instanceId} stackRank={stackRank} state={state} />
+ {instanceIds.map((instanceId) => (
+ <FloatingWidgetWindow
+ key={instanceId}
+ instanceId={instanceId}
+ stackRank={stackRanks.get(instanceId) ?? 0}
+ state={floatingWidgets[instanceId]}
+ />
))}
</Suspense>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
index cd23c3a0f7..2ca387821d 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
@@ -9,6 +9,11 @@ import type {
import { ChakraProvider, HStack } from '@chakra-ui/react';
import { system } from '@theme/system';
+import {
+ createWorkbenchFocusController,
+ FocusRegionProvider,
+ type WorkbenchFocusController,
+} from '@workbench/focusRegions';
import { closeWorkbenchSettings, settingsDialogStore } from '@workbench/settings/settingsDialogStore';
import i18next from 'i18next';
import { MapIcon, TagsIcon } from 'lucide-react';
@@ -153,12 +158,14 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
-const renderWindow = async (floatingState: FloatingWidgetState = state) => {
+const renderWindow = async (floatingState: FloatingWidgetState = state, controller?: WorkbenchFocusController) => {
await act(async () => {
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <FloatingWidgetWindow instanceId="image-map-instance" stackRank={0} state={floatingState} />
+ <FocusRegionProvider controller={controller}>
+ <FloatingWidgetWindow instanceId="image-map-instance" stackRank={0} state={floatingState} />
+ </FocusRegionProvider>
</ChakraProvider>
</I18nextProvider>
);
@@ -175,6 +182,7 @@ beforeEach(() => {
windowMocks.actionsRegion = null;
windowMocks.useFailingWidget = false;
windowMocks.dockFloating.mockClear();
+ windowMocks.focusFloating.mockClear();
windowMocks.setFloatingGeometry.mockClear();
host = document.createElement('div');
document.body.append(host);
@@ -292,6 +300,96 @@ describe('FloatingWidgetWindow chrome', () => {
});
});
+describe('FloatingWidgetWindow focus', () => {
+ const floatingWindow = () => host!.querySelector<HTMLElement>('[data-floating-window="image-map-instance"]')!;
+
+ it('becomes the active, outlined window on pointer-down or keyboard focus, and raises itself', async () => {
+ const controller = createWorkbenchFocusController(() => 'project-1');
+ await renderWindow(state, controller);
+
+ expect(floatingWindow().getAttribute('data-highlighted')).toBe('false');
+
+ await act(() => floatingWindow().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+
+ expect(controller.getTarget()).toEqual({ instanceId: 'image-map-instance', kind: 'floating' });
+ expect(floatingWindow().getAttribute('data-highlighted')).toBe('true');
+ expect(windowMocks.focusFloating).toHaveBeenCalledWith('image-map-instance');
+
+ controller.clear();
+ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!.focus());
+
+ expect(controller.getTarget()).toEqual({ instanceId: 'image-map-instance', kind: 'floating' });
+ });
+
+ it('takes keyboard focus from elsewhere when pressed, so keys follow the outline', async () => {
+ const outside = document.createElement('button');
+ document.body.append(outside);
+ await renderWindow(
+ state,
+ createWorkbenchFocusController(() => 'project-1')
+ );
+ outside.focus();
+
+ await act(() =>
+ host!.querySelector('[data-testid="map-body"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
+ );
+
+ expect(document.activeElement).toBe(floatingWindow());
+
+ // Focus already inside the window stays where it is.
+ const shade = host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!;
+ shade.focus();
+ await act(() =>
+ host!.querySelector('[data-testid="map-body"]')!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
+ );
+
+ expect(document.activeElement).toBe(shade);
+ outside.remove();
+ });
+
+ it('is not activated or raised by hover', async () => {
+ const controller = createWorkbenchFocusController(() => 'project-1');
+ await renderWindow(state, controller);
+
+ await act(() => {
+ for (const type of ['pointerover', 'pointerenter', 'pointermove']) {
+ floatingWindow().dispatchEvent(new PointerEvent(type, { bubbles: true }));
+ }
+ });
+
+ expect(controller.getTarget()).toBeNull();
+ expect(windowMocks.focusFloating).not.toHaveBeenCalled();
+ });
+
+ it('neither activates nor raises once its project has left the screen', async () => {
+ // The window was rendered for project-1; the controller now answers for another project.
+ const controller = createWorkbenchFocusController(() => 'project-2');
+ await renderWindow(state, controller);
+
+ await act(() => floatingWindow().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));
+ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!.focus());
+
+ expect(controller.getTarget()).toBeNull();
+ expect(windowMocks.focusFloating).not.toHaveBeenCalled();
+ });
+
+ it('can take scripted focus, and sends focus to its return region when it docks', async () => {
+ const controller = createWorkbenchFocusController(() => 'project-1');
+ const focusRegion = vi.spyOn(controller, 'focusRegion');
+ await renderWindow(state, controller);
+
+ await act(() => floatingWindow().focus());
+ expect(document.activeElement).toBe(floatingWindow());
+
+ await act(async () => {
+ host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to right panel"]')?.click();
+ await Promise.resolve();
+ });
+
+ expect(focusRegion).toHaveBeenCalledWith('right', 'image-map');
+ });
+});
+
describe('FloatingWidgetWindow gestures', () => {
const pointer = (type: string, clientX: number, clientY: number, buttons: number) =>
new PointerEvent(type, { bubbles: true, buttons, clientX, clientY, pointerId: 1 });
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx
index 60e803e8fe..eac4248472 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx
@@ -12,9 +12,10 @@ import {
FLOATING_MIN_WIDTH_PX,
type FloatingGeometry,
} from '@workbench/floatingWindows';
+import { useFloatingWindowFocus, useWorkbenchFocus } from '@workbench/focusRegions';
import { WidgetIcon } from '@workbench/iconResolver';
import { DOCK_DESTINATION_ICONS, resolveDockLabel, resolveWidgetInstanceLabel } from '@workbench/widgetLabels';
-import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
+import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';
import { ChevronsDownUpIcon, ChevronsUpDownIcon, Maximize2Icon, Minimize2Icon, TriangleAlertIcon } from 'lucide-react';
import {
@@ -87,6 +88,9 @@ export const FloatingWidgetWindow = ({
(project) => project.widgetInstances[instanceId],
areWidgetRenderInstancesEqual
);
+ const projectId = useActiveProjectId();
+ const { activate, isHighlighted } = useFloatingWindowFocus(instanceId, projectId);
+ const { focusRegion } = useWorkbenchFocus();
const windowRef = useRef<HTMLDivElement>(null);
const liveGeometryRef = useRef<FloatingGeometry | null>(null);
const startDrag = usePointerDrag();
@@ -216,12 +220,38 @@ export const FloatingWidgetWindow = ({
[commitGeometry, state]
);
- const handleFocus = useCallback(() => widgets.focusFloating(instanceId), [instanceId, widgets]);
- // Flush drafts before docking remounts the widget; registry cleanup only removes flushers.
+ // Pointer-down and keyboard focus make this the active window and raise it; hover does neither. Raising is a
+ // no-op for the topmost window, so focus returning from a closing dialog or popover writes nothing, and a late
+ // event from a project that has left the screen is refused before it can raise anything.
+ const handleActivate = useCallback(() => {
+ if (activate()) {
+ widgets.focusFloating(instanceId);
+ }
+ }, [activate, instanceId, widgets]);
+ // A press on content that takes no focus of its own (or on the title bar, whose drag prevents it) would leave
+ // keyboard focus wherever it was, and the keys would go there while this window shows as active. Presses that
+ // reach here from a menu or popover portaled out of the window keep their own focus.
+ const handlePointerDownCapture = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ const element = event.currentTarget;
+
+ handleActivate();
+ if (event.target instanceof Node && element.contains(event.target) && !element.contains(document.activeElement)) {
+ element.focus({ preventScroll: true });
+ }
+ },
+ [handleActivate]
+ );
+ const typeId = instance?.typeId;
+ // Flush drafts before docking remounts the widget; registry cleanup only removes flushers. Focus follows the
+ // widget to the region it returns to.
const handleDock = useCallback(() => {
flushWorkbenchDrafts();
widgets.dockFloating(instanceId);
- }, [instanceId, widgets]);
+ if (typeId) {
+ focusRegion(state.returnRegion, typeId);
+ }
+ }, [focusRegion, instanceId, state.returnRegion, typeId, widgets]);
const handleToggleShade = useCallback(
() => widgets.setFloatingMode(instanceId, state.mode === 'shaded' ? 'windowed' : 'shaded'),
[instanceId, state.mode, widgets]
@@ -259,20 +289,29 @@ export const FloatingWidgetWindow = ({
return (
<Flex
ref={windowRef}
+ aria-label={label}
bg="bg.subtle"
- borderColor="border.emphasized"
+ // The active window carries the same accent outline, under the same preference, as a focused region.
+ borderColor={isHighlighted ? 'accent.solid' : 'border.emphasized'}
borderWidth="1px"
direction="column"
overflow="hidden"
position="fixed"
rounded={isMaximized ? 'none' : 'md'}
+ role="group"
shadow="xl"
+ // Focusable by script only, so focus can move into a window that has just been floated or revealed.
+ tabIndex={-1}
+ transition="border-color var(--wb-motion-duration-fast) ease"
zIndex={FLOATING_BASE_Z_INDEX + stackRank}
+ data-floating-window={instanceId}
+ data-highlighted={isHighlighted}
// Mark floating widget identity and region so hotkeys target it rather than the last focused docked widget.
data-hotkey-widget-instance-id={instanceId}
data-hotkey-widget-region="floating"
data-hotkey-widget-type-id={instance.typeId}
- onPointerDownCapture={handleFocus}
+ onFocusCapture={handleActivate}
+ onPointerDownCapture={handlePointerDownCapture}
{...positionProps}
>
<HStack
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx
index 3fe547b628..32305edb8f 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFloatButton.browser.test.tsx
@@ -4,6 +4,7 @@ import type * as workbenchContext from '@workbench/WorkbenchContext';
import { ChakraProvider } from '@chakra-ui/react';
import { system } from '@theme/system';
+import { createWorkbenchFocusController, FocusRegionProvider } from '@workbench/focusRegions';
import i18next from 'i18next';
import { MapIcon } from 'lucide-react';
import { act } from 'react';
@@ -76,12 +77,17 @@ let host: HTMLDivElement | null = null;
let root: Root | null = null;
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+const focusController = createWorkbenchFocusController(() => 'project-1');
+const focusFloating = vi.spyOn(focusController, 'focusFloating');
+
const renderButton = async (region: WorkbenchRegion, allowFloating = true) => {
await act(async () => {
root?.render(
<I18nextProvider i18n={i18n}>
<ChakraProvider value={system}>
- <WidgetFloatButton instanceId="image-map-instance" manifest={manifest(allowFloating)} region={region} />
+ <FocusRegionProvider controller={focusController}>
+ <WidgetFloatButton instanceId="image-map-instance" manifest={manifest(allowFloating)} region={region} />
+ </FocusRegionProvider>
</ChakraProvider>
</I18nextProvider>
);
@@ -95,6 +101,7 @@ beforeEach(() => {
floatMocks.centerInstanceIds = ['image-map-instance'];
floatMocks.float.mockClear();
floatMocks.flushWorkbenchDrafts.mockClear();
+ focusFloating.mockClear();
host = document.createElement('div');
document.body.append(host);
root = createRoot(host);
@@ -123,6 +130,8 @@ describe('WidgetFloatButton', () => {
expect(floatMocks.flushWorkbenchDrafts.mock.invocationCallOrder[0]).toBeLessThan(
floatMocks.float.mock.invocationCallOrder[0]
);
+ // Focus follows the widget into the window it just became.
+ expect(focusFloating).toHaveBeenCalledWith('image-map-instance');
});
it('renders nothing for a widget its manifest does not allow to float', async () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
index d8a6253b1c..0feb9dd8c2 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetFrames.tsx
@@ -17,7 +17,7 @@ import { IconButton } from '@platform/ui/Button';
import { PanelHeader } from '@platform/ui/PanelHeader';
import { isResizeDragActive, ResizeHandle, subscribeResizeDrag } from '@platform/ui/ResizeHandle';
import { Tooltip } from '@platform/ui/Tooltip';
-import { useFocusRegionProps, useHighlightedRegion } from '@workbench/focusRegions';
+import { useFocusRegionProps, useHighlightedRegion, useWorkbenchFocus } from '@workbench/focusRegions';
import { isWidgetRegion } from '@workbench/layoutContracts';
import { WidgetSettingsButton } from '@workbench/settings/WidgetSettingsButton';
import { resolveWidgetInstanceLabel } from '@workbench/widgetLabels';
@@ -162,9 +162,10 @@ export const WidgetFloatButton = ({
}) => {
const { t } = useTranslation();
const { widgets } = useWorkbenchCommands();
+ const { focusFloating } = useWorkbenchFocus();
const dockableRegion = isWidgetRegion(region) && region !== 'center' ? region : undefined;
// Flush drafts before floating unmounts the docked view; preserve the clicked region as the multi-region
- // instance's dock origin.
+ // instance's dock origin. Focus follows the widget into its window.
const handleFloat = useCallback(() => {
if (!dockableRegion) {
return;
@@ -172,7 +173,8 @@ export const WidgetFloatButton = ({
flushWorkbenchDrafts();
widgets.float(instanceId, dockableRegion);
- }, [dockableRegion, instanceId, widgets]);
+ focusFloating(instanceId);
+ }, [dockableRegion, focusFloating, instanceId, widgets]);
const canFloat = Boolean(manifest.allowFloating) && dockableRegion !== undefined;
if (!canFloat) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index b03901f80f..d287a53f4f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -32,7 +32,7 @@ import {
renderableSourceOf,
} from '@workbench/canvas-engine/api';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
-import { focusOpenedWidget } from '@workbench/focusRegions';
+import { useWorkbenchFocus } from '@workbench/focusRegions';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
@@ -646,10 +646,11 @@ const LayerMenu = ({
}
}, [engine, layer.id, makeStatusError]);
+ const { focusRegion } = useWorkbenchFocus();
const handleOpenProperties = useCallback(() => {
revealProperties(layer.id);
- focusOpenedWidget('right', 'layers');
- }, [layer.id, revealProperties]);
+ focusRegion('right', 'layers');
+ }, [focusRegion, layer.id, revealProperties]);
const handleBooleanRaster = useCallback(
async (operation: BooleanRasterOperation) => {
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
index 53ec2ef36f..6bb45e04a3 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
@@ -629,6 +629,49 @@ describe('createWorkbenchStore', () => {
expect(placementWatcher.changeCount).toBe(0);
});
+ it('changes the rail-facing placement only when a window floats or docks, not while it moves, shades, or is raised', () => {
+ const store = createWorkbenchStore();
+ const placementWatcher = watchSelector(
+ store,
+ (snapshot) => getWidgetPlacementProject(snapshot.activeProject),
+ areWidgetPlacementProjectsEqual
+ );
+ const windowsWatcher = watchSelector(store, (snapshot) => snapshot.activeProject.floatingWidgets);
+
+ store.commands.widgets.float('image-map');
+ store.commands.widgets.float('gallery');
+ expect(placementWatcher.changeCount).toBe(2);
+
+ for (let step = 1; step <= 20; step += 1) {
+ store.commands.widgets.setFloatingGeometry('image-map', { heightPx: 300, widthPx: 320, x: 100 + step, y: 100 });
+ }
+ store.commands.widgets.setFloatingMode('image-map', 'shaded');
+ store.commands.widgets.focusFloating('image-map');
+ store.commands.widgets.revealFloating('gallery');
+
+ // 23 window writes, none of which reach the rails.
+ expect(windowsWatcher.changeCount).toBe(2 + 23);
+ expect(placementWatcher.changeCount).toBe(2);
+
+ store.commands.widgets.dockFloating('gallery');
+ expect(placementWatcher.changeCount).toBe(3);
+ });
+
+ it('writes nothing when focus keeps returning to the window already on top', () => {
+ const store = createWorkbenchStore();
+
+ store.commands.widgets.float('image-map');
+ store.commands.widgets.float('gallery');
+ const stateWatcher = watchSelector(store, (snapshot) => snapshot.activeProject);
+
+ // What a click inside the window, then a closing dialog or popover handing focus back, each send.
+ for (let repeat = 0; repeat < 5; repeat += 1) {
+ store.commands.widgets.focusFloating('gallery');
+ }
+
+ expect(stateWatcher.changeCount).toBe(0);
+ });
+
it('treats identical widget placement in a different project as a placement change', () => {
const store = createWorkbenchStore();
const placementWatcher = watchSelector(