Skip to content

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

feat(webv2): keep a return marker for floating widgets

Josh Corbett2c4763e53587
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.mdx
index 5a10b7a21d..52d43fbf31 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
@@ -32,7 +32,7 @@ Hover over a numbered circle, or tap it on a touchscreen, for a short descriptio
| 10 | **Center panel** | The main work area: Preview, Canvas, Gallery, Workflow editor or Image Map. |
| 11 | **Center view menu** | Switches what the center shows, and adds or closes center views. |
| 12 | **Floating window** | A panel detached from its rail, which you can move and resize anywhere. |
-| 13 | **Floating panel's rail slot** | A dashed icon that marks where a floating panel came from. Click it to dock the panel again. |
+| 13 | **Floating panel's rail slot** | A dashed icon that marks where a floating panel came from. Click it to bring the window to the front; right-click it to dock or remove the panel. |
| 14 | **Status bar** | Small status chips: server connection, queue, gallery, autosave and notifications. |
### Rails and side panels
@@ -66,7 +66,10 @@ The status bar along the bottom holds small chips. Hover over **Server Status**,
- 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.
-- **Dock to panel** returns the panel to the rail it came from. Clicking its dashed rail icon does the same.
+- 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.
+
+If the panel you float was also the only view in the center, the center shows where it went, with **Show window** and a dock button. Docking or removing the window gives the center its view back.
A floating Preview is handy on the **Edit** layout: keep the canvas in the center and watch results in a small window beside your work.
diff --git a/invokeai/frontend/webv2/ARCHITECTURE.md b/invokeai/frontend/webv2/ARCHITECTURE.md
index 34d1e96da3..4b5530a936 100644
--- a/invokeai/frontend/webv2/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/ARCHITECTURE.md
@@ -103,6 +103,18 @@ Feature interfaces remain ordinary module interfaces unless two adapters add lev
| Upscale | Upscale settings, validation, compilation and UI; Workbench invocation and Queue | Platform and public Models/Gallery/Queue interfaces; value/validation reads, submission command and widget contribution |
| Intermediates | Per-project intermediates read models, cleanup previews/operations and the Settings section that manages them; Workbench settings, project menus, account administration | Platform plus Identity's public session/capability reads; query keys, read models, the focus intent, the browser hold lease and the `settingsContribution` metadata whose loader owns the section body |
+## Widget placement and floating windows
+
+A project places each widget instance in regions (`widgetRegions`) or in a floating window (`floatingWidgets`), never both. `workbench/floatingWindows.ts` owns the rules; the reducer, placement normalization, and the rails all read placement through it.
+
+- **A floating instance belongs to no region's `instanceIds`.** Floating removes every membership, repairs the active selections it leaves behind, and records one return destination (`returnRegion`, `returnIndex`).
+- **A return region keeps a marker for each of its windows.** `getRegionOrder` is the region's complete order — docked members plus markers — and a marker's `returnIndex` is its position in it. Docking counts the docked members ahead of the marker, so docking in any order never moves what the rail shows. Reducer edits that add, remove, or move members go through that order so the indices stay in step; reordering docked members fills the docked positions around stationary markers.
+- **Empty-center recovery is the one exception to origin-only docking.** A center emptied by a float keeps naming the instance in `activeInstanceId`. While it is still empty and still names that instance, Dock restores center membership along with the origin, and Remove restores center membership only (no rail slot, no panel). No extra field is persisted; a center that has gained a view or changed its pointer is left alone. "Empty" means no members at all: the reducer has no widget registry, so a center left holding only a disabled or unregistered view is not recovered and shows that view's unavailable state until another view is chosen.
+- **Region requests never discard a window.** Selecting, moving, or reordering an instance a region does not hold is a no-op, and so is enabling an instance that floats. Opening a widget type whose instance floats restores its return placement first, then opens the requested one, and auto-routes once.
+- **One normalization.** `normalizeFloatingPlacement` runs on project hydration, on stored presets, on preset application, and inside preset comparison (which includes `returnIndex`), so an applied preset always matches the snapshot it came from. It is idempotent. Indices stored before markers were counted are read deterministically (ascending, ties by instance id, missing ones appended); that is best-effort and does not reconstruct the original arrangement.
+
+The rails subscribe to placement only (`getWidgetPlacementProject` projects `floatingPlacements`), so a window's geometry, mode, and stacking change without re-rendering them. A marker is not a tab: it stays out of the sortable list, activating it raises and expands its window, and Dock and Remove live in its context menu. Marker UI exists only on the left and right rails.
+
## Settings contributions
Settings are declared by their owners and presented by Workbench. Platform UI owns domain-neutral field metadata and controls; it does not own setting values or persistence. A widget manifest exposes a `settings` contribution containing localized field metadata, an ordered `quick` subset, and a deferred field binding loader. The full dialog includes every declared field. Bindings retain the owner's normalization and command path, including Gallery's size/density conversion and project/instance fencing.
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 025608e435..eaf73cefdf 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2046,14 +2046,23 @@
"title": "{{label}} failed"
},
"floating": {
- "dock": "Dock to panel",
+ "centerFloating": "{{label}} is in a floating window",
+ "destinations": {
+ "bottom": "bottom panel",
+ "center": "center",
+ "left": "left panel",
+ "right": "right panel"
+ },
+ "dockTo": "Dock to {{destination}}",
"floatWindow": "Float Window",
"maximize": "Maximize",
"move": "Move {{label}} window",
- "railSlot": "{{label}} (floating — click to dock)",
+ "railMarker": "{{label}}, floating window",
+ "railMarkerHint": "{{label}} is floating — click to show the window",
"resize": "Resize window",
"restore": "Restore",
"shade": "Collapse",
+ "showWindow": "Show window",
"unshade": "Expand"
},
"loadingLabel": "Loading {{label}}",
diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
index 6b6852a452..a29d506dad 100644
--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs
@@ -926,6 +926,75 @@ const runLayersPanesJourney = async (browser) => {
}
};
+/**
+ * Floating a rail panel that is also the center's only view: the rail keeps a marker, the center says where the
+ * view went, and removing or docking the window gives the center its view — and keyboard focus — back.
+ */
+const runFloatingWindowJourney = async (browser) => {
+ const { context, page, pageErrors } = await openRepresentativePage(browser, representativeProjectPath);
+ const id = 'workbench-floating-window';
+
+ try {
+ await waitForWorkbench(page);
+ await selectLayoutPreset(page, 'Video', 'Preview');
+
+ const rail = page.getByRole('navigation', { exact: true, name: 'Inspect widget visibility' });
+ const center = centerRegion(page);
+ const floatingWindow = page.locator('[data-hotkey-widget-region="floating"]');
+ const marker = rail.getByRole('button', { exact: true, name: 'Preview, floating window' });
+ const floatPreviewFromRail = async () => {
+ await rail.getByRole('button', { exact: true, name: 'Inspect widgets' }).click();
+ await page.getByRole('menuitemcheckbox', { exact: true, name: 'Preview' }).click();
+ await page.keyboard.press('Escape');
+ await page.getByRole('button', { exact: true, name: 'Float Window' }).click();
+ await floatingWindow.waitFor();
+ await marker.waitFor();
+ };
+ const focusedRegion = () =>
+ page.evaluate(() => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region'));
+
+ await floatPreviewFromRail();
+ await center.getByText('Preview is in a floating window', { exact: true }).waitFor();
+ await waitForSettledDocument(page);
+ await assertNoAxeViolations(page, `${id}:floating`);
+
+ // The marker is a keyboard stop with a visible focus ring, and it shows the window rather than docking it.
+ await marker.focus();
+ await page.keyboard.press('Enter');
+ assert.equal(await floatingWindow.count(), 1, 'Activating the marker must keep the window floating.');
+
+ await marker.click({ button: 'right' });
+ assert.deepEqual(await page.getByRole('menuitem').allInnerTexts(), ['Dock to right panel', 'Remove Preview']);
+ await page.getByRole('menuitem', { exact: true, name: 'Remove Preview' }).click();
+ await centerViewTrigger(page, 'Preview').waitFor();
+ await floatingWindow.waitFor({ state: 'detached' });
+ assert.equal(await marker.count(), 0, 'Removing the window must free its rail slot.');
+ await page.waitForFunction(
+ () => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region') === 'center'
+ );
+
+ await floatPreviewFromRail();
+ await center.getByRole('button', { exact: true, name: 'Dock to right panel' }).click();
+ await centerViewTrigger(page, 'Preview').waitFor();
+ await floatingWindow.waitFor({ state: 'detached' });
+ await rail.getByRole('button', { exact: true, name: 'Preview' }).waitFor();
+ await page.waitForFunction(
+ () => document.activeElement?.closest('[data-focus-region]')?.getAttribute('data-focus-region') === 'center'
+ );
+ assert.equal(await focusedRegion(), 'center');
+ await waitForSettledDocument(page);
+ await assertNoAxeViolations(page, `${id}:docked`);
+
+ if (pageErrors.length > 0) {
+ throw new AggregateError(pageErrors, `${id} raised uncaught browser errors.`);
+ }
+
+ return { id, status: 'passed' };
+ } finally {
+ await context.close();
+ }
+};
+
const SETTINGS_DIALOG_SCOPE = { include: ['[data-scope="dialog"][data-part="content"]'] };
const runSettingsJourney = async (browser) => {
@@ -1036,6 +1105,9 @@ try {
if (!requestedJourney || requestedJourney === 'workbench-layers-panes') {
reports.push(await runLayersPanesJourney(browser));
}
+ if (!requestedJourney || requestedJourney === 'workbench-floating-window') {
+ reports.push(await runFloatingWindowJourney(browser));
+ }
if (!requestedJourney || requestedJourney === 'workbench-settings') {
reports.push(await runSettingsJourney(browser));
}
diff --git a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts
index f07a7a9a1e..02566734f6 100644
--- a/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/floatingWidgets.test.ts
@@ -10,7 +10,15 @@ import {
FLOATING_MIN_WIDTH_PX,
nextStackOrder,
} from './floatingWindows';
-import { doesProjectMatchLayoutPreset, resolveSavedLayoutPreset } from './layoutPresetSnapshots';
+import {
+ areLayoutPresetSnapshotsEqual,
+ createLayoutPresetSnapshot,
+ doesProjectMatchLayoutPreset,
+ resolveSavedLayoutPreset,
+} from './layoutPresetSnapshots';
+import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from './widgetPlacementMeta';
+import { createWidgetRegionViewModelFromState } from './widgetRegionViewModel';
+import { getWidgetsForRegion } from './widgetRegistry';
import { normalizeWorkbenchAccount, normalizeWorkbenchProject } from './workbenchState';
import { createInitialWorkbenchState, workbenchReducer } from './workbenchState.testing';
@@ -32,6 +40,36 @@ const getRegionsHolding = (project: Project, instanceId: string): string[] =>
.filter(([, region]) => region.instanceIds.includes(instanceId))
.map(([regionId]) => regionId);
+const withActiveProject = (state: WorkbenchState, update: (project: Project) => Project): WorkbenchState => ({
+ ...state,
+ projects: state.projects.map((project) => (project.id === state.activeProjectId ? update(project) : project)),
+});
+
+/** What a reload does to the active project: the autosaved JSON comes back through normalization. */
+const reload = (state: WorkbenchState): WorkbenchState =>
+ withActiveProject(state, (project) => normalizeWorkbenchProject(JSON.parse(JSON.stringify(project))));
+
+/** The right rail exactly as the shell derives it: reducer state -> placement selector -> region view model. */
+const getRightRail = (state: WorkbenchState): string[] => {
+ const placement = getWidgetPlacementProject(getActiveProject(state));
+
+ return createWidgetRegionViewModelFromState({
+ floatingWidgets: placement.floatingPlacements,
+ region: 'right',
+ regionState: getActiveProject(state).widgetRegions.right,
+ widgetInstances: placement.widgetInstances,
+ widgets: getWidgetsForRegion('right'),
+ }).placedItems.map((item) => (item.isFloating ? `${item.id}*` : item.id));
+};
+
+/** Video shows Preview only in the center; put it on the right rail too, then float it from there. */
+const floatVideoPreviewFromRail = (): WorkbenchState => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'video', type: 'applyPreset' });
+ state = workbenchReducer(state, { region: 'right', type: 'openRegionWidget', widgetId: 'preview' });
+
+ return workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+};
+
describe('floatWidget', () => {
it('detaches the instance from its region and repairs the active instance', () => {
const initial = createInitialWorkbenchState();
@@ -87,32 +125,40 @@ describe('floatWidget', () => {
});
});
- it('docks back into the region the float was asked from, not the first member region', () => {
- // Preview belongs to center and right; right precedes center, so this catches loss of the explicit float
- // origin.
+ it('leaves every region that held the instance and records one return destination', () => {
+ // Edit shows Preview in the center and on the right rail at once.
let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
- state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
const project = getActiveProject(state);
- expect(project.widgetRegions.center.instanceIds).not.toContain('preview');
- expect(project.widgetRegions.right.instanceIds).toContain('preview');
- expect(project.floatingWidgets?.preview).toMatchObject({ returnRegion: 'center' });
+ expect(getRegionsHolding(project, 'preview')).toEqual([]);
+ expect(project.floatingWidgets?.preview).toMatchObject({ returnIndex: 1, returnRegion: 'right' });
+ // The center had another view, so it simply moves on.
+ expect(project.widgetRegions.center).toMatchObject({ activeInstanceId: 'canvas', instanceIds: ['canvas'] });
+ });
+
+ it('returns to the region the float was asked from, not the first member region', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });
+
+ expect(getActiveProject(state).floatingWidgets?.preview).toMatchObject({ returnRegion: 'center' });
- const docked = workbenchReducer(state, { instanceId: 'preview', type: 'dockFloatingWidget' });
+ const docked = getActiveProject(workbenchReducer(state, { instanceId: 'preview', type: 'dockFloatingWidget' }));
- expect(getActiveProject(docked).widgetRegions.center.instanceIds).toContain('preview');
- expect(getActiveProject(docked).widgetRegions.center.activeInstanceId).toBe('preview');
+ expect(docked.widgetRegions.center).toMatchObject({
+ activeInstanceId: 'preview',
+ instanceIds: ['canvas', 'preview'],
+ });
+ // The rail membership was given up on float; docking restores the one recorded origin.
+ expect(docked.widgetRegions.right.instanceIds).not.toContain('preview');
});
- it('falls back to a member region when the float carries no region hint', () => {
+ it('picks a member region deterministically when the float carries no region hint', () => {
let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
state = workbenchReducer(state, { instanceId: 'preview', type: 'floatWidget' });
- const project = getActiveProject(state);
- const floating = project.floatingWidgets?.preview;
- // Without an origin hint, the chosen member region is unspecified map order.
- expect(floating).toBeDefined();
- expect(['center', 'right']).toContain(floating!.returnRegion);
+ // Rails come before the center, whatever order the regions happen to be stored in.
+ expect(getActiveProject(state).floatingWidgets?.preview).toMatchObject({ returnRegion: 'right' });
});
it('collapses a rail it empties instead of leaving it open and blank', () => {
@@ -151,6 +197,122 @@ describe('closeFloatingWidget', () => {
expect(workbenchReducer(state, { instanceId: 'gallery', type: 'closeFloatingWidget' })).toBe(state);
});
+
+ it('frees the rail slot, closing the gap ahead of later markers', () => {
+ let state = floatGallery();
+ state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });
+ expect(getRightRail(state)).toEqual(['gallery*', 'image-map', 'queue*']);
+
+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'closeFloatingWidget' });
+
+ expect(getRightRail(state)).toEqual(['image-map', 'queue*']);
+ expect(getActiveProject(state).floatingWidgets?.queue.returnIndex).toBe(1);
+ });
+});
+
+describe('empty-center recovery', () => {
+ it('Video: docking gives both the right rail and the emptied center their Preview back', () => {
+ const floated = floatVideoPreviewFromRail();
+ const emptied = getActiveProject(floated).widgetRegions.center;
+
+ // The center keeps naming the view it lost; that pointer is the whole record of the debt.
+ expect(emptied).toMatchObject({ activeInstanceId: 'preview', instanceIds: [], isCollapsed: false });
+
+ const project = getActiveProject(workbenchReducer(floated, { instanceId: 'preview', type: 'dockFloatingWidget' }));
+
+ expect(project.floatingWidgets).toBeUndefined();
+ expect(project.widgetRegions.center).toMatchObject({ activeInstanceId: 'preview', instanceIds: ['preview'] });
+ expect(project.widgetRegions.right).toMatchObject({
+ activeInstanceId: 'preview',
+ instanceIds: ['gallery', 'queue', 'preview'],
+ isCollapsed: false,
+ });
+ });
+
+ it('Video: removing gives the center its Preview back but restores no rail slot and opens no panel', () => {
+ let floated = floatVideoPreviewFromRail();
+ floated = workbenchReducer(floated, { region: 'right', type: 'setRegionWidgetCollapsed', isCollapsed: true });
+ const before = getActiveProject(floated);
+ const project = getActiveProject(workbenchReducer(floated, { instanceId: 'preview', type: 'closeFloatingWidget' }));
+
+ expect(project.floatingWidgets).toBeUndefined();
+ expect(project.widgetRegions.center).toMatchObject({ activeInstanceId: 'preview', instanceIds: ['preview'] });
+ expect(project.widgetRegions.right).toBe(before.widgetRegions.right);
+ expect(project.layout).toBe(before.layout);
+ });
+
+ it('Video: both recoveries still work after a reload', () => {
+ const reloaded = reload(floatVideoPreviewFromRail());
+
+ expect(getActiveProject(reloaded).widgetRegions.center).toMatchObject({
+ activeInstanceId: 'preview',
+ instanceIds: [],
+ });
+
+ const docked = getActiveProject(workbenchReducer(reloaded, { instanceId: 'preview', type: 'dockFloatingWidget' }));
+ const removed = getActiveProject(
+ workbenchReducer(reloaded, { instanceId: 'preview', type: 'closeFloatingWidget' })
+ );
+
+ expect(getRegionsHolding(docked, 'preview')).toEqual(['right', 'center']);
+ expect(getRegionsHolding(removed, 'preview')).toEqual(['center']);
+ });
+
+ it('Edit: docking returns Preview to the rail only, because the center kept its other view', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
+ const railBefore = [...getActiveProject(state).widgetRegions.right.instanceIds];
+
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'preview', type: 'dockFloatingWidget' });
+ const project = getActiveProject(state);
+
+ expect(project.widgetRegions.right.instanceIds).toEqual(railBefore);
+ // Not a round trip: the center's Preview membership is gone for good.
+ expect(project.widgetRegions.center.instanceIds).toEqual(['canvas']);
+ });
+
+ it.each(['dockFloatingWidget', 'closeFloatingWidget'] as const)(
+ '%s leaves the center alone once it has gained another view',
+ (type) => {
+ let state = floatVideoPreviewFromRail();
+ state = workbenchReducer(state, { region: 'center', type: 'openRegionWidget', widgetId: 'gallery' });
+ const center = getActiveProject(state).widgetRegions.center;
+
+ expect(center.instanceIds).not.toContain('preview');
+
+ state = workbenchReducer(state, { instanceId: 'preview', type });
+
+ expect(getActiveProject(state).widgetRegions.center).toBe(center);
+ }
+ );
+
+ it.each(['dockFloatingWidget', 'closeFloatingWidget'] as const)(
+ '%s leaves an empty center alone once its pointer names another view',
+ (type) => {
+ const state = withActiveProject(floatVideoPreviewFromRail(), (project) => ({
+ ...project,
+ widgetRegions: {
+ ...project.widgetRegions,
+ center: { ...project.widgetRegions.center, activeInstanceId: 'canvas' },
+ },
+ }));
+ const center = getActiveProject(state).widgetRegions.center;
+ const project = getActiveProject(workbenchReducer(state, { instanceId: 'preview', type }));
+
+ expect(project.widgetRegions.center).toBe(center);
+ }
+ );
+
+ it('does not duplicate the view when the center is itself the return region', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'video', type: 'applyPreset' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });
+
+ const docked = getActiveProject(workbenchReducer(state, { instanceId: 'preview', type: 'dockFloatingWidget' }));
+ const removed = getActiveProject(workbenchReducer(state, { instanceId: 'preview', type: 'closeFloatingWidget' }));
+
+ expect(docked.widgetRegions.center.instanceIds).toEqual(['preview']);
+ expect(removed.widgetRegions.center.instanceIds).toEqual(['preview']);
+ });
});
describe('dockFloatingWidget', () => {
@@ -174,34 +336,24 @@ describe('dockFloatingWidget', () => {
expect(getActiveProject(state).widgetRegions.right.instanceIds).not.toContain('gallery');
});
- it('restores the tab to the position it floated from', () => {
+ it.each([
+ ['gallery', 'queue'],
+ ['queue', 'gallery'],
+ ])('docks %s then %s without moving either return destination', (first, second) => {
const initial = createInitialWorkbenchState();
const before = [...getActiveProject(initial).widgetRegions.right.instanceIds];
+ expect(before).toEqual(['gallery', 'image-map', 'queue']);
- let state = workbenchReducer(initial, { instanceId: 'image-map', type: 'floatWidget' });
- state = workbenchReducer(state, { instanceId: 'image-map', type: 'dockFloatingWidget' });
-
- expect(getActiveProject(state).widgetRegions.right.instanceIds).toEqual(before);
- });
-
- it('docks to the end when the remembered index is gone or nonsensical', () => {
- // 'gallery' leads the right rail, so a docked-to-the-end result is only
- // reachable by discarding the remembered index rather than honouring it.
- const floated = floatGallery();
- const withBadIndex: WorkbenchState = {
- ...floated,
- projects: floated.projects.map((project) => ({
- ...project,
- floatingWidgets: project.floatingWidgets && {
- ...project.floatingWidgets,
- gallery: { ...project.floatingWidgets.gallery!, returnIndex: Number.NaN },
- },
- })),
- };
+ let state = workbenchReducer(initial, { instanceId: 'gallery', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });
+ expect(getRightRail(state)).toEqual(['gallery*', 'image-map', 'queue*']);
- const state = workbenchReducer(withBadIndex, { instanceId: 'gallery', type: 'dockFloatingWidget' });
+ state = workbenchReducer(state, { instanceId: first, type: 'dockFloatingWidget' });
+ // The window still out keeps the slot the rail was already showing for it.
+ expect(getRightRail(state).map((id) => id.replace('*', ''))).toEqual(before);
- expect(getActiveProject(state).widgetRegions.right.instanceIds.at(-1)).toBe('gallery');
+ state = workbenchReducer(state, { instanceId: second, type: 'dockFloatingWidget' });
+ expect(getActiveProject(state).widgetRegions.right.instanceIds).toEqual(before);
});
it('is a no-op when nothing is floating', () => {
@@ -292,19 +444,224 @@ describe('interaction with region placement', () => {
const state = workbenchReducer(floated, { region: 'right', type: 'openRegionWidget', widgetId: 'gallery' });
const project = getActiveProject(state);
- expect(project.floatingWidgets?.gallery).toBeUndefined();
- expect(project.widgetRegions.right.instanceIds).toContain('gallery');
+ expect(project.floatingWidgets).toBeUndefined();
+ // Back at its return slot, not appended.
+ expect(project.widgetRegions.right).toMatchObject({
+ activeInstanceId: 'gallery',
+ instanceIds: ['gallery', 'image-map', 'queue'],
+ });
});
- it('selectRegionWidget docks a floating instance instead of double-rendering it', () => {
- // Selecting Preview's remaining rail slot must dock it rather than show it alongside the floating copy.
+ it('openRegionWidget restores the return placement before opening the requested one', () => {
let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
- state = workbenchReducer(state, { instanceId: 'preview', region: 'center', type: 'floatWidget' });
- state = workbenchReducer(state, { region: 'right', type: 'selectRegionWidget', widgetId: 'preview' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+ const layoutBefore = getActiveProject(state).layout;
+
+ state = workbenchReducer(state, { region: 'center', type: 'openRegionWidget', widgetId: 'preview' });
+ const project = getActiveProject(state);
+
+ expect(project.floatingWidgets).toBeUndefined();
+ expect(project.widgetRegions.center).toMatchObject({
+ activeInstanceId: 'preview',
+ instanceIds: ['canvas', 'preview'],
+ });
+ // The rail gets its tab back where it was, without being brought to the front or opened.
+ expect(project.widgetRegions.right).toMatchObject({
+ activeInstanceId: 'layers',
+ instanceIds: ['layers', 'preview'],
+ });
+ expect(project.layout.panels).toEqual(layoutBefore.panels);
+ });
+
+ it('openRegionWidget routes once, to the widget it reveals', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { instanceId: 'generate', type: 'floatWidget' });
+ state = workbenchReducer(state, { sourceId: 'upscale', type: 'setInvocationSource' });
+
+ state = workbenchReducer(state, { region: 'left', type: 'openRegionWidget', widgetId: 'generate' });
+
+ expect(getActiveProject(state).invocation.sourceId).toBe('generate');
+ expect(getActiveProject(state).widgetRegions.left.instanceIds).toEqual(['generate', 'upscale']);
+ });
+
+ it('openRegionWidget hands an emptied center its view back when it docks the window', () => {
+ // Opening Preview on the left: the window returns to the right rail, the center it emptied gets it back,
+ // and the requested rail shows it.
+ const state = workbenchReducer(floatVideoPreviewFromRail(), {
+ region: 'left',
+ type: 'openRegionWidget',
+ widgetId: 'preview',
+ });
const project = getActiveProject(state);
- expect(project.floatingWidgets?.preview).toBeUndefined();
- expect(project.widgetRegions.right.activeInstanceId).toBe('preview');
+ expect(project.floatingWidgets).toBeUndefined();
+ expect(getRegionsHolding(project, 'preview').sort()).toEqual(['center', 'left', 'right']);
+ expect(project.widgetRegions.center).toMatchObject({ activeInstanceId: 'preview', instanceIds: ['preview'] });
+ expect(project.widgetRegions.left.activeInstanceId).toBe('preview');
+ });
+
+ it('a stale move or reorder cannot place a floating instance back in a region', () => {
+ const state = floatGallery();
+ const moved = workbenchReducer(state, {
+ fromRegion: 'right',
+ instanceId: 'gallery',
+ toIndex: 0,
+ toRegion: 'left',
+ type: 'moveWidgetInstance',
+ });
+ const reordered = workbenchReducer(state, {
+ instanceIds: ['gallery', 'image-map', 'queue'],
+ region: 'right',
+ type: 'reorderWidgetInstances',
+ });
+
+ expect(moved).toBe(state);
+ expect(reordered).toBe(state);
+ });
+
+ it('a stale selection of a floating instance changes nothing and keeps the window', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+
+ for (const region of ['right', 'center'] as const) {
+ expect(workbenchReducer(state, { region, type: 'selectRegionWidget', widgetId: 'preview' })).toBe(state);
+ }
+ });
+
+ it('a stale toggle cannot enable a floating instance in a region', () => {
+ const state = floatGallery();
+
+ expect(workbenchReducer(state, { region: 'right', type: 'toggleRegionWidget', widgetId: 'gallery' })).toBe(state);
+ });
+});
+
+describe('rail order around floating markers', () => {
+ // The default right rail is gallery, image-map, queue; image-map floats, leaving a marker between the others.
+ const floatImageMap = (): WorkbenchState =>
+ workbenchReducer(createInitialWorkbenchState(), { instanceId: 'image-map', type: 'floatWidget' });
+ const dockImageMap = (state: WorkbenchState): string[] =>
+ getActiveProject(workbenchReducer(state, { instanceId: 'image-map', type: 'dockFloatingWidget' })).widgetRegions
+ .right.instanceIds;
+
+ it('shows the marker where the reducer will dock the window', () => {
+ const state = floatImageMap();
+
+ expect(getRightRail(state)).toEqual(['gallery', 'image-map*', 'queue']);
+ expect(dockImageMap(state)).toEqual(['gallery', 'image-map', 'queue']);
+ });
+
+ it('does not re-derive the rail when a window only moves, shades, or is raised', () => {
+ let state = floatImageMap();
+ state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });
+ const placement = getWidgetPlacementProject(getActiveProject(state));
+
+ state = workbenchReducer(state, {
+ heightPx: 300,
+ instanceId: 'image-map',
+ type: 'setFloatingWidgetGeometry',
+ widthPx: 300,
+ x: 400,
+ y: 300,
+ });
+ state = workbenchReducer(state, { instanceId: 'image-map', mode: 'shaded', type: 'setFloatingWidgetMode' });
+ state = workbenchReducer(state, { instanceId: 'image-map', type: 'focusFloatingWidget' });
+
+ // 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);
+
+ state = workbenchReducer(state, { instanceId: 'queue', type: 'dockFloatingWidget' });
+
+ expect(areWidgetPlacementProjectsEqual(placement, getWidgetPlacementProject(getActiveProject(state)))).toBe(false);
+ });
+
+ it('closes the gap when a member ahead of the marker is removed', () => {
+ const state = workbenchReducer(floatImageMap(), {
+ region: 'right',
+ type: 'toggleRegionWidget',
+ widgetId: 'gallery',
+ });
+
+ expect(getRightRail(state)).toEqual(['image-map*', 'queue']);
+ expect(dockImageMap(state)).toEqual(['image-map', 'queue']);
+ });
+
+ it('appends an added member after the marker', () => {
+ const state = workbenchReducer(floatImageMap(), { region: 'right', type: 'openRegionWidget', widgetId: 'preview' });
+
+ expect(getRightRail(state)).toEqual(['gallery', 'image-map*', 'queue', 'preview']);
+ expect(dockImageMap(state)).toEqual(['gallery', 'image-map', 'queue', 'preview']);
+ });
+
+ it('keeps the marker stationary while the docked members reorder around it', () => {
+ const state = workbenchReducer(floatImageMap(), {
+ instanceIds: ['queue', 'gallery'],
+ region: 'right',
+ type: 'reorderWidgetInstances',
+ });
+
+ expect(getRightRail(state)).toEqual(['queue', 'image-map*', 'gallery']);
+ expect(dockImageMap(state)).toEqual(['queue', 'image-map', 'gallery']);
+ });
+
+ it('lands a dragged-in widget in front of the member it was dropped on, wherever the marker sits', () => {
+ // `toIndex` counts docked members: 1 is "in front of queue", which sits after the marker.
+ const beforeQueue = workbenchReducer(floatImageMap(), {
+ fromRegion: 'center',
+ instanceId: 'preview',
+ toIndex: 1,
+ toRegion: 'right',
+ type: 'moveWidgetInstance',
+ });
+ const beforeGallery = workbenchReducer(floatImageMap(), {
+ fromRegion: 'center',
+ instanceId: 'preview',
+ toIndex: 0,
+ toRegion: 'right',
+ type: 'moveWidgetInstance',
+ });
+
+ expect(getRightRail(beforeQueue)).toEqual(['gallery', 'image-map*', 'preview', 'queue']);
+ expect(getRightRail(beforeGallery)).toEqual(['preview', 'gallery', 'image-map*', 'queue']);
+ expect(dockImageMap(beforeGallery)).toEqual(['preview', 'gallery', 'image-map', 'queue']);
+ });
+
+ it('keeps markers through a reload', () => {
+ let state = floatImageMap();
+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'floatWidget' });
+ const reloaded = reload(state);
+
+ expect(getRightRail(reloaded)).toEqual(['gallery*', 'image-map*', 'queue']);
+ expect(getActiveProject(reloaded).floatingWidgets).toEqual(getActiveProject(state).floatingWidgets);
+ });
+});
+
+describe('revealFloatingWidget', () => {
+ it('raises the window and expands it when it is shaded', () => {
+ let state = floatGallery();
+ state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'gallery', mode: 'shaded', type: 'setFloatingWidgetMode' });
+
+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'revealFloatingWidget' });
+ const floating = getActiveProject(state).floatingWidgets;
+
+ expect(floating?.gallery).toMatchObject({ mode: 'windowed', stackOrder: 2 });
+ expect(floating?.queue.stackOrder).toBe(1);
+ });
+
+ it('leaves a maximized window maximized', () => {
+ let state = floatGallery();
+ state = workbenchReducer(state, { instanceId: 'queue', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'gallery', mode: 'maximized', type: 'setFloatingWidgetMode' });
+
+ state = workbenchReducer(state, { instanceId: 'gallery', type: 'revealFloatingWidget' });
+
+ expect(getActiveProject(state).floatingWidgets?.gallery).toMatchObject({ mode: 'maximized', stackOrder: 2 });
+ });
+
+ it('is a no-op for a window already expanded on top, and for an instance that is not floating', () => {
+ const state = floatGallery();
+
+ expect(workbenchReducer(state, { instanceId: 'gallery', type: 'revealFloatingWidget' })).toBe(state);
+ expect(workbenchReducer(state, { instanceId: 'queue', type: 'revealFloatingWidget' })).toBe(state);
});
});
@@ -402,6 +759,53 @@ describe('normalization of persisted floating windows', () => {
});
});
+ it('reads return indices stored before markers were counted the same way on every load', () => {
+ // An older build stored each index against the docked members only, so two windows can share one.
+ const stored = withActiveProject(floatGallery(), (project) => ({
+ ...project,
+ floatingWidgets: {
+ queue: { ...project.floatingWidgets!.gallery, returnIndex: 0, stackOrder: 1 },
+ gallery: { ...project.floatingWidgets!.gallery, returnIndex: 0, stackOrder: 2 },
+ },
+ widgetRegions: {
+ ...project.widgetRegions,
+ right: { ...project.widgetRegions.right, activeInstanceId: 'image-map', instanceIds: ['image-map'] },
+ },
+ }));
+ const restacked = withActiveProject(stored, (project) => ({
+ ...project,
+ floatingWidgets: {
+ gallery: { ...project.floatingWidgets!.gallery, stackOrder: 1 },
+ queue: { ...project.floatingWidgets!.queue, stackOrder: 2 },
+ },
+ }));
+ const once = reload(stored);
+
+ // Ties break by instance id; the order the windows were floated in is not recoverable and is not claimed.
+ expect(getRightRail(once)).toEqual(['gallery*', 'queue*', 'image-map']);
+ expect(getRightRail(reload(restacked))).toEqual(getRightRail(once));
+ expect(getActiveProject(once).floatingWidgets).toMatchObject({
+ gallery: { returnIndex: 0 },
+ queue: { returnIndex: 1 },
+ });
+ expect(getActiveProject(reload(once))).toEqual(getActiveProject(once));
+ });
+
+ it('appends a window whose stored return index is missing', () => {
+ const stored = withActiveProject(floatGallery(), (project) => {
+ const { returnIndex: _dropped, ...gallery } = project.floatingWidgets!.gallery;
+
+ return { ...project, floatingWidgets: { gallery } };
+ });
+ const reloaded = reload(stored);
+
+ expect(getRightRail(reloaded)).toEqual(['image-map', 'queue', 'gallery*']);
+ expect(
+ getActiveProject(workbenchReducer(reloaded, { instanceId: 'gallery', type: 'dockFloatingWidget' })).widgetRegions
+ .right.instanceIds
+ ).toEqual(['image-map', 'queue', 'gallery']);
+ });
+
it('lets a sole center view keep floating across a reload', () => {
// An explicitly empty center with a floated active pointer must survive normalization without default views
// being added.
@@ -510,6 +914,8 @@ describe('interaction with presets and undo', () => {
expect(project.floatingWidgets?.gallery).toBeUndefined();
expect(getRegionsHolding(project, 'queue')).toEqual([]);
expect(project.floatingWidgets?.queue).toBeDefined();
+ // The dropped window's instance is placed nowhere, on either side of the comparison.
+ expect(doesProjectMatchLayoutPreset(project, resolveSavedLayoutPreset(state.account, 'compose'))).toBe(true);
});
it('reads a floated window as unsaved layout drift until it is saved', () => {
@@ -526,6 +932,47 @@ describe('interaction with presets and undo', () => {
).toBe(true);
});
+ it('reads a moved return slot as layout drift', () => {
+ const snapshot = createLayoutPresetSnapshot(getActiveProject(floatGallery()));
+ const moved = {
+ ...snapshot,
+ floatingWidgets: { gallery: { ...snapshot.floatingWidgets!.gallery, returnIndex: 2 } },
+ };
+
+ expect(snapshot.floatingWidgets?.gallery.returnIndex).toBe(0);
+ expect(areLayoutPresetSnapshotsEqual(snapshot, moved)).toBe(false);
+ });
+
+ it('matches a freshly applied preset against a snapshot stored by an older build', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'edit', type: 'applyPreset' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+ state = workbenchReducer(state, { presetId: 'edit', type: 'saveLayoutPreset' });
+ const saved = state.account.layoutPresetOverrides!.edit!;
+ const { returnIndex: _dropped, ...preview } = saved.floatingWidgets!.preview;
+ // As an older build stored it: no return index, and the window still a member of the center it also showed in.
+ const legacy = {
+ ...saved,
+ floatingWidgets: { preview },
+ widgetRegions: {
+ ...saved.widgetRegions,
+ center: { ...saved.widgetRegions.center, instanceIds: ['canvas', 'preview'] },
+ },
+ };
+
+ for (const account of [
+ // Read straight from account storage, and as account hydration rewrites it.
+ { ...state.account, layoutPresetOverrides: { edit: legacy } },
+ normalizeWorkbenchAccount({ ...state.account, layoutPresetOverrides: { edit: legacy } }),
+ ]) {
+ const applied = workbenchReducer({ ...state, account }, { presetId: 'edit', type: 'applyPreset' });
+ const project = getActiveProject(applied);
+
+ expect(getRegionsHolding(project, 'preview')).toEqual([]);
+ expect(project.floatingWidgets?.preview).toMatchObject({ returnIndex: 1, returnRegion: 'right' });
+ expect(doesProjectMatchLayoutPreset(project, resolveSavedLayoutPreset(applied.account, 'edit'))).toBe(true);
+ }
+ });
+
it('undo restores floating state together with the regions', () => {
// Snapshot A: gallery docked. The undoable action (apply preset) captures it.
let state = createInitialWorkbenchState();
diff --git a/invokeai/frontend/webv2/src/workbench/floatingWindows.test.ts b/invokeai/frontend/webv2/src/workbench/floatingWindows.test.ts
new file mode 100644
index 0000000000..0dcb5c7f38
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/floatingWindows.test.ts
@@ -0,0 +1,184 @@
+import { describe, expect, it } from 'vitest';
+
+import type { FloatingWidgetState, WidgetRegion, WidgetRegionState } from './layoutContracts';
+
+import { getRegionOrder, normalizeFloatingPlacement, writeRegionOrder } from './floatingWindows';
+
+const floating = (overrides: Partial<FloatingWidgetState> = {}): FloatingWidgetState => ({
+ heightPx: 400,
+ mode: 'windowed',
+ returnRegion: 'right',
+ stackOrder: 1,
+ widthPx: 500,
+ x: 40,
+ y: 40,
+ ...overrides,
+});
+
+const region = (instanceIds: string[], activeInstanceId = instanceIds[0] ?? ''): WidgetRegionState => ({
+ activeInstanceId,
+ instanceIds,
+ isCollapsed: false,
+ sizePx: 320,
+});
+
+const regions = (
+ overrides: Partial<Record<WidgetRegion, WidgetRegionState>>
+): Record<WidgetRegion, WidgetRegionState> => ({
+ bottom: region([]),
+ center: region(['canvas']),
+ left: region([]),
+ right: region([]),
+ ...overrides,
+});
+
+const orderIds = (slots: { instanceId: string; isFloating: boolean }[]): string[] =>
+ slots.map((slot) => (slot.isFloating ? `${slot.instanceId}*` : slot.instanceId));
+
+describe('getRegionOrder', () => {
+ it('places each marker at its index in the complete order, docked members filling the rest', () => {
+ const slots = getRegionOrder('right', ['b', 'd'], {
+ a: { returnIndex: 0, returnRegion: 'right' },
+ c: { returnIndex: 2, returnRegion: 'right' },
+ // Returns elsewhere, so it has no slot here.
+ z: { returnIndex: 0, returnRegion: 'left' },
+ });
+
+ expect(orderIds(slots)).toEqual(['a*', 'b', 'c*', 'd']);
+ });
+
+ it('breaks colliding indices by instance id, whatever order the windows are stored or stacked in', () => {
+ const forwards = getRegionOrder('right', ['x'], {
+ b: { returnIndex: 1, returnRegion: 'right' },
+ a: { returnIndex: 1, returnRegion: 'right' },
+ });
+ const backwards = getRegionOrder('right', ['x'], {
+ a: { returnIndex: 1, returnRegion: 'right' },
+ b: { returnIndex: 1, returnRegion: 'right' },
+ });
+
+ expect(orderIds(forwards)).toEqual(['x', 'a*', 'b*']);
+ expect(backwards).toEqual(forwards);
+ });
+
+ it('appends markers whose index is missing, nonsensical, or past the end', () => {
+ const slots = getRegionOrder('right', ['x'], {
+ beyond: { returnIndex: 99, returnRegion: 'right' },
+ missing: { returnRegion: 'right' },
+ nan: { returnIndex: Number.NaN, returnRegion: 'right' },
+ negative: { returnIndex: -1, returnRegion: 'right' },
+ });
+
+ // The finite index comes first; the rest append in id order.
+ expect(orderIds(slots)).toEqual(['x', 'beyond*', 'missing*', 'nan*', 'negative*']);
+ });
+});
+
+describe('writeRegionOrder', () => {
+ it('round-trips an order it wrote, so docking one marker never moves another', () => {
+ const floatingWidgets = { a: floating(), c: floating() };
+ const written = writeRegionOrder(
+ [
+ { instanceId: 'a', isFloating: true },
+ { instanceId: 'b', isFloating: false },
+ { instanceId: 'c', isFloating: true },
+ { instanceId: 'd', isFloating: false },
+ ],
+ floatingWidgets
+ );
+
+ expect(written.instanceIds).toEqual(['b', 'd']);
+ expect(written.floatingWidgets).toMatchObject({ a: { returnIndex: 0 }, c: { returnIndex: 2 } });
+ expect(orderIds(getRegionOrder('right', written.instanceIds, written.floatingWidgets))).toEqual([
+ 'a*',
+ 'b',
+ 'c*',
+ 'd',
+ ]);
+ });
+
+ it('keeps the window map untouched when every marker already holds its index', () => {
+ const floatingWidgets = { a: floating({ returnIndex: 1 }) };
+ const written = writeRegionOrder(
+ [
+ { instanceId: 'b', isFloating: false },
+ { instanceId: 'a', isFloating: true },
+ ],
+ floatingWidgets
+ );
+
+ expect(written.floatingWidgets).toBe(floatingWidgets);
+ });
+});
+
+describe('normalizeFloatingPlacement', () => {
+ const hasInstance = () => true;
+
+ it('takes a floating instance out of every region and gives each marker its canonical index', () => {
+ const normalized = normalizeFloatingPlacement(
+ regions({
+ // Stored before floating removed every membership: the window is still listed in two regions.
+ center: region(['canvas', 'preview'], 'preview'),
+ right: region(['layers', 'preview', 'queue'], 'preview'),
+ }),
+ { preview: floating({ returnIndex: 1 }), queue: floating() },
+ hasInstance
+ );
+
+ expect(normalized.widgetRegions.center).toMatchObject({ activeInstanceId: 'canvas', instanceIds: ['canvas'] });
+ expect(normalized.widgetRegions.right).toMatchObject({ activeInstanceId: 'layers', instanceIds: ['layers'] });
+ expect(normalized.floatingWidgets).toMatchObject({ preview: { returnIndex: 1 }, queue: { returnIndex: 2 } });
+ });
+
+ it('leaves an emptied center naming the view it lost, and collapses an emptied rail', () => {
+ const normalized = normalizeFloatingPlacement(
+ regions({ center: region(['preview']), right: region(['preview']) }),
+ { preview: floating() },
+ hasInstance
+ );
+
+ expect(normalized.widgetRegions.center).toMatchObject({
+ activeInstanceId: 'preview',
+ instanceIds: [],
+ isCollapsed: false,
+ });
+ expect(normalized.widgetRegions.right).toMatchObject({ activeInstanceId: '', instanceIds: [], isCollapsed: true });
+ });
+
+ it('changes nothing on a second pass', () => {
+ const once = normalizeFloatingPlacement(
+ regions({ center: region(['preview']), right: region(['x', 'preview', 'y'], 'preview') }),
+ { preview: floating(), late: floating({ returnIndex: 7 }), early: floating({ returnIndex: 0 }) },
+ hasInstance
+ );
+ const twice = normalizeFloatingPlacement(once.widgetRegions, once.floatingWidgets, hasInstance);
+
+ expect(twice).toEqual(once);
+ });
+
+ it('drops windows it cannot place and reports none as undefined', () => {
+ const widgetRegions = regions({ right: region(['x']) });
+ const normalized = normalizeFloatingPlacement(
+ widgetRegions,
+ {
+ gone: floating(),
+ nowhere: floating({ returnRegion: 'nowhere' as WidgetRegion }),
+ unsized: floating({ widthPx: Number.NaN }),
+ },
+ (instanceId) => instanceId !== 'gone'
+ );
+
+ expect(normalized.floatingWidgets).toBeUndefined();
+ expect(normalized.widgetRegions).toBe(widgetRegions);
+ });
+
+ it('returns a window floated out of a retired right-rail dock to the rail', () => {
+ const normalized = normalizeFloatingPlacement(
+ regions({ right: region(['x']) }),
+ { a: floating({ returnRegion: 'rightBottom' as WidgetRegion }) },
+ hasInstance
+ );
+
+ expect(normalized.floatingWidgets?.a).toMatchObject({ returnIndex: 1, returnRegion: 'right' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/floatingWindows.ts b/invokeai/frontend/webv2/src/workbench/floatingWindows.ts
index 526b10e43d..5737f3af2c 100644
--- a/invokeai/frontend/webv2/src/workbench/floatingWindows.ts
+++ b/invokeai/frontend/webv2/src/workbench/floatingWindows.ts
@@ -1,10 +1,16 @@
-import type { FloatingWidgetState } from '@workbench/layoutContracts';
+import type {
+ FloatingWidgetMode,
+ FloatingWidgetState,
+ WidgetRegion,
+ WidgetRegionState,
+} from '@workbench/layoutContracts';
import type { WidgetInstanceId } from '@workbench/widgetContracts';
+import { isWidgetRegion, WIDGET_REGIONS } from '@workbench/layoutContracts';
+
/**
- * Pure geometry and stacking helpers for floating widget windows. The reducer
- * owns the state; components clamp against the live viewport (the reducer
- * never reads window dimensions).
+ * Pure geometry, stacking, and placement rules for floating widget windows. The reducer owns the state;
+ * components clamp against the live viewport (the reducer never reads window dimensions).
*/
export const FLOATING_DEFAULT_WIDTH_PX = 520;
@@ -58,3 +64,196 @@ export const clampWindowToViewport = (
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)),
});
+
+// 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.
+
+/** The placement half of a window: the slot its return region keeps for it. */
+export type FloatingWidgetPlacement = Pick<FloatingWidgetState, 'returnIndex' | 'returnRegion'>;
+
+export interface RegionOrderSlot {
+ instanceId: WidgetInstanceId;
+ isFloating: boolean;
+}
+
+const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
+
+// Code-unit order, not `localeCompare`: the result must not vary with the browser's locale.
+const compareInstanceIds = (left: WidgetInstanceId, right: WidgetInstanceId): number =>
+ left < right ? -1 : left > right ? 1 : 0;
+
+/**
+ * One region's complete order: its docked instances plus a marker for each window that returns to it. A marker's
+ * `returnIndex` is its position in this order, so docking never moves anything the rail shows.
+ *
+ * Indices persisted before markers were counted, and missing or colliding ones, are read best-effort: ascending,
+ * ties broken by instance id, absent ones appended. That is deterministic, but it does not reconstruct the
+ * arrangement those windows were floated from.
+ */
+export const getRegionOrder = (
+ region: WidgetRegion,
+ instanceIds: readonly WidgetInstanceId[],
+ floatingWidgets: Readonly<Record<WidgetInstanceId, FloatingWidgetPlacement>> | undefined
+): RegionOrderSlot[] => {
+ const slots: RegionOrderSlot[] = instanceIds.map((instanceId) => ({ instanceId, isFloating: false }));
+
+ if (!floatingWidgets) {
+ return slots;
+ }
+
+ const markers = Object.entries(floatingWidgets)
+ .filter(([instanceId, placement]) => placement.returnRegion === region && !instanceIds.includes(instanceId))
+ .map(([instanceId, { returnIndex }]) => ({
+ index: isFiniteNumber(returnIndex) && returnIndex >= 0 ? Math.floor(returnIndex) : Number.POSITIVE_INFINITY,
+ instanceId,
+ }))
+ .sort((left, right) => left.index - right.index || compareInstanceIds(left.instanceId, right.instanceId));
+ let previousPosition = -1;
+
+ for (const { index, instanceId } of markers) {
+ // Each marker lands after the one before it, so colliding indices keep their id order.
+ const position = Math.max(Math.min(index, slots.length), previousPosition + 1);
+
+ slots.splice(position, 0, { instanceId, isFloating: true });
+ previousPosition = position;
+ }
+
+ return slots;
+};
+
+/** Write a complete order back as the region's docked members and its markers' return indices. */
+export const writeRegionOrder = (
+ slots: readonly RegionOrderSlot[],
+ floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined
+): { floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined; instanceIds: WidgetInstanceId[] } => {
+ let nextFloatingWidgets = floatingWidgets;
+
+ slots.forEach(({ instanceId, isFloating }, index) => {
+ const floating = nextFloatingWidgets?.[instanceId];
+
+ if (isFloating && floating && floating.returnIndex !== index) {
+ nextFloatingWidgets = { ...nextFloatingWidgets, [instanceId]: { ...floating, returnIndex: index } };
+ }
+ });
+
+ return {
+ floatingWidgets: nextFloatingWidgets,
+ instanceIds: slots.filter((slot) => !slot.isFloating).map((slot) => slot.instanceId),
+ };
+};
+
+/**
+ * Whether the center is still waiting for this instance: it emptied when the instance floated and nothing has
+ * taken its place since. Docking or removing the window then gives the center its view back. Emptiness is by
+ * membership, not by what can render — state has no widget registry to ask.
+ */
+export const isAwaitedCenterView = (
+ center: Pick<WidgetRegionState, 'activeInstanceId' | 'instanceIds'>,
+ instanceId: WidgetInstanceId
+): boolean => center.instanceIds.length === 0 && center.activeInstanceId === instanceId;
+
+const FLOATING_WIDGET_MODES: readonly FloatingWidgetMode[] = ['windowed', 'maximized', 'shaded'];
+
+/** Drop malformed windows so invalid region names or geometry cannot reach reducers or CSS. */
+const validateFloatingWidgets = (
+ value: unknown,
+ hasInstance: (instanceId: WidgetInstanceId) => boolean
+): Record<WidgetInstanceId, FloatingWidgetState> => {
+ const floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> = {};
+
+ if (!value || typeof value !== 'object') {
+ return floatingWidgets;
+ }
+
+ for (const [instanceId, entry] of Object.entries(value as Record<string, unknown>)) {
+ if (!entry || typeof entry !== 'object' || !hasInstance(instanceId)) {
+ continue;
+ }
+
+ const state = entry as Partial<FloatingWidgetState>;
+ // The right rail's docks folded back into one region; a window floated out of one returns to the rail.
+ const rawReturnRegion: unknown = state.returnRegion;
+ const returnRegion =
+ rawReturnRegion === 'rightTop' || rawReturnRegion === 'rightBottom' ? 'right' : rawReturnRegion;
+
+ if (
+ !isFiniteNumber(state.x) ||
+ !isFiniteNumber(state.y) ||
+ !isFiniteNumber(state.widthPx) ||
+ !isFiniteNumber(state.heightPx) ||
+ !isFiniteNumber(state.stackOrder) ||
+ !FLOATING_WIDGET_MODES.includes(state.mode as FloatingWidgetMode) ||
+ !isWidgetRegion(returnRegion)
+ ) {
+ continue;
+ }
+
+ floatingWidgets[instanceId] = {
+ ...clampSizeToMinimum({ heightPx: state.heightPx, widthPx: state.widthPx, x: state.x, y: state.y }),
+ mode: state.mode as FloatingWidgetMode,
+ returnIndex: state.returnIndex,
+ returnRegion,
+ stackOrder: state.stackOrder,
+ };
+ }
+
+ return floatingWidgets;
+};
+
+/**
+ * The one normalization for stored placements — hydrated projects, stored presets, applied presets, and preset
+ * comparison all pass through it, so the same arrangement always reads the same way. Malformed windows are
+ * dropped, a floating instance leaves every region (an emptied center keeps naming it, so it can come back), and
+ * every marker's return index becomes its position in {@link getRegionOrder}. Running it twice changes nothing.
+ */
+export const normalizeFloatingPlacement = (
+ widgetRegions: Record<WidgetRegion, WidgetRegionState>,
+ storedFloatingWidgets: unknown,
+ hasInstance: (instanceId: WidgetInstanceId) => boolean
+): {
+ floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined;
+ widgetRegions: Record<WidgetRegion, WidgetRegionState>;
+} => {
+ let floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined = validateFloatingWidgets(
+ storedFloatingWidgets,
+ hasInstance
+ );
+
+ if (Object.keys(floatingWidgets).length === 0) {
+ return { floatingWidgets: undefined, widgetRegions };
+ }
+
+ const normalizedRegions = { ...widgetRegions };
+
+ for (const regionId of WIDGET_REGIONS) {
+ const region = normalizedRegions[regionId];
+ const dockedIds = region.instanceIds.filter((instanceId) => !floatingWidgets?.[instanceId]);
+ const order = writeRegionOrder(getRegionOrder(regionId, dockedIds, floatingWidgets), floatingWidgets);
+
+ floatingWidgets = order.floatingWidgets;
+
+ if (dockedIds.length !== region.instanceIds.length) {
+ normalizedRegions[regionId] = withoutFloatedInstances(regionId, region, dockedIds);
+ }
+ }
+
+ return { floatingWidgets, widgetRegions: normalizedRegions };
+};
+
+/**
+ * A region after some of its instances floated away. The center never collapses and, once empty, keeps naming the
+ * view it lost; an emptied rail collapses and names nothing.
+ */
+export const withoutFloatedInstances = (
+ regionId: WidgetRegion,
+ region: WidgetRegionState,
+ instanceIds: WidgetInstanceId[]
+): WidgetRegionState => ({
+ ...region,
+ activeInstanceId: instanceIds.includes(region.activeInstanceId)
+ ? region.activeInstanceId
+ : (instanceIds[0] ?? (regionId === 'center' ? region.activeInstanceId : '')),
+ instanceIds,
+ isCollapsed: instanceIds.length === 0 ? regionId !== 'center' : region.isCollapsed,
+});
diff --git a/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts b/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts
index 723a477780..95f5a64cf6 100644
--- a/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts
+++ b/invokeai/frontend/webv2/src/workbench/image-actions/recallEventRuntime.ts
@@ -163,11 +163,7 @@ export const bringRecallWidgetToFront = ({
const floating = Object.keys(project.floatingWidgets ?? {}).find(isTarget);
if (floating) {
- // A shaded window is rolled up to its title bar; raising it alone would still hide the change.
- if (project.floatingWidgets?.[floating]?.mode === 'shaded') {
- commands.widgets.setFloatingMode(floating, 'windowed');
- }
- commands.widgets.focusFloating(floating);
+ commands.widgets.revealFloating(floating);
return;
}
diff --git a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts
index 5e582fb45b..2241d80fb2 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutContracts.ts
@@ -32,7 +32,10 @@ export interface FloatingWidgetState {
mode: FloatingWidgetMode;
/** The dockable region this window returns to when docked. */
returnRegion: WidgetRegion;
- /** Original rail index for docking; absent or invalid indices append. */
+ /**
+ * Position in the return region's complete order: its docked members plus one marker per floating window.
+ * Placement normalization makes it canonical; only data stored by an older build lacks it or disagrees.
+ */
returnIndex?: number;
/** Z-order within the floating layer; higher renders on top. */
stackOrder: number;
diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts
index 8bc58ac0ac..933fdfdd72 100644
--- a/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts
+++ b/invokeai/frontend/webv2/src/workbench/layoutPresetSnapshots.ts
@@ -10,6 +10,8 @@ import type {
import type { AccountState, Project } from '@workbench/projectContracts';
import type { WidgetInstanceId } from '@workbench/widgetContracts';
+import { normalizeFloatingPlacement } from '@workbench/floatingWindows';
+import { WIDGET_REGIONS } from '@workbench/layoutContracts';
import {
builtInLayoutPresetDescriptors,
getLayoutPreset,
@@ -30,8 +32,6 @@ export const getLayoutPresetCommandTitleOverrides = (
})
);
-const widgetRegions: WidgetRegion[] = ['left', 'right', 'bottom', 'center'];
-
/** Apply, revert, and drift checks all resolve account overrides here so Save changes has consistent meaning. */
export const resolveSavedLayoutPreset = (account: AccountState, presetId: LayoutPresetId): LayoutPreset => {
const resolvedPresetId = resolveLayoutPresetId(presetId);
@@ -53,7 +53,7 @@ export const resolveSavedLayoutPreset = (account: AccountState, presetId: Layout
: builtInPreset;
};
-export const cloneFloatingWidgets = (
+const cloneFloatingWidgets = (
floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState>
): Record<WidgetInstanceId, FloatingWidgetState> =>
Object.fromEntries(Object.entries(floatingWidgets).map(([instanceId, state]) => [instanceId, { ...state }]));
@@ -76,7 +76,7 @@ export const cloneLayoutPresetWidgetRegions = (
export const createLayoutPresetSnapshot = (project: Project): LayoutPresetSnapshot => {
const referencedInstanceIds = new Set<WidgetInstanceId>();
- for (const region of widgetRegions) {
+ for (const region of WIDGET_REGIONS) {
referencedInstanceIds.add(project.widgetRegions[region].activeInstanceId);
for (const instanceId of project.widgetRegions[region].instanceIds) {
@@ -108,6 +108,39 @@ export const createLayoutPresetSnapshot = (project: Project): LayoutPresetSnapsh
};
};
+/**
+ * Read a snapshot's placements the way a hydrated project's are. Stored presets, applied presets, and drift
+ * comparison share this, so a freshly applied preset always matches the snapshot it came from.
+ */
+export const normalizeLayoutPresetSnapshot = (snapshot: LayoutPresetSnapshot): LayoutPresetSnapshot => {
+ const { floatingWidgets, widgetRegions } = normalizeFloatingPlacement(
+ snapshot.widgetRegions,
+ snapshot.floatingWidgets,
+ (instanceId) => Object.hasOwn(snapshot.widgetInstances, instanceId)
+ );
+ // A window normalization dropped leaves an instance nothing places; applying the preset would not place it
+ // either, so the snapshot stops naming it.
+ const orphanedIds = Object.keys(snapshot.floatingWidgets ?? {}).filter(
+ (instanceId) =>
+ !floatingWidgets?.[instanceId] &&
+ WIDGET_REGIONS.every(
+ (region) =>
+ widgetRegions[region].activeInstanceId !== instanceId &&
+ !widgetRegions[region].instanceIds.includes(instanceId)
+ )
+ );
+
+ return {
+ ...(floatingWidgets ? { floatingWidgets } : {}),
+ layout: snapshot.layout,
+ widgetInstances:
+ orphanedIds.length > 0
+ ? Object.fromEntries(Object.entries(snapshot.widgetInstances).filter(([id]) => !orphanedIds.includes(id)))
+ : snapshot.widgetInstances,
+ widgetRegions,
+ };
+};
+
const areArraysEqual = (left: string[], right: string[]): boolean =>
left.length === right.length && left.every((value, index) => value === right[index]);
@@ -131,7 +164,7 @@ const areWidgetInstanceSnapshotsEqual = (
);
};
-/** Geometry counts as saved-layout drift; focus-driven stack ordering does not. */
+/** Geometry and the return slot count as saved-layout drift; focus-driven stack ordering does not. */
const areFloatingWidgetsEqual = (
left: LayoutPresetSnapshot['floatingWidgets'],
right: LayoutPresetSnapshot['floatingWidgets']
@@ -151,20 +184,30 @@ const areFloatingWidgetsEqual = (
leftState?.widthPx === rightState?.widthPx &&
leftState?.heightPx === rightState?.heightPx &&
leftState?.mode === rightState?.mode &&
- leftState?.returnRegion === rightState?.returnRegion
+ leftState?.returnRegion === rightState?.returnRegion &&
+ leftState?.returnIndex === rightState?.returnIndex
);
})
);
};
-export const areLayoutPresetSnapshotsEqual = (left: LayoutPresetSnapshot, right: LayoutPresetSnapshot): boolean =>
- left.layout.centerViewId === right.layout.centerViewId &&
- left.layout.panels.isBottomOpen === right.layout.panels.isBottomOpen &&
- left.layout.panels.isLeftOpen === right.layout.panels.isLeftOpen &&
- left.layout.panels.isRightOpen === right.layout.panels.isRightOpen &&
- widgetRegions.every((region) => areWidgetRegionsEqual(left.widgetRegions[region], right.widgetRegions[region])) &&
- areFloatingWidgetsEqual(left.floatingWidgets, right.floatingWidgets) &&
- areWidgetInstanceSnapshotsEqual(left.widgetInstances, right.widgetInstances);
+export const areLayoutPresetSnapshotsEqual = (
+ leftSnapshot: LayoutPresetSnapshot,
+ rightSnapshot: LayoutPresetSnapshot
+): boolean => {
+ const left = normalizeLayoutPresetSnapshot(leftSnapshot);
+ const right = normalizeLayoutPresetSnapshot(rightSnapshot);
+
+ return (
+ left.layout.centerViewId === right.layout.centerViewId &&
+ left.layout.panels.isBottomOpen === right.layout.panels.isBottomOpen &&
+ left.layout.panels.isLeftOpen === right.layout.panels.isLeftOpen &&
+ left.layout.panels.isRightOpen === right.layout.panels.isRightOpen &&
+ WIDGET_REGIONS.every((region) => areWidgetRegionsEqual(left.widgetRegions[region], right.widgetRegions[region])) &&
+ areFloatingWidgetsEqual(left.floatingWidgets, right.floatingWidgets) &&
+ areWidgetInstanceSnapshotsEqual(left.widgetInstances, right.widgetInstances)
+ );
+};
export const doesProjectMatchLayoutPreset = (project: Project, preset: LayoutPreset): boolean =>
areLayoutPresetSnapshotsEqual(createLayoutPresetSnapshot(project), preset.snapshot);
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
index f412ddc6be..88054d008f 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.browser.test.tsx
@@ -7,6 +7,17 @@ import { createRoot, type Root } from 'react-dom/client';
import { I18nextProvider, initReactI18next } from 'react-i18next';
import { afterEach, describe, expect, it, vi } from 'vitest';
+interface CenterAreaTestProject {
+ floatingWidgets?: Record<string, { returnIndex: number; returnRegion: string }>;
+ id: string;
+ invocation: { sourceId: string };
+ queue: { items: never[] };
+ widgetInstances: Record<string, { id: string; title?: string; typeId: string }>;
+ widgetRegions: {
+ center: { activeInstanceId: string; instanceIds: string[]; isCollapsed: boolean; sizePx: number };
+ };
+}
+
const centerAreaMocks = vi.hoisted(() => {
const icon = () => null;
// Use a settled resource so the center icon reads synchronously without suspending.
@@ -36,18 +47,17 @@ const centerAreaMocks = vi.hoisted(() => {
},
};
- return {
- activeItem,
- project: {
- id: 'test-project',
- invocation: { sourceId: 'generate' },
- queue: { items: [] },
- widgetInstances: {},
- widgetRegions: {
- center: { activeInstanceId: activeItem.id, instanceIds: [activeItem.id], isCollapsed: false, sizePx: 0 },
- },
+ const project: CenterAreaTestProject = {
+ id: 'test-project',
+ invocation: { sourceId: 'generate' },
+ queue: { items: [] },
+ widgetInstances: {},
+ widgetRegions: {
+ center: { activeInstanceId: activeItem.id, instanceIds: [activeItem.id], isCollapsed: false, sizePx: 0 },
},
};
+
+ return { activeItem, dockFloating: vi.fn(), focusOpenedWidget: vi.fn(), project, revealFloating: vi.fn() };
});
vi.mock('@features/models', () => ({ useModelLoads: () => [] }));
@@ -55,18 +65,32 @@ vi.mock('@features/queue/contracts', () => ({
getProjectQueueIndicatorState: () => ({ hasOpenQueueWork: false, progressState: null, runningQueueItemId: null }),
}));
vi.mock('@features/queue/react', () => ({ useQueueItemProgress: () => null }));
-vi.mock('@workbench/focusRegions', () => ({ useFocusRegionProps: () => ({}), useHighlightedRegion: () => null }));
+vi.mock('@workbench/focusRegions', () => ({
+ focusOpenedWidget: centerAreaMocks.focusOpenedWidget,
+ useFocusRegionProps: () => ({}),
+ useHighlightedRegion: () => null,
+}));
vi.mock('@workbench/widgetRegionViewModel', () => ({
- createWidgetRegionViewModelFromState: () => ({ placedItems: [centerAreaMocks.activeItem] }),
+ // The center's placed views are exactly its docked members.
+ createWidgetRegionViewModelFromState: ({ regionState }: { regionState: { instanceIds: string[] } }) => ({
+ placedItems: regionState.instanceIds.length > 0 ? [centerAreaMocks.activeItem] : [],
+ }),
getWidgetRegionItems: () => [],
isRequiredCenterView: () => true,
}));
-vi.mock('@workbench/widgetRegistry', () => ({ getWidgetById: () => undefined, getWidgetsForRegion: () => [] }));
+vi.mock('@workbench/widgetRegistry', () => ({
+ // Only the floated-view state resolves a widget by type, for its label.
+ getWidgetById: (typeId: string) =>
+ typeId === 'preview' ? { manifest: { id: 'preview', label: 'Preview' }, status: 'enabled' } : undefined,
+ getWidgetsForRegion: () => [],
+}));
vi.mock('@workbench/WorkbenchContext', () => ({
useActiveProjectId: () => centerAreaMocks.project.id,
useActiveProjectSelector: (selector: (project: typeof centerAreaMocks.project) => unknown) =>
selector(centerAreaMocks.project),
- useWorkbenchCommands: () => ({ widgets: {} }),
+ useWorkbenchCommands: () => ({
+ widgets: { dockFloating: centerAreaMocks.dockFloating, revealFloating: centerAreaMocks.revealFloating },
+ }),
useWorkbenchSelector: (selector: (snapshot: { backendConnection: { status: string } }) => unknown) =>
selector({ backendConnection: { status: 'connected' } }),
}));
@@ -103,7 +127,14 @@ void i18n.use(initReactI18next).init({
translation: {
widgets: {
centerRegion: 'Center view',
+ centerViewEmpty: 'No view',
centerViewLabel: 'Center view: {{label}}',
+ floating: {
+ centerFloating: '{{label}} is in a floating window',
+ destinations: { right: 'right panel' },
+ dockTo: 'Dock to {{destination}}',
+ showWindow: 'Show window',
+ },
},
},
},
@@ -158,3 +189,60 @@ describe('CenterArea chrome layout', () => {
);
});
});
+
+describe('CenterArea with its last view floating', () => {
+ const dockedCenter = centerAreaMocks.project.widgetRegions.center;
+
+ afterEach(() => {
+ centerAreaMocks.project.floatingWidgets = undefined;
+ centerAreaMocks.project.widgetInstances = {};
+ centerAreaMocks.project.widgetRegions.center = dockedCenter;
+ centerAreaMocks.dockFloating.mockClear();
+ centerAreaMocks.focusOpenedWidget.mockClear();
+ centerAreaMocks.revealFloating.mockClear();
+ });
+
+ const floatLastView = () => {
+ centerAreaMocks.project.floatingWidgets = { 'preview-instance': { returnIndex: 2, returnRegion: 'right' } };
+ centerAreaMocks.project.widgetInstances = {
+ 'preview-instance': { id: 'preview-instance', typeId: 'preview' },
+ };
+ // Emptied, and still naming the view that left.
+ centerAreaMocks.project.widgetRegions.center = { ...dockedCenter, instanceIds: [] };
+ };
+ const button = (name: string) =>
+ [...host!.querySelectorAll<HTMLButtonElement>('button')].find((candidate) => candidate.textContent === name);
+
+ it('says where the view went and offers both ways back, instead of calling it unavailable', async () => {
+ floatLastView();
+ await render(<CenterArea />);
+
+ expect(host?.textContent).toContain('Preview is in a floating window');
+ expect(host?.textContent).not.toContain('unavailable');
+
+ await act(async () => {
+ button('Show window')?.click();
+ await Promise.resolve();
+ });
+
+ expect(centerAreaMocks.revealFloating).toHaveBeenCalledWith('preview-instance');
+ expect(centerAreaMocks.dockFloating).not.toHaveBeenCalled();
+
+ await act(async () => {
+ button('Dock to right panel')?.click();
+ await Promise.resolve();
+ });
+
+ expect(centerAreaMocks.dockFloating).toHaveBeenCalledWith('preview-instance');
+ // Docking from here restores the center view, so focus follows it.
+ expect(centerAreaMocks.focusOpenedWidget).toHaveBeenCalledWith('center', 'preview');
+ });
+
+ it('still reports an empty center whose view is not floating as unavailable', async () => {
+ centerAreaMocks.project.widgetRegions.center = { ...dockedCenter, instanceIds: [] };
+ await render(<CenterArea />);
+
+ expect(host?.textContent).toContain('unavailable');
+ expect(button('Show window')).toBeUndefined();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
index 5f240b7efc..2aff2959ec 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/CenterArea.tsx
@@ -1,3 +1,4 @@
+import type { WidgetRegion } from '@workbench/layoutContracts';
import type { RegisteredWidget } from '@workbench/widgetContracts';
import type {
PlacedWidgetRegionItem,
@@ -6,8 +7,9 @@ import type {
} from '@workbench/widgetRegionViewModel';
import { Box, Flex, HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
-import { IconButton, MenuContent } from '@platform/ui';
-import { useFocusRegionProps } from '@workbench/focusRegions';
+import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
+import { Button, IconButton, MenuContent } from '@platform/ui';
+import { focusOpenedWidget, useFocusRegionProps } from '@workbench/focusRegions';
import { WidgetIcon } from '@workbench/iconResolver';
import {
WidgetChromeSlotById,
@@ -18,7 +20,7 @@ import {
type WidgetEnableMenuItem,
} from '@workbench/widget-frame';
import { areWidgetRenderInstancesEqual } from '@workbench/widget-frame/widgetRenderInstance';
-import { resolveWidgetLabel } from '@workbench/widgetLabels';
+import { resolveDockLabel, resolveWidgetInstanceLabel, resolveWidgetLabel } from '@workbench/widgetLabels';
import { closeWidgetPlacement, openWidgetPlacement, revealWidgetPlacement } from '@workbench/widgetPlacementCommands';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import {
@@ -87,6 +89,14 @@ export const CenterArea = () => {
? centerRegion.activeInstanceId
: centerViewItems[0]?.id;
const activeItem = centerViewItems.find((item) => item.id === activeCenterViewId);
+ // The center emptied because its last view floated away: say so, rather than call the view unavailable.
+ const floatedView =
+ centerRegion.instanceIds.length === 0
+ ? {
+ instance: placementProject.widgetInstances[centerRegion.activeInstanceId],
+ placement: placementProject.floatingPlacements?.[centerRegion.activeInstanceId],
+ }
+ : null;
const projectId = useActiveProjectId();
const activeIdsElsewhere = useActiveProjectSelector(
(project) => getActiveInstanceIdsOutside(project.widgetRegions, 'center', project.floatingWidgets),
@@ -164,6 +174,13 @@ export const CenterArea = () => {
<KeptCenterViewSlot instanceId={instanceId} />
</Activity>
))
+ ) : floatedView?.instance && floatedView.placement ? (
+ <FloatedCenterView
+ instanceId={floatedView.instance.id}
+ returnRegion={floatedView.placement.returnRegion}
+ title={floatedView.instance.title}
+ typeId={floatedView.instance.typeId}
+ />
) : (
<FallbackCenterView label="Center widget unavailable" />
)}
@@ -415,6 +432,47 @@ const KeptCenterViewSlot = ({ instanceId }: { instanceId: string }) => {
return <WidgetRendererById instanceId={instance.id} widget={widget} region="center" />;
};
+/** The empty center while its last view is a floating window: where the view went, and the two ways back. */
+const FloatedCenterView = ({
+ instanceId,
+ returnRegion,
+ title,
+ typeId,
+}: {
+ instanceId: string;
+ returnRegion: WidgetRegion;
+ title?: string;
+ typeId: string;
+}) => {
+ const { t } = useTranslation();
+ const { widgets } = useWorkbenchCommands();
+ const widget = getWidgetById(typeId);
+ const label = widget ? resolveWidgetInstanceLabel({ title }, widget.manifest, t) : (title ?? instanceId);
+ const handleShow = useCallback(() => widgets.revealFloating(instanceId), [instanceId, widgets]);
+ // Docking from here always gives the center its view back, so focus follows it.
+ const handleDock = useCallback(() => {
+ flushWorkbenchDrafts();
+ widgets.dockFloating(instanceId);
+ focusOpenedWidget('center', typeId);
+ }, [instanceId, typeId, widgets]);
+
+ return (
+ <Flex align="center" direction="column" gap="3" h="full" justify="center" px="6" textAlign="center" w="full">
+ <Text color="fg.muted" fontSize="sm">
+ {t('widgets.floating.centerFloating', { label })}
+ </Text>
+ <HStack gap="2" wrap="wrap" justify="center">
+ <Button size="xs" variant="outline" onClick={handleShow}>
+ {t('widgets.floating.showWindow')}
+ </Button>
+ <Button size="xs" variant="outline" onClick={handleDock}>
+ {resolveDockLabel(returnRegion, t)}
+ </Button>
+ </HStack>
+ </Flex>
+ );
+};
+
const FallbackCenterView = ({ label }: { label: string }) => (
<Flex align="center" h="full" justify="center" w="full">
<Text color="fg.subtle" fontSize="sm" textTransform="capitalize">
diff --git a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
index 68387c9093..6ded587231 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/PresetSwitchKeepAlive.browser.test.tsx
@@ -147,7 +147,11 @@ vi.mock('@features/workflow/react', async (importOriginal) => {
selector({ status: 'loaded', templates }),
};
});
-vi.mock('@workbench/focusRegions', () => ({ useFocusRegionProps: () => ({}), useHighlightedRegion: () => null }));
+vi.mock('@workbench/focusRegions', () => ({
+ focusOpenedWidget: () => {},
+ useFocusRegionProps: () => ({}),
+ useHighlightedRegion: () => null,
+}));
vi.mock('@workbench/widgetRegionViewModel', () => ({
createWidgetRegionViewModelFromState: ({ regionState }: { regionState: { instanceIds: string[] } }) => ({
placedItems: regionState.instanceIds.map((instanceId) => {
diff --git a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
index 6774dd5407..ea550a5ac0 100644
--- a/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
+++ b/invokeai/frontend/webv2/src/workbench/shell/WorkbenchShell.tsx
@@ -1,5 +1,3 @@
-import type { Project } from '@workbench/projectContracts';
-
import { Flex, HStack, Text, VisuallyHidden } from '@chakra-ui/react';
import {
DndContext,
@@ -13,9 +11,8 @@ import {
import { restrictToWindowEdges } from '@dnd-kit/modifiers';
import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';
import { GalleryDragCursor, GalleryDragScope } from '@features/gallery/utility';
-import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
import { useMountEffect } from '@platform/react/useMountEffect';
-import { FocusRegionProvider } from '@workbench/focusRegions';
+import { focusOpenedWidget, FocusRegionProvider } from '@workbench/focusRegions';
import { WidgetIcon } from '@workbench/iconResolver';
import { PROJECT_CONTENT_PANEL_ID } from '@workbench/projects/projectTabsA11y';
import { WidgetBar, type WidgetBarGroup } from '@workbench/widget-frame';
@@ -31,10 +28,12 @@ import {
} from '@workbench/widgetDnd';
import { resolveWidgetLabel } from '@workbench/widgetLabels';
import {
+ activateRailPlacement,
closeWidgetPlacement,
dispatchWidgetDragEndPlacement,
+ dockFloatingPlacement,
openWidgetPlacement,
- revealWidgetPlacement,
+ removeFloatingPlacement,
} from '@workbench/widgetPlacementCommands';
import { areWidgetPlacementProjectsEqual, getWidgetPlacementProject } from '@workbench/widgetPlacementMeta';
import { createWidgetRegionViewModelFromState, getWidgetRegionItems } from '@workbench/widgetRegionViewModel';
@@ -62,8 +61,6 @@ import { TopBar } from './topbar';
const DND_MODIFIERS = [restrictToWindowEdges];
-const EMPTY_FLOATING: NonNullable<Project['floatingWidgets']> = {};
-
export const WorkbenchShell = () => {
const { notifications, widgets } = useWorkbenchCommands();
const { t } = useTranslation();
@@ -71,8 +68,9 @@ export const WorkbenchShell = () => {
const projectName = useActiveProjectSelector((project) => project.name);
const leftRegion = useActiveProjectSelector((project) => project.widgetRegions.left);
const rightRegion = useActiveProjectSelector((project) => project.widgetRegions.right);
- const floatingWidgets = useActiveProjectSelector((project) => project.floatingWidgets ?? EMPTY_FLOATING);
+ // Placement only: a window's geometry, mode, and stacking change without re-rendering the shell or its rails.
const placementProject = useActiveProjectSelector(getWidgetPlacementProject, areWidgetPlacementProjectsEqual);
+ const { floatingPlacements } = placementProject;
const sensors = useSensors(
useSensor(PrimaryMouseSensor, { activationConstraint: { distance: 6 } }),
useSensor(HoldToDragSensor, {
@@ -88,26 +86,26 @@ export const WorkbenchShell = () => {
const leftRegionViewModel = useMemo(
() =>
createWidgetRegionViewModelFromState({
- floatingWidgets,
+ floatingWidgets: floatingPlacements,
region: 'left',
regionState: leftRegion,
widgetInstances: placementProject.widgetInstances,
widgets: getWidgetsForRegion('left'),
getWidgetLabel,
}),
- [floatingWidgets, getWidgetLabel, leftRegion, placementProject.widgetInstances]
+ [floatingPlacements, getWidgetLabel, leftRegion, placementProject.widgetInstances]
);
const rightRegionViewModel = useMemo(
() =>
createWidgetRegionViewModelFromState({
- floatingWidgets,
+ floatingWidgets: floatingPlacements,
region: 'right',
regionState: rightRegion,
widgetInstances: placementProject.widgetInstances,
widgets: getWidgetsForRegion('right'),
getWidgetLabel,
}),
- [floatingWidgets, getWidgetLabel, placementProject.widgetInstances, rightRegion]
+ [floatingPlacements, getWidgetLabel, placementProject.widgetInstances, rightRegion]
);
const leftMenuItems = useMemo(() => getWidgetRegionItems(leftRegionViewModel), [leftRegionViewModel]);
const rightMenuItems = useMemo(() => getWidgetRegionItems(rightRegionViewModel), [rightRegionViewModel]);
@@ -190,28 +188,27 @@ export const WorkbenchShell = () => {
[placementProject, widgets]
);
const handleDragCancel = useCallback(() => setActiveDrag(null), []);
- // Flush drafts before rail-side docking, as the window's dock control does.
const handleSelect = useCallback(
(region: WidgetBarGroup['region'], instanceId: string) => {
- if (floatingWidgets[instanceId]) {
- flushWorkbenchDrafts();
- widgets.dockFloating(instanceId);
-
- return;
- }
-
- revealWidgetPlacement({ instanceId, project: placementProject, region, widgets });
+ activateRailPlacement({ instanceId, project: placementProject, region, widgets });
+ },
+ [placementProject, widgets]
+ );
+ const handleDock = useCallback(
+ (instanceId: string) => {
+ dockFloatingPlacement({ instanceId, project: placementProject, widgets });
},
- [floatingWidgets, placementProject, widgets]
+ [placementProject, widgets]
);
- // Removing a floating slot closes the window outright — never dock-then-
- // toggle, which would pop the panel open and retarget the route on the way.
const closeFloating = useCallback(
(instanceId: string) => {
- flushWorkbenchDrafts();
- widgets.closeFloating(instanceId);
+ const typeId = placementProject.widgetInstances[instanceId]?.typeId;
+
+ if (removeFloatingPlacement({ instanceId, project: placementProject, widgets })?.restoresCenter && typeId) {
+ focusOpenedWidget('center', typeId);
+ }
},
- [widgets]
+ [placementProject, widgets]
);
const handleToggleLeft = useCallback(
(item: (typeof leftMenuItems)[number]) =>
@@ -313,6 +310,7 @@ export const WorkbenchShell = () => {
groups={leftRailGroups}
menuItems={leftMenuItems}
side="left"
+ onDock={handleDock}
onSelect={handleSelect}
onToggle={handleToggleLeft}
/>
@@ -324,6 +322,7 @@ export const WorkbenchShell = () => {
groups={rightRailGroups}
menuItems={rightMenuItems}
side="right"
+ onDock={handleDock}
onSelect={handleSelect}
onToggle={handleToggleRight}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.browser.test.tsx
index 0fbe114dff..cd23c3a0f7 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
@@ -134,7 +134,13 @@ await i18n.use(initReactI18next).init({
en: {
translation: {
widgets: {
- floating: { dock: 'Dock to panel', maximize: 'Maximize', move: 'Move {{label}} window', shade: 'Shade' },
+ floating: {
+ destinations: { right: 'right panel' },
+ dockTo: 'Dock to {{destination}}',
+ maximize: 'Maximize',
+ move: 'Move {{label}} window',
+ shade: 'Shade',
+ },
labels: { imageMap: 'Image Map' },
settingsLabel: '{{label}} settings',
},
@@ -197,7 +203,7 @@ describe('FloatingWidgetWindow chrome', () => {
expect(host?.querySelectorAll('button[aria-label="Image Map settings"]')).toHaveLength(1);
expect(host?.querySelector('button[aria-label*="actions"]')).toBeNull();
expect(host?.querySelector('button[aria-label="Float Window"]')).toBeNull();
- expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')).not.toBeNull();
+ expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to right panel"]')).not.toBeNull();
});
it('keeps the settings gear in the title-bar strip instead of beneath the widget actions', async () => {
@@ -237,7 +243,7 @@ describe('FloatingWidgetWindow chrome', () => {
// Contain repeated rejected-resource throws in the title bar so the window's dock control survives.
expect(host?.querySelector('button[aria-label="Toggle cluster labels"]')).toBeNull();
- expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')).not.toBeNull();
+ expect(host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to right panel"]')).not.toBeNull();
});
it('does not move the window when an arrow key is pressed on a widget action', async () => {
@@ -278,7 +284,7 @@ describe('FloatingWidgetWindow chrome', () => {
await renderWindow();
await act(async () => {
- host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to panel"]')?.click();
+ host?.querySelector<HTMLButtonElement>('button[aria-label="Dock to right panel"]')?.click();
await Promise.resolve();
});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx
index 030d393ba5..60e803e8fe 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/FloatingWidgetWindow.tsx
@@ -13,17 +13,10 @@ import {
type FloatingGeometry,
} from '@workbench/floatingWindows';
import { WidgetIcon } from '@workbench/iconResolver';
-import { resolveWidgetInstanceLabel } from '@workbench/widgetLabels';
+import { DOCK_DESTINATION_ICONS, resolveDockLabel, resolveWidgetInstanceLabel } from '@workbench/widgetLabels';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useWorkbenchWidgetRegistry } from '@workbench/WorkbenchWidgetRegistryContext';
-import {
- ChevronsDownUpIcon,
- ChevronsUpDownIcon,
- Maximize2Icon,
- Minimize2Icon,
- PanelRightIcon,
- TriangleAlertIcon,
-} from 'lucide-react';
+import { ChevronsDownUpIcon, ChevronsUpDownIcon, Maximize2Icon, Minimize2Icon, TriangleAlertIcon } from 'lucide-react';
import {
Component,
Suspense,
@@ -255,6 +248,7 @@ export const FloatingWidgetWindow = ({
// Retain window chrome for missing or failed widgets so users can dock them back to the retry surface.
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';
@@ -343,15 +337,9 @@ export const FloatingWidgetWindow = ({
<Icon as={isMaximized ? Minimize2Icon : Maximize2Icon} boxSize="3.5" />
</IconButton>
</Tooltip>
- <Tooltip content={t('widgets.floating.dock')}>
- <IconButton
- aria-label={t('widgets.floating.dock')}
- color="fg.muted"
- size="2xs"
- variant="ghost"
- onClick={handleDock}
- >
- <Icon as={PanelRightIcon} boxSize="3.5" />
+ <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>
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx
index 86a46c5056..9c955128c0 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx
@@ -3,12 +3,13 @@ import type { WidgetInstanceId } from '@workbench/widgetContracts';
import type { WidgetRegionDropState } from '@workbench/widgetDnd';
import type { WidgetPlacementInstanceMeta, WidgetRegionItem } from '@workbench/widgetRegionViewModel';
-import { Box, Flex, type SystemStyleObject } from '@chakra-ui/react';
+import { Box, Flex, Icon, type SystemStyleObject } from '@chakra-ui/react';
import { verticalListSortingStrategy } from '@dnd-kit/sortable';
import { Row } from '@platform/ui/Row';
import { Tooltip } from '@platform/ui/Tooltip';
import { useHighlightedRegion } from '@workbench/focusRegions';
import { WidgetIcon } from '@workbench/iconResolver';
+import { PictureInPicture2Icon } from 'lucide-react';
import { type MouseEvent, useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -36,11 +37,13 @@ interface WidgetBarProps {
side: 'left' | 'right';
groups: WidgetBarGroup[];
menuItems: WidgetBarItem[];
+ /** Dock the floating window a marker stands for. */
+ onDock: (instanceId: WidgetInstanceId) => void;
onSelect: (region: WidgetBarGroup['region'], instanceId: WidgetInstanceId) => void;
onToggle: (item: WidgetBarItem) => void;
}
-export const WidgetBar = ({ edgeRegion, groups, menuItems, onSelect, onToggle, side }: WidgetBarProps) => {
+export const WidgetBar = ({ edgeRegion, groups, menuItems, onDock, onSelect, onToggle, side }: WidgetBarProps) => {
const { t } = useTranslation();
const isEdgeOutlined = useHighlightedRegion() === edgeRegion;
const region = side;
@@ -73,6 +76,9 @@ export const WidgetBar = ({ edgeRegion, groups, menuItems, onSelect, onToggle, s
const handleContextClose = useCallback(() => setEnableMenuTarget(null), []);
const handleMenuToggle = useCallback((item: WidgetEnableMenuItem) => onToggle(item as WidgetBarItem), [onToggle]);
const handleInstanceClose = useCallback(() => setInstanceMenuTarget(null), []);
+ const handleInstanceDock = useCallback((item: WidgetEnableMenuItem) => onDock(item.id), [onDock]);
+ // A marker only ever shows in the rail its window returns to.
+ const isMarkerMenu = (instanceMenuTarget?.item as WidgetBarItem | undefined)?.isFloating === true;
return (
<Flex
@@ -115,8 +121,10 @@ export const WidgetBar = ({ edgeRegion, groups, menuItems, onSelect, onToggle, s
/>
<WidgetInstanceContextMenu
+ dockRegion={isMarkerMenu ? region : undefined}
target={instanceMenuTarget}
onClose={handleInstanceClose}
+ onDock={handleInstanceDock}
onRemove={handleMenuToggle}
/>
</Flex>
@@ -188,7 +196,7 @@ export const WIDGET_ITEM_SX: SystemStyleObject = {
h: 9,
w: 9,
color: 'fg.muted',
- '&[aria-pressed="false"]:hover': {
+ '&[aria-pressed="false"]:hover, &[data-floating]:hover': {
bg: 'bg.emphasized',
color: 'fg',
},
@@ -196,12 +204,16 @@ export const WIDGET_ITEM_SX: SystemStyleObject = {
bg: 'bg.emphasized',
color: 'brand.fg',
},
- // A floating slot reads as a placeholder for the window: outlined, not filled.
+ // A floating marker reads as a placeholder for the window: outlined, not filled, with a popped-out badge.
'&[data-floating]': {
+ color: 'fg.subtle',
+ position: 'relative',
+ },
+ // The dashed outline yields to the row's focus ring, which a keyboard user needs more.
+ '&[data-floating]:not(:focus-visible)': {
outline: '1px dashed',
outlineColor: 'border.emphasized',
outlineOffset: '-1px',
- color: 'fg.subtle',
},
_disabled: WIDGET_SLOT_DISABLED_PROPS,
};
@@ -223,10 +235,12 @@ const WidgetSlot = ({
}) => {
const { t } = useTranslation();
const tooltipLabel = item.isFloating
- ? t('widgets.floating.railSlot', { label: item.label })
+ ? t('widgets.floating.railMarkerHint', { label: item.label })
: item.failureMessage
? `${item.label}: ${item.failureMessage}`
: item.label;
+ // The name says what the control is; how to use it belongs to the tooltip.
+ const accessibleName = item.isFloating ? t('widgets.floating.railMarker', { label: item.label }) : tooltipLabel;
const isDisabled = item.status === 'disabled';
const positioning = useMemo(() => ({ placement: tooltipPlacement }) as const, [tooltipPlacement]);
@@ -250,11 +264,13 @@ const WidgetSlot = ({
<Tooltip showArrow closeDelay={80} content={tooltipLabel} openDelay={250} positioning={positioning}>
<Box ref={setNodeRef} pb="1" style={style}>
<Row
- {...dragHandleProps}
+ // A marker is not a tab: it takes no drag listeners and does not announce itself as sortable.
+ {...(item.isFloating ? undefined : dragHandleProps)}
css={WIDGET_ITEM_SX}
- aria-label={tooltipLabel}
+ aria-label={accessibleName}
aria-disabled={isDisabled}
- aria-pressed={isActive}
+ // A marker is a plain button: activating it shows the window and toggles nothing.
+ aria-pressed={item.isFloating ? undefined : isActive}
as="button"
data-disabled={isDisabled ? '' : undefined}
data-floating={item.isFloating ? '' : undefined}
@@ -264,6 +280,19 @@ const WidgetSlot = ({
onContextMenu={handleContextMenu}
>
<WidgetIcon icon={item.icon} boxSize="5" />
+ {item.isFloating ? (
+ <Icon
+ as={PictureInPicture2Icon}
+ bg="bg.subtle"
+ boxSize="3"
+ color="fg.muted"
+ data-floating-badge=""
+ position="absolute"
+ right="-0.5"
+ rounded="xs"
+ top="-0.5"
+ />
+ ) : null}
</Row>
</Box>
</Tooltip>
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsx
new file mode 100644
index 0000000000..da49451bdd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBarFloatingMarker.browser.test.tsx
@@ -0,0 +1,232 @@
+/* oxlint-disable react-perf/jsx-no-new-object-as-prop */
+import type {
+ NormalizedWidgetManifest,
+ RegisteredWidget,
+ WidgetInstanceContract,
+ WidgetTypeId,
+} from '@workbench/widgetContracts';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { DndContext } from '@dnd-kit/core';
+import { system } from '@theme/system';
+import { createWidgetImplementationResource } from '@workbench/widgetImplementationResource';
+import { createWidgetRegionViewModel } from '@workbench/widgetRegionViewModel';
+import i18next from 'i18next';
+import { MapIcon } from 'lucide-react';
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { userEvent } from 'vitest/browser';
+
+import { WidgetBar, type WidgetBarGroup } from './WidgetBar';
+
+/**
+ * A floated widget keeps its rail slot as a marker: it points at the window instead of docking it, and docking
+ * and removing are its context menu's job.
+ */
+
+const TestView = () => null;
+
+const createWidget = (id: WidgetTypeId, label: string): RegisteredWidget => ({
+ implementation: createWidgetImplementationResource(id, () => Promise.resolve({ view: TestView })),
+ manifest: {
+ apiVersion: 1,
+ allowMultiple: false,
+ allowedRegions: ['left', 'right'],
+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },
+ icon: MapIcon,
+ id,
+ label,
+ load: () => Promise.resolve({ view: TestView }),
+ state: { createInitial: () => ({}), persistence: 'project', version: 1 },
+ version: 1,
+ } as NormalizedWidgetManifest,
+ status: 'enabled',
+});
+
+const createInstance = (id: string): WidgetInstanceContract => ({
+ createdAt: '2026-01-01T00:00:00.000Z',
+ id,
+ state: { id, label: id, values: {}, version: 1 },
+ typeId: id,
+});
+
+const viewModel = createWidgetRegionViewModel({
+ activeInstanceId: 'gallery',
+ floatingWidgets: { 'image-map': { returnIndex: 1, returnRegion: 'right' } },
+ instanceIds: ['gallery', 'queue'],
+ region: 'right',
+ widgetInstances: {
+ gallery: createInstance('gallery'),
+ 'image-map': createInstance('image-map'),
+ queue: createInstance('queue'),
+ },
+ widgets: [createWidget('gallery', 'Gallery'), createWidget('image-map', 'Image Map'), createWidget('queue', 'Queue')],
+});
+
+const i18n = i18next.createInstance();
+await i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ widgets: {
+ floating: {
+ destinations: { right: 'right panel' },
+ dockTo: 'Dock to {{destination}}',
+ railMarker: '{{label}}, floating window',
+ railMarkerHint: '{{label}} is floating — click to show the window',
+ },
+ removeWidget: 'Remove {{label}}',
+ },
+ },
+ },
+ },
+});
+
+const handlers = { onDock: vi.fn(), onSelect: vi.fn(), onToggle: vi.fn() };
+const GROUPS: WidgetBarGroup[] = [
+ {
+ activeId: 'gallery',
+ dropState: { helperText: '', isActive: false, isAllowed: false },
+ railItems: viewModel.placedItems,
+ region: 'right',
+ },
+];
+
+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 renderBar = async () => {
+ await act(async () => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <DndContext>
+ <WidgetBar
+ edgeRegion="right"
+ groups={GROUPS}
+ menuItems={viewModel.placedItems}
+ side="right"
+ {...handlers}
+ />
+ </DndContext>
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ await Promise.resolve();
+ });
+};
+
+const slot = (label: string) => host!.querySelector<HTMLButtonElement>(`button[aria-label="${label}"]`)!;
+const marker = () => slot('Image Map, floating window');
+
+const openMenu = async (button: HTMLElement) => {
+ await act(async () => {
+ button.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 20 }));
+ await Promise.resolve();
+ });
+};
+
+const menuItem = (value: string) =>
+ document.body.querySelector<HTMLElement>(`[role="menuitem"][data-value="${value}"]`);
+
+beforeEach(() => {
+ for (const handler of Object.values(handlers)) {
+ handler.mockClear();
+ }
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(async () => {
+ await act(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+describe('WidgetBar floating marker', () => {
+ it('keeps the floated widget in its slot as a badged marker that is not a sortable tab', async () => {
+ await renderBar();
+
+ const labels = [...host!.querySelectorAll('[data-rail-group="right"] button')].map((button) =>
+ button.getAttribute('aria-label')
+ );
+
+ expect(labels).toEqual(['Gallery', 'Image Map, floating window', 'Queue']);
+ expect(marker().querySelector('[data-floating-badge]')).not.toBeNull();
+ // A plain button: not a sortable tab, and not a toggle.
+ expect(marker().getAttribute('aria-roledescription')).toBeNull();
+ expect(marker().hasAttribute('aria-pressed')).toBe(false);
+ expect(slot('Gallery').getAttribute('aria-roledescription')).toBe('sortable');
+ expect(slot('Gallery').getAttribute('aria-pressed')).toBe('true');
+ expect(slot('Gallery').querySelector('[data-floating-badge]')).toBeNull();
+ });
+
+ it('trades its dashed outline for the focus ring under keyboard focus', async () => {
+ await renderBar();
+
+ expect(getComputedStyle(marker()).outlineStyle).toBe('dashed');
+
+ slot('Gallery').focus();
+ await userEvent.keyboard('{Tab}');
+
+ expect(document.activeElement).toBe(marker());
+ expect(marker().matches(':focus-visible')).toBe(true);
+ expect(getComputedStyle(marker())).toMatchObject({ outlineStyle: 'solid', outlineWidth: '2px' });
+ });
+
+ it('reports activation as a selection, leaving docking to its menu', async () => {
+ await renderBar();
+
+ await act(async () => {
+ marker().click();
+ await Promise.resolve();
+ });
+
+ expect(handlers.onSelect).toHaveBeenCalledWith('right', 'image-map');
+ expect(handlers.onDock).not.toHaveBeenCalled();
+ });
+
+ it('offers Dock to its return region and Remove from the context menu', async () => {
+ await renderBar();
+ await openMenu(marker());
+
+ expect(menuItem('dock-widget')?.textContent).toBe('Dock to right panel');
+ expect(menuItem('remove-widget')?.textContent).toBe('Remove Image Map');
+
+ await act(async () => {
+ menuItem('dock-widget')?.click();
+ await Promise.resolve();
+ });
+
+ expect(handlers.onDock).toHaveBeenCalledWith('image-map');
+ expect(handlers.onToggle).not.toHaveBeenCalled();
+ });
+
+ it('removes the window from the marker menu', async () => {
+ await renderBar();
+ await openMenu(marker());
+
+ await act(async () => {
+ menuItem('remove-widget')?.click();
+ await Promise.resolve();
+ });
+
+ expect(handlers.onToggle).toHaveBeenCalledWith(expect.objectContaining({ id: 'image-map', isFloating: true }));
+ expect(handlers.onDock).not.toHaveBeenCalled();
+ });
+
+ it('offers no Dock item for a docked tab', async () => {
+ await renderBar();
+ await openMenu(slot('Queue'));
+
+ expect(menuItem('remove-widget')).not.toBeNull();
+ expect(menuItem('dock-widget')).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetInstanceContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetInstanceContextMenu.tsx
index 59474fe9db..2a876a676e 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetInstanceContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetInstanceContextMenu.tsx
@@ -1,5 +1,8 @@
+import type { WidgetRegion } from '@workbench/layoutContracts';
+
import { Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { MenuContent } from '@platform/ui/Menu';
+import { DOCK_DESTINATION_ICONS, resolveDockLabel } from '@workbench/widgetLabels';
import { ArrowLeftToLineIcon, ArrowRightToLineIcon, XIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -14,11 +17,14 @@ export interface WidgetInstanceContextMenuTarget {
interface WidgetInstanceContextMenuProps {
target: WidgetInstanceContextMenuTarget | null;
+ /** Set, with `onDock`, when the target is a floating window's marker: the region docking returns it to. */
+ dockRegion?: WidgetRegion;
/** With `onSetAlignment`, offers moving the widget between the strip's two clusters. */
isAlignedEnd?: (item: WidgetEnableMenuItem) => boolean;
isRemoveDisabled?: (item: WidgetEnableMenuItem) => boolean;
removeDisabledLabel?: string;
onClose: () => void;
+ onDock?: (item: WidgetEnableMenuItem) => void;
onRemove: (item: WidgetEnableMenuItem) => void;
onSetAlignment?: (item: WidgetEnableMenuItem, align: 'start' | 'end') => void;
}
@@ -26,9 +32,11 @@ interface WidgetInstanceContextMenuProps {
const REMOVE_DISABLED_PROPS = { opacity: 0.4 };
export const WidgetInstanceContextMenu = ({
+ dockRegion,
isAlignedEnd,
isRemoveDisabled,
onClose,
+ onDock,
onRemove,
onSetAlignment,
removeDisabledLabel = 'Required',
@@ -57,6 +65,11 @@ export const WidgetInstanceContextMenu = ({
onSetAlignment?.(target.item, isEnd ? 'start' : 'end');
}
}, [isEnd, onSetAlignment, target]);
+ const handleDock = useCallback(() => {
+ if (target) {
+ onDock?.(target.item);
+ }
+ }, [onDock, target]);
const handleRemove = useCallback(() => {
if (target && isRemoveDisabled?.(target.item) !== true) {
onRemove(target.item);
@@ -76,6 +89,12 @@ export const WidgetInstanceContextMenu = ({
<Menu.Positioner>
{target ? (
<MenuContent minW="12rem">
+ {onDock && dockRegion ? (
+ <Menu.Item value="dock-widget" onClick={handleDock}>
+ <Icon as={DOCK_DESTINATION_ICONS[dockRegion]} boxSize="3.5" />
+ <Menu.ItemText>{resolveDockLabel(dockRegion, t)}</Menu.ItemText>
+ </Menu.Item>
+ ) : null}
{onSetAlignment && target.item.isEnabled ? (
<Menu.Item value="toggle-alignment" onClick={handleToggleAlignment}>
<Icon as={isEnd ? ArrowLeftToLineIcon : ArrowRightToLineIcon} boxSize="3.5" />
diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
index 522cb1d55c..b4402a6409 100644
--- a/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/createWidgetRuntime.test.ts
@@ -66,6 +66,7 @@ const createDispatch = () => {
dispatch({ instanceId, projectId, type: 'patchWidgetInstanceValues', values }),
patchValues: (widgetId, values, projectId) => dispatch({ projectId, type: 'patchWidgetValues', values, widgetId }),
reorder: (options) => dispatch({ ...options, type: 'reorderWidgetInstances' }),
+ revealFloating: (instanceId) => dispatch({ instanceId, type: 'revealFloatingWidget' }),
select: (options) => dispatch({ ...options, type: 'selectRegionWidget' }),
setFloatingGeometry: (instanceId, geometry) =>
dispatch({ instanceId, type: 'setFloatingWidgetGeometry', ...geometry }),
diff --git a/invokeai/frontend/webv2/src/workbench/widgetLabels.ts b/invokeai/frontend/webv2/src/workbench/widgetLabels.ts
index 1665e1d123..e61897eb94 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetLabels.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetLabels.ts
@@ -1,5 +1,9 @@
+import type { WidgetRegion } from '@workbench/layoutContracts';
import type { WidgetInstanceRuntimeMeta, WidgetManifest, WidgetTypeId } from '@workbench/widgetContracts';
import type { TFunction } from 'i18next';
+import type { LucideIcon } from 'lucide-react';
+
+import { AppWindowIcon, PanelBottomIcon, PanelLeftIcon, PanelRightIcon } from 'lucide-react';
type WidgetLabelSource = Pick<WidgetManifest, 'id' | 'label'>;
@@ -12,5 +16,17 @@ export const resolveWidgetInstanceLabel = (
t: TFunction
): string => instance.title ?? resolveWidgetLabel(manifest, t);
+/** Names where docking a floating window puts it, e.g. "Dock to right panel". */
+export const resolveDockLabel = (returnRegion: WidgetRegion, t: TFunction): string =>
+ t('widgets.floating.dockTo', { destination: t(`widgets.floating.destinations.${returnRegion}`) });
+
+/** The icon that goes with {@link resolveDockLabel}, by the region the window returns to. */
+export const DOCK_DESTINATION_ICONS: Record<WidgetRegion, LucideIcon> = {
+ bottom: PanelBottomIcon,
+ center: AppWindowIcon,
+ left: PanelLeftIcon,
+ right: PanelRightIcon,
+};
+
export const getWidgetFallbackLabel = (manifest: { id: WidgetTypeId; label: WidgetManifest['label'] }): string =>
typeof manifest.label === 'string' ? manifest.label : manifest.id;
diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts
index d7d472313c..2026165883 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.test.ts
@@ -9,9 +9,12 @@ import type { WorkbenchWidgetCommands } from './workbenchStore';
import { createWidgetImplementationResource } from './widgetImplementationResource';
import {
+ activateRailPlacement,
closeWidgetPlacement,
+ dockFloatingPlacement,
getCenterPreviewToggleState,
openWidgetPlacement,
+ removeFloatingPlacement,
revealWidgetPlacement,
toggleCenterPreview,
} from './widgetPlacementCommands';
@@ -77,6 +80,7 @@ const createWidgetCommands = (dispatch: (action: WorkbenchAction) => void): Work
dispatch({ instanceId, projectId, type: 'patchWidgetInstanceValues', values }),
patchValues: (widgetId, values, projectId) => dispatch({ projectId, type: 'patchWidgetValues', values, widgetId }),
reorder: (options) => dispatch({ ...options, type: 'reorderWidgetInstances' }),
+ revealFloating: (instanceId) => dispatch({ instanceId, type: 'revealFloatingWidget' }),
select: (options) => dispatch({ ...options, type: 'selectRegionWidget' }),
setFloatingGeometry: (instanceId, geometry) =>
dispatch({ instanceId, type: 'setFloatingWidgetGeometry', ...geometry }),
@@ -269,10 +273,94 @@ describe('widget placement commands', () => {
});
});
+describe('floating window rail commands', () => {
+ /** Run a rail command against the real reducer, with the placement projection the shell hands it. */
+ const run = <Result>(
+ state: WorkbenchState,
+ command: (widgets: WorkbenchWidgetCommands, project: ReturnType<typeof getWidgetPlacementProject>) => Result
+ ): { project: Project; result: Result } => {
+ let result!: Result;
+ const next = applyCommand(state, (widgets) => {
+ result = command(widgets, getWidgetPlacementProject(getActiveProject(state)));
+ });
+
+ return { project: getActiveProject(next), result };
+ };
+ const float = (state: WorkbenchState, instanceId: string, region?: WidgetRegion): WorkbenchState =>
+ workbenchReducer(state, region ? { instanceId, region, type: 'floatWidget' } : { instanceId, type: 'floatWidget' });
+
+ it('activates a marker by raising and expanding its window, not by docking it', () => {
+ let state = float(float(createInitialWorkbenchState(), 'image-map'), 'gallery');
+ state = workbenchReducer(state, { instanceId: 'image-map', mode: 'shaded', type: 'setFloatingWidgetMode' });
+ const railBefore = getActiveProject(state).widgetRegions.right;
+
+ const { project, result } = run(state, (widgets, placement) =>
+ activateRailPlacement({ instanceId: 'image-map', project: placement, region: 'right', widgets })
+ );
+
+ expect(result).toBe('window');
+ expect(project.floatingWidgets?.['image-map']).toMatchObject({ mode: 'windowed', stackOrder: 2 });
+ expect(project.widgetRegions.right).toBe(railBefore);
+ });
+
+ it('activates a docked tab by revealing it in its rail', () => {
+ const { project, result } = run(createInitialWorkbenchState(), (widgets, placement) =>
+ activateRailPlacement({ instanceId: 'queue', project: placement, region: 'right', widgets })
+ );
+
+ expect(result).toBe('tab');
+ expect(project.widgetRegions.right.activeInstanceId).toBe('queue');
+ });
+
+ it('docks a window where it came from and names that region', () => {
+ const state = float(createInitialWorkbenchState(), 'image-map');
+ const docked = run(state, (widgets, placement) =>
+ dockFloatingPlacement({ instanceId: 'image-map', project: placement, widgets })
+ );
+ const stale = run(createInitialWorkbenchState(), (widgets, placement) =>
+ dockFloatingPlacement({ instanceId: 'image-map', project: placement, widgets })
+ );
+
+ expect(docked.result).toBe('right');
+ expect(docked.project.floatingWidgets).toBeUndefined();
+ expect(docked.project.widgetRegions.right.instanceIds).toEqual(['gallery', 'image-map', 'queue']);
+ // Nothing floats there: no dispatch, no region to move focus to.
+ expect(stale.result).toBeNull();
+ });
+
+ it('reports that removing the window hands an emptied center its view back', () => {
+ // Video shows Preview only in the center; it is added to the right rail and floated from there.
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'video', type: 'applyPreset' });
+ state = workbenchReducer(state, { region: 'right', type: 'openRegionWidget', widgetId: 'preview' });
+ state = float(state, 'preview', 'right');
+
+ const { project, result } = run(state, (widgets, placement) =>
+ removeFloatingPlacement({ instanceId: 'preview', project: placement, widgets })
+ );
+
+ expect(result).toEqual({ restoresCenter: true });
+ expect(project.floatingWidgets).toBeUndefined();
+ expect(project.widgetRegions.center.instanceIds).toEqual(['preview']);
+ });
+
+ it('reports no center restore when the center kept another view', () => {
+ const state = float(createInitialWorkbenchState(), 'image-map');
+ const { project, result } = run(state, (widgets, placement) =>
+ removeFloatingPlacement({ instanceId: 'image-map', project: placement, widgets })
+ );
+
+ expect(result).toEqual({ restoresCenter: false });
+ expect(project.floatingWidgets).toBeUndefined();
+ expect(project.widgetRegions.right.instanceIds).toEqual(['gallery', 'queue']);
+ });
+});
+
const previewRegistry = createRegistry({ center: [createWidget({ id: 'preview', label: 'Preview' })] });
-const createPreviewToggleHarness = () => {
- let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'automate', type: 'applyPreset' });
+const createPreviewToggleHarness = (
+ initial = workbenchReducer(createInitialWorkbenchState(), { presetId: 'automate', type: 'applyPreset' })
+) => {
+ let state = initial;
const dispatch = (action: WorkbenchAction): void => {
state = workbenchReducer(state, action);
};
@@ -287,7 +375,12 @@ const createPreviewToggleHarness = () => {
widgets,
});
- return { getRegions: () => getActiveProject(state).widgetRegions, select: widgets.select, toggle };
+ return {
+ getProject: () => getActiveProject(state),
+ getRegions: () => getActiveProject(state).widgetRegions,
+ select: widgets.select,
+ toggle,
+ };
};
describe('toggleCenterPreview', () => {
@@ -313,6 +406,36 @@ describe('toggleCenterPreview', () => {
expect(getRegions().right.activeInstanceId).toBe('queue');
});
+ it('docks a floating preview back to its rail slot, behind the tab already showing, and fronts it in the center', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'automate', type: 'applyPreset' });
+ const railBefore = getActiveProject(state).widgetRegions.right;
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+ const { getProject, toggle } = createPreviewToggleHarness(state);
+
+ expect(toggle()).toBe(true);
+
+ expect(getProject().floatingWidgets).toBeUndefined();
+ expect(getProject().widgetRegions.center.activeInstanceId).toBe('preview');
+ expect(getProject().widgetRegions.right).toMatchObject({
+ activeInstanceId: railBefore.activeInstanceId,
+ instanceIds: railBefore.instanceIds,
+ });
+ });
+
+ it('gives an emptied center its floating preview back without duplicating it', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { presetId: 'video', type: 'applyPreset' });
+ state = workbenchReducer(state, { region: 'right', type: 'openRegionWidget', widgetId: 'preview' });
+ state = workbenchReducer(state, { instanceId: 'preview', region: 'right', type: 'floatWidget' });
+ const { getProject, toggle } = createPreviewToggleHarness(state);
+
+ expect(getProject().widgetRegions.center.instanceIds).toEqual([]);
+ expect(toggle()).toBe(true);
+
+ expect(getProject().floatingWidgets).toBeUndefined();
+ expect(getProject().widgetRegions.center).toMatchObject({ activeInstanceId: 'preview', instanceIds: ['preview'] });
+ expect(getProject().widgetRegions.right.instanceIds).toEqual(['gallery', 'queue', 'preview']);
+ });
+
it('falls back to another center view when nothing was remembered', () => {
const { getRegions } = createPreviewToggleHarness();
const project = {
diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts
index 928d2bd40d..c562e5bb62 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementCommands.ts
@@ -11,11 +11,16 @@ import { flushWorkbenchDrafts } from '@platform/react/draftRegistry';
import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';
import { createExternalStore } from '@platform/state/externalStore';
+import type { FloatingWidgetPlacement } from './floatingWindows';
import type { WidgetDragEndResolution } from './widgetDnd';
import type { WidgetPlacementMeta } from './widgetRegionViewModel';
import type { WorkbenchWidgetCommands } from './workbenchStore';
+import { isAwaitedCenterView } from './floatingWindows';
+
export interface WidgetPlacementProject {
+ /** Where each floating window returns to; absent means none float, as with `Project.floatingWidgets`. */
+ floatingPlacements?: Record<WidgetInstanceId, FloatingWidgetPlacement>;
projectId?: string;
widgetInstances: WidgetPlacementMeta;
widgetRegions: Record<WidgetRegion, Pick<WidgetRegionState, 'activeInstanceId' | 'instanceIds'>>;
@@ -173,6 +178,79 @@ export const revealWidgetPlacement = ({
return { ok: true, region };
};
+/**
+ * Activate a rail slot. A docked tab is revealed in its region. A floating window's marker brings the window
+ * forward and expands it instead: docking is the window's own control and the marker's menu.
+ */
+export const activateRailPlacement = ({
+ instanceId,
+ project,
+ region,
+ widgets,
+}: {
+ project: WidgetPlacementProject;
+ region: WidgetRegion;
+ instanceId: WidgetInstanceId;
+ widgets: WorkbenchWidgetCommands;
+}): 'tab' | 'window' | null => {
+ if (project.floatingPlacements?.[instanceId]) {
+ widgets.revealFloating(instanceId);
+
+ return 'window';
+ }
+
+ return revealWidgetPlacement({ instanceId, project, region, widgets }).ok ? 'tab' : null;
+};
+
+/** Dock a floating window where it came from; returns that region, or null when the instance does not float. */
+export const dockFloatingPlacement = ({
+ instanceId,
+ project,
+ widgets,
+}: {
+ project: WidgetPlacementProject;
+ instanceId: WidgetInstanceId;
+ widgets: WorkbenchWidgetCommands;
+}): WidgetRegion | null => {
+ const placement = project.floatingPlacements?.[instanceId];
+
+ if (!placement) {
+ return null;
+ }
+
+ // Docking remounts the widget; registry cleanup only removes flushers.
+ flushWorkbenchDrafts();
+ widgets.dockFloating(instanceId);
+
+ return placement.returnRegion;
+};
+
+/**
+ * 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.
+ */
+export const removeFloatingPlacement = ({
+ instanceId,
+ project,
+ widgets,
+}: {
+ project: WidgetPlacementProject;
+ instanceId: WidgetInstanceId;
+ widgets: WorkbenchWidgetCommands;
+}): { restoresCenter: boolean } | null => {
+ if (!project.floatingPlacements?.[instanceId]) {
+ return null;
+ }
+
+ const restoresCenter = isAwaitedCenterView(project.widgetRegions.center, instanceId);
+
+ flushWorkbenchDrafts();
+ widgets.closeFloating(instanceId);
+
+ return { restoresCenter };
+};
+
export const dispatchWidgetDragEndPlacement = ({
resolution,
widgets,
diff --git a/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts b/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts
index 451772e25f..f185f5cfab 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetPlacementMeta.ts
@@ -2,15 +2,17 @@ import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts
import type { Project } from '@workbench/projectContracts';
import type { WidgetInstanceId } from '@workbench/widgetContracts';
+import type { FloatingWidgetPlacement } from './floatingWindows';
import type { WidgetPlacementProject } from './widgetPlacementCommands';
import type { WidgetPlacementMeta } from './widgetRegionViewModel';
export type WidgetPlacementRegionState = Pick<WidgetRegionState, 'activeInstanceId' | 'instanceIds' | 'isCollapsed'>;
+/** Every instance the layout shows somewhere: region members, and windows, which belong to no region. */
export const getWidgetPlacementMeta = (
- project: Pick<Project, 'widgetInstances' | 'widgetRegions'>
+ project: Pick<Project, 'floatingWidgets' | 'widgetInstances' | 'widgetRegions'>
): WidgetPlacementMeta => {
- const placedInstanceIds = new Set<WidgetInstanceId>();
+ const placedInstanceIds = new Set<WidgetInstanceId>(Object.keys(project.floatingWidgets ?? {}));
for (const region of Object.values(project.widgetRegions)) {
for (const instanceId of region.instanceIds) {
@@ -27,14 +29,49 @@ export const getWidgetPlacementMeta = (
);
};
+const NO_FLOATING_PLACEMENTS: Record<WidgetInstanceId, FloatingWidgetPlacement> = {};
+
+/**
+ * Only where each window returns to. Geometry, mode, and stacking stay out, so moving, shading, or raising a
+ * window leaves this projection equal and its subscribers — the rails among them — do not re-render.
+ */
+const getFloatingPlacements = (
+ floatingWidgets: Project['floatingWidgets']
+): Record<WidgetInstanceId, FloatingWidgetPlacement> =>
+ floatingWidgets
+ ? Object.fromEntries(
+ Object.entries(floatingWidgets).map(([instanceId, { returnIndex, returnRegion }]) => [
+ instanceId,
+ { returnIndex, returnRegion },
+ ])
+ )
+ : NO_FLOATING_PLACEMENTS;
+
export const getWidgetPlacementProject = (
- project: Pick<Project, 'id' | 'widgetInstances' | 'widgetRegions'>
+ project: Pick<Project, 'floatingWidgets' | 'id' | 'widgetInstances' | 'widgetRegions'>
): WidgetPlacementProject => ({
+ floatingPlacements: getFloatingPlacements(project.floatingWidgets),
projectId: project.id,
widgetInstances: getWidgetPlacementMeta(project),
widgetRegions: project.widgetRegions,
});
+const areFloatingPlacementsEqual = (
+ left: WidgetPlacementProject['floatingPlacements'] = NO_FLOATING_PLACEMENTS,
+ right: WidgetPlacementProject['floatingPlacements'] = NO_FLOATING_PLACEMENTS
+): boolean => {
+ const leftKeys = Object.keys(left);
+
+ return (
+ leftKeys.length === Object.keys(right).length &&
+ leftKeys.every(
+ (instanceId) =>
+ left[instanceId].returnRegion === right[instanceId]?.returnRegion &&
+ left[instanceId].returnIndex === right[instanceId]?.returnIndex
+ )
+ );
+};
+
export const areWidgetPlacementMetaEqual = (left: WidgetPlacementMeta, right: WidgetPlacementMeta): boolean => {
const leftKeys = Object.keys(left);
const rightKeys = Object.keys(right);
@@ -58,6 +95,7 @@ export const areWidgetPlacementMetaEqual = (left: WidgetPlacementMeta, right: Wi
export const areWidgetPlacementProjectsEqual = (left: WidgetPlacementProject, right: WidgetPlacementProject): boolean =>
left.projectId === right.projectId &&
areWidgetPlacementMetaEqual(left.widgetInstances, right.widgetInstances) &&
+ areFloatingPlacementsEqual(left.floatingPlacements, right.floatingPlacements) &&
(Object.keys(left.widgetRegions) as WidgetRegion[]).every((region) => {
const leftRegion = left.widgetRegions[region];
const rightRegion = right.widgetRegions[region];
diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionItems.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionItems.ts
index f96fd7caf9..3184db93f3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetRegionItems.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionItems.ts
@@ -4,7 +4,6 @@ export {
getWidgetRegionItems,
isPlacedWidgetRegionItem,
type AvailableWidgetTypeItem,
- type FloatingWidgetPlacement,
type PlacedWidgetRegionItem,
type WidgetPlacementInstanceMeta,
type WidgetPlacementMeta,
diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts
index c2f6d76064..f64765f3a7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.test.ts
@@ -83,30 +83,6 @@ describe('widget region view model', () => {
expect(viewModel.availableItems.map((item) => item.typeId)).toEqual([]);
});
- it('orders floating slots by their return index and clamps indices the rail no longer has', () => {
- const widgets = ['a', 'b', 'c', 'd', 'e'].map((id) => createWidget({ id, label: id.toUpperCase() }));
- const widgetInstances = Object.fromEntries(
- widgets.map((widget) => [widget.manifest.id, createInstance(widget.manifest.id, widget.manifest.id)])
- );
- const viewModel = createWidgetRegionViewModel({
- floatingWidgets: {
- // Later-sorted insertions must not displace earlier ones.
- d: { returnIndex: 2, returnRegion: 'left' },
- a: { returnIndex: 0, returnRegion: 'left' },
- // Beyond the rail: appended, as docking would.
- e: { returnIndex: 99, returnRegion: 'left' },
- c: { returnRegion: 'left' },
- },
- instanceIds: ['b'],
- region: 'left',
- widgetInstances,
- widgets,
- });
-
- expect(viewModel.placedItems.map((item) => item.id)).toEqual(['a', 'b', 'd', 'e', 'c']);
- expect(viewModel.sortableInstanceIds).toEqual(['b']);
- });
-
it('filters already placed singleton widget types from available items', () => {
const viewModel = createWidgetRegionViewModel({
instanceIds: ['alpha'],
diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts
index b19f7298b6..882f0fbf35 100644
--- a/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgetRegionViewModel.ts
@@ -1,4 +1,5 @@
-import type { FloatingWidgetState, WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';
+import type { FloatingWidgetPlacement } from '@workbench/floatingWindows';
+import type { WidgetRegion, WidgetRegionState } from '@workbench/layoutContracts';
import type {
NormalizedWidgetManifest,
RegisteredWidget,
@@ -8,6 +9,8 @@ import type {
WidgetTypeId,
} from '@workbench/widgetContracts';
+import { getRegionOrder } from '@workbench/floatingWindows';
+
export interface WidgetPlacementInstanceMeta {
id: WidgetInstanceId;
typeId: WidgetTypeId;
@@ -36,9 +39,6 @@ export interface PlacedWidgetRegionItem<
isFloating?: true;
}
-/** Only the placement half of a window: the slot this region keeps for it. */
-export type FloatingWidgetPlacement = Pick<FloatingWidgetState, 'returnIndex' | 'returnRegion'>;
-
export interface AvailableWidgetTypeItem extends BaseWidgetRegionItem {
instance?: undefined;
isEnabled: false;
@@ -57,33 +57,6 @@ export interface WidgetRegionViewModel<Instance extends WidgetPlacementInstanceM
sortableInstanceIds: WidgetInstanceId[];
}
-/**
- * Keep floated widgets reachable from their original rail slots; insert by ascending dock index to preserve
- * ordering.
- */
-const withFloatingSlots = (
- instanceIds: WidgetInstanceId[],
- region: WidgetRegion,
- floatingWidgets: Record<WidgetInstanceId, FloatingWidgetPlacement> | undefined
-): { instanceId: WidgetInstanceId; isFloating: boolean }[] => {
- const slots = instanceIds.map((instanceId) => ({ instanceId, isFloating: false }));
-
- if (!floatingWidgets) {
- return slots;
- }
-
- const floating = (Object.entries(floatingWidgets) as [WidgetInstanceId, FloatingWidgetPlacement][])
- .filter(([instanceId, state]) => state.returnRegion === region && !instanceIds.includes(instanceId))
- .map(([instanceId, state]) => ({ index: state.returnIndex ?? Number.POSITIVE_INFINITY, instanceId }))
- .sort((left, right) => left.index - right.index);
-
- for (const { index, instanceId } of floating) {
- slots.splice(Math.min(Math.max(0, Math.floor(index)), slots.length), 0, { instanceId, isFloating: true });
- }
-
- return slots;
-};
-
export const createWidgetRegionViewModel = <Instance extends WidgetPlacementInstanceMeta>({
activeInstanceId,
floatingWidgets,
@@ -103,7 +76,8 @@ export const createWidgetRegionViewModel = <Instance extends WidgetPlacementInst
getWidgetLabel?: (manifest: NormalizedWidgetManifest) => string;
}): WidgetRegionViewModel<Instance> => {
const widgetsByType = new Map(widgets.map((widget) => [widget.manifest.id, widget]));
- const placedItems = withFloatingSlots(instanceIds, region, floatingWidgets).flatMap(
+ // The order reducers dock by, so a marker sits exactly where its window returns.
+ const placedItems = getRegionOrder(region, instanceIds, floatingWidgets).flatMap(
({ instanceId, isFloating }): PlacedWidgetRegionItem<Instance>[] => {
const instance = widgetInstances[instanceId];
const widget = instance ? widgetsByType.get(instance.typeId) : undefined;
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
index de7ab0772c..9c90fec991 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts
@@ -181,7 +181,17 @@ import {
getFirstCanvasPlaceholderSlotIndex,
type CanvasStagingSlot,
} from './canvasStagingView';
-import { cascadeDefaultGeometry, clampSizeToMinimum, nextStackOrder } from './floatingWindows';
+import {
+ cascadeDefaultGeometry,
+ clampSizeToMinimum,
+ getRegionOrder,
+ isAwaitedCenterView,
+ nextStackOrder,
+ normalizeFloatingPlacement,
+ withoutFloatedInstances,
+ writeRegionOrder,
+ type RegionOrderSlot,
+} from './floatingWindows';
import { getSourceIdForWidgetTypeId } from './graphWidgets';
import {
defaultInvocationRoute,
@@ -200,9 +210,9 @@ import {
resolveLayoutPresetId,
} from './layoutPresets';
import {
- cloneFloatingWidgets,
cloneLayoutPresetWidgetRegions,
createLayoutPresetSnapshot,
+ normalizeLayoutPresetSnapshot,
resolveSavedLayoutPreset,
} from './layoutPresetSnapshots';
import { normalizeProjectSettings } from './settings/store';
@@ -291,6 +301,8 @@ type WorkbenchReducerAction =
}
| { type: 'setFloatingWidgetMode'; instanceId: WidgetInstanceId; mode: FloatingWidgetMode }
| { type: 'focusFloatingWidget'; 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 }
| {
type: 'patchGenerateSettings';
@@ -1422,7 +1434,7 @@ const withoutRetiredInstances = (
};
};
-// Adopt queue-status for the historical bottom default. reconcileFloatingWidgets removes any instance already
+// Adopt queue-status for the historical bottom default. Placement normalization removes any instance already
// hosted in a window.
const LEGACY_DEFAULT_BOTTOM_REGION_WIDGET_IDS: readonly WidgetInstanceId[] = [
'server-status',
@@ -1493,127 +1505,6 @@ const ensureCenterRegion = (
};
};
-const WIDGET_REGION_IDS: WidgetRegion[] = [...WIDGET_REGIONS];
-const FLOATING_WIDGET_MODES: FloatingWidgetMode[] = ['windowed', 'maximized', 'shaded'];
-
-const isFiniteNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value);
-
-const isFloatingWidgetMode = (value: unknown): value is FloatingWidgetMode =>
- FLOATING_WIDGET_MODES.includes(value as FloatingWidgetMode);
-
-const isWidgetRegionId = (value: unknown): value is WidgetRegion => WIDGET_REGION_IDS.includes(value as WidgetRegion);
-
-/** Restore the pre-float tab index, clamped to the current rail, so float/dock does not reorder the layout. */
-const insertAtReturnIndex = (
- instanceIds: WidgetInstanceId[],
- instanceId: WidgetInstanceId,
- returnIndex: number | undefined
-): WidgetInstanceId[] => {
- const next = [...instanceIds];
-
- next.splice(
- isFiniteNumber(returnIndex) && returnIndex >= 0 ? Math.min(Math.floor(returnIndex), next.length) : next.length,
- 0,
- instanceId
- );
-
- return next;
-};
-
-/**
- * Drop malformed floating entries so widgets remain docked and invalid region names or geometry cannot reach
- * reducers or CSS.
- */
-const normalizeFloatingWidgets = (
- value: unknown,
- widgetInstances: Record<WidgetInstanceId, WidgetInstanceContract>
-): Record<WidgetInstanceId, FloatingWidgetState> | undefined => {
- if (!value || typeof value !== 'object') {
- return undefined;
- }
-
- const floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> = {};
-
- for (const [instanceId, entry] of Object.entries(value as Record<string, unknown>)) {
- if (!entry || typeof entry !== 'object' || !widgetInstances[instanceId]) {
- continue;
- }
-
- const state = entry as Partial<FloatingWidgetState>;
- // The right rail's docks folded back into one region; a window floated out of one returns to the rail.
- const rawReturnRegion: unknown = state.returnRegion;
- const returnRegion =
- rawReturnRegion === 'rightTop' || rawReturnRegion === 'rightBottom' ? 'right' : state.returnRegion;
-
- if (
- !isFiniteNumber(state.x) ||
- !isFiniteNumber(state.y) ||
- !isFiniteNumber(state.widthPx) ||
- !isFiniteNumber(state.heightPx) ||
- !isFiniteNumber(state.stackOrder) ||
- !isFloatingWidgetMode(state.mode) ||
- !isWidgetRegionId(returnRegion)
- ) {
- continue;
- }
-
- floatingWidgets[instanceId] = {
- ...clampSizeToMinimum({ heightPx: state.heightPx, widthPx: state.widthPx, x: state.x, y: state.y }),
- mode: state.mode,
- // Omit invalid docking indices; docking then appends.
- ...(isFiniteNumber(state.returnIndex) && state.returnIndex >= 0
- ? { returnIndex: Math.floor(state.returnIndex) }
- : {}),
- returnRegion,
- stackOrder: state.stackOrder,
- };
- }
-
- return Object.keys(floatingWidgets).length > 0 ? floatingWidgets : undefined;
-};
-
-/**
- * Floating placement wins over migrated rail defaults to prevent duplicate rendering, even when it leaves the
- * center on its fallback view.
- */
-const reconcileFloatingWidgets = (
- widgetRegions: Record<WidgetRegion, WidgetRegionState>,
- floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined
-): {
- widgetRegions: Record<WidgetRegion, WidgetRegionState>;
- floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined;
-} => {
- if (!floatingWidgets) {
- return { floatingWidgets, widgetRegions };
- }
-
- let remainingFloating = floatingWidgets;
- const reconciledRegions = { ...widgetRegions };
-
- for (const regionId of WIDGET_REGION_IDS) {
- const region = reconciledRegions[regionId];
- const instanceIds = region.instanceIds.filter((instanceId) => !remainingFloating[instanceId]);
-
- if (instanceIds.length === region.instanceIds.length) {
- continue;
- }
-
- reconciledRegions[regionId] = {
- ...region,
- activeInstanceId: instanceIds.includes(region.activeInstanceId)
- ? region.activeInstanceId
- : (instanceIds[0] ?? emptiedActiveInstanceId(regionId, region)),
- instanceIds,
- isCollapsed: instanceIds.length === 0 ? regionId !== 'center' : region.isCollapsed,
- };
- }
-
- return {
- floatingWidgets: Object.keys(remainingFloating).length > 0 ? remainingFloating : undefined,
- widgetRegions: reconciledRegions,
- };
-};
-
const normalizePromptHistory = (value: unknown): PromptHistoryItem[] => {
if (!Array.isArray(value)) {
return [];
@@ -1788,14 +1679,15 @@ const assembleWorkbenchProject = (
)
);
- const placement = reconcileFloatingWidgets(
+ const placement = normalizeFloatingPlacement(
{
left: leftRegion,
right: rightRegion,
bottom: bottomRegion,
center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),
},
- normalizeFloatingWidgets((project as Partial<Project>).floatingWidgets, widgetInstances)
+ (project as Partial<Project>).floatingWidgets,
+ (instanceId) => Object.hasOwn(widgetInstances, instanceId)
);
return {
@@ -1916,7 +1808,10 @@ export const resolvePanelToggle = (
return { regions: occupied, shouldCollapse: occupied.some((region) => !widgetRegions[region].isCollapsed) };
};
-/** A region with nothing left names no active instance; the center keeps its id because it never empties. */
+/**
+ * A region with nothing left names no active instance. The center keeps naming the view it lost: that pointer is
+ * what lets a floated last view come back (see `isAwaitedCenterView`).
+ */
const emptiedActiveInstanceId = (regionId: WidgetRegion, region: WidgetRegionState): WidgetInstanceId =>
regionId === 'center' ? region.activeInstanceId : '';
@@ -1928,15 +1823,6 @@ const getNextInstanceId = (region: WidgetRegionState, instanceId: WidgetInstance
return region.instanceIds.find((enabledInstanceId) => enabledInstanceId !== instanceId) ?? null;
};
-const insertAt = <Value>(values: Value[], value: Value, index: number): Value[] => {
- const nextValues = values.filter((candidate) => candidate !== value);
- const nextIndex = Math.min(nextValues.length, Math.max(0, index));
-
- nextValues.splice(nextIndex, 0, value);
-
- return nextValues;
-};
-
const updateActiveWidgetRegion = (
state: WorkbenchState,
region: WidgetRegion,
@@ -1972,6 +1858,116 @@ const openPanelForRegion = (layout: ProjectLayoutState, region: WidgetRegion): P
},
});
+const withoutFloatingWidget = (
+ floatingWidgets: Project['floatingWidgets'],
+ instanceId: WidgetInstanceId
+): Project['floatingWidgets'] => {
+ const { [instanceId]: _removed, ...remaining } = floatingWidgets ?? {};
+
+ return Object.keys(remaining).length > 0 ? remaining : undefined;
+};
+
+/**
+ * Edit one region's complete order — docked members and floating markers together — so the markers' return
+ * indices stay in step with the members around them. A marker the edit docks or drops takes its window with it,
+ * which keeps an instance from ending up both docked and floating.
+ */
+const updateRegionOrder = (
+ project: Project,
+ regionId: WidgetRegion,
+ update: (slots: RegionOrderSlot[]) => RegionOrderSlot[]
+): Project => {
+ const region = project.widgetRegions[regionId];
+ const before = getRegionOrder(regionId, region.instanceIds, project.floatingWidgets);
+ const after = update(before);
+ const markerIds = new Set(after.filter((slot) => slot.isFloating).map((slot) => slot.instanceId));
+ const remaining = before.reduce(
+ (floatingWidgets, slot) =>
+ slot.isFloating && !markerIds.has(slot.instanceId)
+ ? withoutFloatingWidget(floatingWidgets, slot.instanceId)
+ : floatingWidgets,
+ project.floatingWidgets
+ );
+ const order = writeRegionOrder(after, remaining);
+ const isMembershipUnchanged =
+ order.instanceIds.length === region.instanceIds.length &&
+ order.instanceIds.every((instanceId, index) => instanceId === region.instanceIds[index]);
+
+ // An edit that only moves markers leaves the region object alone, so its subscribers do not re-render.
+ if (isMembershipUnchanged) {
+ return order.floatingWidgets === project.floatingWidgets
+ ? project
+ : { ...project, floatingWidgets: order.floatingWidgets };
+ }
+
+ return {
+ ...project,
+ floatingWidgets: order.floatingWidgets,
+ widgetRegions: { ...project.widgetRegions, [regionId]: { ...region, instanceIds: order.instanceIds } },
+ };
+};
+
+/**
+ * Put a floating instance back where it came from: its return region, at its marker's position, and the center
+ * too when the center has stayed empty since the instance left it. `reveal` also fronts it in the return region.
+ */
+const restoreFloatingInstance = (
+ project: Project,
+ instanceId: WidgetInstanceId,
+ { reveal }: { reveal: boolean }
+): Project => {
+ const floating = project.floatingWidgets?.[instanceId];
+
+ if (!floating) {
+ return project;
+ }
+
+ const { returnRegion } = floating;
+ // Counting the docked members ahead of the marker keeps every other slot where the rail shows it.
+ const docked = updateProjectWidgetRegion(
+ updateRegionOrder(project, returnRegion, (slots) =>
+ slots.map((slot) => (slot.instanceId === instanceId ? { ...slot, isFloating: false } : slot))
+ ),
+ returnRegion,
+ (region) =>
+ reveal || !region.instanceIds.includes(region.activeInstanceId)
+ ? { ...region, activeInstanceId: instanceId, isCollapsed: reveal ? false : region.isCollapsed }
+ : region
+ );
+ const restored =
+ returnRegion !== 'center' && isAwaitedCenterView(project.widgetRegions.center, instanceId)
+ ? updateRegionOrder(docked, 'center', (slots) => [...slots, { instanceId, isFloating: false }])
+ : docked;
+
+ return reveal ? { ...restored, layout: openPanelForRegion(restored.layout, returnRegion) } : restored;
+};
+
+/** Raise a window to the top of the stack; the same map comes back when it is missing or already topmost. */
+const raiseFloatingWidget = (
+ floatingWidgets: Project['floatingWidgets'],
+ instanceId: WidgetInstanceId
+): Project['floatingWidgets'] => {
+ const floating = floatingWidgets?.[instanceId];
+
+ if (!floatingWidgets || !floating || floating.stackOrder === nextStackOrder(floatingWidgets) - 1) {
+ return floatingWidgets;
+ }
+
+ // Compact persisted stackOrder to 1..N rather than growing it on every raise.
+ const below = Object.entries(floatingWidgets)
+ .filter(([otherInstanceId]) => otherInstanceId !== instanceId)
+ .sort(([, left], [, right]) => left.stackOrder - right.stackOrder);
+ const raised: Record<WidgetInstanceId, FloatingWidgetState> = {};
+
+ for (const [otherInstanceId, windowState] of below) {
+ raised[otherInstanceId] = { ...windowState, stackOrder: Object.keys(raised).length + 1 };
+ }
+
+ raised[instanceId] = { ...floating, stackOrder: below.length + 1 };
+
+ return raised;
+};
+
const cloneLayoutPresetSnapshot = (snapshot: LayoutPresetSnapshot): LayoutPresetSnapshot => {
// Strip retired editor instances when rebuilding account presets to keep applied layouts drift-free.
const retired = new Set(
@@ -1983,8 +1979,9 @@ const cloneLayoutPresetSnapshot = (snapshot: LayoutPresetSnapshot): LayoutPreset
for (const region of Object.keys(widgetRegions) as WidgetRegion[]) {
widgetRegions[region] = withoutRetiredInstances(widgetRegions[region], retired);
}
- return {
- ...(snapshot.floatingWidgets ? { floatingWidgets: cloneFloatingWidgets(snapshot.floatingWidgets) } : {}),
+ // Stored placements are read the way a project's are, so an applied preset matches the snapshot it came from.
+ return normalizeLayoutPresetSnapshot({
+ floatingWidgets: snapshot.floatingWidgets,
layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },
widgetInstances: Object.fromEntries(
Object.entries(snapshot.widgetInstances)
@@ -1992,7 +1989,7 @@ const cloneLayoutPresetSnapshot = (snapshot: LayoutPresetSnapshot): LayoutPreset
.map(([instanceId, instance]) => [instanceId, { ...instance }])
),
widgetRegions,
- };
+ });
};
const centerViewIds = new Set<CenterViewId>(['canvas', 'gallery', 'preview', 'workflow']);
@@ -2287,7 +2284,8 @@ const setBuiltInLayoutPresetMetadata = (
};
const applyLayoutPresetToProject = (project: Project, preset: LayoutPreset): Project => {
- const snapshot = preset.snapshot;
+ // Presets replace all placements, including floating windows, and bypass normalizeWorkbenchProject.
+ const snapshot = normalizeLayoutPresetSnapshot(preset.snapshot);
const widgetInstances = { ...project.widgetInstances };
for (const instance of Object.values(snapshot.widgetInstances)) {
@@ -2296,23 +2294,16 @@ const applyLayoutPresetToProject = (project: Project, preset: LayoutPreset): Pro
: createWidgetInstance(instance.typeId, instance.id);
}
- // Presets replace all placements, including floating windows. Validate account-stored windows here because
- // presets bypass normalizeWorkbenchProject.
- const placement = reconcileFloatingWidgets(
- cloneLayoutPresetWidgetRegions(snapshot.widgetRegions),
- normalizeFloatingWidgets(snapshot.floatingWidgets, widgetInstances)
- );
-
return {
...project,
- floatingWidgets: placement.floatingWidgets,
+ floatingWidgets: snapshot.floatingWidgets,
layout: {
...snapshot.layout,
panels: { ...snapshot.layout.panels },
presetId: preset.id,
},
widgetInstances,
- widgetRegions: placement.widgetRegions,
+ widgetRegions: cloneLayoutPresetWidgetRegions(snapshot.widgetRegions),
};
};
@@ -3788,30 +3779,29 @@ export const __workbenchReducerInternal = (
Object.values(project.widgetInstances).find((instance) => instance.typeId === action.widgetId);
const instanceId =
action.createNew || !existingInstance ? createId(`widget-${action.widgetId}`) : existingInstance.id;
- const instanceIds = region.instanceIds.includes(instanceId)
- ? region.instanceIds
- : [...region.instanceIds, instanceId];
const widgetInstances = project.widgetInstances[instanceId]
? project.widgetInstances
: {
...project.widgetInstances,
[instanceId]: createWidgetInstance(action.widgetId, instanceId, action.initialValues),
};
- // Placing an instance docks it to prevent simultaneous region/window rendering.
- const { [instanceId]: _floated, ...floatingWidgets } = project.floatingWidgets ?? {};
-
+ // An explicit open docks a floating instance where it came from before placing it here, so it is never
+ // both a window and a region member.
+ const docked = restoreFloatingInstance({ ...project, widgetInstances }, instanceId, { reveal: false });
+ const placed = docked.widgetRegions[action.region].instanceIds.includes(instanceId)
+ ? docked
+ : updateRegionOrder(docked, action.region, (slots) => [...slots, { instanceId, isFloating: false }]);
+
+ // One reveal, for the placement that ends up in front.
return applyAutoRouteForWidgetReveal(
{
- ...project,
- floatingWidgets,
- layout: openPanelForRegion(project.layout, action.region),
- widgetInstances,
+ ...placed,
+ layout: openPanelForRegion(placed.layout, action.region),
widgetRegions: {
- ...project.widgetRegions,
+ ...placed.widgetRegions,
[action.region]: {
- ...region,
+ ...placed.widgetRegions[action.region],
activeInstanceId: instanceId,
- instanceIds,
isCollapsed: false,
},
},
@@ -3825,14 +3815,16 @@ export const __workbenchReducerInternal = (
return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {
const region = project.widgetRegions[action.region];
- // Selecting a region slot docks the instance to prevent simultaneous region/window rendering.
- const { [action.widgetId]: _floated, ...floatingWidgets } = project.floatingWidgets ?? {};
+ // A request that names an instance the region no longer holds — it floated, or left — is stale. It changes
+ // nothing; in particular it must not discard the window.
+ if (!region.instanceIds.includes(action.widgetId)) {
+ return project;
+ }
if (action.region === 'center') {
return applyAutoRouteForRevealedInstance(
{
...project,
- floatingWidgets,
widgetRegions: {
...project.widgetRegions,
center: { ...region, activeInstanceId: action.widgetId, isCollapsed: false },
@@ -3847,7 +3839,6 @@ export const __workbenchReducerInternal = (
if (region.activeInstanceId === action.widgetId) {
const disclosed = {
...project,
- floatingWidgets,
layout: openPanelForRegion(project.layout, action.region),
widgetRegions: {
...project.widgetRegions,
@@ -3863,7 +3854,6 @@ export const __workbenchReducerInternal = (
return applyAutoRouteForRevealedInstance(
{
...project,
- floatingWidgets,
layout: openPanelForRegion(project.layout, action.region),
widgetRegions: {
...project.widgetRegions,
@@ -3878,91 +3868,86 @@ export const __workbenchReducerInternal = (
case 'toggleRegionWidget': {
return updateProjectById(state, action.projectId ?? state.activeProjectId, (project) => {
const previousRegion = project.widgetRegions[action.region];
- const nextProject = updateProjectWidgetRegion(project, action.region, (region) => {
- const isEnabled = region.instanceIds.includes(action.widgetId);
-
- if (action.region === 'center' && isEnabled && region.instanceIds.length === 1) {
- return region;
- }
+ const isEnabled = previousRegion.instanceIds.includes(action.widgetId);
- const instanceIds = isEnabled
- ? region.instanceIds.filter((widgetId) => widgetId !== action.widgetId)
- : [...region.instanceIds, action.widgetId];
- const fallbackInstanceId = getNextInstanceId(region, action.widgetId);
+ // A refused toggle must stay a no-op down to object identity: the persistence layer treats any new
+ // `projects` reference as a change worth autosaving. The work surface keeps its last view, and a floating
+ // instance belongs to no region.
+ if (
+ isEnabled
+ ? action.region === 'center' && previousRegion.instanceIds.length === 1
+ : project.floatingWidgets?.[action.widgetId] !== undefined
+ ) {
+ return project;
+ }
- return {
+ const nextProject = updateProjectWidgetRegion(
+ updateRegionOrder(project, action.region, (slots) =>
+ isEnabled
+ ? slots.filter((slot) => slot.instanceId !== action.widgetId)
+ : [...slots, { instanceId: action.widgetId, isFloating: false }]
+ ),
+ action.region,
+ (region) => ({
...region,
activeInstanceId: isEnabled
- ? (fallbackInstanceId ?? emptiedActiveInstanceId(action.region, region))
+ ? (getNextInstanceId(previousRegion, action.widgetId) ??
+ emptiedActiveInstanceId(action.region, previousRegion))
: action.widgetId,
- instanceIds,
- isCollapsed: action.region === 'center' ? false : instanceIds.length === 0 ? true : region.isCollapsed,
- };
- });
-
- // A refused toggle (the work surface keeping its last view) must stay a
- // no-op down to object identity: the persistence layer treats any new
- // `projects` reference as a change worth autosaving.
- if (nextProject === project) {
- return project;
- }
+ isCollapsed:
+ action.region === 'center' ? false : region.instanceIds.length === 0 ? true : region.isCollapsed,
+ })
+ );
return applyAutoRouteForRegionFront(nextProject, previousRegion, action.region, context);
});
}
case 'floatWidget': {
return updateActiveProject(state, (project) => {
- if (project.floatingWidgets?.[action.instanceId]) {
+ if (project.floatingWidgets?.[action.instanceId] || !project.widgetInstances[action.instanceId]) {
return project;
}
- // Use the clicked region as the dock-back origin for multi-region widgets; map order is not a stable
- // origin.
- const findHost = (match: (regionId: WidgetRegion, region: WidgetRegionState) => boolean) =>
- (Object.entries(project.widgetRegions) as [WidgetRegion, WidgetRegionState][]).find(([regionId, region]) =>
- match(regionId, region)
- );
- const hostEntry = action.region
- ? findHost((regionId, region) => regionId === action.region && region.instanceIds.includes(action.instanceId))
- : undefined;
- const resolvedHostEntry = hostEntry ?? findHost((_, region) => region.instanceIds.includes(action.instanceId));
+ const memberRegions = WIDGET_REGIONS.filter((regionId) =>
+ project.widgetRegions[regionId].instanceIds.includes(action.instanceId)
+ );
+ // The window returns to the chrome the float was asked from; without that hint, to its first member region.
+ // The reducer accepts a center origin; the UI float control only offers dockable panel origins.
+ const returnRegion = action.region && memberRegions.includes(action.region) ? action.region : memberRegions[0];
- if (!resolvedHostEntry || !project.widgetInstances[action.instanceId]) {
+ if (!returnRegion) {
return project;
}
- const [hostRegionId, hostRegion] = resolvedHostEntry;
-
- // The reducer accepts center-origin floating and preserves its fallback; the UI float control only offers
- // dockable panel origins.
- const instanceIds = hostRegion.instanceIds.filter((instanceId) => instanceId !== action.instanceId);
- const fallbackInstanceId = getNextInstanceId(hostRegion, action.instanceId);
- const floating: FloatingWidgetState = {
- ...cascadeDefaultGeometry(Object.keys(project.floatingWidgets ?? {}).length),
- mode: 'windowed',
- returnIndex: hostRegion.instanceIds.indexOf(action.instanceId),
- returnRegion: hostRegionId,
- stackOrder: nextStackOrder(project.floatingWidgets),
+ let floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> | undefined = {
+ ...project.floatingWidgets,
+ [action.instanceId]: {
+ ...cascadeDefaultGeometry(Object.keys(project.floatingWidgets ?? {}).length),
+ mode: 'windowed',
+ returnRegion,
+ stackOrder: nextStackOrder(project.floatingWidgets),
+ },
};
+ const widgetRegions = { ...project.widgetRegions };
+
+ // A floating instance belongs to no region: it leaves every one that held it, and only the return region
+ // keeps its slot, as a marker.
+ for (const regionId of memberRegions) {
+ const region = project.widgetRegions[regionId];
+ const slots = getRegionOrder(regionId, region.instanceIds, project.floatingWidgets);
+ const order = writeRegionOrder(
+ regionId === returnRegion
+ ? slots.map((slot) => (slot.instanceId === action.instanceId ? { ...slot, isFloating: true } : slot))
+ : slots.filter((slot) => slot.instanceId !== action.instanceId),
+ floatingWidgets
+ );
+
+ floatingWidgets = order.floatingWidgets;
+ widgetRegions[regionId] = withoutFloatedInstances(regionId, region, order.instanceIds);
+ }
return applyAutoRouteForRevealedInstance(
- {
- ...project,
- floatingWidgets: { ...project.floatingWidgets, [action.instanceId]: floating },
- widgetRegions: {
- ...project.widgetRegions,
- [hostRegionId]: {
- ...hostRegion,
- activeInstanceId:
- hostRegion.activeInstanceId === action.instanceId
- ? (fallbackInstanceId ?? emptiedActiveInstanceId(hostRegionId, hostRegion))
- : hostRegion.activeInstanceId,
- instanceIds,
- // Empty rails collapse; an empty center uses its fallback view.
- isCollapsed: instanceIds.length === 0 && hostRegionId !== 'center' ? true : hostRegion.isCollapsed,
- },
- },
- },
+ { ...project, floatingWidgets, widgetRegions },
// The window lands on top of everything, so it is the revealed
// surface — not the tab the rail promotes behind it.
action.instanceId,
@@ -3971,6 +3956,17 @@ export const __workbenchReducerInternal = (
});
}
case 'dockFloatingWidget': {
+ return updateActiveProject(state, (project) =>
+ project.floatingWidgets?.[action.instanceId]
+ ? applyAutoRouteForRevealedInstance(
+ restoreFloatingInstance(project, action.instanceId, { reveal: true }),
+ action.instanceId,
+ context
+ )
+ : project
+ );
+ }
+ case 'closeFloatingWidget': {
return updateActiveProject(state, (project) => {
const floating = project.floatingWidgets?.[action.instanceId];
@@ -3978,41 +3974,18 @@ export const __workbenchReducerInternal = (
return project;
}
- const { [action.instanceId]: _docked, ...remaining } = project.floatingWidgets ?? {};
- const region = project.widgetRegions[floating.returnRegion];
- const instanceIds = region.instanceIds.includes(action.instanceId)
- ? region.instanceIds
- : insertAtReturnIndex(region.instanceIds, action.instanceId, floating.returnIndex);
-
- return applyAutoRouteForRevealedInstance(
- {
- ...project,
- floatingWidgets: remaining,
- layout: openPanelForRegion(project.layout, floating.returnRegion),
- widgetRegions: {
- ...project.widgetRegions,
- [floating.returnRegion]: {
- ...region,
- activeInstanceId: action.instanceId,
- instanceIds,
- isCollapsed: false,
- },
- },
- },
- action.instanceId,
- context
+ // Removing closes the window and frees its rail slot. It opens no panel, but a center left empty by this
+ // instance gets its view back rather than staying blank.
+ const closed = updateRegionOrder(project, floating.returnRegion, (slots) =>
+ slots.filter((slot) => slot.instanceId !== action.instanceId)
);
- });
- }
- case 'closeFloatingWidget': {
- return updateActiveProject(state, (project) => {
- if (!project.floatingWidgets?.[action.instanceId]) {
- return project;
- }
-
- const { [action.instanceId]: _closed, ...remaining } = project.floatingWidgets;
- return { ...project, floatingWidgets: Object.keys(remaining).length > 0 ? remaining : undefined };
+ return isAwaitedCenterView(project.widgetRegions.center, action.instanceId)
+ ? updateRegionOrder(closed, 'center', (slots) => [
+ ...slots,
+ { instanceId: action.instanceId, isFloating: false },
+ ])
+ : closed;
});
}
case 'setFloatingWidgetGeometry': {
@@ -4062,43 +4035,61 @@ export const __workbenchReducerInternal = (
}
case 'focusFloatingWidget': {
return updateActiveProject(state, (project) => {
- const floating = project.floatingWidgets?.[action.instanceId];
- const topOrder = nextStackOrder(project.floatingWidgets) - 1;
+ 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.
- if (!floating || floating.stackOrder === topOrder) {
- return project;
- }
-
- // Compact persisted stackOrder to 1..N rather than growing it on every raise.
- const below = Object.entries(project.floatingWidgets ?? {})
- .filter(([instanceId]) => instanceId !== action.instanceId)
- .sort(([, left], [, right]) => left.stackOrder - right.stackOrder);
- const floatingWidgets: Record<WidgetInstanceId, FloatingWidgetState> = {};
-
- for (const [instanceId, windowState] of below) {
- floatingWidgets[instanceId] = { ...windowState, stackOrder: Object.keys(floatingWidgets).length + 1 };
- }
-
- floatingWidgets[action.instanceId] = { ...floating, stackOrder: below.length + 1 };
+ return floatingWidgets === project.floatingWidgets
+ ? project
+ : applyAutoRouteForRevealedInstance({ ...project, floatingWidgets }, action.instanceId, context);
+ });
+ }
+ case 'revealFloatingWidget': {
+ return updateActiveProject(state, (project) => {
+ const raised = raiseFloatingWidget(project.floatingWidgets, action.instanceId);
+ const floating = raised?.[action.instanceId];
+ // A shaded window is rolled up to its title bar; raising it alone would still hide its content.
+ const floatingWidgets: Project['floatingWidgets'] =
+ floating?.mode === 'shaded' ? { ...raised, [action.instanceId]: { ...floating, mode: 'windowed' } } : raised;
- return applyAutoRouteForRevealedInstance({ ...project, floatingWidgets }, action.instanceId, context);
+ return floatingWidgets === project.floatingWidgets
+ ? project
+ : applyAutoRouteForRevealedInstance({ ...project, floatingWidgets }, action.instanceId, context);
});
}
case 'moveWidgetInstance': {
return updateActiveProject(state, (project) => {
const fromRegion = project.widgetRegions[action.fromRegion];
- const toRegion = project.widgetRegions[action.toRegion];
- const nextFromInstanceIds = fromRegion.instanceIds.filter((instanceId) => instanceId !== action.instanceId);
- const nextToInstanceIds = insertAt(toRegion.instanceIds, action.instanceId, action.toIndex);
+
+ // Only a docked member can be dragged; a stale request for one that has left or floated changes nothing.
+ if (!fromRegion.instanceIds.includes(action.instanceId)) {
+ return project;
+ }
+
+ const detached = updateRegionOrder(project, action.fromRegion, (slots) =>
+ slots.filter((slot) => slot.instanceId !== action.instanceId)
+ );
+ // `toIndex` counts docked members; the instance lands in front of the member at that index, wherever the
+ // region's markers sit.
+ const moved = updateRegionOrder(detached, action.toRegion, (slots) => {
+ const others = slots.filter((slot) => slot.instanceId !== action.instanceId);
+ const target = others.filter((slot) => !slot.isFloating)[Math.max(0, action.toIndex)];
+ const position = target ? others.indexOf(target) : others.length;
+
+ return [
+ ...others.slice(0, position),
+ { instanceId: action.instanceId, isFloating: false },
+ ...others.slice(position),
+ ];
+ });
+ const nextFromInstanceIds = detached.widgetRegions[action.fromRegion].instanceIds;
return applyAutoRouteForRevealedInstance(
{
- ...project,
+ ...moved,
layout: openPanelForRegion(project.layout, action.toRegion),
widgetRegions: {
- ...project.widgetRegions,
+ ...moved.widgetRegions,
[action.fromRegion]: {
...fromRegion,
activeInstanceId:
@@ -4110,9 +4101,9 @@ export const __workbenchReducerInternal = (
action.fromRegion === 'center' ? false : nextFromInstanceIds.length === 0 || fromRegion.isCollapsed,
},
[action.toRegion]: {
- ...toRegion,
+ ...project.widgetRegions[action.toRegion],
activeInstanceId: action.instanceId,
- instanceIds: nextToInstanceIds,
+ instanceIds: moved.widgetRegions[action.toRegion].instanceIds,
isCollapsed: false,
},
},
@@ -4126,6 +4117,18 @@ export const __workbenchReducerInternal = (
case 'reorderWidgetInstances': {
return updateActiveProject(state, (project) => {
const previousRegion = project.widgetRegions[action.region];
+ const members = new Set(previousRegion.instanceIds);
+
+ // A reorder only permutes the docked members, which then fill the docked positions around stationary
+ // markers. Anything else is stale: it could re-add an instance that floated or left.
+ if (
+ action.instanceIds.length !== members.size ||
+ new Set(action.instanceIds).size !== members.size ||
+ !action.instanceIds.every((instanceId) => members.has(instanceId))
+ ) {
+ return project;
+ }
+
const nextProject = updateProjectWidgetRegion(project, action.region, (region) => ({
...region,
activeInstanceId: action.activeInstanceId ?? region.activeInstanceId,
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
index 0a319ec8cf..9b1cbb0e88 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStateAutoRoute.test.ts
@@ -101,9 +101,15 @@ const getInvocation = (state: State) => getProject(state).invocation;
const getRegion = (state: State, region: 'left' | 'right' | 'center' | 'bottom') =>
getProject(state).widgetRegions[region];
+/** The default layout keeps Video off the left rail; a tab has to be there before it can be brought to the front. */
+const createStateWithVideoTab = (): State =>
+ workbenchReducer(createInitialWorkbenchState(), { region: 'left', type: 'toggleRegionWidget', widgetId: 'video' });
+
describe('auto invocation route switching on widget reveal', () => {
it('follows the rail tab that is brought to the front', () => {
- let state = createInitialWorkbenchState();
+ let state = createStateWithVideoTab();
+
+ state = workbenchReducer(state, { region: 'left', type: 'selectRegionWidget', widgetId: 'generate' });
expect(getInvocation(state)).toMatchObject({ sourceId: 'generate' });
@@ -117,9 +123,8 @@ describe('auto invocation route switching on widget reveal', () => {
});
it('routes when a collapsed rail is expanded back onto a graph widget, but not when it is collapsed', () => {
- let state = createInitialWorkbenchState();
+ let state = createStateWithVideoTab();
- state = workbenchReducer(state, { region: 'left', type: 'selectRegionWidget', widgetId: 'video' });
// Collapsing the rail puts nothing in front, so the route must not move.
state = workbenchReducer(state, { region: 'left', type: 'selectRegionWidget', widgetId: 'video' });
@@ -224,33 +229,51 @@ describe('auto invocation route switching on widget reveal', () => {
});
it('ignores reveals of widgets that are not invocation sources', () => {
- let state = createInitialWorkbenchState();
+ let state = createStateWithVideoTab();
- state = workbenchReducer(state, { region: 'left', type: 'selectRegionWidget', widgetId: 'video' });
state = workbenchReducer(state, { region: 'right', type: 'selectRegionWidget', widgetId: 'gallery' });
expect(getInvocation(state)).toMatchObject({ sourceId: 'video' });
});
it('respects the source lock and the preference', () => {
- let locked = createInitialWorkbenchState();
+ // Video is on the rail behind Generate, with Generate routed: selecting Video is what would move the route.
+ const generateInFront = workbenchReducer(createStateWithVideoTab(), {
+ region: 'left',
+ type: 'selectRegionWidget',
+ widgetId: 'generate',
+ });
+
+ expect(getInvocation(generateInFront)).toMatchObject({ sourceId: 'generate' });
- locked = workbenchReducer(locked, { type: 'toggleSourceLock' });
+ let locked = workbenchReducer(generateInFront, { type: 'toggleSourceLock' });
locked = workbenchReducer(locked, { region: 'left', type: 'selectRegionWidget', widgetId: 'video' });
+ expect(getRegion(locked, 'left').activeInstanceId).toBe('video');
expect(getInvocation(locked)).toMatchObject({ sourceId: 'generate' });
- let preferenceOffState = createInitialWorkbenchState();
-
- preferenceOffState = workbenchReducer(
- preferenceOffState,
+ const preferenceOffState = workbenchReducer(
+ generateInFront,
{ region: 'left', type: 'selectRegionWidget', widgetId: 'video' },
preferenceOff
);
+ expect(getRegion(preferenceOffState, 'left').activeInstanceId).toBe('video');
expect(getInvocation(preferenceOffState)).toMatchObject({ sourceId: 'generate' });
});
+ it('routes to a floating window that is revealed from behind another', () => {
+ let state = workbenchReducer(createInitialWorkbenchState(), { instanceId: 'generate', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'upscale', type: 'floatWidget' });
+ state = workbenchReducer(state, { instanceId: 'generate', mode: 'shaded', type: 'setFloatingWidgetMode' });
+
+ expect(getInvocation(state)).toMatchObject({ sourceId: 'upscale' });
+
+ state = workbenchReducer(state, { instanceId: 'generate', type: 'revealFloatingWidget' });
+
+ expect(getInvocation(state)).toMatchObject({ sourceId: 'generate' });
+ });
+
it('follows a widget opened into a region', () => {
let state = createInitialWorkbenchState();
@@ -297,7 +320,11 @@ describe('auto invocation route switching on widget reveal', () => {
});
it('follows a tab dragged into another region, and a reorder only when it changes the front tab', () => {
- let state = createInitialWorkbenchState();
+ let state = createStateWithVideoTab();
+
+ // Generate is routed and in front, so the drag is what moves the route.
+ state = workbenchReducer(state, { region: 'left', type: 'selectRegionWidget', widgetId: 'generate' });
+ expect(getInvocation(state)).toMatchObject({ sourceId: 'generate' });
state = workbenchReducer(state, {
fromRegion: 'left',
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
index 02d31f4a7c..9e28cc91c6 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.ts
@@ -455,6 +455,7 @@ const createCommands = (
})
),
reorder: command('reorderWidgetInstances'),
+ revealFloating: command('revealFloatingWidget', (instanceId: string) => ({ instanceId })),
setAlignment: command('setWidgetInstanceAlignment'),
select: command('selectRegionWidget'),
setFloatingGeometry: command(