Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(webv2): add desktop-style floating window interactions
Josh Corbett6d3e041dee0e
diff --git a/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdx b/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdxindex 52d43fbf31..e0be34a361 100644--- a/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/01.Workbench/01.introduction.mdx@@ -63,9 +63,11 @@ The status bar along the bottom holds small chips. Hover over **Server Status**,**Preview** and **Image Map** can float in their own windows above the rest of the workbench. Click **Float Window** in the panel's header to detach it. Then:-- Drag the title bar to move the window, and drag the corner grip to resize it.-- Double-click the title bar, or use **Collapse**, to shrink the window to just its title bar.-- **Maximize** enlarges the window; **Restore** returns it to its previous size.+- Drag the title bar to move the window, and drag any edge or corner to resize it.+- From the keyboard, focus the title bar and press the arrow keys to move the window, or focus the grip in the bottom-right corner and press the arrow keys to resize it. Hold <kbd>Shift</kbd> for larger steps; <kbd>Home</kbd> on the grip shrinks the window to its smallest size.+- Double-click the title bar, or use **Maximize**, to fill the workbench; double-click again, or use **Restore**, to return to the previous size and position. Double-clicking a collapsed window's title bar expands it.+- **Collapse** shrinks the window to just its title bar and **Expand** opens it again. The panel keeps what you were doing while collapsed.+- Click a window, or move keyboard focus into it, to make it the active one: it comes to the front and is outlined like a focused panel, and keyboard shortcuts for its panel apply to it.- The dock button in the title bar, named for where the window came from (for example **Dock to right panel**), returns the panel to the place it floated from.- The panel's dashed rail icon keeps its place while the window floats. Click it to bring the window to the front and expand it; right-click it to dock or remove the panel.diff --git a/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdx b/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdxindex cc68e01393..9badbc024b 100644--- a/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdx+++ b/docs/src/content/docs/Users Guide/09.Image Map/01.introduction.mdx@@ -67,7 +67,7 @@ upper right-hand of the panel.When you open the Image Map in the right rail, a floating window iconwill appear at the far right of its title bar. Click on this to popthe window out. You can then move it around the screen and resize the-floating window by dragging its bottom right corner.+floating window by dragging any of its edges or corners.### Semantic searchdiff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.mdindex f330eef32e..12db711c38 100644--- a/invokeai/frontend/webv2/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/ARCHITECTURE.md@@ -119,12 +119,23 @@ The rails subscribe to placement only (`getWidgetPlacementProject` projects `floWorkbench 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.+- **One judge of the target.** `getTarget()` returns the target only while it describes something on screen: set under the current project and account, and — for a window — still floating. The provider also clears eagerly when the active project changes, the account changes, or the workbench unmounts; that is what notifies subscribers and abandons a focus move still waiting for its widget to mount. Returning to a project never brings old focus back.+- **Activation.** 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. A window passes the project id it was rendered for, so a late event from a project that has left the screen is refused before it can raise anything.+- **Raising.** A press inside a window always asks the reducer to raise it, which is a no-op for the topmost window. Focus raises a window only when it makes that window the active one: focus moving around inside the already-active window, or 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.+- **Recall is the one reveal that moves no focus.** A recall raises and expands its window but leaves keyboard focus, the outline, and the hotkey target where the user had them; the next press or focus change brings them back into agreement. Because focus inside the active window does not re-raise, it cannot re-bury the window a recall just revealed.+- **Keys follow the outline.** A press inside a window moves keyboard focus into it when focus was elsewhere, and a press on a docked region pulls focus out of a floating window. 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 after Remove into the center when it gets its view back, otherwise into the window's own rail. A focus move targets the region frame that is on screen (side regions keep earlier panels mounted but hidden), waits a bounded time for its widget to mount, and is abandoned if the user presses somewhere else first.+- **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 member (`resolveHotkeyTarget`). A region's active pointer counts only while it names a member, so a view that floated out of an emptied center answers as a window, not as the center. 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 follows its window at the same priority it has when docked.++### Window interactions++- **Geometry is stored once and adapted in CSS.** Every window shares one static rule set; the stored geometry and stacking rank arrive as inline custom properties (registered as non-inheriting, so a drag restyles the window and not the widget inside it), so a commit changes values rather than minting a class. The position keeps a 48px sliver reachable (`FLOATING_VIEWPORT_MARGIN_PX`, the same margin `clampWindowToViewport` applies to commits) and the displayed size is capped to the viewport. A viewport that shrinks therefore persists nothing; the stored geometry applies again when there is room.+- **Gestures start from the rendered rectangle**, not the stored geometry, so a window CSS is clamping or capping does not jump. A gesture commits only what it changed: a move keeps the stored size, and a resize keeps the stored values of any axis it did not change (`commitResizedAxes`), because what is on screen there may only be the viewport's clamp or cap. A press that never moves, or a drag against the minimum or the cap, commits nothing. Keyboard steps follow the same rules.+- **One commit per gesture.** Pointer moves are coalesced to animation frames and previewed as inline custom properties on the window element; the store is written once, when the gesture ends — on release, or when the pointer is taken away (`pointercancel`, a release the page never saw), which keeps what was dragged so far. Escape discards the preview. Each keyboard step is its own commit.+- **Resize handles.** Eight pointer-only handles (four edges, four corners) straddle the border with matching cursors and non-overlapping hit areas, above an isolated content frame so widget stacking cannot cover them. Inside the bottom-right corner sits the `ResizeCorner`, the single labelled, keyboard-operable resize control; the pointer-only handle there is clipped to the band outside the border. `resizeFloatingGeometry` anchors the opposite side, holds the size between the minimum and the viewport, and stops the top edge at the viewport's top.+- **One gesture path.** The title bar, the grip, and every handle start through the window's single pointer session, so a new gesture replaces the one before it and resize gestures all raise the platform's resize-drag signal. The preview names the mode the gesture began in and applies only while the window is still in that mode: a window that maximizes or collapses under a gesture shows its new frame at once, and the gesture ends itself — releasing the drag cursor and committing nothing — the next time it hears from the pointer. Docking, removing, or switching project unmounts the host (hosts are keyed by project and instance), which aborts the session.+- **Title bar.** Double-click maximizes or restores, and expands a collapsed window; Restore returns to the windowed geometry, which maximizing never touches. Collapse and Expand are explicit buttons. The label truncates first, down to its icon; contributed widget actions then shrink and clip, with room for their focus rings; the window's own controls never shrink.+- **Shaded bodies stay mounted.** A shaded body is hidden with React `Activity`, so its local state survives and no second copy mounts. Drafts are flushed before shading, docking, and removing, because hiding or unmounting an editor stops its flusher.## Settings contributionsdiff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex eaf73cefdf..c83f23a465 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2060,6 +2060,7 @@"railMarker": "{{label}}, floating window","railMarkerHint": "{{label}} is floating — click to show the window","resize": "Resize window",+ "resizeValue": "{{width}} by {{height}} pixels","restore": "Restore","shade": "Collapse","showWindow": "Show window",diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 5d4d0ef1f9..68bb5e078b 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -972,6 +972,38 @@ const runFloatingWindowJourney = async (browser) => {await waitForSettledDocument(page);await assertNoAxeViolations(page, `${id}:floating`);+ // The window is operable from the keyboard: the one labelled grip resizes it, and the title bar moves it.+ const width = async () => Math.round((await floatingWindow.boundingBox()).width);+ const left = async () => Math.round((await floatingWindow.boundingBox()).x);+ const windowedWidth = await width();+ await floatingWindow.getByRole('separator', { exact: true, name: 'Resize window' }).focus();+ await page.keyboard.press('ArrowRight');+ await page.waitForFunction(+ ([selector, expected]) => Math.round(document.querySelector(selector).getBoundingClientRect().width) === expected,+ ['[data-hotkey-widget-region="floating"]', windowedWidth + 16]+ );+ const windowedLeft = await left();+ await floatingWindow.getByLabel('Move Preview window', { exact: true }).focus();+ await page.keyboard.press('ArrowRight');+ await page.waitForFunction(+ ([selector, expected]) => Math.round(document.querySelector(selector).getBoundingClientRect().left) === expected,+ ['[data-hotkey-widget-region="floating"]', windowedLeft + 16]+ );++ // Maximize and collapse are explicit, labelled controls; each state is scanned.+ await floatingWindow.getByRole('button', { exact: true, name: 'Maximize' }).click();+ await floatingWindow.getByRole('button', { exact: true, name: 'Restore' }).waitFor();+ await waitForSettledDocument(page);+ await assertNoAxeViolations(page, `${id}:maximized`);+ await floatingWindow.getByRole('button', { exact: true, name: 'Restore' }).click();+ assert.equal(await width(), windowedWidth + 16, 'Restore must return to the windowed size.');+ await floatingWindow.getByRole('button', { exact: true, name: 'Collapse' }).click();+ await floatingWindow.getByRole('button', { exact: true, name: 'Expand' }).waitFor();+ await waitForSettledDocument(page);+ await assertNoAxeViolations(page, `${id}:collapsed`);+ await floatingWindow.getByRole('button', { exact: true, name: 'Expand' }).click();+ await floatingWindow.getByRole('button', { exact: true, name: 'Collapse' }).waitFor();+// The marker is a keyboard stop, and it shows the window rather than docking it.await marker.focus();await page.keyboard.press('Enter');@@ -1003,6 +1035,16 @@ const runFloatingWindowJourney = async (browser) => {await floatingWindow.getByRole('button', { exact: true, name: 'Dock to right panel' }).click();await floatingWindow.waitFor({ state: 'detached' });await waitForFocusedRegion('right');++ // The rail's own dock path: the marker's menu, reached from the keyboard, with focus following the panel.+ await page.getByRole('button', { exact: true, name: 'Float Window' }).click();+ await floatingWindow.waitFor();+ await waitForActiveWindow();+ await marker.focus();+ await page.keyboard.press('Shift+F10');+ await page.getByRole('menuitem', { 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/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.jsonindex 46739094d6..15a1431200 100644--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json@@ -100,6 +100,7 @@"controlLayerChecks.ts": "workbench","deferredResource.ts": "workbench","floatingWindows.ts": "workbench",+ "focusRegions.testing.ts": "workbench","focusRegions.tsx": "workbench","generationSettingsOrchestration.ts": "workbench","graphContracts.ts": "workbench",diff --git a/invokeai/frontend/webv2/src/platform/ui/ResizeHandle.tsx b/invokeai/frontend/webv2/src/platform/ui/ResizeHandle.tsxindex 72d3b04928..31c41d3d15 100644--- a/invokeai/frontend/webv2/src/platform/ui/ResizeHandle.tsx+++ b/invokeai/frontend/webv2/src/platform/ui/ResizeHandle.tsx@@ -109,11 +109,14 @@ export const beginPointerDrag = (return session;};-/** Owns one gesture at a time and ends it silently when the component unmounts. */+/**+ * Owns one gesture at a time and ends it silently when the component unmounts. The returned controller lets the+ * caller end the gesture early, without `onEnd`, when what it was dragging stops making sense.+ */export const usePointerDrag = (): ((event: ReactPointerEvent<HTMLElement>,options: PointerDragOptions-) => AbortSignal) => {+) => AbortController) => {const sessionRef = useRef<AbortController | null>(null);useMountEffect(() => () => sessionRef.current?.abort());@@ -122,7 +125,7 @@ export const usePointerDrag = (): ((sessionRef.current?.abort();const session = beginPointerDrag(event, options);sessionRef.current = session;- return session.signal;+ return session;}, []);};@@ -139,6 +142,15 @@ const setResizeActive = (isActive: boolean) => {/** True while a resize handle is being dragged; costly layout consumers may wait for it to end. */export const isResizeDragActive = (): boolean => activeResizeCount > 0;+/** Count a resize gesture a caller runs itself, from now until its session aborts. */+export const trackResizeDrag = (signal: AbortSignal): void => {+ if (signal.aborted) {+ return;+ }+ setResizeActive(true);+ signal.addEventListener('abort', () => setResizeActive(false), { once: true });+};+export const subscribeResizeDrag = (listener: () => void): (() => void) => {resizeListeners.add(listener);return () => resizeListeners.delete(listener);@@ -238,7 +250,7 @@ export const ResizeHandle = ({handle.setAttribute('data-dragging', '');setResizeActive(true);- const signal = startDrag(event, {+ const { signal } = startDrag(event, {cursor: isVertical ? 'col-resize' : 'row-resize',onEnd: (reason) => {const shouldCollapse = isArmed && reason === 'release';@@ -342,56 +354,39 @@ export const ResizeHandle = ({const toCssProperty = (property: NonNullable<ResizeHandleProps['sizeProperty']>) =>property === 'flexBasis' ? 'flex-basis' : property;-/** A window's bottom-right resize grip; the caller applies the 2D offset. */+/**+ * A window's bottom-right resize grip: the labelled, keyboard-operable handle. The caller owns the pointer+ * gesture, so it runs on the same path as the window's other handles, and marks the grip `data-dragging` while+ * it does.+ */export const ResizeCorner = ({label,+ valueMax,valueMin,valueNow,- onDragCancel,- onDragEnd,- onDragMove,+ valueText,onKeyDown,+ onPointerDown,}: {label: string;+ /** The widest the window can be; without it assistive tech assumes 100. */+ valueMax: number;valueMin: number;valueNow: number;- /** The gesture stopped without ending, e.g. the corner unmounted, or `onDragEnd` threw; undo any live preview. */- onDragCancel: () => void;- onDragEnd: (reason: PointerDragEnd) => void;- onDragMove: (deltaX: number, deltaY: number) => void;+ /** The size in words: the grip resizes two dimensions, and a separator's value carries only one. */+ valueText: string;onKeyDown: (event: ReactKeyboardEvent<HTMLDivElement>) => void;+ onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void;}) => {const styles = useSlotRecipe({ recipe: resizeHandleSlotRecipe })({ orientation: 'corner' });- const startDrag = usePointerDrag();- const onPointerDown = useCallback(- (event: ReactPointerEvent<HTMLDivElement>) => {- if (event.button !== 0) {- return;- }- const handle = event.currentTarget;- let hasEnded = false;- handle.setAttribute('data-dragging', '');- setResizeActive(true);- const onEnd = (reason: PointerDragEnd) => {- onDragEnd(reason);- hasEnded = true;- };- startDrag(event, { cursor: 'nwse-resize', onEnd, onMove: onDragMove }).addEventListener('abort', () => {- handle.removeAttribute('data-dragging');- setResizeActive(false);- if (!hasEnded) {- onDragCancel();- }- });- },- [onDragCancel, onDragEnd, onDragMove, startDrag]- );return (<chakra.divaria-label={label}+ aria-valuemax={valueMax}aria-valuemin={valueMin}aria-valuenow={valueNow}+ aria-valuetext={valueText}css={styles.handle}role="separator"tabIndex={0}diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.browser.test.tsxnew file mode 100644index 0000000000..27d25437b8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.browser.test.tsx@@ -0,0 +1,184 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { WorkbenchFocusController } from '@workbench/focusRegions';+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';++import { ChakraProvider } from '@chakra-ui/react';+import { accountLifecycle } from '@platform/state/accountLifecycle';+import { system } from '@theme/system';+import { act, useCallback } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The workbench's focus provider against a real store: focus is forgotten — and any focus move still waiting is+ * abandoned — when the project on screen changes, the account changes, the window closes, or the workbench+ * unmounts. Only the context plumbing is replaced.+ */++const runtimeMocks = vi.hoisted(() => ({ store: null as unknown as WorkbenchInternalStore }));++vi.mock('@workbench/WorkbenchContext', () => ({+ useWorkbenchInternalStore: () => runtimeMocks.store,+ useWorkbenchQueries: () => runtimeMocks.store.queries,+ useWorkbenchSubscription: () => runtimeMocks.store.subscribe,+}));++import {+ useFloatingWindowFocus,+ useFocusRegionProps,+ useWorkbenchFocus,+ useWorkbenchFocusTarget,+} from './focusRegions';+import { WorkbenchFocusProvider } from './WorkbenchRuntime';+import { createWorkbenchStore } from './workbenchStore';++type FocusApi = Pick<WorkbenchFocusController, 'focusFloating' | 'focusRegion' | 'getTarget'>;++let api: FocusApi;++/** Hands the provider's focus API to the test when it mounts. */+const Probe = () => {+ const moves = useWorkbenchFocus();+ const getTarget = useWorkbenchFocusTarget();+ const publish = useCallback(+ (node: HTMLSpanElement | null) => {+ if (node) {+ api = { ...moves, getTarget };+ }+ },+ [getTarget, moves]+ );++ return <span ref={publish} />;+};++const WindowStub = () => {+ const { activate } = useFloatingWindowFocus('image-map', runtimeMocks.store.getSnapshot().activeProject.id);+ const handlePointerDown = useCallback(() => activate({ byPointer: true }), [activate]);++ return (+ <div data-floating-window="image-map" data-testid="window" tabIndex={-1} onPointerDownCapture={handlePointerDown}>+ Image Map+ </div>+ );+};++const Harness = ({ showWindow }: { showWindow: boolean }) => (+ <>+ <Probe />+ <div data-testid="region" {...useFocusRegionProps('right')}>+ <button type="button">Region control</button>+ </div>+ {showWindow ? <WindowStub /> : null}+ </>+);++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 = (showWindow: boolean) =>+ act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <WorkbenchFocusProvider>+ <Harness showWindow={showWindow} />+ </WorkbenchFocusProvider>+ </ChakraProvider>+ );+ });+const frames = (count: number) =>+ act(async () => {+ for (let index = 0; index < count; index += 1) {+ await new Promise((resolve) => {+ requestAnimationFrame(resolve);+ });+ }+ });+const press = (testId: string) =>+ act(() =>+ host!.querySelector(`[data-testid="${testId}"]`)!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))+ );+const opener = () => host!.querySelector<HTMLButtonElement>('button')!;++beforeEach(() => {+ runtimeMocks.store = createWorkbenchStore();+ runtimeMocks.store.commands.widgets.float('image-map');+ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('WorkbenchFocusProvider', () => {+ it('forgets focus and abandons a pending move when the project changes, even after returning to it', async () => {+ const { commands, getSnapshot } = runtimeMocks.store;+ const firstProjectId = getSnapshot().activeProject.id;+ await render(false);+ await press('region');+ opener().focus();+ api.focusFloating('image-map');+ expect(api.getTarget()).toEqual({ kind: 'region', region: 'right' });++ await act(() => commands.projects.create());+ expect(getSnapshot().activeProject.id).not.toBe(firstProjectId);+ expect(api.getTarget()).toBeNull();++ // Back on the first project, where the window the move was waiting for now shows.+ await act(() => commands.projects.switchTo(firstProjectId));+ await render(true);+ await frames(4);++ expect(api.getTarget()).toBeNull();+ expect(document.activeElement).toBe(opener());+ expect(host!.querySelector('[data-testid="region"]')?.getAttribute('data-highlighted')).toBe('false');+ });++ it('forgets focus and abandons a pending move when the account changes', async () => {+ await render(false);+ await press('region');+ opener().focus();+ api.focusFloating('image-map');++ await act(() => {+ accountLifecycle.invalidate();+ });+ await render(true);+ await frames(4);++ expect(api.getTarget()).toBeNull();+ expect(document.activeElement).toBe(opener());+ });++ it('stops naming a window once it is closed or docked', async () => {+ await render(true);+ await press('window');+ expect(api.getTarget()).toEqual({ instanceId: 'image-map', kind: 'floating' });++ await act(() => runtimeMocks.store.commands.widgets.closeFloating('image-map'));++ expect(api.getTarget()).toBeNull();+ });++ it('abandons a pending move when the workbench unmounts', async () => {+ await render(false);+ const move = api.focusFloating;+ move('image-map');++ await act(() => root?.render(null));+ // A window with the awaited id shows up in whatever mounts next.+ const impostor = document.createElement('div');+ impostor.dataset.floatingWindow = 'image-map';+ document.body.append(impostor);+ await frames(4);++ expect(document.activeElement).not.toBe(impostor);+ impostor.remove();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsxindex 973994dc8c..6516431931 100644--- a/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx+++ b/invokeai/frontend/webv2/src/workbench/WorkbenchRuntime.tsx@@ -6,7 +6,7 @@ import { useState } from 'react';import { createCanvasDimsSync } from './canvasDimsSync';import { createWorkbenchFocusController, FocusRegionProvider } from './focusRegions';-import { useWorkbenchInternalStore } from './WorkbenchContext';+import { useWorkbenchInternalStore, useWorkbenchQueries, useWorkbenchSubscription } from './WorkbenchContext';/** Workbench-owned lifecycle adapter for aggregate-local synchronization. Cross-module adapters are constructed by App. */export const WorkbenchRuntime = () => {@@ -27,15 +27,24 @@ export const WorkbenchRuntime = () => {* 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.+ *+ * It lives in this module, beside the other workbench lifecycle adapter, because the editor's startup module set+ * is pinned by the architecture performance gate; a module of its own would have to be added to that baseline.*/export const WorkbenchFocusProvider = ({ children }: { children: ReactNode }) => {- const store = useWorkbenchInternalStore();- const [controller] = useState(() => createWorkbenchFocusController(() => store.getSnapshot().activeProject.id));+ const { getSnapshot } = useWorkbenchQueries();+ const subscribe = useWorkbenchSubscription();+ const [controller] = useState(() =>+ createWorkbenchFocusController({+ getProjectId: () => getSnapshot().activeProject.id,+ isFloating: (instanceId) => getSnapshot().activeProject.floatingWidgets?.[instanceId] !== undefined,+ })+ );useMountEffect(() => {- let projectId = store.getSnapshot().activeProject.id;- const unsubscribe = store.subscribe(() => {- const nextProjectId = store.getSnapshot().activeProject.id;+ let projectId = getSnapshot().activeProject.id;+ const unsubscribe = subscribe(() => {+ const nextProjectId = getSnapshot().activeProject.id;if (nextProjectId !== projectId) {projectId = nextProjectId;diff --git a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.tsindex 02566734f6..f412f59b8d 100644--- a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts@@ -412,7 +412,7 @@ describe('geometry, mode, and stacking actions', () => {state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });for (const instanceId of ['gallery', 'queue', 'gallery', 'queue', 'gallery']) {- state = workbenchReducer(state, { instanceId, type: 'focusFloatingWidget' });+ state = workbenchReducer(state, { instanceId, type: 'raiseFloatingWidget' });}const floating = getActiveProject(state).floatingWidgets;@@ -430,11 +430,11 @@ describe('geometry, mode, and stacking actions', () => {let state = floatGallery();state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });- state = workbenchReducer(state, { instanceId: 'gallery', type: 'focusFloatingWidget' });+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'raiseFloatingWidget' });const floating = getActiveProject(state).floatingWidgets;expect(floating?.gallery.stackOrder).toBeGreaterThan(floating?.queue.stackOrder ?? 0);- expect(workbenchReducer(state, { instanceId: 'gallery', type: 'focusFloatingWidget' })).toBe(state);+ expect(workbenchReducer(state, { instanceId: 'gallery', type: 'raiseFloatingWidget' })).toBe(state);});});@@ -563,7 +563,7 @@ describe('rail order around floating markers', () => {y: 300,});state = workbenchReducer(state, { instanceId: 'image-map', mode: 'shaded', type: 'setFloatingWidgetMode' });- state = workbenchReducer(state, { instanceId: 'image-map', type: 'focusFloatingWidget' });+ state = workbenchReducer(state, { instanceId: 'image-map', type: 'raiseFloatingWidget' });// The shell's selector equality: an equal projection keeps its previous snapshot, so the rails do not render.expect(areWidgetPlacementProjectsEqual(placement, getWidgetPlacementProject(getActiveProject(state)))).toBe(true);diff --git a/invokeai/frontend/webv2/src/workbench/floatingWindows.test.ts b/invokeai/frontend/webv2/src/workbench/floatingWindows.test.tsindex 0dcb5c7f38..0c4d0bff76 100644--- a/invokeai/frontend/webv2/src/workbench/floatingWindows.test.ts+++ b/invokeai/frontend/webv2/src/workbench/floatingWindows.test.ts@@ -2,7 +2,16 @@ import { describe, expect, it } from 'vitest';import type { FloatingWidgetState, WidgetRegion, WidgetRegionState } from './layoutContracts';-import { getRegionOrder, normalizeFloatingPlacement, writeRegionOrder } from './floatingWindows';+import {+ clampWindowToViewport,+ commitResizedAxes,+ FLOATING_MIN_HEIGHT_PX,+ FLOATING_MIN_WIDTH_PX,+ getRegionOrder,+ normalizeFloatingPlacement,+ resizeFloatingGeometry,+ writeRegionOrder,+} from './floatingWindows';const floating = (overrides: Partial<FloatingWidgetState> = {}): FloatingWidgetState => ({heightPx: 400,@@ -182,3 +191,95 @@ describe('normalizeFloatingPlacement', () => {expect(normalized.floatingWidgets?.a).toMatchObject({ returnIndex: 1, returnRegion: 'right' });});});++describe('resizeFloatingGeometry', () => {+ const start = { heightPx: 400, widthPx: 500, x: 100, y: 80 };++ it('moves only the dragged side, keeping the opposite one anchored', () => {+ expect(resizeFloatingGeometry(start, 'e', 40, 999)).toEqual({ ...start, widthPx: 540 });+ expect(resizeFloatingGeometry(start, 's', 999, 30)).toEqual({ ...start, heightPx: 430 });+ expect(resizeFloatingGeometry(start, 'w', -40, 999)).toEqual({ ...start, widthPx: 540, x: 60 });+ expect(resizeFloatingGeometry(start, 'n', 999, -30)).toEqual({ ...start, heightPx: 430, y: 50 });+ expect(resizeFloatingGeometry(start, 'nw', 10, 20)).toEqual({ heightPx: 380, widthPx: 490, x: 110, y: 100 });+ });++ it('stops at the minimum size without letting the anchored side drift', () => {+ const shrunk = resizeFloatingGeometry(start, 'nw', 5000, 5000);++ expect(shrunk).toEqual({+ heightPx: FLOATING_MIN_HEIGHT_PX,+ widthPx: FLOATING_MIN_WIDTH_PX,+ x: 100 + 500 - FLOATING_MIN_WIDTH_PX,+ y: 80 + 400 - FLOATING_MIN_HEIGHT_PX,+ });+ expect(resizeFloatingGeometry(start, 'se', -5000, -5000)).toEqual({+ ...start,+ heightPx: FLOATING_MIN_HEIGHT_PX,+ widthPx: FLOATING_MIN_WIDTH_PX,+ });+ });++ it('stops the top edge at the top of the viewport, growing only as far as that', () => {+ expect(resizeFloatingGeometry(start, 'n', 0, -500)).toEqual({ ...start, heightPx: 480, y: 0 });+ });+});++describe('resizeFloatingGeometry within a viewport', () => {+ const viewport = { heightPx: 500, widthPx: 600 };++ it('does not grow past the viewport, and keeps the anchored side where it is when it stops', () => {+ const start = { heightPx: 300, widthPx: 600, x: 0, y: 40 };++ // Already as wide as the viewport: dragging the left edge further left changes nothing.+ expect(resizeFloatingGeometry(start, 'w', -80, 0, viewport)).toEqual(start);+ expect(resizeFloatingGeometry(start, 'e', 80, 0, viewport)).toEqual(start);+ expect(resizeFloatingGeometry(start, 's', 0, 900, viewport)).toEqual({ ...start, heightPx: 500 });+ });+});++describe('commitResizedAxes', () => {+ // Stored for a larger display; shown clamped and capped by a 600x500 viewport.+ const stored = { heightPx: 900, widthPx: 900, x: 5000, y: 40 };+ const start = { heightPx: 500, widthPx: 600, x: 552, y: 40 };++ it('takes the resized values only on the axes the resize changed', () => {+ expect(commitResizedAxes(stored, start, { ...start, widthPx: 550 })).toEqual({ ...stored, widthPx: 550, x: 552 });+ expect(commitResizedAxes(stored, start, { ...start, heightPx: 350, y: 60 })).toEqual({+ ...stored,+ heightPx: 350,+ y: 60,+ });+ expect(commitResizedAxes(stored, start, { heightPx: 350, widthPx: 550, x: 560, y: 60 })).toEqual({+ heightPx: 350,+ widthPx: 550,+ x: 560,+ y: 60,+ });+ });++ it('commits nothing when the resize changed nothing, as a drag against the cap or the minimum does', () => {+ expect(commitResizedAxes(stored, start, { ...start })).toBeNull();+ });++ it('does not read sub-pixel arithmetic on an axis as a resize of it', () => {+ // At a fractional zoom the rectangle on screen is not on whole pixels, and the untouched axis comes back a+ // fraction off: it must keep what was stored, not take the viewport's cap.+ expect(commitResizedAxes(stored, start, { ...start, heightPx: 350, widthPx: 600.3 })).toEqual({+ ...stored,+ heightPx: 350,+ });+ expect(commitResizedAxes(stored, start, { ...start, widthPx: 599.7, x: 552.2 })).toBeNull();+ });+});++describe('clampWindowToViewport', () => {+ it('keeps a sliver of the width that is shown, not of a wider stored one', () => {+ // Shown no wider than the 600px viewport, so the left limit is 48 - 600, not 48 - 2000.+ const clamped = clampWindowToViewport(+ { heightPx: 300, widthPx: 2000, x: -1900, y: 20 },+ { height: 500, width: 600 }+ );++ expect(clamped.x).toBe(48 - 600);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/floatingWindows.ts b/invokeai/frontend/webv2/src/workbench/floatingWindows.tsindex 5737f3af2c..41bb496c56 100644--- a/invokeai/frontend/webv2/src/workbench/floatingWindows.ts+++ b/invokeai/frontend/webv2/src/workbench/floatingWindows.ts@@ -19,7 +19,7 @@ export const FLOATING_MIN_WIDTH_PX = 280;export const FLOATING_MIN_HEIGHT_PX = 200;/** Minimum sliver of a window that must stay reachable inside the viewport. */-const VIEWPORT_MARGIN_PX = 48;+export const FLOATING_VIEWPORT_MARGIN_PX = 48;const CASCADE_ORIGIN_PX = 96;const CASCADE_STEP_PX = 32;const CASCADE_WRAP = 8;@@ -54,17 +54,86 @@ export const clampSizeToMinimum = (geometry: FloatingGeometry): FloatingGeometry/*** Keep at least a grabbable corner of the window inside the viewport so a- * drag (or a shrunk browser window) can never strand it off-screen.+ * drag (or a shrunk browser window) can never strand it off-screen. The window is never shown wider than the+ * viewport, so that displayed width — not a larger stored one — is what has to stay reachable.*/export const clampWindowToViewport = (geometry: FloatingGeometry,viewport: { width: number; height: number }): FloatingGeometry => ({...geometry,- x: Math.min(Math.max(geometry.x, VIEWPORT_MARGIN_PX - geometry.widthPx), viewport.width - VIEWPORT_MARGIN_PX),- y: Math.min(Math.max(geometry.y, 0), Math.max(0, viewport.height - VIEWPORT_MARGIN_PX)),+ x: Math.min(+ Math.max(geometry.x, FLOATING_VIEWPORT_MARGIN_PX - Math.min(geometry.widthPx, viewport.width)),+ viewport.width - FLOATING_VIEWPORT_MARGIN_PX+ ),+ y: Math.min(Math.max(geometry.y, 0), Math.max(0, viewport.height - FLOATING_VIEWPORT_MARGIN_PX)),});+/**+ * What a resize commits: on each axis the resize actually changed, the result from the rectangle on screen; on an+ * axis it left alone, what was stored. An untouched axis may be showing the viewport's clamp or cap, which is not+ * the user's choice to persist. Null when the resize changed nothing — a drag against the minimum or the cap.+ */+export const commitResizedAxes = (+ stored: FloatingGeometry,+ start: FloatingGeometry,+ resized: FloatingGeometry+): FloatingGeometry | null => {+ // The rectangle on screen can sit on fractional pixels, and what is committed is whole ones: a difference under+ // half a pixel is arithmetic, not the user.+ const changed = (from: number, to: number) => Math.abs(to - from) >= 0.5;+ const horizontal = changed(start.widthPx, resized.widthPx) || changed(start.x, resized.x);+ const vertical = changed(start.heightPx, resized.heightPx) || changed(start.y, resized.y);++ return horizontal || vertical+ ? {+ heightPx: vertical ? resized.heightPx : stored.heightPx,+ widthPx: horizontal ? resized.widthPx : stored.widthPx,+ x: horizontal ? resized.x : stored.x,+ y: vertical ? resized.y : stored.y,+ }+ : null;+};++/** A window edge or corner, by compass point. */+export type FloatingResizeEdge = 'n' | 's' | 'e' | 'w' | 'ne' | 'nw' | 'se' | 'sw';++/**+ * Resize from one edge or corner by a pointer offset. The opposite side stays where it is, the size stays between+ * the minimum and `max` (the viewport, which is as large as a window is ever shown), and the top edge stops at the+ * viewport's top so the title bar stays reachable.+ */+export const resizeFloatingGeometry = (+ start: FloatingGeometry,+ edge: FloatingResizeEdge,+ deltaX: number,+ deltaY: number,+ max: { heightPx: number; widthPx: number } = { heightPx: Number.POSITIVE_INFINITY, widthPx: Number.POSITIVE_INFINITY }+): FloatingGeometry => {+ const right = start.x + start.widthPx;+ const bottom = start.y + start.heightPx;+ const clampWidth = (widthPx: number) => Math.max(FLOATING_MIN_WIDTH_PX, Math.min(widthPx, max.widthPx));+ const clampHeight = (heightPx: number) => Math.max(FLOATING_MIN_HEIGHT_PX, Math.min(heightPx, max.heightPx));+ const geometry = { ...start };++ if (edge.includes('e')) {+ geometry.widthPx = clampWidth(start.widthPx + deltaX);+ }+ if (edge.includes('w')) {+ geometry.widthPx = clampWidth(start.widthPx - deltaX);+ geometry.x = right - geometry.widthPx;+ }+ if (edge.includes('s')) {+ geometry.heightPx = clampHeight(start.heightPx + deltaY);+ }+ if (edge.includes('n')) {+ geometry.heightPx = clampHeight(Math.min(start.heightPx - deltaY, bottom));+ geometry.y = bottom - geometry.heightPx;+ }++ return geometry;+};+// Placement: where a floating window returns to. A floating instance belongs to no region's `instanceIds`; its// return region keeps a marker for it instead, and reducers, normalization, and rails all read that marker's// position here.diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.browser.test.tsxindex d796989015..92d4e94379 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, useState } from 'react';+import { act, useCallback, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { afterEach, describe, expect, it, vi } from 'vitest';@@ -10,13 +10,13 @@ vi.mock('./settings/store', () => ({}));import {- createWorkbenchFocusController,FocusRegionProvider,useFloatingWindowFocus,useFocusRegionProps,useWorkbenchFocus,type WorkbenchFocusController,} from './focusRegions';+import { createTestFocusController } from './focusRegions.testing';const FocusableRegion = () => <Box data-testid="focus-region" h="20" {...useFocusRegionProps('center')} />;@@ -40,7 +40,7 @@ describe('focus region highlight', () => {await act(() => {root?.render(<ChakraProvider value={system}>- <FocusRegionProvider>+ <FocusRegionProvider controller={createTestFocusController()}><FocusableRegion /></FocusRegionProvider></ChakraProvider>@@ -102,7 +102,7 @@ describe('focusRegion', () => {await act(() => {root?.render(<ChakraProvider value={system}>- <FocusRegionProvider>+ <FocusRegionProvider controller={createTestFocusController()}><OpeningHarness onOpen={onOpen} /></FocusRegionProvider></ChakraProvider>@@ -219,7 +219,7 @@ describe('focusRegion with kept-alive panels', () => {await act(() => {root?.render(<ChakraProvider value={system}>- <FocusRegionProvider>+ <FocusRegionProvider controller={createTestFocusController()}><KeptPanelsHarness /></FocusRegionProvider></ChakraProvider>@@ -247,14 +247,16 @@ const WindowHarness = ({ isWindowShown, windowProjectId }: { isWindowShown: boolconst WindowStub = ({ projectId }: { projectId: string }) => {const { activate, isHighlighted } = useFloatingWindowFocus('map', projectId);+ const handleFocus = useCallback(() => activate(), [activate]);+ const handlePointerDown = useCallback(() => activate({ byPointer: true }), [activate]);return (<Boxdata-floating-window="map"data-highlighted={isHighlighted}data-testid="window"- onFocusCapture={activate}- onPointerDownCapture={activate}+ onFocusCapture={handleFocus}+ onPointerDownCapture={handlePointerDown}><button type="button">Window control</button></Box>@@ -263,11 +265,13 @@ const WindowStub = ({ projectId }: { projectId: string }) => {describe('workbench focus across regions and floating windows', () => {let projectId = 'project-1';+ let isWindowFloating = true;let controller: WorkbenchFocusController;const renderWindowHarness = async (isWindowShown = true) => {projectId = 'project-1';- controller = createWorkbenchFocusController(() => projectId);+ isWindowFloating = true;+ controller = createTestFocusController({ getProjectId: () => projectId, isFloating: () => isWindowFloating });host = document.createElement('div');document.body.append(host);root = createRoot(host);@@ -307,19 +311,6 @@ describe('workbench focus across regions and floating windows', () => {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')!;@@ -345,7 +336,7 @@ describe('workbench focus across regions and floating windows', () => {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);+ expect(controller.activate({ instanceId: 'map', kind: 'floating' }, { projectId: 'project-1' })).toBe('refused');});it('forgets the target and abandons a pending focus move when the project changes', async () => {@@ -367,4 +358,48 @@ describe('workbench focus across regions and floating windows', () => {expect(highlighted()).toEqual({ region: 'false', window: 'false' });expect(document.activeElement).toBe(opener);});++ it('stops treating a window as the target once it no longer floats', async () => {+ await renderWindowHarness();+ await act(() => floatingWindow()!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));+ expect(controller.getTarget()).toEqual({ instanceId: 'map', kind: 'floating' });++ // Docked or removed, with nothing else focused since.+ isWindowFloating = false;++ expect(controller.getTarget()).toBeNull();+ });++ it('abandons a pending focus move when the user presses somewhere else first', async () => {+ await renderWindowHarness(false);+ const opener = region().querySelector('button')!;+ opener.focus();+ controller.focusFloating('map');++ // Pressing content that takes no focus of its own: focus falls to the body, where a move would reclaim it.+ await act(() => region().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));+ opener.blur();+ await rerender(true);+ await frames(4);++ expect(floatingWindow()!.contains(document.activeElement)).toBe(false);+ expect(controller.getTarget()).toEqual({ kind: 'region', region: 'left' });+ });++ it('keeps a pending focus move when focus, not a press, passes through another region', async () => {+ await renderWindowHarness(false);+ const opener = region().querySelector('button')!;+ opener.focus();++ controller.focusFloating('map');+ // A closing menu handing focus back to its trigger arrives as focus, and must not cancel the move.+ await act(() => {+ opener.blur();+ opener.focus();+ });+ await rerender(true);+ await frames(4);++ expect(floatingWindow()!.contains(document.activeElement)).toBe(true);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.testing.ts b/invokeai/frontend/webv2/src/workbench/focusRegions.testing.tsnew file mode 100644index 0000000000..80c3146f1d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.testing.ts@@ -0,0 +1,9 @@+import {+ createWorkbenchFocusController,+ type WorkbenchFocusController,+ type WorkbenchFocusScope,+} from './focusRegions';++/** A focus controller for tests that render focus-aware components outside the workbench: one project, every window floating. */+export const createTestFocusController = (scope: Partial<WorkbenchFocusScope> = {}): WorkbenchFocusController =>+ createWorkbenchFocusController({ getProjectId: () => 'project-1', isFloating: () => true, ...scope });diff --git a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx b/invokeai/frontend/webv2/src/workbench/focusRegions.tsxindex 8dd138e8bd..321b4dcec7 100644--- a/invokeai/frontend/webv2/src/workbench/focusRegions.tsx+++ b/invokeai/frontend/webv2/src/workbench/focusRegions.tsx@@ -4,7 +4,7 @@ import type { WidgetInstanceId } from '@workbench/widgetContracts';import type { FocusEvent, PointerEvent, ReactNode } from 'react';import { captureAccountScope, isAccountScopeCurrent, type AccountScope } from '@platform/state/accountLifecycle';-import { createContext, use, useCallback, useState, useSyncExternalStore } from 'react';+import { createContext, use, useCallback, useSyncExternalStore } from 'react';import { useWorkbenchPreferenceSelector } from './settings/store';@@ -19,23 +19,36 @@ export type WorkbenchFocusTarget =* 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;+ /**+ * Record what the user focused: `'activated'` when the target changed, `'unchanged'` when it already held+ * focus, `'refused'` for an event from a project that is no longer on screen. A pointer press on anything but a+ * pending focus move's destination also abandons that move: the user went somewhere else on purpose.+ */+ activate(target: WorkbenchFocusTarget, options?: { byPointer?: boolean; projectId?: string }): FocusActivation;/** 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. */+ /** The focus target, or null once it no longer describes something on screen in this project and account. */getTarget(): WorkbenchFocusTarget | null;subscribe(listener: () => void): () => void;}-/** 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;+export type FocusActivation = 'activated' | 'refused' | 'unchanged';++/** What the controller has to know about the workbench to keep its target honest. */+export interface WorkbenchFocusScope {+ getProjectId(): string;+ /** Whether the instance floats in the project on screen; a window that docked or closed holds no focus. */+ isFloating(instanceId: WidgetInstanceId): boolean;+}++/** How long a focus move waits for its widget to show: a lazy widget, or the window chunk, has to load first. */+const FOCUS_MOVE_WAIT_MS = 1000;+/** How long the move holds after it lands: a closing menu or dialog hands focus back to its trigger on the way out. */+const FOCUS_MOVE_SETTLE_MS = 500;const isSameTarget = (left: WorkbenchFocusTarget | null, right: WorkbenchFocusTarget): boolean =>left !== null &&@@ -43,33 +56,47 @@ const isSameTarget = (left: WorkbenchFocusTarget | null, right: WorkbenchFocusTa? right.kind === 'region' && left.region === right.region: right.kind === 'floating' && left.instanceId === right.instanceId);-export const createWorkbenchFocusController = (getProjectId: () => string): WorkbenchFocusController => {+export const createWorkbenchFocusController = ({+ getProjectId,+ isFloating,+}: WorkbenchFocusScope): 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;+ let moveTarget: WorkbenchFocusTarget | null = null;const listeners = new Set<() => void>();const notify = () => {for (const listener of listeners) {listener();}};+ // The one place a target is judged. The owner clears eagerly on project and account changes, which is what+ // notifies subscribers and stops moves; this read-time check covers the instant between such a change and that+ // clear, and a window that docked or closed without anything else taking focus.const getTarget = (): WorkbenchFocusTarget | null =>- entry && entry.projectId === getProjectId() && isAccountScopeCurrent(entry.owner) ? entry.target : null;+ entry &&+ entry.projectId === getProjectId() &&+ isAccountScopeCurrent(entry.owner) &&+ (entry.target.kind === 'region' || isFloating(entry.target.instanceId))+ ? 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.+ * Leaves focus alone when it is already inside the container, and gives up if the container never shows, the+ * project or account changes first, or the user presses somewhere else.*/- const moveFocus = (findContainer: () => HTMLElement | null): void => {+ const moveFocus = (target: WorkbenchFocusTarget, 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 deadline = performance.now() + FOCUS_MOVE_WAIT_MS;- const settle = (container: HTMLElement, remaining: number) => {+ moveTarget = target;++ const settle = (container: HTMLElement, until: number) => {if (!isCurrent() || !container.isConnected) {return;}@@ -79,8 +106,8 @@ export const createWorkbenchFocusController = (getProjectId: () => string): Workif (!container.contains(active) && (active === opener || active === document.body || active === null)) {container.focus({ preventScroll: true });}- if (remaining > 0) {- requestAnimationFrame(() => settle(container, remaining - 1));+ if (performance.now() < until) {+ requestAnimationFrame(() => settle(container, until));}};@@ -96,13 +123,12 @@ export const createWorkbenchFocusController = (getProjectId: () => string): Workif (!container.hasAttribute('tabindex')) {container.tabIndex = -1;}- settle(container, FOCUS_MOVE_SETTLE_FRAMES);+ settle(container, performance.now() + FOCUS_MOVE_SETTLE_MS);}return;}- frames += 1;- if (frames < FOCUS_MOVE_FRAME_BUDGET) {+ if (performance.now() < deadline) {requestAnimationFrame(attempt);}};@@ -111,27 +137,37 @@ export const createWorkbenchFocusController = (getProjectId: () => string): Work};return {- activate: (target, projectId = getProjectId()) => {+ activate: (target, { byPointer = false, projectId = getProjectId() } = {}) => {if (projectId !== getProjectId()) {- return false;+ return 'refused';}- if (!isSameTarget(getTarget(), target)) {- entry = { owner: captureAccountScope(), projectId, target };- notify();+ if (byPointer && !isSameTarget(moveTarget, target)) {+ focusMove += 1;+ moveTarget = null;}- return true;+ if (isSameTarget(getTarget(), target)) {+ return 'unchanged';+ }++ entry = { owner: captureAccountScope(), projectId, target };+ notify();++ return 'activated';},clear: () => {focusMove += 1;+ moveTarget = null;if (entry) {entry = null;notify();}},focusFloating: (instanceId) =>- moveFocus(() => document.querySelector<HTMLElement>(`[data-floating-window="${CSS.escape(instanceId)}"]`)),+ moveFocus({ instanceId, kind: 'floating' }, () =>+ document.querySelector<HTMLElement>(`[data-floating-window="${CSS.escape(instanceId)}"]`)+ ),focusRegion: (region, typeId) =>- moveFocus(() => {+ moveFocus({ kind: 'region', region }, () => {// 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}"]`)) {@@ -182,60 +218,63 @@ const HIGHLIGHT_STYLES = {right: regionHighlight('0 -1px 0 0'),} satisfies Record<WidgetRegion, unknown>;-/**- * 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.- */+/** Provides the workbench's focus controller (see `WorkbenchFocusProvider`) to everything below it. */export const FocusRegionProvider = ({children,controller,}: {children: ReactNode;- controller?: WorkbenchFocusController;-}) => {- const [ownController] = useState(() => controller ?? createWorkbenchFocusController(() => ''));-- return <FocusRegionContext value={controller ?? ownController}>{children}</FocusRegionContext>;-};+ controller: WorkbenchFocusController;+}) => <FocusRegionContext value={controller}>{children}</FocusRegionContext>;-const NO_FOCUS_TARGET = (): null => null;const subscribeToNothing = (): (() => void) => () => {};-const useFocusTarget = (): WorkbenchFocusTarget | null => {+/**+ * Subscribe to one fact about the focus target. `select` returns a primitive, so a component re-renders only+ * when its own answer changes — not every window and region on every activation.+ */+const useFocusSelector = <Selected extends string | boolean | null>(+ select: (target: WorkbenchFocusTarget | null) => Selected+): Selected => {const controller = use(FocusRegionContext);+ const getSnapshot = () => select(controller?.getTarget() ?? null);- return useSyncExternalStore(- controller?.subscribe ?? subscribeToNothing,- controller?.getTarget ?? NO_FOCUS_TARGET,- controller?.getTarget ?? NO_FOCUS_TARGET- );+ return useSyncExternalStore(controller?.subscribe ?? subscribeToNothing, getSnapshot, getSnapshot);};const useShowsFocusHighlight = (): boolean =>useWorkbenchPreferenceSelector((preferences) => preferences.showFocusRegionHighlight);-const NO_FOCUS_MOVES: Pick<WorkbenchFocusController, 'focusFloating' | 'focusRegion' | 'getTarget'> = {- focusFloating: () => {},- focusRegion: () => {},- getTarget: NO_FOCUS_TARGET,-};+type WorkbenchFocusMoves = Pick<WorkbenchFocusController, 'focusFloating' | 'focusRegion'>;++const NO_FOCUS_MOVES: WorkbenchFocusMoves = { focusFloating: () => {}, focusRegion: () => {} };/**- * 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.+ * Focus moves for controls that open, float, or dock a widget. Some of those controls also render outside the+ * workbench shell, where there is nothing to move focus between and the moves do nothing.*/-export const useWorkbenchFocus = (): Pick<WorkbenchFocusController, 'focusFloating' | 'focusRegion' | 'getTarget'> =>- use(FocusRegionContext) ?? NO_FOCUS_MOVES;+export const useWorkbenchFocus = (): WorkbenchFocusMoves => use(FocusRegionContext) ?? NO_FOCUS_MOVES;++/** Reads the focus target at call time, for the hotkey runtime. It has no meaning outside the provider. */+export const useWorkbenchFocusTarget = (): (() => WorkbenchFocusTarget | null) => {+ const controller = use(FocusRegionContext);++ if (!controller) {+ throw new Error('useWorkbenchFocusTarget must be used within a FocusRegionProvider.');+ }++ return controller.getTarget;+};/*** 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. No region is outlined while a floating window holds focus.*/export const useHighlightedRegion = (): WidgetRegion | null => {- const target = useFocusTarget();+ const region = useFocusSelector((target) => (target?.kind === 'region' ? target.region : null));const showsHighlight = useShowsFocusHighlight();- return showsHighlight && target?.kind === 'region' ? target.region : null;+ return showsHighlight ? region : null;};export const useFocusRegionProps = (region: WidgetRegion) => {@@ -246,38 +285,53 @@ export const useFocusRegionProps = (region: WidgetRegion) => {}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>) => activate(),- onPointerDownCapture: (_event: PointerEvent<HTMLElement>) => activate(),+ onFocusCapture: (_event: FocusEvent<HTMLElement>) => {+ controller.activate({ kind: 'region', region });+ },+ onPointerDownCapture: (event: PointerEvent<HTMLElement>) => {+ const container = event.currentTarget;++ controller.activate({ kind: 'region', region }, { byPointer: true });+ // A press that takes no focus of its own — a resize handle, the canvas — would leave the keys in a floating+ // window while this region shows as focused. Pull focus out of the window; a focusable target then takes+ // it as usual.+ if (+ document.activeElement?.closest('[data-floating-window]') &&+ event.target instanceof Node &&+ container.contains(event.target)+ ) {+ if (!container.hasAttribute('tabindex')) {+ container.tabIndex = -1;+ }+ container.focus({ preventScroll: true });+ }+ },position: 'relative' as const,};};/*** 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.+ * reports what happened: a window whose project has left the screen is refused, so a late event cannot raise a+ * stale one.*/export const useFloatingWindowFocus = (instanceId: WidgetInstanceId,projectId: string-): { activate: () => boolean; isActive: boolean; isHighlighted: boolean } => {+): { activate: (options?: { byPointer?: boolean }) => FocusActivation; isHighlighted: boolean } => {const controller = use(FocusRegionContext);- const target = useFocusTarget();+ const isActive = useFocusSelector((target) => target?.kind === 'floating' && target.instanceId === instanceId);const showsHighlight = useShowsFocusHighlight();- const isActive = target?.kind === 'floating' && target.instanceId === instanceId;const activate = useCallback(- () => controller?.activate({ instanceId, kind: 'floating' }, projectId) ?? true,+ ({ byPointer }: { byPointer?: boolean } = {}) =>+ controller?.activate({ instanceId, kind: 'floating' }, { byPointer, projectId }) ?? 'activated',[controller, instanceId, projectId]);- return {- activate,- isActive,- isHighlighted: isActive && showsHighlight,- };+ return { activate, isHighlighted: isActive && showsHighlight };};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsxnew file mode 100644index 0000000000..519daa6ab3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.browser.test.tsx@@ -0,0 +1,190 @@+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type { ExtensionRegistry } from '@workbench/extensions/extensionRegistry';+import type { Project } from '@workbench/projectContracts';+import type { WidgetContributionSource } from '@workbench/widgetContracts';+import type { WorkbenchInternalStore } from '@workbench/workbenchStore';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import { createExtensionRegistry } from '@workbench/extensions/extensionRegistry';+import { useFloatingWindowFocus, useFocusRegionProps } from '@workbench/focusRegions';+import { WorkbenchFocusProvider } from '@workbench/WorkbenchRuntime';+import { createWorkbenchStore } from '@workbench/workbenchStore';+import { act, useCallback } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The hotkey runtime under the real focus provider, a real store, and the real extension registry: which command+ * a key press runs depends on the floating window that holds focus. Only the context plumbing and the first-party+ * command registrations (which need the whole application) are replaced.+ */++const runtimeMocks = vi.hoisted(() => ({+ extensions: null as unknown as ExtensionRegistry,+ store: null as unknown as WorkbenchInternalStore,+}));++vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: <Selected,>(selector: (project: Project) => Selected) =>+ selector(runtimeMocks.store.getSnapshot().activeProject),+ useOptionalWorkbenchExtensions: () => runtimeMocks.extensions,+ useWorkbenchExtensions: () => runtimeMocks.extensions,+ useWorkbenchInternalStore: () => runtimeMocks.store,+ useWorkbenchQueries: () => runtimeMocks.store.queries,+ useWorkbenchSubscription: () => runtimeMocks.store.subscribe,+}));+vi.mock('./firstPartyCommands', () => ({ useRegisterFirstPartyCommands: () => {} }));++import { WorkbenchHotkeyRuntime } from './WorkbenchHotkeyRuntime';++const Harness = () => {+ const { activate } = useFloatingWindowFocus('image-map', runtimeMocks.store.getSnapshot().activeProject.id);+ const handlePointerDown = useCallback(() => activate({ byPointer: true }), [activate]);++ return (+ <>+ <div data-testid="right" {...useFocusRegionProps('right')}>+ Right panel+ </div>+ <div+ data-floating-window="image-map"+ data-hotkey-widget-instance-id="image-map"+ data-hotkey-widget-region="floating"+ data-hotkey-widget-type-id="image-map"+ data-testid="window"+ onPointerDownCapture={handlePointerDown}+ >+ <button type="button">Window control</button>+ </div>+ </>+ );+};++let host: HTMLDivElement | null = null;+let root: Root | null = null;+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++let ran: string[] = [];++const projectId = () => runtimeMocks.store.getSnapshot().activeProject.id;+/** Register a command and a shortcut for it, the way a widget does through its runtime. */+const contribute = (+ id: string,+ key: string,+ scope: 'focused-region' | 'instance' | 'widget',+ source: WidgetContributionSource+) => {+ runtimeMocks.extensions.commands.register({ handler: () => ran.push(id), id, source, title: id });+ runtimeMocks.extensions.hotkeys.register({ commandId: id, defaultKeys: [key], id, scope, source, title: id });+};+const pressKey = (key: string, target: EventTarget = document.body) =>+ act(async () => {+ target.dispatchEvent(+ new KeyboardEvent('keydown', { bubbles: true, cancelable: true, code: `Key${key.toUpperCase()}`, key })+ );+ await Promise.resolve();+ });+const pressOn = (testId: string) =>+ act(() =>+ host!.querySelector(`[data-testid="${testId}"]`)!.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))+ );++beforeEach(async () => {+ ran = [];+ runtimeMocks.store = createWorkbenchStore();+ runtimeMocks.store.commands.widgets.float('image-map');+ runtimeMocks.extensions = createExtensionRegistry();++ const floating: WidgetContributionSource = {+ instanceId: 'image-map',+ projectId: projectId(),+ region: 'floating',+ typeId: 'image-map',+ };+ const docked: WidgetContributionSource = {+ instanceId: 'gallery',+ projectId: projectId(),+ region: 'right',+ typeId: 'gallery',+ };++ // Keys the first-party catalog does not use.+ contribute('map.instance', 'j', 'instance', floating);+ contribute('map.widget', 'k', 'widget', floating);+ contribute('map.window', 'y', 'focused-region', floating);+ contribute('gallery.rightRegion', 'y', 'focused-region', docked);++ host = document.createElement('div');+ document.body.append(host);+ root = createRoot(host);+ await act(() => {+ root?.render(+ <ChakraProvider value={system}>+ <WorkbenchFocusProvider>+ <WorkbenchHotkeyRuntime />+ <Harness />+ </WorkbenchFocusProvider>+ </ChakraProvider>+ );+ });+});++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ host = null;+ root = null;+});++describe('WorkbenchHotkeyRuntime under a floating window', () => {+ it('runs nothing widget-scoped while nothing holds focus', async () => {+ await pressKey('j');+ await pressKey('k');+ await pressKey('y');++ expect(ran).toEqual([]);+ });++ it('aims key presses outside any widget at the active floating window', async () => {+ await pressOn('window');++ await pressKey('j');+ await pressKey('k');+ await pressKey('y');++ // Instance, widget, and the window's own focused-region shortcut all run; the shortcut tied to the right+ // region shares the key and stays out of it.+ expect(ran).toEqual(['map.instance', 'map.widget', 'map.window']);+ });++ it('aims key presses inside the window at it, whatever focus last recorded', async () => {+ await pressOn('right');+ const control = host!.querySelector('button')!;++ await pressKey('j', control);+ await pressKey('y', control);++ expect(ran).toEqual(['map.instance', 'map.window']);+ });++ it('gives the shared key back to the docked region once that region holds focus', async () => {+ await pressOn('window');+ await pressOn('right');++ await pressKey('y');+ await pressKey('j');++ expect(ran).toEqual(['gallery.rightRegion']);+ });++ it('stops aiming at the window once it is closed', async () => {+ await pressOn('window');+ await act(() => runtimeMocks.store.commands.widgets.closeFloating('image-map'));++ await pressKey('j');+ await pressKey('y');++ expect(ran).toEqual([]);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsx b/invokeai/frontend/webv2/src/workbench/hotkeys/WorkbenchHotkeyRuntime.tsxindex 56927b1b63..3ebc5380db 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 { useWorkbenchFocus } from '@workbench/focusRegions';+import { useWorkbenchFocusTarget } from '@workbench/focusRegions';import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';import { useActiveProjectSelector, useWorkbenchExtensions } from '@workbench/WorkbenchContext';@@ -37,7 +37,7 @@ export const WorkbenchHotkeyRuntime = () => {const project = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);const extensionHotkeys = useExtensionHotkeyDefinitions();const isModalLayerActive = useIsHotkeyModalLayerActive();- const focus = useWorkbenchFocus();+ const getFocusTarget = useWorkbenchFocusTarget();const registeredHotkeys = useMemo(() => {const firstPartyHotkeys = firstPartyHotkeyCatalog.map((hotkey) => applyCustomHotkeys(hotkey, customHotkeys));@@ -56,7 +56,7 @@ export const WorkbenchHotkeyRuntime = () => {}const { source, ...target } = resolveHotkeyTarget({- focusTarget: focus.getTarget(),+ focusTarget: getFocusTarget(),project,targetWidget: getHotkeyTargetWidget(event.target),});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.tsindex ace48ffea7..2d229e9050 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.test.ts@@ -35,10 +35,11 @@ describe('toExtensionHotkeyDefinition', () => {kind: 'focused-region',region: 'right',});- // A window is not a region other widgets share, so the shortcut follows this instance.+ // A window is not a region other widgets share, so the shortcut follows this instance — still as a+ // focused-region shortcut, at that priority.expect(toExtensionHotkeyDefinition({ ...contribution, source: floating })?.scope).toEqual({- instanceId: 'alpha',- kind: 'instance',+ floatingInstanceId: 'alpha',+ kind: 'focused-region',});});});diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.tsindex 8a5fb42540..c47e35eb25 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/extensionHotkeys.ts@@ -36,12 +36,13 @@ export const toExtensionHotkeyDefinition = (hotkey: WidgetHotkeyContribution): H}// A floating window is not a region other widgets share: "while my region is focused" means "while my window is".+ // It stays a focused-region shortcut, so floating a widget does not change which binding wins a shared key.if (scope === 'focused-region' && source?.region === 'floating') {return {...hotkey,category: 'app',implemented: true,- scope: { instanceId: source.instanceId, kind: 'instance' },+ scope: { floatingInstanceId: source.instanceId, kind: 'focused-region' },};}diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.tsindex 0222fe63a2..3d100bac72 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.test.ts@@ -140,6 +140,8 @@ describe('resolveHotkey', () => {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 thisWindow = hotkey('this-window', { floatingInstanceId: 'map-1', kind: 'focused-region' });+ const otherWindow = hotkey('other-window', { floatingInstanceId: 'map-2', kind: 'focused-region' });const widget = hotkey('widget', { kind: 'widget', typeId: 'image-map' });const instance = hotkey('instance', { instanceId: 'map-1', kind: 'instance' });const resolve = (hotkeys: RegisteredHotkey[]) =>@@ -151,6 +153,11 @@ describe('resolveHotkey', () => {expect(resolve([global, rightOnly, anyRegion, widget])).toBe('widget');expect(resolve([global, rightOnly, anyRegion, widget, instance])).toBe('instance');expect(resolve([rightOnly])).toBeUndefined();+ // A floating widget's own focused-region shortcut follows its window, at focused-region priority: above+ // global, below a widget-scoped binding on the same key, exactly as when it is docked.+ expect(resolve([global, otherWindow, thisWindow])).toBe('this-window');+ expect(resolve([global, otherWindow])).toBe('global');+ expect(resolve([thisWindow, widget])).toBe('widget');// Modal suppression is unchanged by where focus is.expect(resolveHotkey({diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.tsindex c939525477..f19fbc0840 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/resolve.ts@@ -18,6 +18,10 @@ const getScopePriority = (hotkey: RegisteredHotkey, context: HotkeyContext): num}if (scope.kind === 'focused-region') {+ if (scope.floatingInstanceId) {+ return context.focusedRegion === 'floating' && scope.floatingInstanceId === context.activeInstanceId ? 200 : -1;+ }+return context.focusedRegion && (!scope.region || scope.region === context.focusedRegion) ? 200 : -1;}diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.tsindex 92b073d40a..0840951288 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.test.ts@@ -82,17 +82,31 @@ describe('resolveHotkeyTarget', () => {});it('prefers the widget under the event target over whatever holds focus', () => {+ // Focus was last recorded on a window, but the press landed in the center: the press decides both the widget+ // and the region.+ expect(+ resolveHotkeyTarget({+ focusTarget: { instanceId: 'map', kind: 'floating' },+ project,+ targetWidget: { instanceId: 'canvas', region: 'center', typeId: 'canvas' },+ })+ ).toEqual({+ activeInstanceId: 'canvas',+ activeWidgetTypeId: 'canvas',+ focusedRegion: 'center',+ source: { instanceId: 'canvas', projectId: 'project-1', region: 'center', typeId: 'canvas' },+ });+ });++ it('keeps the focused region when the press lands in a popover or dialog a widget opened', () => {const target = resolveHotkeyTarget({- focusTarget: { instanceId: 'map', kind: 'floating' },+ focusTarget: { kind: 'region', region: 'right' },project,- targetWidget: { instanceId: 'canvas', region: 'center', typeId: 'canvas' },+ targetWidget: { instanceId: 'gallery', region: 'popover', typeId: 'gallery' },});- expect(target).toMatchObject({- activeInstanceId: 'canvas',- activeWidgetTypeId: 'canvas',- source: { instanceId: 'canvas', region: 'center' },- });+ expect(target.focusedRegion).toBe('right');+ expect(target.source?.region).toBe('popover');});it('gives a key press inside a floating window a floating source', () => {@@ -111,10 +125,23 @@ describe('resolveHotkeyTarget', () => {});});- it('ignores a floating focus whose instance no longer floats in this project', () => {+ it('does not aim at a view that floated out of the focused region, even though the region still points at it', () => {+ // The center emptied when its last view floated; it keeps naming that view so docking can bring it back.+ const emptied: WidgetPlacementProject = {+ ...project,+ widgetRegions: { ...project.widgetRegions, center: region('map', []) },+ };++ // The view answers as a window. As "the center's widget" it would get a `center` source, and the commands it+ // registered under `floating` would not be found while the key was still swallowed.expect(- resolveHotkeyTarget({ focusTarget: { instanceId: 'gallery', kind: 'floating' }, project, targetWidget: null })- ).toEqual({ activeInstanceId: null, activeWidgetTypeId: null, focusedRegion: null, source: null });+ resolveHotkeyTarget({ focusTarget: { kind: 'region', region: 'center' }, project: emptied, targetWidget: null })+ ).toEqual({+ activeInstanceId: null,+ activeWidgetTypeId: null,+ focusedRegion: 'center',+ source: null,+ });});it('has no widget target for a focused region that is empty, or when nothing holds focus', () => {diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.tsindex 361bcd74c3..eb22b94196 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/targetWidget.ts@@ -8,6 +8,8 @@ import type {} from '@workbench/widgetContracts';import type { WidgetPlacementProject } from '@workbench/widgetPlacementCommands';+import { isWidgetRegion } from '@workbench/layoutContracts';+export const getHotkeyTargetWidget = (target: EventTarget | null): { instanceId: WidgetInstanceId; region: WorkbenchRegion | null; typeId: WidgetTypeId } | null => {@@ -36,40 +38,55 @@ export interface HotkeyTarget {/*** 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.+ * docked region. A floating target is never used to index `widgetRegions`. A region's active pointer counts only+ * while it names one of the region's members: an emptied center keeps pointing at the view that floated out of+ * it, and that view answers as a window, not as the center.*/export const resolveHotkeyTarget = ({focusTarget,project,targetWidget,}: {+ /** From the focus controller, which already drops a floating target whose window is gone. */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;+ // Where the press landed says more than where focus was last recorded; a popover or dialog is no region.+ const targetRegion = targetWidget?.region;+ const focusedRegion =+ targetRegion === 'floating' || isWidgetRegion(targetRegion)+ ? targetRegion+ : focusTarget === null+ ? null+ : focusTarget.kind === 'floating'+ ? 'floating'+ : focusTarget.region;+ const region = focusTarget?.kind === 'region' ? project.widgetRegions[focusTarget.region] : null;const focusedInstanceId =- focus === null- ? null- : focus.kind === 'floating'- ? focus.instanceId- : project.widgetRegions[focus.region].activeInstanceId;- const activeInstanceId = targetWidget?.instanceId ?? (focusedInstanceId || null);+ focusTarget?.kind === 'floating'+ ? focusTarget.instanceId+ : region?.instanceIds.includes(region.activeInstanceId)+ ? region.activeInstanceId+ : null;+ const activeInstanceId = targetWidget?.instanceId ?? focusedInstanceId;const activeWidgetTypeId = activeInstanceId? (targetWidget?.typeId ?? project.widgetInstances[activeInstanceId]?.typeId ?? null): null;- const region = targetWidget?.region ?? focusedRegion;+ const sourceRegion = targetWidget?.region ?? focusedRegion;return {activeInstanceId,activeWidgetTypeId,focusedRegion,source:- activeInstanceId && activeWidgetTypeId && region- ? { instanceId: activeInstanceId, projectId: project.projectId ?? '', region, typeId: activeWidgetTypeId }+ activeInstanceId && activeWidgetTypeId && sourceRegion+ ? {+ instanceId: activeInstanceId,+ projectId: project.projectId ?? '',+ region: sourceRegion,+ typeId: activeWidgetTypeId,+ }: null,};};diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/types.tsindex 6e43fe3680..e4571ef5b5 100644--- a/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/types.ts@@ -5,7 +5,11 @@ export type HotkeyCategory = 'app' | 'canvas' | 'gallery' | 'viewer' | 'workflowexport type HotkeyScope =| { kind: 'global' }- | { kind: 'focused-region'; region?: WidgetRegion }+ /**+ * Matches while a region holds focus: any region, one named docked region, or — for a contribution made by a+ * floating widget, whose window is no region others share — that one floating instance.+ */+ | { kind: 'focused-region'; region?: WidgetRegion; floatingInstanceId?: WidgetInstanceId }| { kind: 'widget'; typeId: WidgetTypeId }| { kind: 'instance'; instanceId: WidgetInstanceId };diff --git a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsxindex b6bf114e6b..c24c87d8bb 100644--- a/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx+++ b/invokeai/frontend/webv2/src/workbench/settings/HotkeysSettingsSection.tsx@@ -92,7 +92,15 @@ const canScopesOverlap = (left: HotkeyDefinition, right: HotkeyDefinition): bool}if (left.scope.kind === 'focused-region' && right.scope.kind === 'focused-region') {- return !left.scope.region || !right.scope.region || left.scope.region === right.scope.region;+ const { floatingInstanceId: leftWindow, region: leftRegion } = left.scope;+ const { floatingInstanceId: rightWindow, region: rightRegion } = right.scope;++ // A shortcut for any focused region meets every other; one for a floating window meets only that window's.+ if ((!leftRegion && !leftWindow) || (!rightRegion && !rightWindow)) {+ return true;+ }++ return leftWindow || rightWindow ? leftWindow === rightWindow : leftRegion === rightRegion;}return false;diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsxindex 33984289b0..0ae71520bd 100644--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx@@ -212,10 +212,21 @@ export const WorkbenchShell = () => {);const closeFloating = useCallback((instanceId: string) => {- const typeId = placementProject.widgetInstances[instanceId]?.typeId;+ const { widgetInstances, widgetRegions } = placementProject;+ const removed = removeFloatingPlacement({ instanceId, project: placementProject, widgets });++ if (!removed) {+ return;+ }++ // The menu that asked and the marker it hung from are both gone. Focus goes to the center when it gets its+ // view back, otherwise to whatever the window's own rail is showing.+ const region = removed.restoresCenter ? 'center' : removed.returnRegion;+ const shownInstanceId = removed.restoresCenter ? instanceId : widgetRegions[region].activeInstanceId;+ const typeId = widgetInstances[shownInstanceId]?.typeId;- if (removeFloatingPlacement({ instanceId, project: placementProject, widgets })?.restoresCenter && typeId) {- focusRegion('center', typeId);+ if (typeId) {+ focusRegion(region, typeId);}},[focusRegion, placementProject, widgets]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.tsxindex 79b19e1885..bd58467d33 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.browser.test.tsx@@ -15,6 +15,7 @@ const layerMocks = vi.hoisted(() => ({vi.mock('@workbench/WorkbenchContext', () => ({shallowEqual: Object.is,+ useActiveProjectId: () => layerMocks.project.id,useActiveProjectSelector: (selector: (project: typeof layerMocks.project) => unknown) => selector(layerMocks.project),}));@@ -96,4 +97,17 @@ describe('FloatingWidgetLayer', () => {expect(host!.querySelector('[data-window="queue"]')).toBe(queue);expect(document.activeElement).toBe(queue);});++ it('mounts a fresh host when another project floats an instance with the same id', async () => {+ await render({ gallery: windowState(1) });+ const first = host!.querySelector('[data-window="gallery"]');++ // Instance ids repeat across projects; nothing of the old window — a gesture, its widget's state — may carry+ // over.+ layerMocks.project = { ...layerMocks.project, id: 'project-2' };+ await render({ gallery: windowState(1) });++ expect(host!.querySelector('[data-window="gallery"]')).not.toBe(first);+ expect(first?.isConnected).toBe(false);+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsxindex a2994d27a7..fad28a0226 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetLayer.tsx@@ -1,7 +1,7 @@import type { FloatingWidgetState } from '@workbench/layoutContracts';import type { WidgetInstanceId } from '@workbench/widgetContracts';-import { shallowEqual, useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { shallowEqual, useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';import { lazy, Suspense } from 'react';// The window chrome loads only once a widget actually floats, keeping it out@@ -16,8 +16,12 @@ const EMPTY_FLOATING: Record<WidgetInstanceId, FloatingWidgetState> = {};* Render floating windows with z-order derived from stackOrder rank, keeping persisted ordering within UI layer* 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.+ *+ * Each host is keyed by project as well as instance: instance ids repeat across projects, and a window carried+ * over from the previous project would keep that project's gesture, pending cleanup, and widget state.*/export const FloatingWidgetLayer = () => {+ const projectId = useActiveProjectId();const floatingWidgets = useActiveProjectSelector((project) => project.floatingWidgets ?? EMPTY_FLOATING,shallowEqual@@ -38,7 +42,7 @@ export const FloatingWidgetLayer = () => {<Suspense fallback={null}>{instanceIds.map((instanceId) => (<FloatingWidgetWindow- key={instanceId}+ key={`${projectId}:${instanceId}`}instanceId={instanceId}stackRank={stackRanks.get(instanceId) ?? 0}state={floatingWidgets[instanceId]}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.tsxindex 2ca387821d..38a9b83e83 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@@ -1,5 +1,7 @@/* oxlint-disable react-perf/jsx-no-new-object-as-prop */+import type * as draftRegistry from '@platform/react/draftRegistry';import type { FloatingWidgetState } from '@workbench/layoutContracts';+import type * as settingsStore from '@workbench/settings/store';import type {RegisteredWidget,WidgetImplementation,@@ -9,18 +11,16 @@ import type {import { ChakraProvider, HStack } from '@chakra-ui/react';import { system } from '@theme/system';-import {- createWorkbenchFocusController,- FocusRegionProvider,- type WorkbenchFocusController,-} from '@workbench/focusRegions';+import { FocusRegionProvider, type WorkbenchFocusController } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';import { closeWorkbenchSettings, settingsDialogStore } from '@workbench/settings/settingsDialogStore';import i18next from 'i18next';import { MapIcon, TagsIcon } from 'lucide-react';-import { act } from 'react';+import { act, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';/*** Floating windows must retain widget actions and settings while substituting their own shade/maximize/dock@@ -30,8 +30,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const windowMocks = vi.hoisted(() => ({actionsRegion: null as string | null,dockFloating: vi.fn(),+ flushWorkbenchDrafts: vi.fn(),+ showFocusHighlight: true,useFailingWidget: false,- focusFloating: vi.fn(),+ useWideActions: false,+ raiseFloating: vi.fn(),setFloatingGeometry: vi.fn(),setFloatingMode: vi.fn(),}));@@ -59,6 +62,23 @@ vi.mock('@workbench/WorkbenchContext', () => ({useWorkbenchCommands: () => ({ widgets: windowMocks }),}));+vi.mock('@platform/react/draftRegistry', async (importOriginal) => ({+ ...(await importOriginal<typeof draftRegistry>()),+ flushWorkbenchDrafts: windowMocks.flushWorkbenchDrafts,+}));++vi.mock('@workbench/settings/store', async (importOriginal) => {+ const original = await importOriginal<typeof settingsStore>();++ return {+ ...original,+ // Only the outline preference is steered; every other preference reads through.+ useWorkbenchPreferenceSelector: <Selected,>(+ selector: (preferences: ReturnType<typeof settingsStore.getWorkbenchPreferences>) => Selected+ ) => selector({ ...original.getWorkbenchPreferences(), showFocusRegionHighlight: windowMocks.showFocusHighlight }),+ };+});+vi.mock('@workbench/WorkbenchWidgetRegistryContext', () => ({useWorkbenchWidgetRegistry: () => ({getWidgetById: () => (windowMocks.useFailingWidget ? failingWidget : registeredWidget),@@ -84,6 +104,17 @@ const manifest = {version: 1,} as unknown as WidgetManifest;+/** A body with local state, to tell a hidden body from a remounted one. */+const MapBody = () => {+ const [count, setCount] = useState(0);++ return (+ <button data-testid="map-body" type="button" onClick={() => setCount(count + 1)}>+ {count}+ </button>+ );+};+const implementation: WidgetImplementation = {headerActions: ({ region }: WidgetViewProps) => {windowMocks.actionsRegion = region;@@ -95,11 +126,19 @@ const implementation: WidgetImplementation = {<button aria-label="Toggle cluster labels" type="button"><TagsIcon /></button>+ {/* More actions than a narrow title bar can hold. */}+ {windowMocks.useWideActions+ ? ['Fit', 'Reset', 'Legend', 'Density', 'Export'].map((name) => (+ <button key={name} style={{ flexShrink: 0, width: '72px' }} type="button">+ {name}+ </button>+ ))+ : null}</HStack>);},headerMenu: () => <div data-testid="header-menu" />,- view: () => <div data-testid="map-body" />,+ view: () => <MapBody />,};const implementationPromise = Promise.resolve(implementation);@@ -144,7 +183,11 @@ await i18n.use(initReactI18next).init({dockTo: 'Dock to {{destination}}',maximize: 'Maximize',move: 'Move {{label}} window',+ resize: 'Resize window',+ resizeValue: '{{width}} by {{height}} pixels',+ restore: 'Restore',shade: 'Shade',+ unshade: 'Unshade',},labels: { imageMap: 'Image Map' },settingsLabel: '{{label}} settings',@@ -158,7 +201,12 @@ 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, controller?: WorkbenchFocusController) => {+let testController = createTestFocusController();++const renderWindow = async (+ floatingState: FloatingWidgetState = state,+ controller: WorkbenchFocusController = testController+) => {await act(async () => {root?.render(<I18nextProvider i18n={i18n}>@@ -177,12 +225,19 @@ const renderWindow = async (floatingState: FloatingWidgetState = state, controll});};-beforeEach(() => {+beforeEach(async () => {+ // Room for the 500x400 test window at (40, 40) without the viewport capping or clamping it.+ await page.viewport(1200, 800);closeWorkbenchSettings();windowMocks.actionsRegion = null;windowMocks.useFailingWidget = false;+ windowMocks.useWideActions = false;+ windowMocks.showFocusHighlight = true;+ testController = createTestFocusController();+ windowMocks.flushWorkbenchDrafts.mockClear();+ windowMocks.setFloatingMode.mockClear();windowMocks.dockFloating.mockClear();- windowMocks.focusFloating.mockClear();+ windowMocks.raiseFloating.mockClear();windowMocks.setFloatingGeometry.mockClear();host = document.createElement('div');document.body.append(host);@@ -285,7 +340,108 @@ describe('FloatingWidgetWindow chrome', () => {expect(host?.querySelector('button[aria-label="Toggle cluster labels"]')).not.toBeNull();expect(host?.querySelector('button[aria-label="Image Map settings"]')).not.toBeNull();- expect(host?.querySelector('[data-testid="map-body"]')).toBeNull();+ expect(host!.querySelector('[data-testid="map-body"]')!.getClientRects()).toHaveLength(0);+ });++ it('hides a shaded body without unmounting it, saving drafts first', async () => {+ await renderWindow();+ const body = host!.querySelector<HTMLElement>('[data-testid="map-body"]')!;+ await act(() => body.click());+ expect(body.textContent).toBe('1');++ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!.click());++ expect(windowMocks.flushWorkbenchDrafts).toHaveBeenCalledOnce();+ expect(windowMocks.setFloatingMode).toHaveBeenCalledWith('image-map-instance', 'shaded');+ expect(windowMocks.flushWorkbenchDrafts.mock.invocationCallOrder[0]).toBeLessThan(+ windowMocks.setFloatingMode.mock.invocationCallOrder[0]+ );++ await renderWindow({ ...state, mode: 'shaded' });+ // Rolled up to the title bar: the body is out of layout, and it is still the same element.+ expect(host!.querySelector('[data-floating-window]')!.getBoundingClientRect().height).toBeLessThan(60);+ expect(host!.querySelector('[data-testid="map-body"]')).toBe(body);+ expect(body.getClientRects()).toHaveLength(0);++ // Expanding saves nothing more, and the body comes back with its state.+ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Unshade"]')!.click());+ expect(windowMocks.flushWorkbenchDrafts).toHaveBeenCalledOnce();+ await renderWindow();+ expect(host!.querySelector('[data-testid="map-body"]')?.textContent).toBe('1');+ });++ it('maximizes and restores on a title-bar double-click, but not from a title-bar button', async () => {+ await renderWindow();+ const titleBar = () => host!.querySelector<HTMLElement>('[aria-label="Move Image Map window"]')!;+ const doubleClick = (element: Element) =>+ act(() => element.dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));++ await doubleClick(host!.querySelector('button[aria-label="Shade"]')!);+ await doubleClick(host!.querySelector('button[aria-label="Toggle cluster labels"]')!);+ expect(windowMocks.setFloatingMode).not.toHaveBeenCalled();++ await doubleClick(titleBar());+ expect(windowMocks.setFloatingMode).toHaveBeenLastCalledWith('image-map-instance', 'maximized');++ await renderWindow({ ...state, mode: 'maximized' });+ const rect = host!.querySelector('[data-floating-window]')!.getBoundingClientRect();+ expect([rect.left, rect.top, rect.width, rect.height]).toEqual([0, 0, 1200, 800]);++ await doubleClick(titleBar());+ // Restore goes back to the windowed geometry, which maximizing never touched.+ expect(windowMocks.setFloatingMode).toHaveBeenLastCalledWith('image-map-instance', 'windowed');+ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ });++ it('expands a collapsed window on a title-bar double-click instead of maximizing it', async () => {+ await renderWindow({ ...state, mode: 'shaded' });++ await act(() =>+ host!+ .querySelector('[aria-label="Move Image Map window"]')!+ .dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))+ );++ expect(windowMocks.setFloatingMode).toHaveBeenCalledExactlyOnceWith('image-map-instance', 'windowed');+ });++ it('leaves room for the focus ring of a contributed action inside the row that clips them', async () => {+ await renderWindow();++ const row = host!.querySelector('[data-floating-actions]')!;+ const clip = row.getBoundingClientRect();+ const action = host!.querySelector('button[aria-label="Toggle cluster labels"]')!.getBoundingClientRect();+ // The ring is a 2px outline offset by 2px.+ const ring = 4;++ expect(getComputedStyle(row).overflowX).toBe('clip');+ expect(action.top - ring).toBeGreaterThanOrEqual(clip.top);+ expect(action.bottom + ring).toBeLessThanOrEqual(clip.bottom);+ expect(action.left - ring).toBeGreaterThanOrEqual(clip.left);+ });++ it('keeps its own controls inside a minimum-width window whatever the widget contributes', async () => {+ windowMocks.useWideActions = true;+ await renderWindow({ ...state, widthPx: 280 });++ const frame = host!.querySelector('[data-floating-window]')!.getBoundingClientRect();+ const actions = host!.querySelector('[data-floating-actions]')!.getBoundingClientRect();+ const controls = host!.querySelector('[data-floating-controls]')!.getBoundingClientRect();++ expect(frame.width).toBe(280);+ for (const name of ['Shade', 'Maximize', 'Dock to right panel']) {+ const button = host!.querySelector(`button[aria-label="${name}"]`)!.getBoundingClientRect();++ expect(button.width).toBeGreaterThan(0);+ expect(button.left).toBeGreaterThanOrEqual(frame.left);+ expect(button.right).toBeLessThanOrEqual(frame.right);+ }+ // The contributed actions give way: they are clipped where the window's controls begin, and the title keeps+ // its icon rather than letting it slide over them.+ expect(actions.right).toBeLessThanOrEqual(controls.left);+ expect(+ host!.querySelector('[aria-label="Move Image Map window"] svg')!.getBoundingClientRect().right+ ).toBeLessThanOrEqual(actions.left);});it('still docks from the title bar with the widget actions alongside', async () => {@@ -303,31 +459,67 @@ 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);+ /** The frame that draws the window's border; the outline is its colour. */+ const borderColor = () => getComputedStyle(floatingWindow().firstElementChild!).borderTopColor;- expect(floatingWindow().getAttribute('data-highlighted')).toBe('false');+ it('becomes the active, outlined window on pointer-down, and raises itself', async () => {+ const controller = createTestFocusController();+ await renderWindow(state, controller);+ const restingBorder = borderColor();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');+ expect(windowMocks.raiseFloating).toHaveBeenCalledWith('image-map-instance');+ // The outline is the border the user sees, not just a state attribute.+ await vi.waitFor(() => expect(borderColor()).not.toBe(restingBorder));controller.clear();+ await act(() => Promise.resolve());+ await vi.waitFor(() => expect(borderColor()).toBe(restingBorder));+ });++ it('becomes the active window and raises itself when keyboard focus arrives, with no press', async () => {+ const controller = createTestFocusController();+ await renderWindow(state, controller);++ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!.focus());++ expect(controller.getTarget()).toEqual({ instanceId: 'image-map-instance', kind: 'floating' });+ expect(windowMocks.raiseFloating).toHaveBeenCalledWith('image-map-instance');+ });++ it('does not raise again when focus moves around inside the window that is already active', async () => {+ await renderWindow();+ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!.focus());+ expect(windowMocks.raiseFloating).toHaveBeenCalledOnce();++ // A Tab to the next control, or a closing dialog handing focus back: nothing to write, and nothing that+ // could pull this window back over one a recall has since revealed on top of it.+ await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Maximize"]')!.focus());await act(() => host!.querySelector<HTMLButtonElement>('button[aria-label="Shade"]')!.focus());+ expect(windowMocks.raiseFloating).toHaveBeenCalledOnce();+ });++ it('is active without an outline when the highlight preference is off', async () => {+ windowMocks.showFocusHighlight = false;+ const controller = createTestFocusController();+ await renderWindow(state, controller);+ const restingBorder = borderColor();++ await act(() => floatingWindow().dispatchEvent(new PointerEvent('pointerdown', { bubbles: true })));+expect(controller.getTarget()).toEqual({ instanceId: 'image-map-instance', kind: 'floating' });+ expect(windowMocks.raiseFloating).toHaveBeenCalledWith('image-map-instance');+ expect(floatingWindow().getAttribute('data-highlighted')).toBe('false');+ expect(borderColor()).toBe(restingBorder);});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')- );+ await renderWindow(state, createTestFocusController());outside.focus();await act(() =>@@ -348,33 +540,54 @@ describe('FloatingWidgetWindow focus', () => {});it('is not activated or raised by hover', async () => {- const controller = createWorkbenchFocusController(() => 'project-1');+ const controller = createTestFocusController();await renderWindow(state, controller);await act(() => {for (const type of ['pointerover', 'pointerenter', 'pointermove']) {floatingWindow().dispatchEvent(new PointerEvent(type, { bubbles: true }));}+ floatingWindow().dispatchEvent(new MouseEvent('mouseover', { bubbles: true }));});expect(controller.getTarget()).toBeNull();- expect(windowMocks.focusFloating).not.toHaveBeenCalled();+ expect(windowMocks.raiseFloating).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');+ const controller = createTestFocusController({ getProjectId: () => '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();+ expect(windowMocks.raiseFloating).not.toHaveBeenCalled();+ });++ it('shows a ring on its frame when keyboard focus lands on the window itself', async () => {+ const before = document.createElement('button');+ host!.before(before);+ await renderWindow();+ const frame = floatingWindow().firstElementChild!;++ expect(getComputedStyle(frame).outlineStyle).toBe('none');++ // A keyboard user floats a panel: focus is moved onto the window root by script.+ before.focus();+ await userEvent.keyboard('{Tab}');+ await act(() => floatingWindow().focus());++ expect(floatingWindow().matches(':focus-visible')).toBe(true);+ // Drawn on the frame, which is its own layer and would cover a ring on the root.+ expect(getComputedStyle(frame)).toMatchObject({ outlineStyle: 'solid', outlineWidth: '2px' });+ expect(getComputedStyle(floatingWindow()).outlineStyle).toBe('none');+ before.remove();});it('can take scripted focus, and sends focus to its return region when it docks', async () => {- const controller = createWorkbenchFocusController(() => 'project-1');+ const controller = createTestFocusController();const focusRegion = vi.spyOn(controller, 'focusRegion');await renderWindow(state, controller);@@ -391,8 +604,8 @@ describe('FloatingWidgetWindow focus', () => {});describe('FloatingWidgetWindow gestures', () => {- const pointer = (type: string, clientX: number, clientY: number, buttons: number) =>- new PointerEvent(type, { bubbles: true, buttons, clientX, clientY, pointerId: 1 });+ const pointer = (type: string, clientX: number, clientY: number, buttons: number, init: PointerEventInit = {}) =>+ new PointerEvent(type, { bubbles: true, buttons, clientX, clientY, pointerId: 1, ...init });const nextFrame = () =>act(() =>@@ -400,57 +613,547 @@ describe('FloatingWidgetWindow gestures', () => {requestAnimationFrame(() => resolve());}));- const windowElement = () => host!.querySelector<HTMLElement>('[data-hotkey-widget-region="floating"]')!;-- it('renders a corner resize live and commits it once on release', async () => {+ const windowElement = () => host!.querySelector<HTMLElement>('[data-floating-window]')!;+ const titleBar = () => host!.querySelector<HTMLElement>('[aria-label="Move Image Map window"]')!;+ // The title bar's divider is a separator too; the resize grip is the one with a value.+ const corner = () => host!.querySelector<HTMLElement>('[role="separator"][aria-valuemin]')!;+ const edge = (name: string) => host!.querySelector<HTMLElement>(`[data-resize-edge="${name}"]`)!;+ /** What the gesture in flight is previewing, as written on the window element. */+ const preview = () => ({+ h: windowElement().style.getPropertyValue('--fw-preview-h'),+ mode: windowElement().dataset.floatingPreview,+ w: windowElement().style.getPropertyValue('--fw-preview-w'),+ x: windowElement().style.getPropertyValue('--fw-preview-x'),+ y: windowElement().style.getPropertyValue('--fw-preview-y'),+ });+ const NO_PREVIEW = { h: '', mode: undefined, w: '', x: '', y: '' };+ const rect = () => {+ const { height, left, top, width } = windowElement().getBoundingClientRect();++ return { height, left, top, width };+ };+ const press = (handle: HTMLElement, init?: PointerEventInit) =>+ act(() => handle.dispatchEvent(pointer('pointerdown', 100, 100, 1, init)));+ const moveBy = async (deltaX: number, deltaY: number, init?: PointerEventInit) => {+ await act(() => window.dispatchEvent(pointer('pointermove', 100 + deltaX, 100 + deltaY, 1, init)));+ await nextFrame();+ };+ const release = (deltaX: number, deltaY: number, init?: PointerEventInit) =>+ act(() => window.dispatchEvent(pointer('pointerup', 100 + deltaX, 100 + deltaY, 0, init)));+ /** Press, drag by an offset over several pointer moves, and (optionally) release. */+ const drag = async (handle: HTMLElement, deltaX: number, deltaY: number, { release: doRelease = true } = {}) => {+ await press(handle);+ for (const step of [0.25, 0.5, 0.75, 1]) {+ await moveBy(deltaX * step, deltaY * step);+ }+ if (doRelease) {+ await release(deltaX, deltaY);+ }+ };+ /** Every store command the window can issue, to show a drag in flight issues none. */+ const commandCalls = () =>+ [+ windowMocks.dockFloating,+ windowMocks.raiseFloating,+ windowMocks.setFloatingGeometry,+ windowMocks.setFloatingMode,+ ].reduce((total, command) => total + command.mock.calls.length, 0);++ it('renders a corner resize live, issues no command while the pointer moves, and commits once on release', async () => {await renderWindow();- const corner = host!.querySelector<HTMLElement>('[role="separator"][aria-valuemin]')!;- await act(() => corner.dispatchEvent(pointer('pointerdown', 0, 0, 1)));- await act(() => window.dispatchEvent(pointer('pointermove', 60, 40, 1)));- await nextFrame();+ await press(corner());+ const commandsAfterPress = commandCalls();+ for (const step of [0.25, 0.5, 0.75, 1]) {+ await moveBy(60 * step, 40 * step);+ }- expect(windowElement().style.width).toBe('560px');- expect(windowElement().style.height).toBe('440px');+ expect(preview()).toEqual({ h: '440px', mode: 'windowed', w: '560px', x: '40px', y: '40px' });+ expect(rect()).toEqual({ height: 440, left: 40, top: 40, width: 560 });+ // Four coalesced pointer moves, zero store commands of any kind.+ expect(commandCalls()).toBe(commandsAfterPress);expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();- await act(() => window.dispatchEvent(pointer('pointerup', 60, 40, 0)));- expect(windowMocks.setFloatingGeometry).toHaveBeenCalledOnce();+ await release(60, 40);+ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledExactlyOnceWith('image-map-instance', {+ heightPx: 440,+ widthPx: 560,+ x: 40,+ y: 40,+ });await nextFrame();- expect(windowElement().style.width).toBe('');+ expect(preview()).toEqual(NO_PREVIEW);+ });++ it.each([+ // The opposite side stays put: dragging the left edge left moves x and grows the width.+ ['w', -50, 30, 'ew-resize', { heightPx: 400, widthPx: 550, x: -10, y: 40 }],+ ['e', 50, 30, 'ew-resize', { heightPx: 400, widthPx: 550, x: 40, y: 40 }],+ ['s', 30, 50, 'ns-resize', { heightPx: 450, widthPx: 500, x: 40, y: 40 }],+ // The top edge stops at the viewport's top, so the title bar stays reachable.+ ['n', 30, -100, 'ns-resize', { heightPx: 440, widthPx: 500, x: 40, y: 0 }],+ ['nw', 20, 20, 'nwse-resize', { heightPx: 380, widthPx: 480, x: 60, y: 60 }],+ ['ne', 20, 20, 'nesw-resize', { heightPx: 380, widthPx: 520, x: 40, y: 60 }],+ // The minimum size holds, and the anchored right edge keeps the window from sliding.+ ['sw', 400, -400, 'nesw-resize', { heightPx: 200, widthPx: 280, x: 260, y: 40 }],+ // The band outside the bottom-right corner, around the labelled grip.+ ['se', 30, 20, 'nwse-resize', { heightPx: 420, widthPx: 530, x: 40, y: 40 }],+ ] as const)('resizes from the %s handle', async (name, deltaX, deltaY, cursor, expected) => {+ await renderWindow();++ expect(getComputedStyle(edge(name)).cursor).toBe(cursor);++ await drag(edge(name), deltaX, deltaY);++ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledExactlyOnceWith('image-map-instance', expected);+ });++ it('puts a handle under the pointer just outside and just inside every edge and corner, and no two at once', async () => {+ await renderWindow();+ const { bottom, left, right, top } = windowElement().getBoundingClientRect();+ const middleX = (left + right) / 2;+ const middleY = (top + bottom) / 2;+ const at = (x: number, y: number) => {+ const element = document.elementFromPoint(x, y);++ return element === corner() ? 'grip' : ((element as HTMLElement | null)?.dataset.resizeEdge ?? null);+ };++ // 2px outside the border, then 2px inside it.+ expect([at(middleX, top - 2), at(middleX, top + 2)]).toEqual(['n', 'n']);+ expect([at(middleX, bottom + 2), at(middleX, bottom - 2)]).toEqual(['s', 's']);+ expect([at(left - 2, middleY), at(left + 2, middleY)]).toEqual(['w', 'w']);+ expect([at(right + 2, middleY), at(right - 2, middleY)]).toEqual(['e', 'e']);+ expect([at(left - 2, top - 2), at(left + 2, top + 2)]).toEqual(['nw', 'nw']);+ expect([at(right + 2, top - 2), at(right - 2, top + 2)]).toEqual(['ne', 'ne']);+ expect([at(left - 2, bottom + 2), at(left + 2, bottom - 2)]).toEqual(['sw', 'sw']);+ // The bottom-right corner: the pointer-only band outside, the labelled grip inside.+ expect([at(right + 2, bottom + 2), at(right + 2, bottom - 6), at(right - 6, bottom + 2)]).toEqual([+ 'se',+ 'se',+ 'se',+ ]);+ expect(at(right - 6, bottom - 6)).toBe('grip');+ // Past the reach on either side there is no handle: the content inside, nothing of the window outside.+ expect(at(middleX, top + 6)).toBeNull();+ expect(at(middleX, top - 6)).toBeNull();+ });++ it('leaves every title-bar control fully clickable beside the resize corners', async () => {+ await renderWindow();++ for (const name of ['Shade', 'Maximize', 'Dock to right panel', 'Toggle cluster labels']) {+ const button = host!.querySelector(`button[aria-label="${name}"]`)!;+ const { bottom, left, right, top } = button.getBoundingClientRect();++ // Just inside each side, at the middle: no resize handle may sit over any part of the control.+ for (const [x, y] of [+ [(left + right) / 2, top + 1],+ [(left + right) / 2, bottom - 1],+ [left + 1, (top + bottom) / 2],+ [right - 1, (top + bottom) / 2],+ ]) {+ expect(document.elementFromPoint(x, y)?.closest('button')).toBe(button);+ }+ }+ });++ it('keeps one labelled, keyboard-operable resize control and leaves the rest to the pointer', async () => {+ await renderWindow();++ const pointerOnly = [...host!.querySelectorAll<HTMLElement>('[data-resize-edge]')];++ expect(pointerOnly.map((handle) => handle.dataset.resizeEdge).sort()).toEqual([+ 'e',+ 'n',+ 'ne',+ 'nw',+ 's',+ 'se',+ 'sw',+ 'w',+ ]);+ for (const handle of pointerOnly) {+ expect(handle.getAttribute('aria-hidden')).toBe('true');+ expect(handle.hasAttribute('tabindex')).toBe(false);+ expect(handle.hasAttribute('role')).toBe(false);+ }+ expect(host!.querySelectorAll('[role="separator"][aria-valuemin]')).toHaveLength(1);+ expect(corner().tabIndex).toBe(0);+ expect(corner().getAttribute('aria-label')).toBe('Resize window');+ // A separator's value is one number; the size in words covers both dimensions.+ expect(corner().getAttribute('aria-valuetext')).toBe('500 by 400 pixels');+ expect(Number(corner().getAttribute('aria-valuemax'))).toBeGreaterThanOrEqual(500);+ });++ it('has no resize handles while maximized or collapsed', async () => {+ for (const mode of ['maximized', 'shaded'] as const) {+ await renderWindow({ ...state, mode });++ expect(host!.querySelectorAll('[data-resize-edge]')).toHaveLength(0);+ expect(host!.querySelector('[role="separator"][aria-valuemin]')).toBeNull();+ }});- it('drops the live size when the window maximizes mid-resize', async () => {+ it('resizes from the keyboard through the one labelled handle', async () => {await renderWindow();- const corner = host!.querySelector<HTMLElement>('[role="separator"][aria-valuemin]')!;+ const key = (init: KeyboardEventInit) =>+ act(() => corner().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, ...init })));++ await key({ key: 'ArrowRight' });+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 400,+ widthPx: 516,+ x: 40,+ y: 40,+ });++ await key({ key: 'ArrowDown', shiftKey: true });+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 432,+ widthPx: 500,+ x: 40,+ y: 40,+ });++ await key({ key: 'Home' });+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 200,+ widthPx: 280,+ x: 40,+ y: 40,+ });+ });++ it('caps the displayed size and keeps a sliver reachable without rewriting what is stored', async () => {+ await page.viewport(600, 500);+ // Stored on a larger display: wider and taller than this viewport, and far off its right edge.+ await renderWindow({ ...state, heightPx: 900, widthPx: 900, x: 5000, y: 40 });++ expect(rect()).toEqual({ height: 500, left: 600 - 48, top: 40, width: 600 });++ // The viewport grows back: the stored rectangle returns, as far as it fits.+ await page.viewport(1200, 800);+ expect(rect()).toEqual({ height: 800, left: 1200 - 48, top: 40, width: 900 });+ // None of that wrote anything.+ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ });++ it('commits nothing for a press that never moves, even where the viewport clamps or caps the window', async () => {+ await page.viewport(600, 500);+ await renderWindow({ ...state, heightPx: 300, widthPx: 900, x: 5000, y: 40 });++ // A click on the title bar — the first half of a double-click — and one on an edge, with pointer jitter that+ // nets to nothing.+ for (const handle of [titleBar(), edge('s')]) {+ await press(handle);+ await moveBy(3, 2);+ await moveBy(0, 0);+ await release(0, 0);+ await nextFrame();+ }++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ expect(preview()).toEqual(NO_PREVIEW);+ });++ it('starts a move from where the window is on screen, and keeps the stored size', async () => {+ await page.viewport(600, 500);+ await renderWindow({ ...state, heightPx: 300, widthPx: 900, x: 5000, y: 40 });++ await drag(titleBar(), -100, 20, { release: false });++ // No jump: the preview continues from the clamped position, 552px, not from the stored 5000px.+ expect(rect().left).toBe(452);++ await release(-100, 20);++ // The viewport's 600px cap on the width is not the user's choice to persist.+ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledExactlyOnceWith('image-map-instance', {+ heightPx: 300,+ widthPx: 900,+ x: 452,+ y: 60,+ });+ });++ it('starts keyboard steps from where the window is on screen too', async () => {+ await page.viewport(600, 500);+ await renderWindow({ ...state, heightPx: 300, widthPx: 900, x: 5000, y: 40 });++ await act(() => titleBar().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowLeft' })));+ // One 16px step left of the clamped 552px, keeping the stored size.+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 300,+ widthPx: 900,+ x: 536,+ y: 40,+ });++ await act(() =>+ titleBar().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown', shiftKey: true }))+ );+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 300,+ widthPx: 900,+ x: 552,+ y: 72,+ });+ });++ it('does not move a maximized window from the keyboard', async () => {+ await renderWindow({ ...state, mode: 'maximized' });++ await act(() => titleBar().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowLeft' })));++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ });++ it('resizes the axis that was dragged from its size on screen, and leaves the other axis as stored', async () => {+ await page.viewport(600, 500);+ // 900px wide in storage, shown capped at 600px.+ await renderWindow({ ...state, heightPx: 300, widthPx: 900, x: 0, y: 40 });++ await drag(edge('s'), 0, 50);+ // Only the height was the user's to change; the 600px cap on the width is not persisted.+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 350,+ widthPx: 900,+ x: 0,+ y: 40,+ });- await act(() => corner.dispatchEvent(pointer('pointerdown', 0, 0, 1)));- await act(() => window.dispatchEvent(pointer('pointermove', 60, 40, 1)));await nextFrame();- expect(windowElement().style.width).toBe('560px');+ await drag(edge('e'), -50, 0);+ // Dragging the width starts from the 600px on screen, not the 900px stored for a larger display.+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 300,+ widthPx: 550,+ x: 0,+ y: 40,+ });++ await nextFrame();+ await act(() => corner().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowDown' })));+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 316,+ widthPx: 900,+ x: 0,+ y: 40,+ });+ });++ it('does not grow a window past the viewport, so an edge at the cap resizes nothing instead of sliding it', async () => {+ await page.viewport(600, 500);+ await renderWindow({ ...state, heightPx: 300, widthPx: 600, x: 0, y: 40 });++ await drag(edge('w'), -80, 0, { release: false });++ // Already as wide as it can be shown: the anchored right edge stays where it is.+ expect(rect()).toMatchObject({ left: 0, width: 600 });++ await release(-80, 0);+ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ });++ it('commits nothing for a drag or key step against the viewport cap, so the cap is never what gets stored', async () => {+ await page.viewport(600, 500);+ // 900px wide in storage, shown capped at 600px.+ await renderWindow({ ...state, heightPx: 300, widthPx: 900, x: 0, y: 40 });++ await drag(edge('e'), 80, 0);+ await act(() => corner().dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'ArrowRight' })));++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ });++ it('moves a collapsed window by its title bar and keeps its stored height', async () => {+ await renderWindow({ ...state, mode: 'shaded' });++ await drag(titleBar(), 30, 20);++ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledExactlyOnceWith('image-map-instance', {+ heightPx: 400,+ widthPx: 500,+ x: 70,+ y: 60,+ });+ });++ it('ignores a press that is not the primary button', async () => {+ await renderWindow();++ for (const handle of [titleBar(), edge('e'), corner()]) {+ await press(handle, { button: 2 });+ await moveBy(40, 40);+ await release(40, 40);+ }++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ expect(preview()).toEqual(NO_PREVIEW);+ });++ it.each([+ ['the corner grip', () => corner()],+ ['an edge handle', () => edge('e')],+ ['the title bar', () => titleBar()],+ ] as const)('stands a gesture from %s down when the window maximizes under it', async (_name, handle) => {+ await renderWindow();++ await drag(handle(), 30, 20, { release: false });+ expect(preview().mode).toBe('windowed');await renderWindow({ ...state, mode: 'maximized' });- await act(() => window.dispatchEvent(pointer('pointerup', 60, 40, 0)));+ // The new frame shows at once: the preview is for a mode the window is no longer in.+ expect(rect()).toEqual({ height: 800, left: 0, top: 0, width: 1200 });++ // The next the gesture hears from the pointer, it ends itself: no preview, no drag cursor, no commit.+ await moveBy(60, 60);+ expect(preview()).toEqual(NO_PREVIEW);+ expect(document.documentElement.hasAttribute('data-pointer-drag')).toBe(false);- expect(windowElement().style.width).toBe('');+ await release(60, 60);+ await nextFrame();expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();});- it('moves by the title bar and abandons the move on Escape', async () => {+ it('stands a title-bar move down when the window collapses under it', async () => {await renderWindow();- const titleBar = host!.querySelector<HTMLElement>('[aria-label="Move Image Map window"]')!;- await act(() => titleBar.dispatchEvent(pointer('pointerdown', 0, 0, 1)));- await act(() => window.dispatchEvent(pointer('pointermove', 30, 20, 1)));+ await drag(titleBar(), 30, 20, { release: false });+ expect(preview().x).toBe('70px');++ await renderWindow({ ...state, mode: 'shaded' });+ // Back at its stored position, rolled up, before the pointer moves again.+ expect(rect()).toMatchObject({ left: 40, top: 40, width: 500 });+ expect(rect().height).toBeLessThan(60);++ await release(30, 20);await nextFrame();- expect(windowElement().style.left).toContain('70px');+ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ expect(preview()).toEqual(NO_PREVIEW);+ });++ it('moves by the title bar and abandons the move on Escape', async () => {+ await renderWindow();++ await drag(titleBar(), 30, 20, { release: false });+ expect(preview().x).toBe('70px');await act(() => window.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, key: 'Escape' })));- await act(() => window.dispatchEvent(pointer('pointerup', 30, 20, 0)));+ await release(30, 20);+ await nextFrame();++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ expect(preview()).toEqual(NO_PREVIEW);+ });++ it('keeps what was dragged so far when the pointer is taken away', async () => {+ await renderWindow();++ // The browser cancels the pointer (a touch gesture taken over, a system interruption).+ await drag(titleBar(), 30, 20, { release: false });+ await act(() => window.dispatchEvent(pointer('pointercancel', 130, 120, 0)));+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 400,+ widthPx: 500,+ x: 70,+ y: 60,+ });++ // The release happened outside the page; the next move arrives with no button held.+ await nextFrame();+ await drag(edge('e'), 40, 0, { release: false });+ await act(() => window.dispatchEvent(pointer('pointermove', 400, 400, 0)));+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 400,+ widthPx: 540,+ x: 40,+ y: 40,+ });+ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledTimes(2);+ });++ it('lets a gesture that starts in the frame after a commit keep its own preview', async () => {+ await renderWindow();++ await drag(titleBar(), 30, 20);+ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledOnce();++ // No frame has passed: the first gesture's preview is still up, waiting to be cleared. The second gesture+ // starts from the stored rectangle (this test's store is a mock, so the commit did not move the window) and+ // the stale clear must not wipe it.+ await press(edge('e'));+ await act(() => window.dispatchEvent(pointer('pointermove', 150, 100, 1)));+ await nextFrame();+ await nextFrame();++ expect(preview()).toEqual({ h: '400px', mode: 'windowed', w: '550px', x: '40px', y: '40px' });++ await release(50, 0);+ expect(windowMocks.setFloatingGeometry).toHaveBeenLastCalledWith('image-map-instance', {+ heightPx: 400,+ widthPx: 550,+ x: 40,+ y: 40,+ });+ });++ it('hands the window to a second gesture: the first commits nothing and stops steering', async () => {+ await renderWindow();++ // One pointer is dragging the title bar when a second presses the grip.+ await drag(titleBar(), 30, 20, { release: false });+ await press(corner(), { pointerId: 2 });+ expect(preview()).toEqual(NO_PREVIEW);++ // The first pointer keeps moving and lets go: it no longer owns anything.+ await moveBy(200, 200);+ await release(200, 200);+ expect(preview()).toEqual(NO_PREVIEW);+ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();++ await moveBy(60, 40, { pointerId: 2 });+ expect(preview()).toMatchObject({ h: '440px', w: '560px' });+ await release(60, 40, { pointerId: 2 });++ expect(windowMocks.setFloatingGeometry).toHaveBeenCalledExactlyOnceWith('image-map-instance', {+ heightPx: 440,+ widthPx: 560,+ x: 40,+ y: 40,+ });+ });++ it('maximizes on a real double-click without writing geometry for the two presses', async () => {+ await renderWindow();++ for (let click = 0; click < 2; click += 1) {+ await press(titleBar());+ await release(0, 0);+ }+ await act(() => titleBar().dispatchEvent(new MouseEvent('dblclick', { bubbles: true })));+ await nextFrame();++ expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();+ expect(windowMocks.setFloatingMode).toHaveBeenCalledExactlyOnceWith('image-map-instance', 'maximized');+ });++ it('commits nothing and releases the pointer when the window unmounts mid-gesture', async () => {+ await renderWindow();++ await drag(titleBar(), 30, 20, { release: false });+ expect(document.documentElement.hasAttribute('data-pointer-drag')).toBe(true);++ // Docking, removing, or switching project all take the window away.+ await act(() => root?.render(null));+ expect(document.documentElement.hasAttribute('data-pointer-drag')).toBe(false);++ await act(() => window.dispatchEvent(pointer('pointermove', 300, 300, 1)));+ await release(200, 200);await nextFrame();expect(windowMocks.setFloatingGeometry).not.toHaveBeenCalled();- expect(windowElement().style.left).toBe('');});});diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsxindex eac4248472..2948868886 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx@@ -1,16 +1,20 @@-import type { FloatingWidgetState } from '@workbench/layoutContracts';+import type { FloatingWidgetMode, FloatingWidgetState } from '@workbench/layoutContracts';import type { WidgetInstanceId } from '@workbench/widgetContracts';-import { Flex, HStack, Icon, Separator, Text } from '@chakra-ui/react';+import { Box, Flex, HStack, Icon, Separator, type SystemStyleObject, Text } from '@chakra-ui/react';import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';import { IconButton } from '@platform/ui/Button';-import { type PointerDragEnd, ResizeCorner, usePointerDrag } from '@platform/ui/ResizeHandle';+import { ResizeCorner, trackResizeDrag, usePointerDrag } from '@platform/ui/ResizeHandle';import { Tooltip } from '@platform/ui/Tooltip';import {clampWindowToViewport,+ commitResizedAxes,FLOATING_MIN_HEIGHT_PX,FLOATING_MIN_WIDTH_PX,+ FLOATING_VIEWPORT_MARGIN_PX,+ resizeFloatingGeometry,type FloatingGeometry,+ type FloatingResizeEdge,} from '@workbench/floatingWindows';import { useFloatingWindowFocus, useWorkbenchFocus } from '@workbench/focusRegions';import { WidgetIcon } from '@workbench/iconResolver';@@ -19,11 +23,13 @@ import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } frimport { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';import { ChevronsDownUpIcon, ChevronsUpDownIcon, Maximize2Icon, Minimize2Icon, TriangleAlertIcon } from 'lucide-react';import {+ Activity,Component,Suspense,useCallback,useMemo,useRef,+ type CSSProperties,type KeyboardEvent as ReactKeyboardEvent,type MouseEvent as ReactMouseEvent,type PointerEvent as ReactPointerEvent,@@ -39,17 +45,201 @@ const FLOATING_BASE_Z_INDEX = 800;/** Keyboard step for moving and resizing, matching the panel resize handles. */const FLOATING_STEP_PX = 16;-// CSS clamp keeps a grabbable sliver on-screen even for geometry persisted on a larger display (or after the-// browser window shrinks); the commit clamp only covers drags on the current viewport.-const toWindowPosition = (geometry: FloatingGeometry) => ({- height: `${geometry.heightPx}px`,- left: `clamp(${48 - geometry.widthPx}px, ${geometry.x}px, calc(100vw - 48px))`,- top: `clamp(0px, ${geometry.y}px, calc(100vh - 48px))`,- width: `${geometry.widthPx}px`,-});+const MARGIN = `${FLOATING_VIEWPORT_MARGIN_PX}px`;++// Inset, so it shows on a maximized window too and is not clipped at the viewport's edge.+const FOCUS_RING = { outline: '2px solid', outlineColor: 'accent.solid', outlineOffset: '-2px' } as const;++/**+ * One static rule set for every window. The stored geometry arrives as custom properties, so committing a move+ * or a raise changes inline values rather than minting a class per geometry.+ *+ * The position keeps a grabbable sliver on screen and the size never exceeds the viewport, both without touching+ * what is stored: a window persisted on a larger display, or left behind by a shrunken browser window, comes back+ * as it was when there is room again (`clampWindowToViewport` is the same policy for what a gesture commits).+ *+ * A gesture previews its geometry in `--fw-preview-*` and names the mode it started in. The preview applies only+ * while the window is still in that mode, so a window that maximizes or shades under a gesture shows its new+ * frame at once.+ */+const WINDOW_SX: SystemStyleObject = {+ '--fw-left': 'var(--fw-x)',+ '--fw-top': 'var(--fw-y)',+ '--fw-width': 'var(--fw-w)',+ '--fw-height': 'var(--fw-h)',+ '&[data-floating-mode="windowed"][data-floating-preview="windowed"], &[data-floating-mode="shaded"][data-floating-preview="shaded"]':+ {+ '--fw-left': 'var(--fw-preview-x, var(--fw-x))',+ '--fw-top': 'var(--fw-preview-y, var(--fw-y))',+ '--fw-width': 'var(--fw-preview-w, var(--fw-w))',+ '--fw-height': 'var(--fw-preview-h, var(--fw-h))',+ },+ height: 'min(var(--fw-height), 100vh)',+ left: `clamp(calc(${MARGIN} - min(var(--fw-width), 100vw)), var(--fw-left), calc(100vw - ${MARGIN}))`,+ top: `clamp(0px, var(--fw-top), calc(100vh - ${MARGIN}))`,+ width: 'min(var(--fw-width), 100vw)',+ '&[data-floating-mode="shaded"]': { height: 'auto' },+ '&[data-floating-mode="maximized"]': { height: '100vh', left: '0', top: '0', width: '100vw' },+ // Keyboard focus that lands on the window itself — after Float, or a marker's reveal — shows on its frame: the+ // frame is its own layer and would cover a ring drawn on the root. It shows whatever the outline preference is.+ outline: 'none',+ '&:focus-visible > [data-floating-frame]': FOCUS_RING,+};++/** A window is never shown larger than the viewport, so a resize does not grow past it either. */+const getViewportSize = () => ({ heightPx: window.innerHeight, widthPx: window.innerWidth });++// A drag rewrites the preview properties every frame. Custom properties inherit by default, which would restyle+// the whole widget inside the window each time; registered as non-inheriting, only the window itself is restyled.+// The universal syntax keeps the `var(--fw-preview-x, var(--fw-x))` fallback working while a property is unset.+if (typeof CSS !== 'undefined' && typeof CSS.registerProperty === 'function') {+ for (const name of [+ 'x',+ 'y',+ 'w',+ 'h',+ 'preview-x',+ 'preview-y',+ 'preview-w',+ 'preview-h',+ 'left',+ 'top',+ 'width',+ 'height',+ ]) {+ try {+ CSS.registerProperty({ inherits: false, name: `--fw-${name}`, syntax: '*' });+ } catch {+ // Already registered: this module was evaluated before (hot reload).+ }+ }+}++const PREVIEW_PROPERTIES = {+ heightPx: '--fw-preview-h',+ widthPx: '--fw-preview-w',+ x: '--fw-preview-x',+ y: '--fw-preview-y',+} as const satisfies Record<keyof FloatingGeometry, string>;++/** How far a resize handle reaches to either side of the window's border. */+const HANDLE_REACH = '4px';+/** The corner squares' side — the labelled grip's size — so the edge strips run between them without overlap. */+const HANDLE_CORNER = '1rem';+const EDGE_INSET = `calc(${HANDLE_CORNER} - ${HANDLE_REACH})`;+const HANDLE_OFFSET = `-${HANDLE_REACH}`;+const EDGE_THICKNESS = `calc(${HANDLE_REACH} * 2)`;+const OUTER_CORNER = `calc(${HANDLE_CORNER} + ${HANDLE_REACH})`;++/**+ * The pointer-only resize handles: four edges and four corners. The bottom-right corner's inside is the labelled+ * `ResizeCorner`, the one handle that also takes the keyboard, so the strips beside it stop at its square and the+ * pointer-only handle there is clipped to the band outside the border.+ */+const RESIZE_HANDLES: readonly { cursor: string; edge: FloatingResizeEdge; sx: SystemStyleObject }[] = [+ {+ cursor: 'ns-resize',+ edge: 'n',+ sx: { height: EDGE_THICKNESS, left: EDGE_INSET, right: EDGE_INSET, top: HANDLE_OFFSET },+ },+ {+ cursor: 'ns-resize',+ edge: 's',+ sx: { bottom: HANDLE_OFFSET, height: EDGE_THICKNESS, left: EDGE_INSET, right: HANDLE_CORNER },+ },+ {+ cursor: 'ew-resize',+ edge: 'w',+ sx: { bottom: EDGE_INSET, left: HANDLE_OFFSET, top: EDGE_INSET, width: EDGE_THICKNESS },+ },+ {+ cursor: 'ew-resize',+ edge: 'e',+ sx: { bottom: HANDLE_CORNER, right: HANDLE_OFFSET, top: EDGE_INSET, width: EDGE_THICKNESS },+ },+ {+ cursor: 'nwse-resize',+ edge: 'nw',+ sx: { height: HANDLE_CORNER, left: HANDLE_OFFSET, top: HANDLE_OFFSET, width: HANDLE_CORNER },+ },+ {+ cursor: 'nesw-resize',+ edge: 'ne',+ sx: { height: HANDLE_CORNER, right: HANDLE_OFFSET, top: HANDLE_OFFSET, width: HANDLE_CORNER },+ },+ {+ cursor: 'nesw-resize',+ edge: 'sw',+ sx: { bottom: HANDLE_OFFSET, height: HANDLE_CORNER, left: HANDLE_OFFSET, width: HANDLE_CORNER },+ },+ {+ cursor: 'nwse-resize',+ edge: 'se',+ sx: {+ bottom: HANDLE_OFFSET,+ // An L around the grip: the box minus the grip's square, which is the part inside the border.+ clipPath: `polygon(${HANDLE_CORNER} 0, 100% 0, 100% 100%, 0 100%, 0 ${HANDLE_CORNER}, ${HANDLE_CORNER} ${HANDLE_CORNER})`,+ height: OUTER_CORNER,+ right: HANDLE_OFFSET,+ width: OUTER_CORNER,+ },+ },+];++const FloatingResizeHandles = ({+ onResizeStart,+}: {+ onResizeStart: (event: ReactPointerEvent<HTMLDivElement>, edge: FloatingResizeEdge, cursor: string) => void;+}) => {+ const handlePointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => {+ const handle = RESIZE_HANDLES.find(({ edge }) => edge === event.currentTarget.dataset.resizeEdge);++ if (handle) {+ onResizeStart(event, handle.edge, handle.cursor);+ }+ },+ [onResizeStart]+ );++ return (+ <>+ {RESIZE_HANDLES.map(({ cursor, edge, sx }) => (+ <Box+ key={edge}+ aria-hidden+ css={sx}+ cursor={cursor}+ data-resize-edge={edge}+ position="absolute"+ // `preventDefault` on pointerdown does not stop touch panning.+ touchAction="none"+ zIndex="1"+ onPointerDown={handlePointerDown}+ />+ ))}+ </>+ );+};/**- * Isolate arbitrary widget controls from title-bar drag and double-click shade gestures; not every control is a+ * One pointer gesture on the window. Everything it needs from the moment it began is here, so nothing it does+ * later depends on which render its handlers were created in.+ */+interface WindowGesture {+ edge: FloatingResizeEdge | 'move';+ /** What a release would commit; null until the pointer has actually moved. */+ live: FloatingGeometry | null;+ mode: FloatingWidgetMode;+ session: AbortController | null;+ /** Where the window was on screen. */+ start: FloatingGeometry;+ /** What was stored, which the gesture keeps on every axis it does not change. */+ stored: FloatingGeometry;+}++/**+ * Isolate arbitrary widget controls from title-bar drag and double-click maximize gestures; not every control is a* button.*/const stopChromeEvent = (event: ReactPointerEvent<HTMLDivElement> | ReactMouseEvent<HTMLDivElement>): void =>@@ -92,83 +282,166 @@ export const FloatingWidgetWindow = ({const { activate, isHighlighted } = useFloatingWindowFocus(instanceId, projectId);const { focusRegion } = useWorkbenchFocus();const windowRef = useRef<HTMLDivElement>(null);- const liveGeometryRef = useRef<FloatingGeometry | null>(null);+ const gestureRef = useRef<WindowGesture | null>(null);const startDrag = usePointerDrag();const widget = instance ? getWidgetById(instance.typeId) : undefined;+ const { heightPx, mode, widthPx, x, y } = state;const commitGeometry = useCallback((geometry: FloatingGeometry) => {const clamped = clampWindowToViewport(geometry, { height: window.innerHeight, width: window.innerWidth });- widgets.setFloatingGeometry(instanceId, clamped);++ // The rendered rectangle a gesture starts from can sit on fractional pixels.+ widgets.setFloatingGeometry(instanceId, {+ heightPx: Math.round(clamped.heightPx),+ widthPx: Math.round(clamped.widthPx),+ x: Math.round(clamped.x),+ y: Math.round(clamped.y),+ });},[instanceId, widgets]);- // A gesture writes geometry inline so it renders without React; the committed render then replaces it.- const writeLiveGeometry = useCallback(- (geometry: FloatingGeometry | null) => {- const element = windowRef.current;- liveGeometryRef.current = geometry;- if (!element) {- return;+ /**+ * Where the window is on screen right now. Gestures and key steps start here, not from the stored geometry:+ * CSS may be holding the window inside the viewport or capping its size, and starting from the stored values+ * would make it jump.+ */+ const readRenderedGeometry = useCallback((): FloatingGeometry | null => {+ const rect = windowRef.current?.getBoundingClientRect();++ return rect ? { heightPx: rect.height, widthPx: rect.width, x: rect.left, y: rect.top } : null;+ }, []);++ // A gesture writes its geometry as inline custom properties so it renders without React; the committed render+ // then replaces it. The mode it names is what limits the preview to the frame the gesture began in.+ const writePreview = useCallback((preview: { geometry: FloatingGeometry; mode: FloatingWidgetMode } | null) => {+ const element = windowRef.current;++ if (!element) {+ return;+ }++ for (const key of Object.keys(PREVIEW_PROPERTIES) as (keyof FloatingGeometry)[]) {+ if (preview) {+ element.style.setProperty(PREVIEW_PROPERTIES[key], `${preview.geometry[key]}px`);+ } else {+ element.style.removeProperty(PREVIEW_PROPERTIES[key]);}- const position = geometry ? toWindowPosition(geometry) : null;- for (const property of ['left', 'top', 'width', 'height'] as const) {- if (position && !(property === 'height' && state.mode === 'shaded')) {- element.style.setProperty(property, position[property]);- } else {- element.style.removeProperty(property);- }+ }+ if (preview) {+ element.dataset.floatingPreview = preview.mode;+ } else {+ delete element.dataset.floatingPreview;+ }+ }, []);++ const cancelGesture = useCallback(() => {+ const gesture = gestureRef.current;++ gestureRef.current = null;+ writePreview(null);+ // Ends the pointer session too: the drag cursor and the Escape capture do not outlive the gesture.+ gesture?.session?.abort();+ }, [writePreview]);++ /** Every handle and the title bar start here, so one gesture owns the window at a time. */+ const startWindowDrag = useCallback(+ (event: ReactPointerEvent<HTMLElement>, edge: WindowGesture['edge'], cursor: string) => {+ if (event.button !== 0) {+ return;}- },- [state.mode]- );- const endGesture = useCallback(- (reason: PointerDragEnd) => {- const geometry = liveGeometryRef.current;- if (reason === 'escape') {- writeLiveGeometry(null);++ // One gesture at a time. This also drops a committed preview still waiting out its last frame, so the+ // starting rectangle is read from the committed render.+ cancelGesture();++ const handle = event.currentTarget;+ const start = readRenderedGeometry();++ if (!start) {return;}- // Scheduled first so a throwing commit still clears the preview.- requestAnimationFrame(() => writeLiveGeometry(null));- if (geometry) {- commitGeometry(geometry);++ const stored = { heightPx, widthPx, x, y };+ const gesture: WindowGesture = { edge, live: null, mode, session: null, start, stored };+ const isCurrent = () => gestureRef.current === gesture;++ gestureRef.current = gesture;+ gesture.session = startDrag(event, {+ cursor,+ onEnd: (reason) => {+ if (!isCurrent()) {+ return;+ }++ gestureRef.current = null;+ // Nothing moved, the user backed out, or the window is no longer in the mode the offsets were for.+ if (!gesture.live || reason === 'escape' || windowRef.current?.dataset.floatingMode !== gesture.mode) {+ writePreview(null);+ return;+ }++ // Hold the preview one more frame so the committed render replaces it without a flash; scheduled first+ // so a throwing commit still clears it. A gesture that starts before that frame is safe from it: frames+ // run in order, and a gesture writes its first preview in a later one.+ requestAnimationFrame(() => writePreview(null));+ commitGeometry(gesture.live);+ },+ onMove: (deltaX, deltaY) => {+ if (!isCurrent()) {+ return;+ }+ // The window changed mode under the gesture — a shortcut, an undo, a preset. Its offsets no longer+ // describe anything on screen, so it stands down and commits nothing.+ if (windowRef.current?.dataset.floatingMode !== gesture.mode) {+ cancelGesture();+ return;+ }+ // A gesture commits only what it changed. A press that never moves, or a drag against the minimum or+ // the viewport's cap, changes nothing and commits nothing; a move keeps the stored size and a resize+ // keeps the axis it does not touch. What is on screen there may only be the viewport's clamp or cap,+ // which is not the user's choice to persist.+ gesture.live =+ edge !== 'move'+ ? commitResizedAxes(stored, start, resizeFloatingGeometry(start, edge, deltaX, deltaY, getViewportSize()))+ : deltaX === 0 && deltaY === 0+ ? null+ : { heightPx: stored.heightPx, widthPx: stored.widthPx, x: start.x + deltaX, y: start.y + deltaY };+ writePreview(gesture.live ? { geometry: gesture.live, mode: gesture.mode } : null);+ },+ });++ const { signal } = gesture.session;++ handle.setAttribute('data-dragging', '');+ if (edge !== 'move') {+ trackResizeDrag(signal);}+ // The session aborts when it ends, when the window unmounts, and when another gesture replaces it; only a+ // gesture that never ended still has a preview to undo.+ signal.addEventListener('abort', () => {+ handle.removeAttribute('data-dragging');+ if (isCurrent()) {+ gestureRef.current = null;+ writePreview(null);+ }+ });},- [commitGeometry, writeLiveGeometry]+ [cancelGesture, commitGeometry, heightPx, mode, readRenderedGeometry, startDrag, widthPx, writePreview, x, y]);- const cancelGesture = useCallback(() => writeLiveGeometry(null), [writeLiveGeometry]);- const startGeometry: FloatingGeometry = useMemo(- () => ({ heightPx: state.heightPx, widthPx: state.widthPx, x: state.x, y: state.y }),- [state.heightPx, state.widthPx, state.x, state.y]- );-const handleTitlePointerDown = useCallback((event: ReactPointerEvent<HTMLDivElement>) => {- if (event.button !== 0 || state.mode === 'maximized' || (event.target as HTMLElement).closest('button')) {- return;+ if (mode !== 'maximized' && !(event.target as HTMLElement).closest('button')) {+ startWindowDrag(event, 'move', 'move');}-- startDrag(event, {- cursor: 'move',- onEnd: endGesture,- onMove: (deltaX, deltaY) =>- writeLiveGeometry({ ...startGeometry, x: startGeometry.x + deltaX, y: startGeometry.y + deltaY }),- });},- [endGesture, startDrag, startGeometry, state.mode, writeLiveGeometry]+ [mode, startWindowDrag]);-- const handleResizeMove = useCallback(- (deltaX: number, deltaY: number) =>- writeLiveGeometry({- ...startGeometry,- heightPx: Math.max(FLOATING_MIN_HEIGHT_PX, startGeometry.heightPx + deltaY),- widthPx: Math.max(FLOATING_MIN_WIDTH_PX, startGeometry.widthPx + deltaX),- }),- [startGeometry, writeLiveGeometry]+ const handleCornerPointerDown = useCallback(+ (event: ReactPointerEvent<HTMLDivElement>) => startWindowDrag(event, 'se', 'nwse-resize'),+ [startWindowDrag]);// Provide keyboard move/resize alongside shade/maximize/dock, matching panel resize steps.@@ -184,25 +457,38 @@ export const FloatingWidgetWindow = ({const offset = offsets[event.key];// Handle movement keys only on the bar itself; controls' bubbling arrows must not alter geometry.- if (!offset || state.mode === 'maximized' || event.target !== event.currentTarget) {+ if (!offset || mode === 'maximized' || event.target !== event.currentTarget) {+ return;+ }++ const rendered = readRenderedGeometry();++ if (!rendered) {return;}event.preventDefault();- commitGeometry({ ...state, x: state.x + offset[0], y: state.y + offset[1] });+ // Like a pointer move: from where the window is on screen, keeping the stored size.+ commitGeometry({ heightPx, widthPx, x: rendered.x + offset[0], y: rendered.y + offset[1] });},- [commitGeometry, state]+ [commitGeometry, heightPx, mode, readRenderedGeometry, widthPx]);const handleResizeKeyDown = useCallback((event: ReactKeyboardEvent<HTMLDivElement>) => {+ const rendered = readRenderedGeometry();++ if (!rendered) {+ return;+ }+const step = event.shiftKey ? FLOATING_STEP_PX * 2 : FLOATING_STEP_PX;const offsets: Partial<Record<string, [number, number]>> = {ArrowDown: [0, step],ArrowLeft: [-step, 0],ArrowRight: [step, 0],ArrowUp: [0, -step],- Home: [FLOATING_MIN_WIDTH_PX - state.widthPx, FLOATING_MIN_HEIGHT_PX - state.heightPx],+ Home: [FLOATING_MIN_WIDTH_PX - rendered.widthPx, FLOATING_MIN_HEIGHT_PX - rendered.heightPx],};const offset = offsets[event.key];@@ -211,21 +497,29 @@ export const FloatingWidgetWindow = ({}event.preventDefault();- commitGeometry({- ...state,- heightPx: Math.max(FLOATING_MIN_HEIGHT_PX, state.heightPx + offset[1]),- widthPx: Math.max(FLOATING_MIN_WIDTH_PX, state.widthPx + offset[0]),- });++ const resized = commitResizedAxes(+ { heightPx, widthPx, x, y },+ rendered,+ resizeFloatingGeometry(rendered, 'se', offset[0], offset[1], getViewportSize())+ );++ if (resized) {+ commitGeometry(resized);+ }},- [commitGeometry, state]+ [commitGeometry, heightPx, readRenderedGeometry, widthPx, x, y]);- // 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);+ // Pointer-down and keyboard focus make this the active window and raise it; hover does neither. A late event+ // from a project that has left the screen is refused before it can raise anything.+ //+ // Focus raises only when it makes this window the active one. Focus moving around inside the window that is+ // already active — a Tab, a closing dialog or popover handing focus back — writes nothing, and cannot re-bury a+ // window that a recall just revealed on top of it. A press always asks; that is a no-op for the topmost window.+ const handleFocusCapture = useCallback(() => {+ if (activate() === 'activated') {+ widgets.raiseFloating(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@@ -235,12 +529,14 @@ export const FloatingWidgetWindow = ({(event: ReactPointerEvent<HTMLDivElement>) => {const element = event.currentTarget;- handleActivate();+ if (activate({ byPointer: true }) !== 'refused') {+ widgets.raiseFloating(instanceId);+ }if (event.target instanceof Node && element.contains(event.target) && !element.contains(document.activeElement)) {element.focus({ preventScroll: true });}},- [handleActivate]+ [activate, instanceId, widgets]);const typeId = instance?.typeId;// Flush drafts before docking remounts the widget; registry cleanup only removes flushers. Focus follows the@@ -252,23 +548,46 @@ export const FloatingWidgetWindow = ({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]- );+ const handleToggleShade = useCallback(() => {+ // Shading hides the body: its editors keep their state but stop running, so their drafts are saved first.+ if (mode !== 'shaded') {+ flushWorkbenchDrafts();+ }+ widgets.setFloatingMode(instanceId, mode === 'shaded' ? 'windowed' : 'shaded');+ }, [instanceId, mode, widgets]);+ // Maximizing leaves the windowed geometry untouched, so Restore returns to exactly it.const handleToggleMaximize = useCallback(- () => widgets.setFloatingMode(instanceId, state.mode === 'maximized' ? 'windowed' : 'maximized'),- [instanceId, state.mode, widgets]+ () => widgets.setFloatingMode(instanceId, mode === 'maximized' ? 'windowed' : 'maximized'),+ [instanceId, mode, widgets]);const handleTitleDoubleClick = useCallback((event: ReactMouseEvent<HTMLDivElement>) => {- // A double-click on a title-bar button (e.g. Maximize) must not also- // shade the window.- if (state.mode !== 'maximized' && !(event.target as HTMLElement).closest('button')) {- handleToggleShade();+ // A double-click on a title-bar button must not also change the window's mode.+ if ((event.target as HTMLElement).closest('button')) {+ return;+ }+ // A collapsed window opens back up; jumping straight from a title bar to the whole viewport would surprise.+ if (mode === 'shaded') {+ widgets.setFloatingMode(instanceId, 'windowed');+ return;}++ handleToggleMaximize();},- [handleToggleShade, state.mode]+ [handleToggleMaximize, instanceId, mode, widgets]+ );++ // The stored geometry and stacking as inline values of the one static rule set.+ const geometryStyle = useMemo(+ () =>+ ({+ '--fw-h': `${heightPx}px`,+ '--fw-w': `${widthPx}px`,+ '--fw-x': `${x}px`,+ '--fw-y': `${y}px`,+ zIndex: FLOATING_BASE_Z_INDEX + stackRank,+ }) as CSSProperties,+ [heightPx, stackRank, widthPx, x, y]);if (!instance) {@@ -279,133 +598,161 @@ export const FloatingWidgetWindow = ({const isEnabled = widget?.status === 'enabled';const label = widget ? resolveWidgetInstanceLabel(instance, widget.manifest, t) : (instance.title ?? instance.id);const dockLabel = resolveDockLabel(state.returnRegion, t);- const position = toWindowPosition(state);- const isMaximized = state.mode === 'maximized';- const isShaded = state.mode === 'shaded';- const positionProps = isMaximized- ? { h: '100vh', left: 0, top: 0, w: '100vw' }- : { h: isShaded ? 'auto' : position.height, left: position.left, top: position.top, w: position.width };+ const isMaximized = mode === 'maximized';+ const isShaded = mode === 'shaded';return (- <Flex+ <Boxref={windowRef}aria-label={label}- bg="bg.subtle"- // 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"+ css={WINDOW_SX}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.+ style={geometryStyle}tabIndex={-1}- transition="border-color var(--wb-motion-duration-fast) ease"- zIndex={FLOATING_BASE_Z_INDEX + stackRank}+ data-floating-mode={mode}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}- onFocusCapture={handleActivate}+ onFocusCapture={handleFocusCapture}onPointerDownCapture={handlePointerDownCapture}- {...positionProps}>- <HStack- aria-label={t('widgets.floating.move', { label })}- borderBottomWidth={isShaded ? 0 : '1px'}- cursor={isMaximized ? 'default' : 'move'}- flexShrink={0}- gap="1.5"- h={10}- justify="space-between"- pe="2"- ps="3"- tabIndex={isMaximized ? undefined : 0}- // `preventDefault` on pointerdown does not stop touch panning: without- // this the browser claims the gesture and cancels the drag.- touchAction="none"- userSelect="none"- onDoubleClick={handleTitleDoubleClick}- onKeyDown={handleTitleKeyDown}- onPointerDown={handleTitlePointerDown}+ <Flex+ bg="bg.subtle"+ // 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"+ h="full"+ // Its own stacking context: nothing a widget stacks inside can rise above the resize handles.+ isolation="isolate"+ overflow="hidden"+ data-floating-frame=""+ rounded={isMaximized ? 'none' : 'md'}+ shadow="xl"+ transition="border-color var(--wb-motion-duration-fast) ease">- <HStack flex="1" gap="1.5" minW="0">- {widget ? <WidgetIcon boxSize="4" icon={widget.manifest.icon} /> : null}- <Text fontSize="xs" fontWeight="700" truncate>- {label}- </Text>- </HStack>- <HStack flexShrink={0} gap="1">+ <HStack+ aria-label={t('widgets.floating.move', { label })}+ borderBottomWidth={isShaded ? 0 : '1px'}+ cursor={isMaximized ? 'default' : 'move'}+ flexShrink={0}+ gap="1.5"+ // Tighter than a docked panel's header: a window's chrome should take as little of it as it can. The+ // end padding keeps the Dock button clear of the top-right resize corner, which reaches 12px inside.+ h={10}+ pe="3"+ ps="3"+ tabIndex={isMaximized ? undefined : 0}+ // `preventDefault` on pointerdown does not stop touch panning: without+ // this the browser claims the gesture and cancels the drag.+ touchAction="none"+ userSelect="none"+ _focusVisible={FOCUS_RING}+ outline="none"+ onDoubleClick={handleTitleDoubleClick}+ onKeyDown={handleTitleKeyDown}+ onPointerDown={handleTitlePointerDown}+ >+ {/*+ * The label takes only the room the controls leave, so a narrow window truncates it first — down to its+ * icon, which keeps its place rather than sliding over the actions.+ */}+ <HStack flex="1 1 0" gap="1.5" minW="4" overflow="hidden">+ {widget ? <WidgetIcon boxSize="4" flexShrink={0} icon={widget.manifest.icon} /> : null}+ <Text fontSize="xs" fontWeight="700" truncate>+ {label}+ </Text>+ </HStack>{/** Render widget actions and settings in a row because floating content has no frame header; window- * controls already own layout actions.+ * controls already own layout actions. Contributed actions shrink and clip before they can push the+ * window's own controls out of a narrow title bar.*/}{isEnabled && widget ? (<FloatingChromeBoundary><Suspense fallback={null}>- <HStack gap="1" onDoubleClick={stopChromeEvent} onPointerDown={stopChromeEvent}>+ <HStack+ flex="0 1 auto"+ gap="1"+ // Room for a focused action's ring inside the clip, and `clip` rather than `hidden` so focusing+ // a clipped action cannot leave the row scrolled.+ m="-1"+ minW="0"+ overflow="clip"+ p="1"+ data-floating-actions=""+ onDoubleClick={stopChromeEvent}+ onPointerDown={stopChromeEvent}+ ><WidgetChromeSlotById instanceId={instanceId} region="floating" slot="viewActions" widget={widget} /></HStack></Suspense></FloatingChromeBoundary>) : null}- {isEnabled && widget ? <Separator h="4" mx="0.5" orientation="vertical" /> : null}- <Tooltip content={isShaded ? t('widgets.floating.unshade') : t('widgets.floating.shade')}>- <IconButton- aria-label={isShaded ? t('widgets.floating.unshade') : t('widgets.floating.shade')}- color="fg.muted"- size="2xs"- variant="ghost"- onClick={handleToggleShade}- >- <Icon as={isShaded ? ChevronsUpDownIcon : ChevronsDownUpIcon} boxSize="3.5" />- </IconButton>- </Tooltip>- <Tooltip content={isMaximized ? t('widgets.floating.restore') : t('widgets.floating.maximize')}>- <IconButton- aria-label={isMaximized ? t('widgets.floating.restore') : t('widgets.floating.maximize')}- color="fg.muted"- size="2xs"- variant="ghost"- onClick={handleToggleMaximize}- >- <Icon as={isMaximized ? Minimize2Icon : Maximize2Icon} boxSize="3.5" />- </IconButton>- </Tooltip>- <Tooltip content={dockLabel}>- <IconButton aria-label={dockLabel} color="fg.muted" size="2xs" variant="ghost" onClick={handleDock}>- <Icon as={DOCK_DESTINATION_ICONS[state.returnRegion]} boxSize="3.5" />- </IconButton>- </Tooltip>+ <HStack flexShrink={0} gap="1" data-floating-controls="">+ {isEnabled && widget ? <Separator h="4" mx="0.5" orientation="vertical" /> : null}+ <Tooltip content={isShaded ? t('widgets.floating.unshade') : t('widgets.floating.shade')}>+ <IconButton+ aria-label={isShaded ? t('widgets.floating.unshade') : t('widgets.floating.shade')}+ color="fg.muted"+ size="2xs"+ variant="ghost"+ onClick={handleToggleShade}+ >+ <Icon as={isShaded ? ChevronsUpDownIcon : ChevronsDownUpIcon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ <Tooltip content={isMaximized ? t('widgets.floating.restore') : t('widgets.floating.maximize')}>+ <IconButton+ aria-label={isMaximized ? t('widgets.floating.restore') : t('widgets.floating.maximize')}+ color="fg.muted"+ size="2xs"+ variant="ghost"+ onClick={handleToggleMaximize}+ >+ <Icon as={isMaximized ? Minimize2Icon : Maximize2Icon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ <Tooltip content={dockLabel}>+ <IconButton aria-label={dockLabel} color="fg.muted" size="2xs" variant="ghost" onClick={handleDock}>+ <Icon as={DOCK_DESTINATION_ICONS[state.returnRegion]} boxSize="3.5" />+ </IconButton>+ </Tooltip>+ </HStack></HStack>- </HStack>- {isShaded ? null : (- <Flex direction="column" flex="1" minH="0" overflow="hidden">- {isEnabled && widget ? (- <WidgetRendererById instanceId={instance.id} region="floating" widget={widget} />- ) : (- <HStack color="fg.error" gap="1.5" p="3">- <Icon as={TriangleAlertIcon} boxSize="3.5" />- <Text fontSize="xs">{t('widgets.failure.title', { label })}</Text>- </HStack>- )}- </Flex>- )}+ {/* A shaded body is hidden, not unmounted: its local state survives, and no second copy mounts. */}+ <Activity mode={isShaded ? 'hidden' : 'visible'}>+ <Flex direction="column" flex="1" minH="0" overflow="hidden">+ {isEnabled && widget ? (+ <WidgetRendererById instanceId={instance.id} region="floating" widget={widget} />+ ) : (+ <HStack color="fg.error" gap="1.5" p="3">+ <Icon as={TriangleAlertIcon} boxSize="3.5" />+ <Text fontSize="xs">{t('widgets.failure.title', { label })}</Text>+ </HStack>+ )}+ </Flex>+ </Activity>+ </Flex>{isShaded || isMaximized ? null : (- <ResizeCorner- label={t('widgets.floating.resize')}- valueMin={FLOATING_MIN_WIDTH_PX}- valueNow={state.widthPx}- onDragCancel={cancelGesture}- onDragEnd={endGesture}- onDragMove={handleResizeMove}- onKeyDown={handleResizeKeyDown}- />+ <>+ <FloatingResizeHandles onResizeStart={startWindowDrag} />+ <ResizeCorner+ label={t('widgets.floating.resize')}+ valueMax={Math.max(widthPx, window.innerWidth)}+ valueMin={FLOATING_MIN_WIDTH_PX}+ valueNow={widthPx}+ valueText={t('widgets.floating.resizeValue', { height: heightPx, width: widthPx })}+ onKeyDown={handleResizeKeyDown}+ onPointerDown={handleCornerPointerDown}+ />+ </>)}- </Flex>+ </Box>);};diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsxindex 3e0c047406..0a07acc090 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/PanelCollapseDrag.browser.test.tsx@@ -5,6 +5,7 @@ import type { WorkbenchInternalStore } from '@workbench/workbenchStore';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { FocusRegionProvider } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';import { createWorkbenchStore } from '@workbench/workbenchStore';import i18next from 'i18next';import { act, useSyncExternalStore } from 'react';@@ -37,6 +38,8 @@ await i18n.use(initReactI18next).init({resources: { en: { translation: { widgets: { panelLabel: '{{region}} panel' } } } },});+const focusController = createTestFocusController();+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -71,7 +74,7 @@ const renderShell = async (region: 'bottom' | 'left' | 'right') => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <FocusRegionProvider>+ <FocusRegionProvider controller={focusController}><Shell region={region} /></FocusRegionProvider></ChakraProvider>@@ -125,6 +128,8 @@ beforeEach(() => {});afterEach(async () => {+ // Focus is per test: the next one starts with no region outlined and no move pending.+ focusController.clear();await interact(() => root?.unmount());host?.remove();host = null;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.tsxindex 32305edb8f..652e392fa9 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,7 +4,8 @@ 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 { FocusRegionProvider } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';import i18next from 'i18next';import { MapIcon } from 'lucide-react';import { act } from 'react';@@ -77,7 +78,7 @@ 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 focusController = createTestFocusController();const focusFloating = vi.spyOn(focusController, 'focusFloating');const renderButton = async (region: WorkbenchRegion, allowFloating = true) => {diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsxindex 802281d9f1..0ed6f55585 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetLoadingFallback.browser.test.tsx@@ -5,6 +5,7 @@ import type * as workbenchContext from '@workbench/WorkbenchContext';import { ChakraProvider } from '@chakra-ui/react';import { system } from '@theme/system';import { FocusRegionProvider } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';import { createWidgetImplementationResource } from '@workbench/widgetImplementationResource';import i18next from 'i18next';import { act, type ReactNode } from 'react';@@ -84,6 +85,8 @@ const instance: WidgetInstanceContract = {typeId: 'test',};+const focusController = createTestFocusController();+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -104,7 +107,7 @@ const render = async (children: ReactNode) => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <FocusRegionProvider>{children}</FocusRegionProvider>+ <FocusRegionProvider controller={focusController}>{children}</FocusRegionProvider></ChakraProvider></I18nextProvider>);@@ -112,6 +115,8 @@ const render = async (children: ReactNode) => {};afterEach(async () => {+ // Focus is per test: the next one starts with no region outlined and no move pending.+ focusController.clear();await interact(() => root?.unmount());host?.remove();document.querySelectorAll('[data-scope="menu"]').forEach((element) => element.remove());diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsxindex b63c424905..b55af91932 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetPanelFrame.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 { FocusRegionProvider } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';import i18next from 'i18next';import { act } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -47,6 +48,8 @@ await i18n.use(initReactI18next).init({resources: { en: { translation: { widgets: { panelLabel: '{{region}} panel' } } } },});+const focusController = createTestFocusController();+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -62,7 +65,7 @@ const renderFrame = async (region: 'bottom' | 'left' | 'right' = 'left') => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <FocusRegionProvider>+ <FocusRegionProvider controller={focusController}><WidgetPanelFrame instanceId="test-instance" region={region} typeId="gallery"><div /></WidgetPanelFrame>@@ -124,6 +127,8 @@ beforeEach(() => {});afterEach(async () => {+ // Focus is per test: the next one starts with no region outlined and no move pending.+ focusController.clear();await interact(() => root?.unmount());host?.remove();host = null;@@ -237,7 +242,7 @@ describe('WidgetPanelFrame squeezed by the viewport', () => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <FocusRegionProvider>+ <FocusRegionProvider controller={focusController}><WidgetPanelFrame instanceId="test-instance" region="left" typeId="gallery"><div /></WidgetPanelFrame>diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsxindex 911ac64a0f..8ad67a38c3 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetRenderer.browser.test.tsx@@ -11,6 +11,7 @@ import { ChakraProvider, Stack, Text } from '@chakra-ui/react';import { StatusWidgetChip } from '@platform/ui';import { system } from '@theme/system';import { FocusRegionProvider } from '@workbench/focusRegions';+import { createTestFocusController } from '@workbench/focusRegions.testing';import { createWidgetImplementationResource } from '@workbench/widgetImplementationResource';import i18next from 'i18next';import { CircleIcon } from 'lucide-react';@@ -157,6 +158,8 @@ const createInstance = (title?: string): WidgetInstanceContract => ({typeId: 'test',});+const focusController = createTestFocusController();+let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;@@ -171,7 +174,7 @@ const render = async (children: ReactNode) => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <FocusRegionProvider>{children}</FocusRegionProvider>+ <FocusRegionProvider controller={focusController}>{children}</FocusRegionProvider></ChakraProvider></I18nextProvider>);@@ -202,6 +205,8 @@ const getIdentityGeometry = ({ loadedIcon = false } = {}) => {};afterEach(async () => {+ // Focus is per test: the next one starts with no region outlined and no move pending.+ focusController.clear();await act(async () => {root?.unmount();await Promise.resolve();diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.tsindex b4402a6409..c4d433fcdb 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts@@ -58,7 +58,7 @@ const createDispatch = () => {closeFloating: (instanceId) => dispatch({ instanceId, type: 'closeFloatingWidget' }),float: (instanceId, region) =>dispatch(region ? { instanceId, region, type: 'floatWidget' } : { instanceId, type: 'floatWidget' }),- focusFloating: (instanceId) => dispatch({ instanceId, type: 'focusFloatingWidget' }),+ raiseFloating: (instanceId) => dispatch({ instanceId, type: 'raiseFloatingWidget' }),move: (options) => dispatch({ ...options, type: 'moveWidgetInstance' }),setAlignment: (options) => dispatch({ ...options, type: 'setWidgetInstanceAlignment' }),open: (options) => dispatch({ ...options, type: 'openRegionWidget' }),diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.tsindex 2026165883..90e7db8093 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts@@ -72,7 +72,7 @@ const createWidgetCommands = (dispatch: (action: WorkbenchAction) => void): WorkdockFloating: (instanceId) => dispatch({ instanceId, type: 'dockFloatingWidget' }),closeFloating: (instanceId) => dispatch({ instanceId, type: 'closeFloatingWidget' }),float: (instanceId) => dispatch({ instanceId, type: 'floatWidget' }),- focusFloating: (instanceId) => dispatch({ instanceId, type: 'focusFloatingWidget' }),+ raiseFloating: (instanceId) => dispatch({ instanceId, type: 'raiseFloatingWidget' }),move: (options) => dispatch({ ...options, type: 'moveWidgetInstance' }),setAlignment: (options) => dispatch({ ...options, type: 'setWidgetInstanceAlignment' }),open: (options) => dispatch({ ...options, type: 'openRegionWidget' }),@@ -338,7 +338,7 @@ describe('floating window rail commands', () => {removeFloatingPlacement({ instanceId: 'preview', project: placement, widgets }));- expect(result).toEqual({ restoresCenter: true });+ expect(result).toEqual({ restoresCenter: true, returnRegion: 'right' });expect(project.floatingWidgets).toBeUndefined();expect(project.widgetRegions.center.instanceIds).toEqual(['preview']);});@@ -349,7 +349,7 @@ describe('floating window rail commands', () => {removeFloatingPlacement({ instanceId: 'image-map', project: placement, widgets }));- expect(result).toEqual({ restoresCenter: false });+ expect(result).toEqual({ restoresCenter: false, returnRegion: 'right' });expect(project.floatingWidgets).toBeUndefined();expect(project.widgetRegions.right.instanceIds).toEqual(['gallery', 'queue']);});diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.tsindex c562e5bb62..7a4df7fe3b 100644--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts@@ -227,8 +227,8 @@ export const dockFloatingPlacement = ({/*** Close a floating window outright — never dock-then-toggle, which would pop its panel open and retarget the route- * on the way. Reports whether the reducer hands an emptied center its view back, so focus can follow it there- * instead of dying with the window.+ * on the way. Reports where the window would have returned and whether the reducer hands an emptied center its+ * view back, so focus can go somewhere instead of dying with the window.*/export const removeFloatingPlacement = ({instanceId,@@ -238,8 +238,10 @@ export const removeFloatingPlacement = ({project: WidgetPlacementProject;instanceId: WidgetInstanceId;widgets: WorkbenchWidgetCommands;-}): { restoresCenter: boolean } | null => {- if (!project.floatingPlacements?.[instanceId]) {+}): { restoresCenter: boolean; returnRegion: WidgetRegion } | null => {+ const placement = project.floatingPlacements?.[instanceId];++ if (!placement) {return null;}@@ -248,7 +250,7 @@ export const removeFloatingPlacement = ({flushWorkbenchDrafts();widgets.closeFloating(instanceId);- return { restoresCenter };+ return { restoresCenter, returnRegion: placement.returnRegion };};export const dispatchWidgetDragEndPlacement = ({diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 9c90fec991..d2f0418ca3 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -300,7 +300,7 @@ type WorkbenchReducerAction =heightPx: number;}| { type: 'setFloatingWidgetMode'; instanceId: WidgetInstanceId; mode: FloatingWidgetMode }- | { type: 'focusFloatingWidget'; instanceId: WidgetInstanceId }+ | { type: 'raiseFloatingWidget'; instanceId: WidgetInstanceId }/** Bring a window forward so its content shows: raise it, and expand it when it is shaded. */| { type: 'revealFloatingWidget'; instanceId: WidgetInstanceId }| { type: 'setGenerateSettings'; values: GenerateWidgetValues; projectId?: string; origin?: WorkbenchActionOrigin }@@ -4033,12 +4033,12 @@ export const __workbenchReducerInternal = (};});}- case 'focusFloatingWidget': {+ case 'raiseFloatingWidget': {return updateActiveProject(state, (project) => {const floatingWidgets = raiseFloatingWidget(project.floatingWidgets, action.instanceId);- // Pointer capture runs for every interaction inside the window; only raising it should re-route or dirty- // the project.+ // Every press and every focus arriving inside the window asks for this; only an actual raise should+ // re-route or dirty the project.return floatingWidgets === project.floatingWidgets? project: applyAutoRouteForRevealedInstance({ ...project, floatingWidgets }, action.instanceId, context);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.tsindex 9b1cbb0e88..bfca599456 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts@@ -293,7 +293,7 @@ describe('auto invocation route switching on widget reveal', () => {state = workbenchReducer(state, { instanceId: 'upscale', type: 'floatWidget' });state = workbenchReducer(state, { sourceId: 'generate', type: 'setInvocationSource' });- state = workbenchReducer(state, { instanceId: 'video', type: 'focusFloatingWidget' });+ state = workbenchReducer(state, { instanceId: 'video', type: 'raiseFloatingWidget' });expect(getInvocation(state)).toMatchObject({ sourceId: 'video' });@@ -313,7 +313,7 @@ describe('auto invocation route switching on widget reveal', () => {// Bound to `onPointerDownCapture`, so this fires on every scroll and click// inside the window, not just on a raise.- state = workbenchReducer(state, { instanceId: 'upscale', type: 'focusFloatingWidget' });+ state = workbenchReducer(state, { instanceId: 'upscale', type: 'raiseFloatingWidget' });expect(state).toBe(before);expect(getInvocation(state)).toMatchObject({ sourceId: 'workflow' });diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.tsindex 6bb45e04a3..20392e86d2 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts@@ -646,27 +646,30 @@ describe('createWorkbenchStore', () => {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.raiseFloating('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);+ // Raising is ordinary focus: it leaves a shaded window shaded. Only the explicit reveal expands one.+ expect(store.getSnapshot().activeProject.floatingWidgets?.['image-map'].mode).toBe('shaded');store.commands.widgets.dockFloating('gallery');expect(placementWatcher.changeCount).toBe(3);});- it('writes nothing when focus keeps returning to the window already on top', () => {+ it('notifies no subscriber when the window already on top is raised again', () => {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.+ // Every press inside a window asks for a raise. For the topmost window the reducer returns the same state, and+ // the store must turn that into silence: no notification, so no re-render and no autosave.for (let repeat = 0; repeat < 5; repeat += 1) {- store.commands.widgets.focusFloating('gallery');+ store.commands.widgets.raiseFloating('gallery');}expect(stateWatcher.changeCount).toBe(0);diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.tsindex 9e28cc91c6..4e6de7fc6d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts@@ -429,7 +429,7 @@ const createCommands = (float: command('floatWidget', (instanceId: string, region?: ActionPayload<'floatWidget'>['region']) =>region ? { instanceId, region } : { instanceId }),- focusFloating: command('focusFloatingWidget', (instanceId: string) => ({ instanceId })),+ raiseFloating: command('raiseFloatingWidget', (instanceId: string) => ({ instanceId })),move: command('moveWidgetInstance'),open: command('openRegionWidget'),patchInstanceValues: command(