Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): dock Properties and Transform below Layers
Josh Corbett871872f83fee
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex cf783ec625..6fcc3ba935 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1491,6 +1491,31 @@"createWidgets": "Create widgets","inspectWidgets": "Inspect widgets"},+ "properties": {+ "noCanvas": "Open a canvas to edit its properties.",+ "rows": {+ "color": "Color",+ "geometry": "Geometry",+ "intensity": "Intensity",+ "modes": "Modes",+ "more": "More"+ },+ "sections": {+ "operation": "Operation",+ "tool": "Tool"+ }+ },+ "transform": {+ "edit": "Transform layer",+ "groupSelected": "Select a layer inside this group to transform.",+ "hint": "Each field commits one undoable change to the selected layer.",+ "noSelection": "No layer selected",+ "position": "Position",+ "rotation": "Rotation",+ "scale": "Scale",+ "session": "Transform in progress",+ "title": "Transform"+ },"dock": {"collapse": "Collapse {{dock}}","expand": "Expand {{dock}}",@@ -1510,6 +1535,8 @@"generate": "Generate","imageMap": "Image Map","layers": "Layers",+ "properties": "Properties",+ "transform": "Transform","notifications": "Notifications","preview": "Preview","project": "Project",@@ -2334,16 +2361,14 @@"view": "Drag to pan and scroll to zoom."},"toolOptions": {- "applyTransform": "Apply",- "aspectRatio": "Aspect ratio","brushColor": "Brush color","brushSize": "Brush size",- "cancelTransform": "Cancel","deselect": "Deselect","eraseSelection": "Erase","eraserSize": "Eraser size","fillSelection": "Fill","frameHeight": "H",+ "frameSize": "Frame","frameWidth": "W","gradientAngle": "Angle","gradientEdit": "Edit gradient",@@ -2352,6 +2377,7 @@"gradientLinear": "Linear","gradientRadial": "Radial","gradientStart": "Start",+ "gradientStops": "Stops","invertSelection": "Invert","lassoFreehand": "Freehand","lassoHint": "Draw a shape to select. Shift adds, Alt subtracts.",@@ -2359,7 +2385,6 @@"lassoPolygonHint": "Click to place points. Double-click, Enter, or click the first point to close.","lassoShape": "Lasso mode","liftSelectionToLayer": "New layer",- "lockAspect": "Lock aspect ratio","marqueeHint": "Drag to select a region. Shift constrains, Alt draws from centre.","marqueeKind": "Marquee shape","movePosition": "Move layer",@@ -2368,15 +2393,18 @@"positionY": "Y","pressureAffectsOpacity": "Pen pressure affects opacity","pressureAffectsWidth": "Pen pressure affects width",+ "pressure": "Pressure","rotation": "Rotation","scaleHeight": "H %","scaleWidth": "W %",+ "selectionActions": "Actions","selectionAdd": "Add","selectionIntersect": "Intersect","selectionMode": "Selection mode","selectionReplace": "Replace","selectionSubtract": "Subtract","setFrame": "Set generation frame",+ "shapeColors": "Colors","shapeEdit": "Edit shape","shapeEllipse": "Ellipse","shapeFill": "Fill",@@ -2394,6 +2422,7 @@"textFont": "Font","textLineHeight": "Line height","textSize": "Font size",+ "textStyle": "Style","textWeight": "Weight"},"tools": {@@ -2411,18 +2440,6 @@"text": "Text","transform": "Transform","view": "View"- },- "toolbar": {- "label": "Tool options",- "more": "More options",- "regions": {- "color": "Color",- "geometry": "Geometry",- "intensity": "Intensity",- "modes": "Modes",- "more": "More",- "status": "Status"- }}},"workflow": {diff --git a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjsindex 39a1bd7ac6..b4d7159992 100644--- a/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs+++ b/invokeai/frontend/webv2/scripts/run-accessibility-journeys.mjs@@ -179,6 +179,9 @@ const surfaces = [ready: async (page) => {await waitForWorkbench(page);await selectLayoutPreset(page, 'Edit', 'Canvas');+ // The bottom dock's Properties tab is the canvas's settings surface; the journey must scan it, not a fallback.+ await page.getByRole('tab', { exact: true, name: 'Properties', selected: true }).waitFor();+ await page.getByRole('tabpanel').getByText('Tool', { exact: true }).waitFor();},},{diff --git a/invokeai/frontend/webv2/scripts/widget-sources.mjs b/invokeai/frontend/webv2/scripts/widget-sources.mjsindex 50b451242a..725c2069b7 100644--- a/invokeai/frontend/webv2/scripts/widget-sources.mjs+++ b/invokeai/frontend/webv2/scripts/widget-sources.mjs@@ -16,6 +16,8 @@ export const WIDGET_SOURCES = new Map([['src/workbench/widgets/notifications/implementation.ts', 'notifications'],['src/workbench/widgets/preview/implementation.ts', 'preview'],['src/workbench/widgets/project/implementation.ts', 'project'],+ ['src/workbench/widgets/properties/implementation.ts', 'properties'],+ ['src/workbench/widgets/transform/implementation.ts', 'transform'],['src/workbench/widgets/queue-status/implementation.ts', 'queue-status'],['src/workbench/widgets/server-status/implementation.ts', 'server-status'],['src/workbench/widgets/version-status/implementation.ts', 'version-status'],diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.mdindex 14b9728819..ca66f53ada 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md@@ -39,9 +39,9 @@ The document mirror diffs forests by leaf identity and ancestor-effective state:`widgets/layers` consumes the seam and owns nothing about the document. `layerTreeRows.ts` turns `compileDocumentNodes` plus per-project panel state (expansion, a name filter) into `LayerTreeRow`s keyed on the forests, so a selection or bbox change rebuilds no row, and a row keeps its identity while its node, place, effective state, sibling position and expansion are unchanged; `layerPanelRows.ts` flattens the four stacks into one list with a header per non-empty stack. `LayersTree.tsx` virtualizes that list (fixed row heights per density, the focused item always mounted, each slot drawing the row its key names so a list change never relabels a mounted node) and is one WAI-ARIA tree: stack headers are level-one tree items that expand or collapse their stack, rows are tree items beneath them, every control inside an item is pointer-only (`tabIndex={-1}`) and hands focus back to its item when pressed, and the whole tree is a single tab stop with a roving focus that survives the focused item unmounting; the selection toolbar above it is likewise one tab stop with arrow keys between its buttons. Keyboard: arrows, Home/End, Left to the parent or header, Right into a stack or group, Enter/Space to select (with Shift/Ctrl), Alt+arrows to reorder and reparent (carrying the selection when the focused row is part of it, as a drag would), F2 to rename (a rename committed by clicking elsewhere leaves focus where the click put it), Shift+F10 for the row or stack menu, which carries every pointer action including hide-on-canvas. The tree holds the single drag context (pointer-within collision scoped to the stack, deterministic edge auto-scroll, hover-expand, indicator projected in linear time and checked with `model.refusalFor` so a locked, cyclic or too-deep landing shows its refusal inline), the single menu/properties host addressed by node id, and every store subscription and commit; a row receives one view model and one stable command handle, and a primary that changes outside the panel is revealed once: its collapsed stack and groups open and it is scrolled into view, after which the panel's scroll position is its own. Above 2,000 nodes the panel degrades explicitly: thumbnails and drag reordering switch off, every command stays. `layersPanel.budget.test.ts` pins the 2,000-node facts (exact row counts, one node visit per build, row identity across selection and a local expand, linear drop projection) and `LayersTree.browser.test.tsx` pins the mounted-row window, per-row commit counts (`layerPanelDiagnostics`) for selection and scroll, thumbnail requests, drag validation counts, the tab stop, degraded mode on a real 2,001-node document, external reveal, edge auto-scroll, and the keyboard journeys in Chromium; `scripts/run-accessibility-journeys.mjs` runs Axe over the panel on the representative project.-### Context toolbar+### Properties and Transform-`widgets/canvas/context-toolbar` is the one presentation of tool and operation controls above the surface. `CanvasContextToolbar` is a 40px row that never unmounts for a tool or an operation: identity, geometry, intensity, color, modes with the More menu at its right edge, a spacer and status keep their order, and every fixed region keeps its width and position while only its content changes; the row sits in the widget's layout beneath the center chrome islands, and staging keeps its floating bottom slot. `resolveToolbarLayout` decides from the measured width alone which regions the bar shows: identity and status compact at widths derived from the widest tool primary, then modes, color, intensity and geometry move into More in that order (the active tool's primary excepted), geometry shrinks to two slots, and only then does the primary follow — the bar overflows into the menu, never clips or wraps. Each tool supplies one `ToolPresentationAdapter` (`tool-options/*`): a component per region, the region kept in the bar, the bar width its modes need, and what only More shows; a guarded operation supplies an `OperationPresentationAdapter` that takes over modes, More and status while the tool's own regions stay mounted but inert. Adapters read and write the engine's option stores and document transactions directly; there is no state mirror. `CanvasContextToolbar.browser.test.tsx` pins the geometry per tool and width, the shared X/Y boxes, zero unmounts across every tool and an operation start, the keyboard path through the bar and the More menu, and the declared modes widths against rendered content.+Tool and operation settings live off the surface, in the right rail's bottom dock. `widgets/properties` renders the running operation first (its inputs, secondary controls and status with Apply / Cancel) and then the active tool's settings as labelled rows; `widgets/transform` edits the selected layer's transform without a tool — each field commits one undoable `patch`, and while the Transform tool holds a session the same fields drive its preview and Apply / Cancel land or drop it. Both read the engine's option stores and document transactions through one `ToolPresentationAdapter` per tool and one `OperationPresentationAdapter` per operation (`widgets/canvas/tool-presentation`): a component per settings region, no state mirror. Staging and generation lock the tool rows in place (`inert`) while an operation keeps its own controls live and Cancel always reachable. The right rail itself is three docks (`rightTop`, `right`, `rightBottom`), each an ordinary widget region with a tab strip; `shell/RightRail.tsx` owns the docks and `RightRail.browser.test.tsx` pins their layout, keyboard and resize behaviour.## Package and capability boundariesdiff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.tsindex 3a02bd8a3b..df7656ba37 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.test.ts@@ -3,6 +3,16 @@ import { describe, expect, it } from 'vitest';import { builtInLayoutPresetDescriptors, layoutPresets } from './layoutPresets';describe('built-in layout preset descriptors', () => {+ it('has a widget instance for every instance id a preset places', () => {+ for (const preset of layoutPresets) {+ for (const region of Object.values(preset.snapshot.widgetRegions)) {+ for (const instanceId of region.instanceIds) {+ expect(preset.snapshot.widgetInstances[instanceId], `${preset.id} ${instanceId}`).toBeDefined();+ }+ }+ }+ });+it('owns the preset, presentation, and command metadata in strip order', () => {expect(builtInLayoutPresetDescriptors.map(({ defaultKeys, hotkeyId, preset }) => ({@@ -111,16 +121,16 @@ describe('built-in layout preset descriptors', () => {center: 'canvas',left: 'generate',right: 'layers',- rightBottom: 'image-map',+ rightBottom: 'properties',rightTop: '',},bottom: ['server-status', 'queue-status', 'gallery:bottom', 'notifications', 'autosave-status'],center: ['canvas', 'preview'],left: ['generate', 'upscale', 'video'],panels: { isBottomOpen: false, isLeftOpen: true, isRightOpen: true },- right: ['layers', 'preview', 'gallery', 'queue'],- // Overview sits in the bottom dock: the rail is three tab groups, Layers in the middle.- rightBottom: ['image-map'],+ right: ['layers', 'preview', 'gallery', 'image-map', 'queue'],+ // The rail is three tab groups: Layers in the middle, the editors below it.+ rightBottom: ['properties', 'transform'],rightTop: [],},});diff --git a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts b/invokeai/frontend/webv2/src/workbench/layoutPresets.tsindex 78161b420e..eb2ae38f37 100644--- a/invokeai/frontend/webv2/src/workbench/layoutPresets.ts+++ b/invokeai/frontend/webv2/src/workbench/layoutPresets.ts@@ -37,9 +37,11 @@ const defaultInstanceTypes: Record<WidgetInstanceId, WidgetTypeId> = {notifications: 'notifications',preview: 'preview',project: 'project',+ properties: 'properties',queue: 'queue','queue-status': 'queue-status','server-status': 'server-status',+ transform: 'transform','version-status': 'version-status',workflow: 'workflow','workflow:bottom': 'workflow',@@ -218,10 +220,14 @@ export const builtInLayoutPresetDescriptors: BuiltInLayoutPresetDescriptor[] = [}),right: createRegion({activeInstanceId: 'layers',- instanceIds: ['layers', 'preview', 'gallery', 'queue'],+ instanceIds: ['layers', 'preview', 'gallery', 'image-map', 'queue'],sizePx: 450,}),- rightBottom: createRegion({ activeInstanceId: 'image-map', instanceIds: ['image-map'], sizePx: 280 }),+ rightBottom: createRegion({+ activeInstanceId: 'properties',+ instanceIds: ['properties', 'transform'],+ sizePx: 300,+ }),rightTop: createEmptyDock(),},}),diff --git a/invokeai/frontend/webv2/src/workbench/rightRailDocks.test.ts b/invokeai/frontend/webv2/src/workbench/rightRailDocks.test.tsindex 259caf2e33..92b765dd52 100644--- a/invokeai/frontend/webv2/src/workbench/rightRailDocks.test.ts+++ b/invokeai/frontend/webv2/src/workbench/rightRailDocks.test.ts@@ -22,10 +22,14 @@ const preDockEditSnapshot = (): LayoutPresetSnapshot => {instanceIds: ['layers', 'preview', 'gallery', 'image-map', 'queue'],};const snapshot = getLayoutPreset('edit').snapshot;+ const widgetRegions = { ...regions, right } as LayoutPresetSnapshot['widgetRegions'];+ const referenced = new Set(Object.values(widgetRegions).flatMap((region) => region.instanceIds));return {layout: { ...snapshot.layout, panels: { ...snapshot.layout.panels } },- widgetInstances: snapshot.widgetInstances,- widgetRegions: { ...regions, right } as LayoutPresetSnapshot['widgetRegions'],+ widgetInstances: Object.fromEntries(+ Object.entries(snapshot.widgetInstances).filter(([instanceId]) => referenced.has(instanceId))+ ),+ widgetRegions,};};@@ -69,61 +73,49 @@ describe('right rail docks', () => {expect(normalizeWorkbenchAccount({ customLayoutPresets: [preset] }).customLayoutPresets?.length).toBe(1);});- it('leaves an emptied dock naming no instance, so moving a widget out and back matches the preset again', () => {+ it('leaves an emptied dock naming no instance, so moving widgets out and back matches the preset again', () => {let state = editState();- state = workbenchReducer(state, {- fromRegion: 'rightBottom',- instanceId: 'image-map',- toIndex: 0,- toRegion: 'rightTop',- type: 'moveWidgetInstance',- });+ const move = (instanceId: string, fromRegion: 'rightTop' | 'rightBottom', toRegion: 'rightTop' | 'rightBottom') =>+ workbenchReducer(state, { fromRegion, instanceId, toIndex: 99, toRegion, type: 'moveWidgetInstance' });+ state = move('properties', 'rightBottom', 'rightTop');+ state = move('transform', 'rightBottom', 'rightTop');expect(activeProject(state).widgetRegions.rightBottom).toMatchObject({activeInstanceId: '',instanceIds: [],isCollapsed: true,});expect(activeProject(state).widgetRegions.rightTop).toMatchObject({- activeInstanceId: 'image-map',- instanceIds: ['image-map'],+ activeInstanceId: 'transform',+ instanceIds: ['properties', 'transform'],isCollapsed: false,});- state = workbenchReducer(state, {- fromRegion: 'rightTop',- instanceId: 'image-map',- toIndex: 0,- toRegion: 'rightBottom',- type: 'moveWidgetInstance',- });+ state = move('properties', 'rightTop', 'rightBottom');+ state = move('transform', 'rightTop', 'rightBottom');+ state = workbenchReducer(state, { region: 'rightBottom', type: 'selectRegionWidget', widgetId: 'properties' });expect(doesProjectMatchLayoutPreset(activeProject(state), getLayoutPreset('edit'))).toBe(true);- const closed = workbenchReducer(state, {- region: 'rightBottom',- type: 'toggleRegionWidget',- widgetId: 'image-map',- });+ const closed = workbenchReducer(+ workbenchReducer(state, { region: 'rightBottom', type: 'toggleRegionWidget', widgetId: 'transform' }),+ { region: 'rightBottom', type: 'toggleRegionWidget', widgetId: 'properties' }+ );expect(activeProject(closed).widgetRegions.rightBottom.activeInstanceId).toBe('');- const floated = workbenchReducer(state, { instanceId: 'image-map', type: 'floatWidget' });- expect(activeProject(floated).widgetRegions.rightBottom).toMatchObject({ activeInstanceId: '', isCollapsed: true });- expect(activeProject(floated).floatingWidgets?.['image-map']?.returnRegion).toBe('rightBottom');+ const floated = workbenchReducer(state, { instanceId: 'properties', type: 'floatWidget' });+ expect(activeProject(floated).widgetRegions.rightBottom).toMatchObject({ activeInstanceId: 'transform' });+ expect(activeProject(floated).floatingWidgets?.properties?.returnRegion).toBe('rightBottom');});it('reveals an instance already docked elsewhere on the rail instead of placing it twice', () => {let state = editState();state = workbenchReducer(state, { region: 'rightBottom', type: 'setRegionWidgetCollapsed', isCollapsed: true });- state = workbenchReducer(state, { region: 'right', type: 'openRegionWidget', widgetId: 'image-map' });+ state = workbenchReducer(state, { region: 'right', type: 'openRegionWidget', widgetId: 'transform' });const { right, rightBottom } = activeProject(state).widgetRegions;- expect(right.instanceIds).not.toContain('image-map');- expect(rightBottom).toMatchObject({- activeInstanceId: 'image-map',- instanceIds: ['image-map'],- isCollapsed: false,- });+ expect(right.instanceIds).not.toContain('transform');+ expect(rightBottom).toMatchObject({ activeInstanceId: 'transform', isCollapsed: false });});- it('migrates a pre-dock Edit rail keeping the rail shut if it was, and re-homes a floated Image Map to the new dock', () => {+ it('migrates a pre-dock Edit rail keeping the rail shut if it was, and leaves a floated Image Map in the middle', () => {const initial = createInitialWorkbenchState();const preDock = (mutate: (project: Project) => Project): WorkbenchState => ({...initial,@@ -144,7 +136,10 @@ describe('right rail docks', () => {});const shut = activeProject(workbenchReducer(initial, { state: preDock((p) => p), type: 'hydrateWorkbench' }));- expect(shut.widgetRegions.rightBottom).toMatchObject({ instanceIds: ['image-map'], isCollapsed: true });+ expect(shut.widgetRegions.rightBottom).toMatchObject({+ instanceIds: ['properties', 'transform'],+ isCollapsed: true,+ });const floated = activeProject(workbenchReducer(initial, {@@ -169,15 +164,32 @@ describe('right rail docks', () => {type: 'hydrateWorkbench',}));- expect(floated.floatingWidgets?.['image-map']?.returnRegion).toBe('rightBottom');- expect(floated.widgetRegions.rightBottom).toMatchObject({- activeInstanceId: '',- instanceIds: [],- isCollapsed: true,- });+ expect(floated.floatingWidgets?.['image-map']?.returnRegion).toBe('right');+ expect(floated.widgetRegions.rightBottom).toMatchObject({ instanceIds: ['properties', 'transform'] });expect(floated.widgetRegions.right.instanceIds).toEqual(['layers', 'preview', 'gallery', 'queue']);});+ it('upgrades the interim rail that docked Image Map alone at the bottom to the shipped docks', () => {+ const initial = createInitialWorkbenchState();+ const interim: WorkbenchState = {+ ...initial,+ projects: initial.projects.map((project) => ({+ ...project,+ widgetRegions: {+ ...project.widgetRegions,+ right: { ...project.widgetRegions.right, instanceIds: ['layers', 'preview', 'gallery', 'queue'] },+ rightBottom: { activeInstanceId: 'image-map', instanceIds: ['image-map'], isCollapsed: false, sizePx: 280 },+ rightTop: { activeInstanceId: '', instanceIds: [], isCollapsed: true, sizePx: 280 },+ },+ })),+ };+ const project = activeProject(workbenchReducer(initial, { state: interim, type: 'hydrateWorkbench' }));+ expect(project.widgetRegions.right.instanceIds).toEqual(['layers', 'preview', 'gallery', 'image-map', 'queue']);+ expect(project.widgetRegions.rightBottom.instanceIds).toEqual(['properties', 'transform']);+ expect(project.widgetInstances.transform?.typeId).toBe('transform');+ expect(project.widgetRegions.rightBottom).toMatchObject({ activeInstanceId: 'properties', isCollapsed: false });+ });+it('toggles only the docks that hold something', () => {const regions = activeProject(editState()).widgetRegions;expect(resolvePanelToggle(regions, ['rightTop', 'right', 'rightBottom'])).toEqual({diff --git a/invokeai/frontend/webv2/src/workbench/shell/RightRail.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/shell/RightRail.browser.test.tsxindex 5b6712bc6e..80e2cdb428 100644--- a/invokeai/frontend/webv2/src/workbench/shell/RightRail.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/shell/RightRail.browser.test.tsx@@ -155,15 +155,19 @@ describe('right rail docks', () => {{ label: 'layers', selected: true },{ label: 'preview', selected: false },{ label: 'gallery', selected: false },+ { label: 'image-map', selected: false },{ label: 'queue', selected: false },]);- expect(tabsOf('rightBottom')).toEqual([{ label: 'image-map', selected: true }]);+ expect(tabsOf('rightBottom')).toEqual([+ { label: 'properties', selected: true },+ { label: 'transform', selected: false },+ ]);const tab = page.getByRole('tab', { exact: true, name: 'layers' }).element();expect(tab.getAttribute('aria-controls')).toBe('rail-dock-right-panel');expect(host!.querySelector('#rail-dock-right-panel')?.getAttribute('role')).toBe('tabpanel');expect(tab.getAttribute('aria-roledescription')).toBeNull();expect(bodyOf('right')).toBe('layers');- expect(bodyOf('rightBottom')).toBe('image-map');+ expect(bodyOf('rightBottom')).toBe('properties');expect(Math.round(dockElement('rightBottom')!.getBoundingClientRect().height)).toBe(region('rightBottom').sizePx);expect(dockElement('right')!.getBoundingClientRect().height).toBeGreaterThan(400);expect(host!.querySelector('[data-chrome-actions="layers"]')).not.toBeNull();@@ -206,7 +210,7 @@ describe('right rail docks', () => {expect(region('rightBottom').isCollapsed).toBe(true);expect(bodyOf('rightBottom')).toBeUndefined();expect(dockElement('rightBottom')!.getBoundingClientRect().height).toBeLessThan(48);- expect(tabsOf('rightBottom')).toEqual([{ label: 'image-map', selected: true }]);+ expect(tabsOf('rightBottom').map((tab) => tab.label)).toEqual(['properties', 'transform']);await interact(() =>page@@ -215,7 +219,7 @@ describe('right rail docks', () => {.dispatchEvent(new MouseEvent('click', { bubbles: true })));expect(region('rightBottom').isCollapsed).toBe(false);- expect(bodyOf('rightBottom')).toBe('image-map');+ expect(bodyOf('rightBottom')).toBe('properties');});it('resizes the bottom dock from its handle by keyboard and collapses it below the floor', async () => {@@ -250,16 +254,13 @@ describe('right rail docks', () => {it('follows a widget between docks: the top dock appears when it gains a widget and a dock with nothing left disappears', async () => {const store = storeRef.current!;- await interact(() =>- store.commands.widgets.move({- fromRegion: 'rightBottom',- instanceId: 'image-map',- toIndex: 0,- toRegion: 'rightTop',- })- );+ for (const instanceId of ['properties', 'transform']) {+ await interact(() =>+ store.commands.widgets.move({ fromRegion: 'rightBottom', instanceId, toIndex: 9, toRegion: 'rightTop' })+ );+ }expect(dockElement('rightBottom')).toBeNull();- expect(tabsOf('rightTop')).toEqual([{ label: 'image-map', selected: true }]);+ expect(tabsOf('rightTop').map((tab) => tab.label)).toEqual(['properties', 'transform']);expect([...host!.querySelectorAll<HTMLElement>('[data-rail-dock]')].map((el) => el.dataset.railDock)).toEqual(['rightTop','right',diff --git a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsxindex 28754663db..043330f180 100644--- a/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widget-frame/WidgetBar.tsx@@ -146,7 +146,8 @@ const RailGroup = ({data-rail-group={group.region}direction="column"dropState={group.dropState}- minH={group.railItems.length === 0 ? (group.dropState.isActive ? '10' : '4') : undefined}+ display={group.railItems.length === 0 && !group.dropState.isActive ? 'none' : undefined}+ minH={group.railItems.length === 0 ? '10' : undefined}pt={separated ? '1' : undefined}region={group.region}sortableInstanceIds={sortableInstanceIds}diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.tsindex 68b49d9775..6c930e3fd0 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.test.ts@@ -32,7 +32,10 @@ describe('widget registry', () => {it('registers first-party widget manifests without icon validation failures', () => {const widgets = registerFirstPartyWidgets();- expect(widgets).toHaveLength(17);+ expect(widgets).toHaveLength(19);+ expect(widgets.map((widget) => widget.manifest.id)).toEqual(+ expect.arrayContaining(['layers', 'properties', 'transform', 'image-map'])+ );expect(widgets.flatMap((widget) => widget.failure ?? [])).toEqual([]);expect(widgets.every((widget) => widget.status === 'enabled')).toBe(true);});diff --git a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts b/invokeai/frontend/webv2/src/workbench/widgetRegistry.tsindex 3b671e1ea5..daa9c1786f 100644--- a/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts+++ b/invokeai/frontend/webv2/src/workbench/widgetRegistry.ts@@ -22,9 +22,11 @@ import { layersWidgetManifest } from './widgets/layers/manifest';import { notificationsWidgetManifest } from './widgets/notifications/manifest';import { previewWidgetManifest } from './widgets/preview/manifest';import { projectWidgetManifest } from './widgets/project/manifest';+import { propertiesWidgetManifest } from './widgets/properties/manifest';import { queueStatusWidgetManifest } from './widgets/queue-status/manifest';import { queueWidgetManifest } from './widgets/queue/manifest';import { serverStatusWidgetManifest } from './widgets/server-status/manifest';+import { transformWidgetManifest } from './widgets/transform/manifest';import { upscaleWidgetManifest } from './widgets/upscale/manifest';import { versionStatusWidgetManifest } from './widgets/version-status/manifest';import { videoWidgetManifest } from './widgets/video/manifest';@@ -42,6 +44,8 @@ export const firstPartyWidgetManifests: WidgetManifest[] = [previewWidgetManifest,projectWidgetManifest,layersWidgetManifest,+ propertiesWidgetManifest,+ transformWidgetManifest,queueWidgetManifest,notificationsWidgetManifest,serverStatusWidgetManifest,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsxindex aaf99571ae..a2eb6dc1cb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.test.tsx@@ -41,7 +41,6 @@ vi.mock('./useCanvasGallerySave', () => ({vi.mock('./useCreateFromBbox', () => ({useCreateFromBbox: () => ({ createFromBbox: () => undefined, isCreating: false }),}));-vi.mock('./context-toolbar/CanvasContextToolbar', () => ({ CanvasContextToolbar: () => null }));vi.mock('./CanvasCreateFromBboxSubmenu', () => ({ CanvasCreateFromBboxSubmenu: () => null }));vi.mock('./CanvasGlobalContextMenu', () => ({ CanvasGlobalContextMenu: () => null }));vi.mock('./CanvasImageDropOverlay', () => ({ CanvasImageDropOverlay: () => null }));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex 52cf4abf96..fe2b81673c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -1,7 +1,7 @@import type { WidgetViewProps } from '@workbench/widgetContracts';import type { MouseEvent as ReactMouseEvent } from 'react';-import { Box, Flex } from '@chakra-ui/react';+import { Box } from '@chakra-ui/react';import { useDndMonitor, type DragEndEvent } from '@dnd-kit/core';import { useQueueItemProgressImage } from '@features/queue/react';import { useMountEffect } from '@platform/react/useMountEffect';@@ -14,6 +14,7 @@ import { useWorkbenchSettingsSelector } from '@workbench/settings/store';import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { useNotify } from '@workbench/useNotify';import { CanvasLayerContextMenu } from '@workbench/widgets/layers/LayerContextMenu';+import { clearLayerPropertiesRequest } from '@workbench/widgets/layers/layerPropertiesRequestStore';import { getProjectWidgetValues } from '@workbench/widgetState';import {useActiveProjectId,@@ -48,7 +49,6 @@ import {import { CanvasSurface } from './CanvasSurface';import { CanvasSurfaceContextLayout } from './CanvasSurfaceContextLayout';import { resolveCheckerColors } from './checkerColors';-import { CanvasContextToolbar } from './context-toolbar/CanvasContextToolbar';import { useCanvasOperation } from './engineStoreHooks';import { executeCanvasImageDropImport } from './executeCanvasImageDropImport';import { StagingBar } from './StagingBar';@@ -60,15 +60,12 @@ import { useCanvasGallerySave } from './useCanvasGallerySave';import { useCreateFromBbox } from './useCreateFromBbox';import { reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';-/** The center region's floating chrome islands overlay this much of the widget; the toolbar starts beneath them. */-const CENTER_CHROME_INSET = 'var(--wb-center-chrome-inset, 0px)';-/*** The canvas widget shell. The engine owns pixels and interaction and renders* into {@link CanvasSurface}; this component only wires the reducer-backed- * chrome around it — command/hotkey registration, the settings-store feed, the- * in-layout context toolbar above the surface and the floating staging bar- * over it. Zoom / fit / settings live in the widget header+ * chrome around it — command/hotkey registration, the settings-store feed and+ * the floating staging bar. Tool and operation settings live in the+ * Properties widget; zoom / fit / settings in the widget header* ({@link CanvasHeaderActions}).*/export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {@@ -84,6 +81,13 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const antialiasProgressImages = useActiveProjectSelector((project) => project.settings.antialiasProgressImages);const { document, stagingArea } = canvas;const operation = useCanvasOperation(engine);+ const operationKind = operation?.status === 'active' ? operation.identity.kind : null;+ // An operation's panel supersedes any pending layer-properties request.+ useEffect(() => {+ if (operationKind) {+ clearLayerPropertiesRequest();+ }+ }, [operationKind]);const { isSaving, save: saveToGallery } = useCanvasGallerySave(engine);const { createFromBbox, isCreating } = useCreateFromBbox(engine);@@ -160,7 +164,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {hasSelectedCandidate: selectedCandidate !== undefined,hasStagingSlots,isCanvasGenerationInFlight,- operationKind: operation?.status === 'active' ? operation.identity.kind : null,+ operationKind,});const isInteractionLocked = interactionCapabilities.isSurfaceInteractionLocked;const handleSurfaceContextMenu = useCallback(@@ -485,75 +489,71 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const canvasSurface = useMemo(() => (engine ? <CanvasSurface engine={engine} /> : null), [engine]);return (- <Flex+ <Boxaria-label={t('widgets.canvas.surface')}bg="bg.inset"- direction="column"h="full"overflow="hidden"- pt={CENTER_CHROME_INSET}+ position="relative"role="region"w="full">- <CanvasContextToolbar engine={engine} isSurfaceInteractionLocked={isInteractionLocked} />- <Box flex="1" minH="0" overflow="hidden" position="relative">- <CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}>- <CanvasImageDropOverlay- isDocumentEditingLocked={interactionCapabilities.isDocumentEditingLocked}- isInteractionLocked={isInteractionLocked}- />- {engine ? (- <>- <ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />- <CanvasLayerContextMenu- beforeDangerItems={compositeSubmenus}- dispatch={canvasDispatch}- engine={engine}- showGroupLabels- target={layerContextMenuTarget}- onClose={closeContextMenu}+ <CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}>+ <CanvasImageDropOverlay+ isDocumentEditingLocked={interactionCapabilities.isDocumentEditingLocked}+ isInteractionLocked={isInteractionLocked}+ />+ {engine ? (+ <>+ <ToolStrip engine={engine} isInteractionLocked={isInteractionLocked} />+ <CanvasLayerContextMenu+ beforeDangerItems={compositeSubmenus}+ dispatch={canvasDispatch}+ engine={engine}+ showGroupLabels+ target={layerContextMenuTarget}+ onClose={closeContextMenu}+ />+ </>+ ) : null}+ {contextMenuBranch === 'global' && contextMenuTarget ? (+ <CanvasGlobalContextMenu target={contextMenuTarget} onClose={closeContextMenu}>+ {compositeSubmenus}+ </CanvasGlobalContextMenu>+ ) : null}++ {/* Staging keeps its bottom-center slot; the wrapper is click-through and the bar re-enables pointer events. */}+ <CanvasBottomOverlay.Root>+ {hasStagingSlots || isCanvasGenerationInFlight ? (+ <CanvasBottomOverlay.Staging>+ <StagingBar+ antialiasProgressImages={antialiasProgressImages}+ areThumbnailsVisible={stagingArea.areThumbnailsVisible}+ autoSwitchMode={stagingArea.autoSwitchMode}+ canAccept={interactionCapabilities.canAcceptStagedImage}+ hasMultipleSlots={hasMultipleStagingSlots}+ isGenerating={isCanvasGenerationInFlight}+ isVisible={stagingArea.isVisible}+ selectedCandidate={selectedCandidate}+ selectedImageIndex={stagingArea.selectedImageIndex}+ selectedSlot={selectedSlot}+ slots={stagingSlots}+ onAccept={acceptStagedImage}+ onCancelQueueItem={cancelQueueItem}+ onCycle={cycleStagedImage}+ onDiscardAll={discardAllStagedImages}+ onDiscardSelected={discardSelectedStagedImage}+ onPreloadCandidate={preloadStagedCandidate}+ onSelectImage={selectStagedImage}+ onSaveToLayerAndContinue={saveStagedImageAndContinue}+ onSetAutoSwitch={setStagingAutoSwitch}+ onToggleThumbnails={toggleStagingThumbnails}+ onToggleVisibility={toggleStagingVisibility}/>- </>- ) : null}- {contextMenuBranch === 'global' && contextMenuTarget ? (- <CanvasGlobalContextMenu target={contextMenuTarget} onClose={closeContextMenu}>- {compositeSubmenus}- </CanvasGlobalContextMenu>+ </CanvasBottomOverlay.Staging>) : null}-- {/* Staging keeps its bottom-center slot; the wrapper is click-through and the bar re-enables pointer events. */}- <CanvasBottomOverlay.Root>- {hasStagingSlots || isCanvasGenerationInFlight ? (- <CanvasBottomOverlay.Staging>- <StagingBar- antialiasProgressImages={antialiasProgressImages}- areThumbnailsVisible={stagingArea.areThumbnailsVisible}- autoSwitchMode={stagingArea.autoSwitchMode}- canAccept={interactionCapabilities.canAcceptStagedImage}- hasMultipleSlots={hasMultipleStagingSlots}- isGenerating={isCanvasGenerationInFlight}- isVisible={stagingArea.isVisible}- selectedCandidate={selectedCandidate}- selectedImageIndex={stagingArea.selectedImageIndex}- selectedSlot={selectedSlot}- slots={stagingSlots}- onAccept={acceptStagedImage}- onCancelQueueItem={cancelQueueItem}- onCycle={cycleStagedImage}- onDiscardAll={discardAllStagedImages}- onDiscardSelected={discardSelectedStagedImage}- onPreloadCandidate={preloadStagedCandidate}- onSelectImage={selectStagedImage}- onSaveToLayerAndContinue={saveStagedImageAndContinue}- onSetAutoSwitch={setStagingAutoSwitch}- onToggleThumbnails={toggleStagingThumbnails}- onToggleVisibility={toggleStagingVisibility}- />- </CanvasBottomOverlay.Staging>- ) : null}- </CanvasBottomOverlay.Root>- </CanvasSurfaceContextLayout>- </Box>- </Flex>+ </CanvasBottomOverlay.Root>+ </CanvasSurfaceContextLayout>+ </Box>);};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsxindex 6fdd2bcfee..d2cc5ad254 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/ToolStrip.tsx@@ -43,8 +43,15 @@ const ToolStripButton = ({ engine, icon, isInteractionLocked, label, toolId }: T};/**- * The canvas's left-docked, vertical tool strip, floating over the surface- * beneath the context toolbar. Color-picker is intentionally absent —+ * Clears the center region's floating chrome, whose inset already includes the+ * gap below the islands. Outside the center the variable is undefined and the+ * strip falls back to its own top margin.+ */+const TOOL_STRIP_TOP = 'var(--wb-center-chrome-inset, var(--chakra-spacing-2))';++/**+ * The canvas's left-docked, vertical tool strip, topped out directly beneath+ * the region's floating chrome islands. Color-picker is intentionally absent —* it's alt-hold-only for now (see `canvas-engine/input/pointerPipeline.ts`),* not a sticky tool a user selects directly.*/@@ -58,7 +65,7 @@ const ToolStripRoot = ({const { t } = useTranslation();return (- <Box left="2" position="absolute" top="2" zIndex="2">+ <Box left="2" position="absolute" top={TOOL_STRIP_TOP} zIndex="2"><Toolbar aria-label={t('widgets.canvas.tools.label')}><ToolStripButtonengine={engine}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.tsindex ba79592425..3c44107116 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts@@ -59,8 +59,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: false,canAcceptStagedImage: false,isDocumentEditingLocked: false,- isOperationChromeVisible: false,- isRegularToolOptionsVisible: true,isSurfaceInteractionLocked: false,},generation: false,@@ -72,8 +70,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: true,canAcceptStagedImage: false,isDocumentEditingLocked: true,- isOperationChromeVisible: true,- isRegularToolOptionsVisible: false,isSurfaceInteractionLocked: false,},generation: false,@@ -85,8 +81,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: true,canAcceptStagedImage: false,isDocumentEditingLocked: true,- isOperationChromeVisible: true,- isRegularToolOptionsVisible: false,isSurfaceInteractionLocked: false,},generation: false,@@ -98,8 +92,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: false,canAcceptStagedImage: true,isDocumentEditingLocked: false,- isOperationChromeVisible: false,- isRegularToolOptionsVisible: false,isSurfaceInteractionLocked: true,},generation: false,@@ -111,8 +103,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: false,canAcceptStagedImage: false,isDocumentEditingLocked: false,- isOperationChromeVisible: false,- isRegularToolOptionsVisible: false,isSurfaceInteractionLocked: true,},generation: true,@@ -124,8 +114,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: false,canAcceptStagedImage: false,isDocumentEditingLocked: true,- isOperationChromeVisible: true,- isRegularToolOptionsVisible: false,isSurfaceInteractionLocked: true,},generation: false,@@ -137,8 +125,6 @@ describe('canvas interaction lock', () => {areOperationActionsEnabled: false,canAcceptStagedImage: false,isDocumentEditingLocked: true,- isOperationChromeVisible: true,- isRegularToolOptionsVisible: false,isSurfaceInteractionLocked: true,},generation: true,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.tsindex a37f64b63b..9702efbe03 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts@@ -24,8 +24,6 @@ export interface CanvasInteractionCapabilities {areOperationActionsEnabled: boolean;canAcceptStagedImage: boolean;isDocumentEditingLocked: boolean;- isOperationChromeVisible: boolean;- isRegularToolOptionsVisible: boolean;isSurfaceInteractionLocked: boolean;}@@ -51,8 +49,6 @@ export const getCanvasInteractionCapabilities = ({areOperationActionsEnabled: isDocumentEditingLocked && !isSurfaceInteractionLocked,canAcceptStagedImage: hasCanvasEngine && hasSelectedCandidate && !isDocumentEditingLocked,isDocumentEditingLocked,- isOperationChromeVisible: isDocumentEditingLocked,- isRegularToolOptionsVisible: !isDocumentEditingLocked && !isSurfaceInteractionLocked,isSurfaceInteractionLocked,};};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/CanvasContextToolbar.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/CanvasContextToolbar.browser.test.tsxdeleted file mode 100644index f8cab54fb8..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/CanvasContextToolbar.browser.test.tsx+++ /dev/null@@ -1,403 +0,0 @@-/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { ToolId } from '@workbench/canvas-engine/api';-import type { CanvasOperationState } from '@workbench/canvas-operations/api';-import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';-import type { FilterOperationSessionState } from '@workbench/canvas-operations/filterOperationSession';-import type { SamSessionSnapshot } from '@workbench/canvas-operations/operationTypes';-import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';-import type { Project } from '@workbench/projectContracts';--import { ChakraProvider } from '@chakra-ui/react';-import { system } from '@theme/system';-import {- createEngineRegistry,- type EngineDeps,- type EngineRegistry,-} from '@workbench/canvas-operations/engineRegistry';-import { attachCanvasOperations } from '@workbench/canvas-operations/operationAccess';-import { createEmptyCanvasState } from '@workbench/canvasMigration';-import { createInitialWorkbenchState } from '@workbench/workbenchState';-import { createInstance } from 'i18next';-import { act } from 'react';-import { createRoot, type Root } from 'react-dom/client';-import { I18nextProvider } from 'react-i18next';-import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';-import { page, userEvent } from 'vitest/browser';--import { CanvasContextToolbar, TOOLBAR_INSET_PX } from './CanvasContextToolbar';-import { hasToolRegions, OPERATION_PRESENTATION_ADAPTERS, TOOL_PRESENTATION_ADAPTERS } from './toolAdapters';-import { resolveToolbarLayout, TOOLBAR_HEIGHT_PX, TOOLBAR_REGION_ORDER } from './toolbarLayout';--const harness = vi.hoisted(() => ({ project: null as Project | null }));--vi.mock('@workbench/WorkbenchContext', () => ({- useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project!),- useOptionalWorkbenchCommands: () => null,-}));-vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({- useCanvasProjectMutationDispatch: () => () => true,-}));-const i18n = createInstance();-beforeAll(async () => {- // The catalog is a public asset: the dev server serves it, JavaScript cannot import it.- const translation = (await (await fetch('/locales/en.json')).json()) as Record<string, unknown>;- await i18n.init({ initAsync: false, lng: 'en', resources: { en: { translation } } });-});--(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;--const TOOL_IDS = Object.keys(TOOL_PRESENTATION_ADAPTERS) as ToolId[];-/** 452px is the canvas widget at 1440 with the default Edit preset; 336px (320 + the insets) is the narrowest bar that shows geometry. */-const WIDTHS = [1400, 1000, 700, 600, 540, 452, 336];-const BAR_REGIONS = [...TOOLBAR_REGION_ORDER, 'identity', 'more', 'status'] as const;-type BarRegion = (typeof BAR_REGIONS)[number];--const createEngineDeps = (): EngineDeps => {- const state = createEmptyCanvasState(64, 64);- const mutationPort: CanvasProjectMutationPort = {- commitEdit: () => undefined,- dispatch: () => false,- getCanvasState: () => state,- subscribe: () => () => undefined,- };- return {- getMainModelBase: () => null,- imageResolver: () => Promise.resolve(new Blob()),- mutationPort,- reportError: () => undefined,- };-};--const filterSession = (): FilterOperationSessionState => ({- autoProcess: true,- draft: { settings: { high_threshold: 200, low_threshold: 100 }, type: 'canny_edge_detection' },- error: null,- initialFilter: null,- layerId: 'layer-1',- layerName: 'Portrait',- layerType: 'raster',- preview: null,- status: 'ready',-});--const samSession = (): SamSessionSnapshot => ({- applyPolygonRefinement: false,- autoProcess: false,- error: null,- hasPreview: false,- input: { prompt: 'a cat', type: 'prompt' },- invert: false,- isolatedPreview: true,- layerName: 'Layer 1',- layerType: 'raster',- model: 'segment-anything-2-large',- pointLabel: 'include',- sourceRect: { height: 20, width: 20, x: 0, y: 0 },- status: 'ready',-});--/** Operation state the toolbar reads, driven by the test instead of a backend. */-const createFakeOperations = () => {- const listeners = new Set<() => void>();- const subscribe = (listener: () => void) => {- listeners.add(listener);- return () => listeners.delete(listener);- };- let filter: FilterOperationSessionState | null = null;- let sam: SamSessionSnapshot | null = null;- let state: CanvasOperationState = { status: 'idle' };- const noop = vi.fn();- return {- cancelFilterOperation: noop,- cancelSelectObjectSession: noop,- commitFilterOperation: noop,- getFilterSessionState: () => filter,- getOperationState: () => state,- getSamSessionState: () => sam,- processFilterOperation: noop,- resetFilterOperation: noop,- setFilterOperationAutoProcess: noop,- start: (kind: 'filter' | 'select-object' | null) => {- filter = kind === 'filter' ? filterSession() : null;- sam = kind === 'select-object' ? samSession() : null;- state = kind- ? { error: null, identity: { kind, layerId: 'layer-1', projectId: 'p' }, phase: 'ready', status: 'active' }- : { status: 'idle' };- listeners.forEach((listener) => listener());- },- subscribeFilterSession: subscribe,- subscribeOperation: subscribe,- subscribeSamSession: subscribe,- updateFilterOperation: noop,- updateSelectObjectSession: noop,- };-};--let host: HTMLDivElement | null = null;-let root: Root | null = null;-let registry: EngineRegistry | null = null;-let engine: CanvasEngine | null = null;-let operations: ReturnType<typeof createFakeOperations> | null = null;--const settle = () =>- act(- () =>- new Promise<void>((resolve) => {- requestAnimationFrame(() => requestAnimationFrame(() => resolve()));- })- );--const mount = async (width: number, locked = false) => {- if (!host) {- harness.project = { ...createInitialWorkbenchState().projects[0]!, id: 'p' };- host = document.createElement('div');- host.style.width = `${width}px`;- host.style.marginLeft = '13px';- document.body.append(host);- root = createRoot(host);- registry = createEngineRegistry({ gracePeriodMs: 0 });- engine = registry.getOrCreateEngine('p', createEngineDeps());- operations = createFakeOperations();- attachCanvasOperations(engine, operations as never);- } else {- host.style.width = `${width}px`;- }- await act(() => {- root?.render(- <I18nextProvider i18n={i18n}>- <ChakraProvider value={system}>- <CanvasContextToolbar engine={engine} isSurfaceInteractionLocked={locked} />- </ChakraProvider>- </I18nextProvider>- );- });- await settle();-};--const selectTool = async (toolId: ToolId) => {- await act(() => engine!.tools.setTool(toolId));- await settle();-};--const toolbar = () => host!.querySelector<HTMLElement>('[data-canvas-context-toolbar]')!;-const region = (id: BarRegion) => toolbar().querySelector<HTMLElement>(`[data-region="${id}"]`)!;-const rectOf = (element: Element) => {- const { height, left, width } = element.getBoundingClientRect();- return { height: Math.round(height), left: Math.round(left), width: Math.round(width) };-};-const barRect = (id: BarRegion) => {- const element = region(id);- return element.dataset.placement === 'menu' || element.getClientRects().length === 0 ? null : rectOf(element);-};--afterEach(async () => {- await act(() => root?.unmount());- host?.remove();- registry?.releaseEngine('p');- host = null;- root = null;- registry = null;- engine = null;- operations = null;-});--describe('CanvasContextToolbar geometry', () => {- it('keeps one 40px row at the widget edge and the same region boxes for every tool at every width', async () => {- await mount(WIDTHS[0]!);- for (const width of WIDTHS) {- await mount(width);- const boxes = new Map<BarRegion, ReturnType<typeof rectOf>>();- for (const toolId of TOOL_IDS) {- await selectTool(toolId);- const bar = rectOf(toolbar());- expect(bar, `${toolId} @ ${width}`).toEqual({ height: TOOLBAR_HEIGHT_PX, left: 13, width });- expect(rectOf(region('identity')).left, `${toolId} identity @ ${width}`).toBe(13 + TOOLBAR_INSET_PX);- expect(toolbar().scrollHeight, `${toolId} wraps @ ${width}`).toBeLessThanOrEqual(toolbar().clientHeight);- expect(toolbar().scrollWidth, `${toolId} clips @ ${width}`).toBeLessThanOrEqual(toolbar().clientWidth);- for (const id of BAR_REGIONS) {- const rect = barRect(id);- if (!rect || id === 'modes' || id === 'more') {- continue;- }- const seen = boxes.get(id);- if (seen) {- expect(rect, `${toolId} ${id} @ ${width}`).toEqual(seen);- } else {- boxes.set(id, rect);- }- }- }- }- });-- it('places the bar regions exactly where the layout resolver says, and never below the clipping width', async () => {- await mount(700);- for (const toolId of ['brush', 'shape', 'lasso', 'view'] as const) {- await selectTool(toolId);- const adapter = TOOL_PRESENTATION_ADAPTERS[toolId];- const layout = resolveToolbarLayout({- modesWidth: adapter.modes?.width ?? 0,- primary: adapter.primary,- reservesToolRegions: hasToolRegions(adapter),- width: 700 - 2 * TOOLBAR_INSET_PX,- });- for (const id of TOOLBAR_REGION_ORDER) {- expect(region(id).dataset.placement, `${toolId} ${id}`).toBe(layout.regions[id]);- }- expect(region('status').getBoundingClientRect().right, toolId).toBeLessThanOrEqual(13 + 700 - TOOLBAR_INSET_PX);- }- });-- it('shares the X and Y fields between move, transform and the frame', async () => {- await mount(1400);- for (const width of [1400, 700]) {- await mount(width);- const positions = new Map<string, ReturnType<typeof rectOf>>();- for (const toolId of ['move', 'transform', 'bbox'] as const) {- await selectTool(toolId);- for (const name of ['X', 'Y']) {- const rect = rectOf(page.getByRole('spinbutton', { exact: true, name }).element());- const seen = positions.get(name);- if (seen) {- expect(rect, `${toolId} ${name} @ ${width}`).toEqual(seen);- } else {- positions.set(name, rect);- }- }- }- }- });-- it('never unmounts the shell or a region slot across every tool and an operation start', async () => {- await mount(1000);- const before = [toolbar(), ...BAR_REGIONS.map((id) => region(id))];- for (const toolId of TOOL_IDS) {- await selectTool(toolId);- }- await act(() => operations!.start('filter'));- await settle();- await act(() => operations!.start('select-object'));- await settle();- await act(() => operations!.start(null));- await settle();- expect([toolbar(), ...BAR_REGIONS.map((id) => region(id))]).toEqual(before);- });-- it('keeps identity, geometry and status in place when an operation starts, and hands modes to it', async () => {- for (const width of [1400, 540]) {- await mount(width);- await selectTool('brush');- const idle = { geometry: barRect('geometry'), identity: barRect('identity'), status: barRect('status') };- await act(() => operations!.start('filter'));- await settle();- // At 540px the filter's controls (its primary region) outrank the inert brush geometry, which moves to More.- expect(- {- geometry: width === 540 ? idle.geometry : barRect('geometry'),- identity: barRect('identity'),- status: barRect('status'),- },- `${width}`- ).toEqual(idle);- expect(region('geometry').hasAttribute('inert'), `${width}`).toBe(true);- expect(region('modes').hasAttribute('inert'), `${width}`).toBe(false);- await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeDisabled();- await expect.element(page.getByRole('button', { exact: true, name: 'Cancel' })).toBeEnabled();- await act(() => operations!.start(null));- await settle();- }- });-- it('declares modes widths no narrower than the content they hold', async () => {- await mount(2000);- // Hints truncate, so only the controls count against the declared width.- const check = (label: string, declared: number) => {- const modes = region('modes');- expect(modes.dataset.placement, label).toBe('bar');- const controls = [...modes.children].filter(- (child) => !child.hasAttribute('data-toolbar-hint') && getComputedStyle(child).position !== 'absolute'- );- const width =- controls.reduce((sum, child) => sum + child.getBoundingClientRect().width, 0) + 8 * (controls.length - 1);- expect(- Math.ceil(width),- `${label}: ${controls.map((child) => Math.ceil(child.getBoundingClientRect().width)).join('+')}`- ).toBeLessThanOrEqual(declared);- };- for (const toolId of TOOL_IDS) {- const adapter = TOOL_PRESENTATION_ADAPTERS[toolId];- if (!adapter.modes) {- continue;- }- await selectTool(toolId);- check(toolId, adapter.modes.width);- }- await selectTool('brush');- for (const kind of ['filter', 'select-object'] as const) {- await act(() => operations!.start(kind));- await settle();- check(kind, OPERATION_PRESENTATION_ADAPTERS[kind].modes!.width);- }- });-});--describe('CanvasContextToolbar keyboard', () => {- it('moves displaced regions into the More menu and keeps them reachable from the keyboard', async () => {- await mount(540);- await selectTool('brush');- expect(region('intensity').dataset.placement).toBe('menu');- expect(page.getByRole('slider', { exact: true, name: 'Opacity' }).query()).toBeNull();- const more = page.getByRole('button', { exact: true, name: 'More options' });- await act(async () => {- (more.element() as HTMLElement).focus();- await userEvent.keyboard('{Enter}');- });- await expect.element(page.getByRole('slider', { exact: true, name: 'Opacity' })).toBeVisible();- await expect.element(page.getByRole('button', { exact: true, name: 'Pen pressure affects width' })).toBeVisible();- await act(() => userEvent.keyboard('{Escape}'));- await expect.element(more).toHaveFocus();- });-- it('disables More for a tool with nothing to overflow and keeps its box', async () => {- await mount(1400);- await selectTool('view');- await expect.element(page.getByRole('button', { exact: true, name: 'More options' })).toBeDisabled();- expect(rectOf(region('more')).width).toBe(32);- await expect.element(page.getByText('Drag to pan and scroll to zoom.', { exact: true })).toBeVisible();- await selectTool('brush');- await expect.element(page.getByRole('button', { exact: true, name: 'More options' })).toBeEnabled();- });-- it('reaches every bar control by Tab, in bar order, and the status actions last', async () => {- await mount(1400);- await selectTool('brush');- const visited: string[] = [];- (toolbar().querySelector<HTMLElement>('[role="slider"]') ?? toolbar()).focus();- for (let step = 0; step < 12; step += 1) {- const active = document.activeElement as HTMLElement | null;- if (!active || !toolbar().contains(active)) {- break;- }- visited.push(active.getAttribute('aria-label') ?? active.textContent ?? '');- await act(() => userEvent.keyboard('{Tab}'));- }- // Idle Apply / Cancel are disabled, so the tab order ends at More.- expect(visited).toEqual(['Brush size', 'Brush size', 'Opacity', 'Opacity', 'Brush color', 'More options']);-- await act(() => operations!.start('filter'));- await settle();- const withOperation: string[] = [];- (toolbar().querySelector<HTMLElement>('[data-region="modes"] [role="combobox"]') ?? toolbar()).focus();- for (let step = 0; step < 12; step += 1) {- const active = document.activeElement as HTMLElement | null;- if (!active || !toolbar().contains(active)) {- break;- }- withOperation.push(active.getAttribute('aria-label') ?? active.textContent ?? '');- await act(() => userEvent.keyboard('{Tab}'));- }- // The brush regions are inert while the filter runs; its own controls and Cancel take their place- // (the type select is named by its value).- expect(withOperation).toEqual(['Canny', 'Auto', 'More options', 'Cancel']);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/CanvasContextToolbar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/CanvasContextToolbar.tsxdeleted file mode 100644index 268d0ace57..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/CanvasContextToolbar.tsx+++ /dev/null@@ -1,402 +0,0 @@-import type { Project } from '@workbench/projectContracts';-import type { ComponentType, FocusEvent, ReactNode, RefObject } from 'react';--import { Box, Flex, Icon, Text, VisuallyHidden } from '@chakra-ui/react';-import { Button, Tooltip } from '@platform/ui';-import { collectSubtreeLeaves, getDocumentNode } from '@workbench/canvas-engine/api';-import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';-import { useCanvasActiveTool, useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';-import { clearLayerPropertiesRequest } from '@workbench/widgets/layers/layerPropertiesRequestStore';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { Fragment, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';--import type { CanvasToolOptionsEngine, ToolbarRegionComponent, ToolbarStatusProps } from './toolbarContracts';--import { hasToolRegions, OPERATION_PRESENTATION_ADAPTERS, TOOL_PRESENTATION_ADAPTERS } from './toolAdapters';-import {- resolveToolbarLayout,- TOOLBAR_GAP_PX,- TOOLBAR_HEIGHT_PX,- TOOLBAR_REGION_ORDER,- TOOLBAR_REGION_WIDTH_PX,- type ToolbarLayout,- type ToolbarRegionId,- type ToolbarRegionPlacement,-} from './toolbarLayout';-import { ToolbarMoreMenu, ToolbarMoreSection } from './ToolbarMoreMenu';-import { ToolbarHint, ToolbarStatus } from './ToolbarPrimitives';--/** Horizontal inset of the bar's content; the identity region's left edge sits here at every width. */-export const TOOLBAR_INSET_PX = 8;--const REGION_LABEL_KEYS: Record<ToolbarRegionId | 'status', string> = {- color: 'widgets.canvas.toolbar.regions.color',- geometry: 'widgets.canvas.toolbar.regions.geometry',- intensity: 'widgets.canvas.toolbar.regions.intensity',- modes: 'widgets.canvas.toolbar.regions.modes',- status: 'widgets.canvas.toolbar.regions.status',-};--/** Content width of the bar; a hidden bar (a kept-alive widget) reports unbounded so its regions stay mounted. */-const useMeasuredWidth = (ref: RefObject<HTMLElement | null>): number => {- const [width, setWidth] = useState(Number.POSITIVE_INFINITY);- useLayoutEffect(() => {- const element = ref.current;- if (!element) {- return;- }- const measure = () => {- const next = Math.round(element.getBoundingClientRect().width);- setWidth(next > 0 ? next - 2 * TOOLBAR_INSET_PX : Number.POSITIVE_INFINITY);- };- measure();- const observer = new ResizeObserver(measure);- observer.observe(element);- return () => observer.disconnect();- }, [ref]);- return width;-};--const GAP = `${TOOLBAR_GAP_PX}px`;--/**- * One region's box. Regions space themselves with a start margin rather than a- * container gap, so a region with nothing to show (`display: none`) costs the- * bar neither width nor a gap, exactly as `resolveToolbarLayout` charges it.- */-const RegionSlot = ({- children,- disabled = false,- empty = false,- id,- label,- placement,- vacant = false,- width,-}: {- children: ReactNode;- disabled?: boolean;- /** Nothing to show: the slot collapses and costs no gap. */- empty?: boolean;- id: ToolbarRegionId | 'status';- label: string;- placement: ToolbarRegionPlacement;- /** Reserved for alignment but holding no control for this tool: no group semantics. */- vacant?: boolean;- width?: number;-}) => (- <Flex- align="center"- aria-label={vacant ? undefined : label}- data-placement={placement}- data-region={id}- display={placement !== 'menu' && !empty ? 'flex' : 'none'}- flexShrink={width === undefined ? 1 : 0}- gap={GAP}- h="full"- inert={disabled || undefined}- minW="0"- ms={GAP}- opacity={disabled ? 0.5 : 1}- overflow="hidden"- role={vacant ? undefined : 'group'}- w={width === undefined ? 'auto' : `${width}px`}- >- {/* Keyed on the lock so a popover opened from the region closes with it: portalled content ignores `inert`. */}- {placement === 'menu' ? null : <Fragment key={String(disabled)}>{children}</Fragment>}- </Flex>-);--const regionSlotWidth = (region: ToolbarRegionId, placement: ToolbarRegionPlacement): number | undefined =>- region === 'modes'- ? undefined- : region === 'geometry' && placement === 'compact'- ? TOOLBAR_REGION_WIDTH_PX.geometryCompact- : TOOLBAR_REGION_WIDTH_PX[region];--interface SelectedGroup {- firstLeafId: string | null;- id: string;-}--const selectSelectedGroup = (project: Project): SelectedGroup | null => {- const { document } = project.canvas;- const node = getDocumentNode(document, document.selectedLayerId);- return node?.type === 'group' ? { firstLeafId: collectSubtreeLeaves(node)[0]?.id ?? null, id: node.id } : null;-};--const sameSelectedGroup = (a: SelectedGroup | null, b: SelectedGroup | null): boolean =>- a?.id === b?.id && a?.firstLeafId === b?.firstLeafId;--/** Leaf tools cannot paint into a group: name the way out instead of silently refusing strokes. */-const GroupSelectedNotice = ({ group }: { group: SelectedGroup }) => {- const { t } = useTranslation();- const dispatch = useCanvasProjectMutationDispatch();- const selectFirstLeaf = useCallback(() => {- if (group.firstLeafId) {- dispatch({ id: group.firstLeafId, type: 'setCanvasSelectedLayer' });- }- }, [dispatch, group.firstLeafId]);- return (- <>- <ToolbarHint>{t('widgets.layers.groupSelectedHint')}</ToolbarHint>- {group.firstLeafId ? (- <Button flexShrink={0} size="2xs" variant="subtle" onClick={selectFirstLeaf}>- {t('widgets.layers.actions.selectFirstChild')}- </Button>- ) : null}- </>- );-};--const IdleStatus = ({ compact }: ToolbarStatusProps) => <ToolbarStatus compact={compact} />;--const IDLE_LAYOUT_INPUT = { modesWidth: null, primary: null, reservesToolRegions: true } as const;--const ConnectedToolbar = ({- engine,- isSurfaceInteractionLocked,- width,-}: {- engine: CanvasToolOptionsEngine;- isSurfaceInteractionLocked: boolean;- width: number;-}) => {- const { t } = useTranslation();- const activeTool = useCanvasActiveTool(engine);- const operation = useCanvasOperation(engine);- const operationKind = operation.status === 'active' ? operation.identity.kind : null;- const tool = TOOL_PRESENTATION_ADAPTERS[activeTool];- const running = operationKind ? OPERATION_PRESENTATION_ADAPTERS[operationKind] : null;-- // An operation bar used to consume any pending layer-properties request; the toolbar keeps that contract.- useEffect(() => {- if (operationKind) {- clearLayerPropertiesRequest();- }- }, [operationKind]);-- const selectedGroup = useActiveProjectSelector(selectSelectedGroup, sameSelectedGroup);- const modes = running ? running.modes : tool.modes;- const More = running ? running.more : tool.more;- const Status = running?.status ?? tool.status ?? IdleStatus;- const reservesToolRegions = hasToolRegions(tool);- const hintOnly = !running && !reservesToolRegions;- const notice = !running && tool.paintsLeaf ? selectedGroup : null;- const hasModesContent = !!modes || hintOnly || notice !== null;- const layout: ToolbarLayout = resolveToolbarLayout({- modesWidth: hasModesContent ? (modes?.width ?? 0) : null,- primary: running ? (running.modes ? 'modes' : null) : tool.primary,- reservesToolRegions,- width,- });- const contentKey = running ? `${activeTool}:${running.kind}` : activeTool;- const toolRegions: Record<Exclude<ToolbarRegionId, 'modes'>, ToolbarRegionComponent | undefined> = {- color: tool.color,- geometry: tool.geometry,- intensity: tool.intensity,- };- const renderRegion = (region: ToolbarRegionId, placement: ToolbarRegionPlacement): ReactNode => {- if (region === 'modes') {- const Modes = modes?.component;- return (- <>- {notice ? <GroupSelectedNotice group={notice} /> : null}- {Modes ? (- <Modes- key={contentKey}- engine={engine}- isSurfaceInteractionLocked={isSurfaceInteractionLocked}- placement={placement}- />- ) : hintOnly ? (- <ToolbarHint>{t(`widgets.canvas.toolHints.${tool.id}`)}</ToolbarHint>- ) : null}- </>- );- }- const Region = toolRegions[region];- return Region ? (- <Region- key={activeTool}- engine={engine}- isSurfaceInteractionLocked={isSurfaceInteractionLocked}- placement={placement}- />- ) : null;- };-- // While an operation runs the tool's regions are inert, so none of them belongs in the menu either.- const displaced = TOOLBAR_REGION_ORDER.filter(- (region) => layout.regions[region] === 'menu' && (region === 'modes' ? modes : !running && toolRegions[region])- );-- // `inert` blurs a focused tool control when an operation starts; hand focus to the operation's Cancel instead.- const blurredByInert = useRef<HTMLElement | null>(null);- const onBlurCapture = useCallback((event: FocusEvent<HTMLElement>) => {- blurredByInert.current =- event.relatedTarget === null && event.target.closest('[inert]') !== null- ? event.target.closest<HTMLElement>('[data-canvas-context-toolbar]')- : null;- }, []);- useLayoutEffect(() => {- const root = blurredByInert.current;- blurredByInert.current = null;- if (running && root) {- root.querySelector<HTMLElement>('[data-toolbar-action="cancel"]')?.focus();- }- }, [running]);-- return (- <Flex align="center" display="contents" onBlurCapture={onBlurCapture}>- <Identity compact={layout.identity === 'compact'} icon={tool.icon} name={t(`widgets.canvas.tools.${tool.id}`)} />- {TOOLBAR_REGION_ORDER.map((region) => (- <RegionSlot- key={region}- disabled={isSurfaceInteractionLocked || (running !== null && region !== 'modes')}- empty={region === 'modes' ? !hasModesContent : !reservesToolRegions}- id={region}- label={t(REGION_LABEL_KEYS[region])}- placement={layout.regions[region]}- vacant={region !== 'modes' && !toolRegions[region]}- width={regionSlotWidth(region, layout.regions[region])}- >- {renderRegion(region, layout.regions[region])}- </RegionSlot>- ))}- <ToolbarMoreMenu disabled={isSurfaceInteractionLocked} empty={displaced.length === 0 && !More}>- {displaced.map((region) => (- <ToolbarMoreSection key={region} label={t(REGION_LABEL_KEYS[region])}>- {renderRegion(region, 'menu')}- </ToolbarMoreSection>- ))}- {More ? (- <ToolbarMoreSection label={t('widgets.canvas.toolbar.regions.more')}>- <More- key={contentKey}- engine={engine}- isSurfaceInteractionLocked={isSurfaceInteractionLocked}- placement="menu"- />- </ToolbarMoreSection>- ) : null}- </ToolbarMoreMenu>- <Box flex="1" minW="0" />- <RegionSlot- id="status"- label={t(REGION_LABEL_KEYS.status)}- placement="bar"- width={layout.status === 'full' ? TOOLBAR_REGION_WIDTH_PX.status : TOOLBAR_REGION_WIDTH_PX.statusCompact}- >- <Status- key={contentKey}- compact={layout.status === 'compact'}- engine={engine}- isExternalInteractionLocked={isSurfaceInteractionLocked}- />- </RegionSlot>- </Flex>- );-};--const Identity = ({ compact, icon, name }: { compact: boolean; icon?: ComponentType; name: string }) => {- const content = (- <Flex- align="center"- data-region="identity"- flexShrink={0}- gap="2"- h="full"- overflow="hidden"- w={`${compact ? TOOLBAR_REGION_WIDTH_PX.identityCompact : TOOLBAR_REGION_WIDTH_PX.identity}px`}- >- {icon ? <Icon as={icon} boxSize="4" color="fg.muted" flexShrink={0} /> : null}- {compact ? (- <VisuallyHidden>{name}</VisuallyHidden>- ) : (- <Text fontSize="xs" fontWeight="medium" minW="0" truncate>- {name}- </Text>- )}- </Flex>- );- return compact ? <Tooltip content={name}>{content}</Tooltip> : content;-};--const EmptyToolbar = ({ width }: { width: number }) => {- const { t } = useTranslation();- const layout = resolveToolbarLayout({ ...IDLE_LAYOUT_INPUT, width });- return (- <>- <Identity compact={layout.identity === 'compact'} name="" />- {TOOLBAR_REGION_ORDER.map((region) => (- <RegionSlot- key={region}- empty- id={region}- label={t(REGION_LABEL_KEYS[region])}- placement={layout.regions[region]}- width={regionSlotWidth(region, layout.regions[region])}- >- {null}- </RegionSlot>- ))}- <ToolbarMoreMenu empty />- <Box flex="1" minW="0" />- <RegionSlot- id="status"- label={t(REGION_LABEL_KEYS.status)}- placement="bar"- width={layout.status === 'full' ? TOOLBAR_REGION_WIDTH_PX.status : TOOLBAR_REGION_WIDTH_PX.statusCompact}- >- <ToolbarStatus compact={layout.status === 'compact'} />- </RegionSlot>- </>- );-};--/**- * The canvas context toolbar: one fixed-height row at the top of the canvas- * widget with seven regions in a stable order — identity, geometry,- * intensity, color, modes (with the More menu at its right edge), a spacer,- * and status. The shell never unmounts for a tool or an operation; each region- * keeps its width and position, and only its content changes. Regions that do- * not fit the measured width move into the More menu in a fixed priority- * (`resolveToolbarLayout`), so the bar never wraps or changes height.- */-export const CanvasContextToolbar = ({- engine,- isSurfaceInteractionLocked,-}: {- engine: CanvasToolOptionsEngine | null;- isSurfaceInteractionLocked: boolean;-}) => {- const { t } = useTranslation();- const ref = useRef<HTMLDivElement>(null);- const width = useMeasuredWidth(ref);- return (- <Flex- ref={ref}- align="center"- aria-label={t('widgets.canvas.toolbar.label')}- aria-orientation="horizontal"- bg="bg.subtle"- borderBottomWidth="1px"- borderColor="border.subtle"- data-canvas-context-toolbar=""- flexShrink={0}- h={`${TOOLBAR_HEIGHT_PX}px`}- overflow="hidden"- px={`${TOOLBAR_INSET_PX}px`}- role="toolbar"- w="full"- >- {engine ? (- <ConnectedToolbar engine={engine} isSurfaceInteractionLocked={isSurfaceInteractionLocked} width={width} />- ) : (- <EmptyToolbar width={width} />- )}- </Flex>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/ToolbarMoreMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/ToolbarMoreMenu.tsxdeleted file mode 100644index db2d5e7e88..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/ToolbarMoreMenu.tsx+++ /dev/null@@ -1,80 +0,0 @@-import type { ReactNode } from 'react';--import { Flex, Popover, Portal, Stack, Text } from '@chakra-ui/react';-import { IconButton } from '@platform/ui';-import { EllipsisIcon } from 'lucide-react';-import { useCallback, useId, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { TOOLBAR_GAP_PX, TOOLBAR_REGION_WIDTH_PX } from './toolbarLayout';--const POSITIONING = { placement: 'bottom-end' } as const;--/** One labelled row of the More menu; a displaced region or the tool's secondary controls. */-export const ToolbarMoreSection = ({ children, label }: { children: ReactNode; label: string }) => {- const headingId = useId();- return (- <Stack aria-labelledby={headingId} gap="1" role="group">- <Text color="fg.muted" fontSize="2xs" fontWeight="medium" id={headingId} textTransform="uppercase">- {label}- </Text>- <Flex align="center" gap="2" minW="0" w="full">- {children}- </Flex>- </Stack>- );-};--/**- * The one overflow for everything the bar cannot show at its width: displaced- * regions first, in bar order, then the tool's or operation's secondary- * controls. Always present so the bar's geometry never depends on whether it- * has content; disabled when empty or while staging or generation owns the surface.- */-export const ToolbarMoreMenu = ({- children,- disabled = false,- empty,-}: {- children?: ReactNode;- disabled?: boolean;- empty: boolean;-}) => {- const { t } = useTranslation();- const [open, setOpen] = useState(false);- const onOpenChange = useCallback(({ open: next }: { open: boolean }) => setOpen(next), []);- const unavailable = empty || disabled;- return (- <Popover.Root- lazyMount- open={open && !unavailable}- positioning={POSITIONING}- unmountOnExit- onOpenChange={onOpenChange}- >- <Popover.Trigger asChild>- <IconButton- aria-label={t('widgets.canvas.toolbar.more')}- data-region="more"- disabled={unavailable}- flexShrink={0}- ms={`${TOOLBAR_GAP_PX}px`}- size="xs"- variant="ghost"- w={`${TOOLBAR_REGION_WIDTH_PX.more}px`}- >- <EllipsisIcon />- </IconButton>- </Popover.Trigger>- <Portal>- <Popover.Positioner>- <Popover.Content aria-label={t('widgets.canvas.toolbar.more')} w="22rem">- <Popover.Body p="3">- <Stack gap="3">{children}</Stack>- </Popover.Body>- </Popover.Content>- </Popover.Positioner>- </Portal>- </Popover.Root>- );-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/ToolbarPrimitives.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/ToolbarPrimitives.tsxdeleted file mode 100644index 125ab50f7f..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/ToolbarPrimitives.tsx+++ /dev/null@@ -1,272 +0,0 @@-import type { NumberInput as ChakraNumberInput, SliderValueChangeDetails } from '@chakra-ui/react';-import type { KeyboardEvent, ReactNode } from 'react';--import { Box, Flex, NumberInput, Text } from '@chakra-ui/react';-import { Button, IconButton, Slider } from '@platform/ui';-import { CheckIcon, XIcon } from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { TOOLBAR_NUMBER_FIELD_WIDTH_PX } from './toolbarLayout';--interface ToolbarNumberFieldProps {- 'aria-label': string;- disabled?: boolean;- /** Short prefix drawn inside the field (X, Y, W, H). */- label?: string;- max?: number;- min?: number;- step?: number;- suffix?: string;- value: string;- /** Live mode: every keystroke reaches the owner (session previews). */- onValueChange?: (details: ChakraNumberInput.ValueChangeDetails) => void;- /** Commit mode: the field keeps a draft and hands it over on blur or Enter (document edits). */- onValueCommit?: (details: ChakraNumberInput.ValueChangeDetails) => void;-}--const FieldAffix = ({ children, disabled, side }: { children: string; disabled?: boolean; side: 'start' | 'end' }) => (- <Text- aria-hidden- color={disabled ? 'fg.subtle' : 'fg.muted'}- fontSize="2xs"- fontWeight={side === 'start' ? 'medium' : undefined}- insetEnd={side === 'end' ? '1.5' : undefined}- insetStart={side === 'start' ? '1.5' : undefined}- lineHeight="1"- pointerEvents="none"- position="absolute"- top="50%"- transform="translateY(-50%)"- zIndex="1"- >- {children}- </Text>-);--/**- * A fixed-width numeric field with tabular figures. In commit mode a draft- * survives typing and only the accepted value is shown afterwards, so a- * clamped or rounded commit never leaves the field disagreeing with its owner- * and never remounts (focus stays where it was).- */-export const ToolbarNumberField = ({- 'aria-label': ariaLabel,- disabled,- label,- max,- min,- step,- suffix,- value,- onValueChange,- onValueCommit,-}: ToolbarNumberFieldProps) => {- const [draft, setDraft] = useState<string | null>(null);- const onDraftChange = useCallback(({ value: next }: ChakraNumberInput.ValueChangeDetails) => setDraft(next), []);- const onDraftCommit = useCallback(- (details: ChakraNumberInput.ValueChangeDetails) => {- setDraft(null);- onValueCommit?.(details);- },- [onValueCommit]- );- const live = onValueChange !== undefined;- return (- <Box flexShrink={0} position="relative" w={`${TOOLBAR_NUMBER_FIELD_WIDTH_PX}px`}>- {label ? (- <FieldAffix disabled={disabled} side="start">- {label}- </FieldAffix>- ) : null}- {suffix ? (- <FieldAffix disabled={disabled} side="end">- {suffix}- </FieldAffix>- ) : null}- <NumberInput.Root- disabled={disabled}- max={max}- min={min}- size="xs"- step={step}- value={live ? value : (draft ?? value)}- w="full"- onValueChange={live ? onValueChange : onDraftChange}- onValueCommit={live ? undefined : onDraftCommit}- >- <NumberInput.Input- aria-label={ariaLabel}- fontSize="xs"- fontVariantNumeric="tabular-nums"- pe={suffix ? '3.5' : '1.5'}- ps={label ? '3.5' : '1.5'}- textAlign="end"- />- </NumberInput.Root>- </Box>- );-};--/** Commit-mode handler: applies a finite number and ignores the rest. */-export const useNumberCommit = (apply: (value: number) => void) =>- useCallback(- ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {- if (Number.isFinite(valueAsNumber)) {- apply(valueAsNumber);- }- },- [apply]- );--interface ToolbarSliderProps {- 'aria-label': string;- disabled?: boolean;- formatValue?: (value: number) => string;- getAriaValueText?: (value: number) => string;- max: number;- min: number;- step?: number;- value: number;- onKeyDownCapture?: (event: KeyboardEvent<HTMLDivElement>) => void;- onValueChange: (value: number) => void;-}--/** A slider that fills its region; pairs with a {@link ToolbarNumberField}. */-export const ToolbarSlider = ({- 'aria-label': ariaLabel,- disabled,- formatValue,- getAriaValueText,- max,- min,- step,- value,- onKeyDownCapture,- onValueChange,-}: ToolbarSliderProps) => {- const labels = useMemo(() => [ariaLabel], [ariaLabel]);- const values = useMemo(() => [value], [value]);- const valueText = useMemo(- () => (getAriaValueText ? ({ value: current }: { value: number }) => getAriaValueText(current) : undefined),- [getAriaValueText]- );- const handleChange = useCallback(- ({ value: next }: SliderValueChangeDetails) => {- const first = next[0];- if (first !== undefined && Number.isFinite(first)) {- onValueChange(first);- }- },- [onValueChange]- );- return (- <Slider- aria-label={labels}- disabled={disabled}- flex="1"- formatValue={formatValue}- getAriaValueText={valueText}- max={max}- min={min}- minW="0"- size="sm"- step={step}- value={values}- onKeyDownCapture={onKeyDownCapture}- onValueChange={handleChange}- />- );-};--/**- * The status region's fixed frame: a truncating chip, then Apply and Cancel in- * place at every width (icon-only when compact, disabled when nothing is pending).- */-export const ToolbarStatus = ({- applyDisabled = true,- applyLoading = false,- cancelDisabled = true,- children,- compact,- onApply,- onCancel,-}: {- applyDisabled?: boolean;- applyLoading?: boolean;- cancelDisabled?: boolean;- children?: ReactNode;- compact: boolean;- onApply?: () => void;- onCancel?: () => void;-}) => {- const { t } = useTranslation();- const applyLabel = t('common.apply');- const cancelLabel = t('common.cancel');- return (- <Flex align="center" gap="1" h="full" minW="0" w="full">- <Box flex="1" minW="0" overflow="hidden" whiteSpace="nowrap">- {children}- </Box>- {compact ? (- <IconButton- aria-label={applyLabel}- data-toolbar-action="apply"- disabled={applyDisabled}- flexShrink={0}- loading={applyLoading}- size="xs"- variant="solid"- onClick={onApply}- >- <CheckIcon />- </IconButton>- ) : (- <Button- data-toolbar-action="apply"- disabled={applyDisabled}- flexShrink={0}- loading={applyLoading}- size="xs"- variant="solid"- w="14"- onClick={onApply}- >- {applyLabel}- </Button>- )}- {compact ? (- <IconButton- aria-label={cancelLabel}- data-toolbar-action="cancel"- disabled={cancelDisabled}- flexShrink={0}- size="xs"- variant="ghost"- onClick={onCancel}- >- <XIcon />- </IconButton>- ) : (- <Button- data-toolbar-action="cancel"- disabled={cancelDisabled}- flexShrink={0}- size="xs"- variant="ghost"- w="16"- onClick={onCancel}- >- {cancelLabel}- </Button>- )}- </Flex>- );-};--/** Muted, truncating guidance for tools and states without a control to show. */-export const ToolbarHint = ({ children }: { children: string }) => (- <Text color="fg.muted" data-toolbar-hint="" fontSize="xs" minW="0" title={children} truncate>- {children}- </Text>-);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolAdapters.test.tsdeleted file mode 100644index dcc360da89..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolAdapters.test.ts+++ /dev/null@@ -1,107 +0,0 @@-import type { ToolId } from '@workbench/canvas-engine/api';--import { describe, expect, it } from 'vitest';--import { hasToolRegions, OPERATION_PRESENTATION_ADAPTERS, TOOL_PRESENTATION_ADAPTERS } from './toolAdapters';-import { TOOLBAR_PRIMARY_MAX_WIDTH_PX, TOOLBAR_REGION_ORDER, TOOLBAR_REGION_WIDTH_PX } from './toolbarLayout';--const TOOL_IDS = Object.keys({- bbox: true,- brush: true,- colorPicker: true,- eraser: true,- gradient: true,- lasso: true,- marquee: true,- move: true,- sam: true,- shape: true,- text: true,- transform: true,- view: true,-} satisfies Record<ToolId, true>) as ToolId[];--const englishCatalogModules = import.meta.glob('../../../../../public/locales/en.json', {- eager: true,- import: 'default',-});-const en = Object.values(englishCatalogModules)[0] as {- widgets: {- canvas: {- toolHints: Record<string, string>;- toolbar: { label: string; more: string; regions: Record<string, string> };- tools: Record<string, string>;- };- };-};--describe('tool presentation adapters', () => {- it('registers every tool under its own id with an icon and a name in the English catalog', () => {- for (const toolId of TOOL_IDS) {- const adapter = TOOL_PRESENTATION_ADAPTERS[toolId];- expect(adapter.id, toolId).toBe(toolId);- expect(adapter.icon, toolId).toBeDefined();- expect(en.widgets.canvas.tools[toolId], toolId).toEqual(expect.any(String));- }- });-- it('hints exactly the tools without a control, and never names a primary region they lack', () => {- for (const toolId of TOOL_IDS) {- const adapter = TOOL_PRESENTATION_ADAPTERS[toolId];- if (hasToolRegions(adapter)) {- expect(en.widgets.canvas.toolHints[toolId], toolId).toBeUndefined();- if (adapter.primary) {- expect(adapter[adapter.primary], `${toolId} primary`).toBeDefined();- }- } else {- expect(en.widgets.canvas.toolHints[toolId], toolId).toEqual(expect.any(String));- expect(adapter.primary, toolId).toBeNull();- }- }- });-- it('keeps the shared geometry slots on the tools that edit position: move, transform and the frame', () => {- for (const toolId of ['bbox', 'move', 'transform'] as const) {- expect(TOOL_PRESENTATION_ADAPTERS[toolId].primary, toolId).toBe('geometry');- }- for (const toolId of ['gradient', 'lasso', 'marquee', 'shape'] as const) {- expect(TOOL_PRESENTATION_ADAPTERS[toolId].primary, toolId).toBe('modes');- }- });-- it('declares a positive bar width for every modes region and names every region in the catalog', () => {- for (const adapter of [- ...Object.values(TOOL_PRESENTATION_ADAPTERS),- ...Object.values(OPERATION_PRESENTATION_ADAPTERS),- ]) {- if (adapter.modes) {- expect(adapter.modes.width, 'id' in adapter ? adapter.id : adapter.kind).toBeGreaterThan(0);- }- }- for (const region of [...TOOLBAR_REGION_ORDER, 'more', 'status']) {- expect(en.widgets.canvas.toolbar.regions[region], region).toEqual(expect.any(String));- }- expect(en.widgets.canvas.toolbar.label).toEqual(expect.any(String));- expect(en.widgets.canvas.toolbar.more).toEqual(expect.any(String));- });-- it('keeps every tool and operation primary within the width the identity and status thresholds assume', () => {- expect(TOOLBAR_REGION_WIDTH_PX.geometry).toBeLessThanOrEqual(TOOLBAR_PRIMARY_MAX_WIDTH_PX);- for (const adapter of Object.values(TOOL_PRESENTATION_ADAPTERS)) {- if (adapter.primary === 'modes') {- expect(adapter.modes?.width, adapter.id).toBeLessThanOrEqual(TOOLBAR_PRIMARY_MAX_WIDTH_PX);- }- }- for (const adapter of Object.values(OPERATION_PRESENTATION_ADAPTERS)) {- expect(adapter.modes?.width, adapter.kind).toBeLessThanOrEqual(TOOLBAR_PRIMARY_MAX_WIDTH_PX);- }- });-- it('gives both guarded operations a status region so Apply and Cancel stay in place', () => {- expect(Object.keys(OPERATION_PRESENTATION_ADAPTERS).sort()).toEqual(['filter', 'select-object']);- for (const adapter of Object.values(OPERATION_PRESENTATION_ADAPTERS)) {- expect(adapter.status).toBeDefined();- expect(adapter.modes).toBeDefined();- }- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarLayout.test.tsdeleted file mode 100644index 1affb976fd..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarLayout.test.ts+++ /dev/null@@ -1,182 +0,0 @@-import { describe, expect, it } from 'vitest';--import {- fullToolbarWidth,- resolveToolbarLayout,- TOOLBAR_GAP_PX,- TOOLBAR_IDENTITY_FULL_MIN_WIDTH_PX,- TOOLBAR_PRIMARY_MAX_WIDTH_PX,- TOOLBAR_REGION_ORDER,- TOOLBAR_REGION_WIDTH_PX,- TOOLBAR_STATUS_FULL_MIN_WIDTH_PX,- type ToolbarLayout,- type ToolbarRegionId,-} from './toolbarLayout';--const barRegions = (layout: ToolbarLayout): ToolbarRegionId[] =>- TOOLBAR_REGION_ORDER.filter((region) => layout.regions[region] !== 'menu');--const shape = (layout: ToolbarLayout) => ({- bar: barRegions(layout),- geometry: layout.regions.geometry,- identity: layout.identity,- status: layout.status,-});--describe('resolveToolbarLayout', () => {- it('keeps every region in the bar once the full width fits, and nothing beyond that width changes', () => {- const full = fullToolbarWidth(200);- expect(full).toBe(108 + 196 + 152 + 64 + 200 + 32 + 236 + 6 * TOOLBAR_GAP_PX);- const atFull = resolveToolbarLayout({- reservesToolRegions: true,- modesWidth: 200,- primary: 'geometry',- width: full,- });- expect(atFull).toEqual({- identity: 'full',- regions: { color: 'bar', geometry: 'bar', intensity: 'bar', modes: 'bar' },- status: 'full',- });- expect(- resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 200, primary: 'geometry', width: 4000 })- ).toEqual(atFull);- expect(- barRegions(- resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 200, primary: 'geometry', width: full - 1 })- )- ).toEqual(['geometry', 'intensity', 'color']);- });-- it('compacts identity and status at fixed widths and demotes modes, color, intensity, then geometry', () => {- expect(TOOLBAR_IDENTITY_FULL_MIN_WIDTH_PX).toBe(108 + TOOLBAR_PRIMARY_MAX_WIDTH_PX + 32 + 236 + 3 * TOOLBAR_GAP_PX);- expect(TOOLBAR_STATUS_FULL_MIN_WIDTH_PX).toBe(32 + TOOLBAR_PRIMARY_MAX_WIDTH_PX + 32 + 236 + 3 * TOOLBAR_GAP_PX);- const sequence: Array<[number, ReturnType<typeof shape>]> = [- [1400, { bar: ['geometry', 'intensity', 'color', 'modes'], geometry: 'bar', identity: 'full', status: 'full' }],- [1000, { bar: ['geometry', 'intensity', 'color'], geometry: 'bar', identity: 'full', status: 'full' }],- [800, { bar: ['geometry', 'intensity'], geometry: 'bar', identity: 'full', status: 'full' }],- [644, { bar: ['geometry'], geometry: 'bar', identity: 'full', status: 'full' }],- [643, { bar: ['geometry'], geometry: 'bar', identity: 'compact', status: 'full' }],- // A compact status frees room for intensity again: the secondary regions may gain at a threshold.- [567, { bar: ['geometry', 'intensity'], geometry: 'bar', identity: 'compact', status: 'compact' }],- [300, { bar: [], geometry: 'menu', identity: 'compact', status: 'compact' }],- ];- for (const [width, expected] of sequence) {- expect(- shape(resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 300, primary: null, width })),- `${width}px`- ).toEqual(expected);- }- });-- it('gives every tool the same identity and status boxes at a width, whatever its primary region costs', () => {- for (const width of [1400, 700, 640, 560, 452, 340]) {- const brush = resolveToolbarLayout({ reservesToolRegions: true, modesWidth: null, primary: 'geometry', width });- const shapeTool = resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 176, primary: 'modes', width });- const selection = resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 244, primary: 'modes', width });- expect([shapeTool.identity, selection.identity], `${width}px`).toEqual([brush.identity, brush.identity]);- expect([shapeTool.status, selection.status], `${width}px`).toEqual([brush.status, brush.status]);- }- });-- it('keeps the primary region in the bar past every other region, shrinking geometry to two slots first', () => {- const modes = resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 300, primary: 'modes', width: 720 });- expect(barRegions(modes)).toEqual(['modes']);- expect(modes.identity).toBe('full');- // A tool's primary never leaves because identity or status upgraded: the thresholds assume the widest primary.- for (const width of [TOOLBAR_STATUS_FULL_MIN_WIDTH_PX, TOOLBAR_IDENTITY_FULL_MIN_WIDTH_PX]) {- const layout = resolveToolbarLayout({- reservesToolRegions: true,- modesWidth: TOOLBAR_PRIMARY_MAX_WIDTH_PX,- primary: 'modes',- width,- });- expect(layout.regions.modes, `${width}px`).toBe('bar');- }- // A compact identity, compact geometry, More and a compact status: the narrowest bar that shows geometry.- const narrowestCompact = 32 + 128 + 32 + 104 + 3 * TOOLBAR_GAP_PX;- const compact = resolveToolbarLayout({- reservesToolRegions: true,- modesWidth: null,- primary: 'geometry',- width: narrowestCompact,- });- expect(shape(compact)).toEqual({- bar: ['geometry', 'modes'],- geometry: 'compact',- identity: 'compact',- status: 'compact',- });- const full = resolveToolbarLayout({- reservesToolRegions: true,- modesWidth: null,- primary: 'geometry',- width: narrowestCompact + 68,- });- expect(full.regions.geometry).toBe('bar');- });-- it('moves even the primary region into the menu rather than clipping the bar', () => {- const tooNarrow = resolveToolbarLayout({- reservesToolRegions: true,- modesWidth: 400,- primary: 'modes',- width: 400,- });- expect(shape(tooNarrow)).toEqual({ bar: [], geometry: 'menu', identity: 'compact', status: 'compact' });- const geometry = resolveToolbarLayout({- reservesToolRegions: true,- modesWidth: null,- primary: 'geometry',- width: 300,- });- expect(geometry.regions.geometry).toBe('menu');- });-- it('leaves a modes region without width (a hint, or nothing) in the bar at every width, and charges it nothing', () => {- for (const width of [1400, 700, 400, 100]) {- expect(- resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 0, primary: null, width }).regions.modes,- `${width}px`- ).toBe('bar');- expect(- resolveToolbarLayout({ reservesToolRegions: true, modesWidth: null, primary: null, width }).regions.modes,- `${width}px`- ).toBe('bar');- }- expect(fullToolbarWidth(null) - fullToolbarWidth(0)).toBe(-TOOLBAR_GAP_PX);- });-- it('is monotonic for the primary region, identity and status, and for the rest between the thresholds', () => {- for (const primary of ['geometry', 'modes', null] as const) {- let previousChrome = -1;- let previousRegions = -1;- let previousPrimary = -1;- for (let width = 100; width <= 1600; width += 4) {- const layout = resolveToolbarLayout({ reservesToolRegions: true, modesWidth: 240, primary, width });- const chrome = (layout.identity === 'full' ? 1 : 0) + (layout.status === 'full' ? 2 : 0);- const regions = barRegions(layout).length * 2 + (layout.regions.geometry === 'bar' ? 1 : 0);- const primaryScore = primary === null ? 0 : layout.regions[primary] === 'menu' ? 0 : 1;- expect(chrome, `${primary} ${width}px`).toBeGreaterThanOrEqual(previousChrome);- expect(primaryScore, `${primary} ${width}px`).toBeGreaterThanOrEqual(previousPrimary);- if (chrome === previousChrome) {- expect(regions, `${primary} ${width}px`).toBeGreaterThanOrEqual(previousRegions);- }- previousChrome = chrome;- previousRegions = regions;- previousPrimary = primaryScore;- }- }- });-- it('charges nothing for the tool regions a hint-only tool does not reserve', () => {- const hint = resolveToolbarLayout({ modesWidth: 0, primary: null, reservesToolRegions: false, width: 300 });- expect(hint.regions).toEqual({ color: 'bar', geometry: 'bar', intensity: 'bar', modes: 'bar' });- expect(fullToolbarWidth(0, false)).toBe(108 + 0 + 32 + 236 + 3 * TOOLBAR_GAP_PX);- });-- it('reports region widths that add up to the documented fixed sum', () => {- const { color, geometry, identity, intensity, status } = TOOLBAR_REGION_WIDTH_PX;- expect(identity + geometry + intensity + color + status).toBe(756);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarLayout.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarLayout.tsdeleted file mode 100644index 9acafe9dba..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarLayout.ts+++ /dev/null@@ -1,146 +0,0 @@-/** Fixed geometry of the canvas context toolbar; every number is a CSS pixel. */-export const TOOLBAR_HEIGHT_PX = 40;-export const TOOLBAR_GAP_PX = 8;-export const TOOLBAR_NUMBER_FIELD_WIDTH_PX = 60;--export type ToolbarRegionId = 'geometry' | 'intensity' | 'color' | 'modes';-/** `compact` is the geometry region at two numeric slots; `menu` is the More menu. */-export type ToolbarRegionPlacement = 'bar' | 'compact' | 'menu';--export const TOOLBAR_REGION_WIDTH_PX = {- color: 64,- geometry: 3 * TOOLBAR_NUMBER_FIELD_WIDTH_PX + 2 * TOOLBAR_GAP_PX,- geometryCompact: 2 * TOOLBAR_NUMBER_FIELD_WIDTH_PX + TOOLBAR_GAP_PX,- identity: 108,- identityCompact: 32,- intensity: 152,- more: 32,- status: 236,- statusCompact: 104,-} as const;--/** Bar order; the spacer sits between `more` and `status`. */-export const TOOLBAR_REGION_ORDER: readonly ToolbarRegionId[] = ['geometry', 'intensity', 'color', 'modes'];--/** First to leave the bar when the widget narrows; the active tool's primary region leaves last of all. */-const DEMOTION_ORDER: readonly ToolbarRegionId[] = ['modes', 'color', 'intensity', 'geometry'];--export interface ToolbarLayoutInput {- /** The region kept in the bar for as long as anything fits, or null for tools with no primary control. */- primary: ToolbarRegionId | null;- /**- * Width the tool's modes content needs in the bar: 0 for content that- * truncates (a hint), null when the region is empty and hidden, so it costs- * neither width nor a gap.- */- modesWidth: number | null;- /** Whether geometry, intensity and color are reserved; hint-only tools reserve nothing. */- reservesToolRegions: boolean;- width: number;-}--export interface ToolbarLayout {- identity: 'full' | 'compact';- /** Where each region renders; a hidden region still reads `bar`. */- regions: Readonly<Record<ToolbarRegionId, ToolbarRegionPlacement>>;- status: 'full' | 'compact';-}--const regionWidth = (region: ToolbarRegionId, placement: ToolbarRegionPlacement, modesWidth: number | null): number =>- region === 'modes'- ? (modesWidth ?? 0)- : region === 'geometry' && placement === 'compact'- ? TOOLBAR_REGION_WIDTH_PX.geometryCompact- : TOOLBAR_REGION_WIDTH_PX[region];--/** Every displayed region costs its width plus the gap before it; a hidden region costs nothing. */-const requiredWidth = (layout: ToolbarLayout, modesWidth: number | null, reservesToolRegions = true): number => {- const identity =- layout.identity === 'full' ? TOOLBAR_REGION_WIDTH_PX.identity : TOOLBAR_REGION_WIDTH_PX.identityCompact;- const status = layout.status === 'full' ? TOOLBAR_REGION_WIDTH_PX.status : TOOLBAR_REGION_WIDTH_PX.statusCompact;- let total = identity + TOOLBAR_REGION_WIDTH_PX.more + status + 2 * TOOLBAR_GAP_PX;- for (const region of TOOLBAR_REGION_ORDER) {- const placement = layout.regions[region];- const displayed = region === 'modes' ? modesWidth !== null : reservesToolRegions;- if (placement !== 'menu' && displayed) {- total += regionWidth(region, placement, modesWidth) + TOOLBAR_GAP_PX;- }- }- return total;-};--const ALL_IN_BAR = { color: 'bar', geometry: 'bar', intensity: 'bar', modes: 'bar' } as const;-const MODES_ONLY = { color: 'menu', geometry: 'menu', intensity: 'menu', modes: 'bar' } as const;--/**- * The widest primary region any tool or operation declares- * (`toolAdapters.test.ts` enforces it). Identity and status compact at widths derived from it, so upgrading- * either never evicts a tool's primary region as the bar widens.- */-export const TOOLBAR_PRIMARY_MAX_WIDTH_PX = 244;--/** Below this width the identity shows only its icon: a full identity, the widest primary and a full status no longer fit. */-export const TOOLBAR_IDENTITY_FULL_MIN_WIDTH_PX = requiredWidth(- { identity: 'full', regions: MODES_ONLY, status: 'full' },- TOOLBAR_PRIMARY_MAX_WIDTH_PX-);-/** Below this width Apply and Cancel become icons and the chip an icon: a compact identity, the widest primary and a full status no longer fit. */-export const TOOLBAR_STATUS_FULL_MIN_WIDTH_PX = requiredWidth(- { identity: 'compact', regions: MODES_ONLY, status: 'full' },- TOOLBAR_PRIMARY_MAX_WIDTH_PX-);--const withRegion = (- layout: ToolbarLayout,- region: ToolbarRegionId,- placement: ToolbarRegionPlacement-): ToolbarLayout => ({- ...layout,- regions: { ...layout.regions, [region]: placement },-});--/**- * Identity and status compact at fixed widths, so their boxes depend on the- * width alone and every tool shares them (an upgrade of either can send a- * secondary region to the menu at that exact width; never the primary). The- * regions between then fit- * greedily in a fixed priority: modes, color, intensity and geometry leave for- * the More menu, the active tool's primary region excepted; then geometry- * shrinks to two slots; and only when the primary still does not fit does it- * leave too, so the bar overflows into the menu rather than clipping. A region- * without width (a truncating hint, or no modes content) is never demoted- * because demoting it frees nothing.- */-export const resolveToolbarLayout = ({- modesWidth,- primary,- reservesToolRegions,- width,-}: ToolbarLayoutInput): ToolbarLayout => {- let layout: ToolbarLayout = {- identity: width >= TOOLBAR_IDENTITY_FULL_MIN_WIDTH_PX ? 'full' : 'compact',- regions: ALL_IN_BAR,- status: width >= TOOLBAR_STATUS_FULL_MIN_WIDTH_PX ? 'full' : 'compact',- };- const fits = () => requiredWidth(layout, modesWidth, reservesToolRegions) <= width;- for (const region of DEMOTION_ORDER) {- if (fits()) {- return layout;- }- const present = region === 'modes' ? modesWidth !== null : reservesToolRegions;- if (region !== primary && present && regionWidth(region, 'bar', modesWidth) > 0) {- layout = withRegion(layout, region, 'menu');- }- }- if (!fits() && reservesToolRegions && layout.regions.geometry === 'bar') {- layout = withRegion(layout, 'geometry', 'compact');- }- if (!fits() && primary && regionWidth(primary, 'bar', modesWidth) > 0) {- layout = withRegion(layout, primary, 'menu');- }- return layout;-};--/** Width the bar needs before any region leaves it for the given modes width. */-export const fullToolbarWidth = (modesWidth: number | null, reservesToolRegions = true): number =>- requiredWidth({ identity: 'full', regions: ALL_IN_BAR, status: 'full' }, modesWidth, reservesToolRegions);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsxindex 5f90a6d309..41e78c6acd 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BboxOptions.tsx@@ -2,14 +2,12 @@ import type { AspectRatioId } from '@features/generation/contracts';import type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { AspectRatioLockButton, AspectRatioSelect } from '@features/generation/components';import { ASPECT_RATIO_MAP, deriveAspectRatioId } from '@features/generation/settings';import { constrainBboxToRatio } from '@workbench/canvas-engine/api';-import { TOOLBAR_GAP_PX, TOOLBAR_NUMBER_FIELD_WIDTH_PX } from '@workbench/widgets/canvas/context-toolbar/toolbarLayout';-import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';-import { FrameIcon } from 'lucide-react';+import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -109,9 +107,8 @@ const FrameSize = ({ engine }: ToolbarRegionProps) => {};export const bboxAdapter: ToolPresentationAdapter = {+ rowLabels: { geometry: 'widgets.transform.position', modes: 'widgets.canvas.toolOptions.frameSize' },geometry: FramePosition,- icon: FrameIcon,id: 'bbox',- modes: { component: FrameSize, width: 2 * TOOLBAR_NUMBER_FIELD_WIDTH_PX + 120 + 32 + 3 * TOOLBAR_GAP_PX },- primary: 'geometry',+ modes: FrameSize,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsxindex 0f80ab9529..a0c81f6cfb 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx@@ -3,20 +3,20 @@ import type { BrushOptions as BrushOptionsState } from '@workbench/canvas-engineimport type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import type { KeyboardEvent } from 'react';import { HStack } from '@chakra-ui/react';import { ColorPicker, ToggleIconButton } from '@platform/ui';import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/api';+import { useBrushOptions } from '@workbench/widgets/canvas/engineStoreHooks';import {ToolbarNumberField,ToolbarSlider,useNumberCommit,-} from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';-import { useBrushOptions } from '@workbench/widgets/canvas/engineStoreHooks';+} from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';-import { BrushIcon, DropletIcon, PenLineIcon } from 'lucide-react';+import { DropletIcon, PenLineIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -238,12 +238,15 @@ const BrushPressure = ({ engine }: ToolbarRegionProps) => {};export const brushAdapter: ToolPresentationAdapter = {+ rowLabels: {+ geometry: 'widgets.canvas.toolOptions.size',+ intensity: 'widgets.canvas.toolOptions.opacity',+ more: 'widgets.canvas.toolOptions.pressure',+ },color: BrushColor,geometry: BrushSize,- icon: BrushIcon,id: 'brush',intensity: BrushOpacity,more: BrushPressure,paintsLeaf: true,- primary: 'geometry',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsxindex 035e99bfd6..a407e9d07c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/EraserOptions.tsx@@ -1,10 +1,9 @@import type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { useEraserOptions } from '@workbench/widgets/canvas/engineStoreHooks';-import { EraserIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -30,10 +29,9 @@ const EraserOpacity = ({ engine }: ToolbarRegionProps) => {};export const eraserAdapter: ToolPresentationAdapter = {+ rowLabels: { geometry: 'widgets.canvas.toolOptions.size', intensity: 'widgets.canvas.toolOptions.opacity' },geometry: EraserSize,- icon: EraserIcon,id: 'eraser',intensity: EraserOpacity,paintsLeaf: true,- primary: 'geometry',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsxindex 638ee6ee34..1000f53965 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.test.tsx@@ -166,16 +166,10 @@ const renderRegions = (session: FilterOperationSessionState) => {));return {- modes: render(- createElement(FilterModes, { engine: engine as never, isSurfaceInteractionLocked: false, placement: 'bar' })- ),- more: render(- createElement(FilterMore, { engine: engine as never, isSurfaceInteractionLocked: false, placement: 'menu' })- ),+ modes: render(createElement(FilterModes, { engine: engine as never, isSurfaceInteractionLocked: false })),+ more: render(createElement(FilterMore, { engine: engine as never, isSurfaceInteractionLocked: false })),operations,- status: render(- createElement(FilterStatus, { compact: false, engine: engine as never, isExternalInteractionLocked: false })- ),+ status: render(createElement(FilterStatus, { engine: engine as never, isExternalInteractionLocked: false })),};};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsxindex b9ea2cc597..87b04fbe9f 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/FilterOptions.tsx@@ -2,7 +2,7 @@ import type {OperationPresentationAdapter,ToolbarRegionProps,ToolbarStatusProps,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import { HStack, Stack } from '@chakra-ui/react';@@ -15,8 +15,8 @@ import {isFilterConfigValid,type FilterOperationSessionState,} from '@workbench/canvas-operations/api';-import { ToolbarStatus } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';import { useFilterSession } from '@workbench/widgets/canvas/engineStoreHooks';+import { ToolbarStatus } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { LayerFilterControls } from '@workbench/widgets/layers/LayerFilterControls';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -185,7 +185,7 @@ export const FilterMore = ({ engine, isSurfaceInteractionLocked }: ToolbarRegion);};-export const FilterStatus = ({ compact, engine, isExternalInteractionLocked }: ToolbarStatusProps) => {+export const FilterStatus = ({ engine, isExternalInteractionLocked }: ToolbarStatusProps) => {const { t } = useTranslation();const session = useFilterSession(engine);const operations = getCanvasOperations(engine);@@ -195,7 +195,7 @@ export const FilterStatus = ({ compact, engine, isExternalInteractionLocked }: T);const onCancel = useCallback(() => operations.cancelFilterOperation(), [operations]);if (!session) {- return <ToolbarStatus compact={compact} />;+ return <ToolbarStatus />;}const eligibility = getFilterActionEligibility(session, isExternalInteractionLocked);const sourceLabel = `${session.layerName} · ${t(`widgets.layers.selectObject.saveAs_${session.layerType}`)}`;@@ -205,12 +205,10 @@ export const FilterStatus = ({ compact, engine, isExternalInteractionLocked }: TapplyDisabled={!eligibility.canApply}applyLoading={session.status === 'committing'}cancelDisabled={!eligibility.canCancel}- compact={compact}onApply={onApply}onCancel={onCancel}><OperationStatusChip- compact={compact}errorDetail={null}errorText={session.error}isBusy={isBusy}@@ -225,7 +223,7 @@ export const FilterStatus = ({ compact, engine, isExternalInteractionLocked }: Texport const filterOperationAdapter: OperationPresentationAdapter = {kind: 'filter',- modes: { component: FilterModes, width: 232 },+ modes: FilterModes,more: FilterMore,status: FilterStatus,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsxindex e27e3d5805..c04f09d5d0 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx@@ -3,17 +3,16 @@ import type { CanvasLayerSourceContract, GradientStop, GradientToolOptions } froimport type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { createListCollection } from '@chakra-ui/react';import { ColorPicker, Select } from '@platform/ui';import { getDocumentLayer } from '@workbench/canvas-engine/api';-import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';import { useGradientOptions } from '@workbench/widgets/canvas/engineStoreHooks';+import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { PaintBucketIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -168,11 +167,14 @@ const GradientStops = ({ engine }: ToolbarRegionProps) => {};export const gradientAdapter: ToolPresentationAdapter = {+ rowLabels: {+ color: 'widgets.canvas.toolOptions.gradientStops',+ geometry: 'widgets.canvas.toolOptions.gradientAngle',+ modes: 'widgets.canvas.toolOptions.gradientKind',+ },color: GradientStops,geometry: GradientAngle,- icon: PaintBucketIcon,id: 'gradient',- modes: { component: GradientKindSelect, width: 96 },+ modes: GradientKindSelect,paintsLeaf: true,- primary: 'modes',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsxindex 4ae92e040a..8361016534 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/LassoOptions.tsx@@ -3,16 +3,15 @@ import type { LassoToolOptions, SelectionOp } from '@workbench/canvas-engine/apiimport type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { createListCollection } from '@chakra-ui/react';import { Select } from '@platform/ui';import { useLassoOptions } from '@workbench/widgets/canvas/engineStoreHooks';-import { LassoIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { SELECTION_MODES_WIDTH_PX, SelectionActions, SelectionModes } from './SelectionOptionsRow';+import { SelectionActions, SelectionModes } from './SelectionOptionsRow';type LassoShape = LassoToolOptions['shape'];@@ -20,7 +19,7 @@ const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: false } as coconst SELECT_TRIGGER_PROPS = { minW: '6rem', w: '6rem' } as const;/** How the path is drawn (freehand drag / polygon clicks), then the shared selection op mode. */-const LassoModes = ({ engine, isSurfaceInteractionLocked, placement }: ToolbarRegionProps) => {+const LassoModes = ({ engine, isSurfaceInteractionLocked }: ToolbarRegionProps) => {const { t } = useTranslation();const options = useLassoOptions(engine);const shapeCollection = useMemo(@@ -69,7 +68,6 @@ const LassoModes = ({ engine, isSurfaceInteractionLocked, placement }: ToolbarRe}isSurfaceInteractionLocked={isSurfaceInteractionLocked}mode={options.mode}- placement={placement}onModeChange={onModeChange}/></>@@ -77,9 +75,8 @@ const LassoModes = ({ engine, isSurfaceInteractionLocked, placement }: ToolbarRe};export const lassoAdapter: ToolPresentationAdapter = {- icon: LassoIcon,+ rowLabels: { modes: 'widgets.canvas.toolOptions.selectionMode', more: 'widgets.canvas.toolOptions.selectionActions' },id: 'lasso',- modes: { component: LassoModes, width: 96 + 8 + SELECTION_MODES_WIDTH_PX },+ modes: LassoModes,more: SelectionActions,- primary: 'modes',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsxindex 91d641ea6f..0b43dae9c3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MarqueeOptions.tsx@@ -3,16 +3,15 @@ import type { MarqueeToolOptions, SelectionOp } from '@workbench/canvas-engine/aimport type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { createListCollection } from '@chakra-ui/react';import { Select } from '@platform/ui';import { useMarqueeOptions } from '@workbench/widgets/canvas/engineStoreHooks';-import { SquareDashedIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import { SELECTION_MODES_WIDTH_PX, SelectionActions, SelectionModes } from './SelectionOptionsRow';+import { SelectionActions, SelectionModes } from './SelectionOptionsRow';type MarqueeKind = MarqueeToolOptions['kind'];@@ -20,7 +19,7 @@ const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: false } as coconst SELECT_TRIGGER_PROPS = { minW: '6rem', w: '6rem' } as const;/** The shape the next drag traces (rectangle / ellipse), then the shared selection op mode. */-const MarqueeModes = ({ engine, isSurfaceInteractionLocked, placement }: ToolbarRegionProps) => {+const MarqueeModes = ({ engine, isSurfaceInteractionLocked }: ToolbarRegionProps) => {const { t } = useTranslation();const options = useMarqueeOptions(engine);const kindCollection = useMemo(@@ -65,7 +64,6 @@ const MarqueeModes = ({ engine, isSurfaceInteractionLocked, placement }: ToolbarhintKey="widgets.canvas.toolOptions.marqueeHint"isSurfaceInteractionLocked={isSurfaceInteractionLocked}mode={options.mode}- placement={placement}onModeChange={onModeChange}/></>@@ -73,9 +71,8 @@ const MarqueeModes = ({ engine, isSurfaceInteractionLocked, placement }: Toolbar};export const marqueeAdapter: ToolPresentationAdapter = {- icon: SquareDashedIcon,+ rowLabels: { modes: 'widgets.canvas.toolOptions.selectionMode', more: 'widgets.canvas.toolOptions.selectionActions' },id: 'marquee',- modes: { component: MarqueeModes, width: 96 + 8 + SELECTION_MODES_WIDTH_PX },+ modes: MarqueeModes,more: SelectionActions,- primary: 'modes',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsxindex be2bb5ec04..a797ab14d8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx@@ -1,13 +1,12 @@import type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';-import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';+import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { MoveIcon } from 'lucide-react';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -80,8 +79,7 @@ const MovePosition = ({ engine }: ToolbarRegionProps) => {};export const moveAdapter: ToolPresentationAdapter = {+ rowLabels: { geometry: 'widgets.transform.position' },geometry: MovePosition,- icon: MoveIcon,id: 'move',- primary: 'geometry',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsxindex 0b6331316f..1f59d0f055 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/OperationStatusSlot.tsx@@ -2,7 +2,7 @@ import type { CSSProperties } from 'react';import { Flex, HStack, IconButton, Spinner, Text, VisuallyHidden } from '@chakra-ui/react';import { Tooltip } from '@platform/ui';-import { CircleAlertIcon, InfoIcon } from 'lucide-react';+import { InfoIcon } from 'lucide-react';const ERROR_CLAMP_STYLE: CSSProperties = {display: '-webkit-box',@@ -71,7 +71,6 @@ export const OperationStatusSlot = ({};interface OperationStatusChipProps {- compact: boolean;errorDetail: string | null;errorText: string | null;isBusy: boolean;@@ -82,13 +81,8 @@ interface OperationStatusChipProps {title: string;}-/**- * The toolbar's status chip for a running operation: title plus the live- * status slot, or at compact widths a single icon (spinner, error, info) whose- * tooltip carries the text while the live region stays mounted for announcements.- */+/** The status of a running operation: its title, then the live status slot. */export const OperationStatusChip = ({- compact,errorDetail,errorText,isBusy,@@ -96,8 +90,14 @@ export const OperationStatusChip = ({statusText,technicalDetailsLabel,title,-}: OperationStatusChipProps) => {- const slot = (+}: OperationStatusChipProps) => (+ <HStack gap="1" minW="0">+ <Tooltip content={sourceLabel}>+ <Text flexShrink={0} fontSize="xs" fontWeight="semibold" minW="0" truncate>+ {title}+ <VisuallyHidden>{sourceLabel}</VisuallyHidden>+ </Text>+ </Tooltip><OperationStatusSloterrorDetail={errorDetail}errorText={errorText}@@ -106,29 +106,5 @@ export const OperationStatusChip = ({statusText={statusText}technicalDetailsLabel={technicalDetailsLabel}/>- );- if (compact) {- return (- <Tooltip content={`${title} · ${errorText ?? (isBusy ? statusText : sourceLabel)}`}>- <Flex align="center" boxSize="8" color={errorText ? 'fg.error' : 'fg.muted'} justify="center">- {errorText ? <CircleAlertIcon size={16} /> : isBusy ? <Spinner size="xs" /> : <InfoIcon size={16} />}- <VisuallyHidden>- {title}- {slot}- </VisuallyHidden>- </Flex>- </Tooltip>- );- }- return (- <HStack gap="1" minW="0">- <Tooltip content={sourceLabel}>- <Text flexShrink={0} fontSize="xs" fontWeight="semibold" minW="0" truncate>- {title}- <VisuallyHidden>{sourceLabel}</VisuallyHidden>- </Text>- </Tooltip>- {slot}- </HStack>- );-};+ </HStack>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.tsindex 520fd071fa..5a55cb619b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.test.ts@@ -485,15 +485,9 @@ describe('select object regions', () => {createElement(I18nextProvider, { i18n: testI18n }, element)));- const modes = render(- createElement(SamModes, { engine: engine as never, isSurfaceInteractionLocked: false, placement: 'bar' })- );- const more = render(- createElement(SamMore, { engine: engine as never, isSurfaceInteractionLocked: false, placement: 'menu' })- );- const status = render(- createElement(SamStatus, { compact: false, engine: engine as never, isExternalInteractionLocked: false })- );+ const modes = render(createElement(SamModes, { engine: engine as never, isSurfaceInteractionLocked: false }));+ const more = render(createElement(SamMore, { engine: engine as never, isSurfaceInteractionLocked: false }));+ const status = render(createElement(SamStatus, { engine: engine as never, isExternalInteractionLocked: false }));expect(modes.indexOf('>Visual<')).toBeLessThan(modes.indexOf('aria-label="Include 1"'));expect(modes).not.toContain('>Invert<');diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsxindex cbc86a60fb..cf4cfbeb9b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SamOptions.tsx@@ -2,7 +2,7 @@ import type {OperationPresentationAdapter,ToolbarRegionProps,ToolbarStatusProps,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';/* oxlint-disable react-perf/jsx-no-jsx-as-prop, react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop */import type { ChangeEvent } from 'react';@@ -19,8 +19,8 @@ import {type SamModel,type SelectObjectSaveTarget,} from '@workbench/canvas-operations/api';-import { ToolbarStatus } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';import { useSamSession } from '@workbench/widgets/canvas/engineStoreHooks';+import { ToolbarStatus } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { SquareMinusIcon, SquarePlusIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -394,9 +394,6 @@ export const SamSettings = ({);};-/** Bar width of the mode toggle plus the point buttons or the prompt input; invert lives in More. */-export const SAM_MODES_WIDTH_PX = 244;-/** Input mode, the visual point labels or the prompt, and invert: what changes between previews. */export const SamModes = ({ engine, isSurfaceInteractionLocked }: ToolbarRegionProps) => {const { t } = useTranslation();@@ -515,14 +512,14 @@ export const SamMore = ({ engine, isSurfaceInteractionLocked }: ToolbarRegionPro);};-export const SamStatus = ({ compact, engine, isExternalInteractionLocked }: ToolbarStatusProps) => {+export const SamStatus = ({ engine, isExternalInteractionLocked }: ToolbarStatusProps) => {const { t } = useTranslation();const session = useSamSession(engine);const actions = useMemo(() => getSamActionHandlers(getCanvasOperations(engine)), [engine]);const onApply = useCallback(() => actions.apply(), [actions]);const onCancel = useCallback(() => actions.cancel(), [actions]);if (!session) {- return <ToolbarStatus compact={compact} />;+ return <ToolbarStatus />;}const eligibility = getSamActionEligibility(session, isExternalInteractionLocked);const isProcessing = isSamProcessingStatus(session.status);@@ -538,12 +535,10 @@ export const SamStatus = ({ compact, engine, isExternalInteractionLocked }: ToolapplyDisabled={!eligibility.canApply}applyLoading={session.status === 'committing'}cancelDisabled={!eligibility.canCancel}- compact={compact}onApply={onApply}onCancel={onCancel}><OperationStatusChip- compact={compact}errorDetail={session.error?.detail ?? null}errorText={session.error ? t(getSamErrorTranslationKey(session.error.code)) : null}isBusy={isBusy}@@ -558,7 +553,7 @@ export const SamStatus = ({ compact, engine, isExternalInteractionLocked }: Toolexport const selectObjectOperationAdapter: OperationPresentationAdapter = {kind: 'select-object',- modes: { component: SamModes, width: SAM_MODES_WIDTH_PX },+ modes: SamModes,more: SamMore,status: SamStatus,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsxindex f0a11b5891..5c5257e2fe 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.test.tsx@@ -64,7 +64,7 @@ const renderRow = (layer: CanvasLayerContract): Map<string, CapturedButton> => {activeProject.current = project;renderToStaticMarkup(<ChakraProvider value={system}>- <SelectionActions engine={engine} isSurfaceInteractionLocked={false} placement="bar" />+ <SelectionActions engine={engine} isSurfaceInteractionLocked={false} /></ChakraProvider>);return new Map(buttons);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsxindex 275608c7e0..a17338bfaa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/SelectionOptionsRow.tsx@@ -1,11 +1,11 @@import type { SelectionOp } from '@workbench/canvas-engine/api';-import type { ToolbarRegionProps } from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+import type { ToolbarRegionProps } from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { HStack } from '@chakra-ui/react';import { Button, IconButton, Tooltip } from '@platform/ui';import { isLeafPixelEditEligible, lookupDocumentLeaf } from '@workbench/canvas-engine/api';-import { ToolbarHint } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';import { useCanvasHasSelection } from '@workbench/widgets/canvas/engineStoreHooks';+import { ToolbarHint } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { SquareIcon, SquareMinusIcon, SquarePlusIcon, SquaresIntersectIcon } from 'lucide-react';import { useCallback } from 'react';@@ -27,9 +27,6 @@ const OP_MODE_ICONS: Record<SelectionOp, typeof SquareIcon> = {subtract: SquareMinusIcon,};-/** Bar width of the four op-mode icon buttons; the hint after them truncates. */-export const SELECTION_MODES_WIDTH_PX = 4 * 32 + 3 * 4;-const OpModeButton = ({active,mode,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsxindex 0118ac9512..6055992650 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx@@ -3,21 +3,21 @@ import type { CanvasLayerSourceContract, ShapeToolOptions } from '@workbench/canimport type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { createListCollection } from '@chakra-ui/react';import { ColorPicker, Select, ToggleIconButton } from '@platform/ui';import { MAX_SHAPE_STROKE_WIDTH, getDocumentLayer } from '@workbench/canvas-engine/api';+import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';import {ToolbarHint,ToolbarNumberField,useNumberCommit,-} from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';-import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';+} from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { PaintBucketIcon, ShapesIcon, SquareIcon } from 'lucide-react';+import { PaintBucketIcon, SquareIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -188,11 +188,14 @@ const ShapeColors = ({ engine }: ToolbarRegionProps) => {};export const shapeAdapter: ToolPresentationAdapter = {+ rowLabels: {+ color: 'widgets.canvas.toolOptions.shapeColors',+ geometry: 'widgets.canvas.toolOptions.shapeStrokeWidth',+ modes: 'widgets.canvas.toolOptions.shapeKind',+ },color: ShapeColors,geometry: ShapeStrokeWidth,- icon: ShapesIcon,id: 'shape',- modes: { component: ShapeModes, width: 176 },+ modes: ShapeModes,paintsLeaf: true,- primary: 'modes',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsxindex 393859e98e..f980142f12 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx@@ -3,7 +3,7 @@ import type { CanvasLayerSourceContract, TextToolOptions } from '@workbench/canvimport type {ToolbarRegionProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';import { createListCollection, HStack } from '@chakra-ui/react';import { ColorPicker, IconButton, Select } from '@platform/ui';@@ -14,12 +14,12 @@ import {TEXT_FONT_WEIGHTS,getDocumentLayer,} from '@workbench/canvas-engine/api';-import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';import { useTextEditSession, useTextOptions } from '@workbench/widgets/canvas/engineStoreHooks';+import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';-import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon, TypeIcon } from 'lucide-react';+import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -244,11 +244,14 @@ const TextColor = ({ engine }: ToolbarRegionProps) => {};export const textAdapter: ToolPresentationAdapter = {+ rowLabels: {+ color: 'widgets.canvas.toolOptions.textColor',+ geometry: 'widgets.canvas.toolOptions.textFont',+ modes: 'widgets.canvas.toolOptions.textStyle',+ },color: TextColor,geometry: TextFamily,- icon: TypeIcon,id: 'text',- modes: { component: TextStyle, width: 320 },+ modes: TextStyle,paintsLeaf: true,- primary: 'geometry',};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsxindex 186ad9e2cd..de87412bf1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TransformOptions.tsx@@ -4,12 +4,10 @@ import type {ToolbarRegionProps,ToolbarStatusProps,ToolPresentationAdapter,-} from '@workbench/widgets/canvas/context-toolbar/toolbarContracts';+} from '@workbench/widgets/canvas/tool-presentation/toolbarContracts';-import { TOOLBAR_GAP_PX, TOOLBAR_NUMBER_FIELD_WIDTH_PX } from '@workbench/widgets/canvas/context-toolbar/toolbarLayout';-import { ToolbarNumberField, ToolbarStatus } from '@workbench/widgets/canvas/context-toolbar/ToolbarPrimitives';import { useCanvasHasFloatingSelection, useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';-import { Rotate3dIcon } from 'lucide-react';+import { ToolbarNumberField, ToolbarStatus } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -121,28 +119,19 @@ const TransformScale = ({ engine }: ToolbarRegionProps) => {* pixels instead of opening a layer session; the numerics stay disabled* because the float's transform is layer-local, not document space.*/-const TransformStatus = ({ compact, engine }: ToolbarStatusProps) => {+const TransformStatus = ({ engine }: ToolbarStatusProps) => {const session = useTransformSession(engine);const hasFloat = useCanvasHasFloatingSelection(engine);const disabled = !session && !hasFloat;const onApply = useCallback(() => engine.layers.applyTransform(), [engine]);const onCancel = useCallback(() => engine.layers.cancelTransform(), [engine]);- return (- <ToolbarStatus- applyDisabled={disabled}- cancelDisabled={disabled}- compact={compact}- onApply={onApply}- onCancel={onCancel}- />- );+ return <ToolbarStatus applyDisabled={disabled} cancelDisabled={disabled} onApply={onApply} onCancel={onCancel} />;};export const transformAdapter: ToolPresentationAdapter = {+ rowLabels: { geometry: 'widgets.transform.position', modes: 'widgets.transform.scale' },geometry: TransformPosition,- icon: Rotate3dIcon,id: 'transform',- modes: { component: TransformScale, width: 3 * TOOLBAR_NUMBER_FIELD_WIDTH_PX + 2 * TOOLBAR_GAP_PX },- primary: 'geometry',+ modes: TransformScale,status: TransformStatus,};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/ToolbarPrimitives.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/ToolbarPrimitives.tsxnew file mode 100644index 0000000000..4a941de5c6--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/ToolbarPrimitives.tsx@@ -0,0 +1,255 @@+/* oxlint-disable react-perf/jsx-no-jsx-as-prop */+import type { NumberInput as ChakraNumberInput, SliderValueChangeDetails } from '@chakra-ui/react';+import type { KeyboardEvent, ReactNode } from 'react';++import { Box, Flex, Icon, InputGroup, NumberInput, Text } from '@chakra-ui/react';+import { Button, Slider } from '@platform/ui';+import { MoveHorizontalIcon } from 'lucide-react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++/** Width of every numeric field, so X / Y / W / H line up across tools; fits "-1234.56" beside its affixes. */+const TOOLBAR_NUMBER_FIELD_WIDTH_PX = 80;++interface ToolbarNumberFieldProps {+ 'aria-label': string;+ disabled?: boolean;+ /** Short prefix drawn inside the field (X, Y, W, H); it doubles as the scrub handle. */+ label?: string;+ max?: number;+ min?: number;+ step?: number;+ suffix?: string;+ value: string;+ /** Live mode: every keystroke reaches the owner (session previews). */+ onValueChange?: (details: ChakraNumberInput.ValueChangeDetails) => void;+ /** Commit mode: the field keeps a draft and hands it over on blur, Enter or the end of a scrub (document edits). */+ onValueCommit?: (details: ChakraNumberInput.ValueChangeDetails) => void;+}++const AFFIX_PROPS = { color: 'fg.muted', fontSize: '2xs', lineHeight: '1' } as const;+// InputGroup pads the input by `--input-height` (32px at size xs) minus the offset; the text must clear the affix.+const INPUT_HEIGHT_PX = 32;+const AFFIX_CHAR_PX = 6;+const AFFIX_GUTTER_PX = 8;+const affixOffset = (chars: number): string => `${INPUT_HEIGHT_PX - AFFIX_GUTTER_PX - chars * AFFIX_CHAR_PX}px`;+const START_ELEMENT_PROPS = { ...AFFIX_PROPS, fontWeight: 'medium', pointerEvents: 'auto', ps: '1.5' } as const;+const END_ELEMENT_PROPS = { ...AFFIX_PROPS, pe: '1.5', pointerEvents: 'none' } as const;++/**+ * A fixed-width numeric field with tabular figures whose prefix is a scrub+ * handle (drag sideways with the mouse to change the value by `step` per+ * pixel). In commit mode a draft survives typing and scrubbing; the owner+ * hears one value on blur, Enter or pointer-up, and only when something was+ * edited to a different string, so tabbing through fields never commits the+ * rounded display back over a precise value. Only the accepted value shows+ * afterwards, so a clamped commit never leaves the field disagreeing with its owner.+ */+export const ToolbarNumberField = ({+ 'aria-label': ariaLabel,+ disabled,+ label,+ max,+ min,+ step,+ suffix,+ value,+ onValueChange,+ onValueCommit,+}: ToolbarNumberFieldProps) => {+ const [draft, setDraft] = useState<string | null>(null);+ const draftRef = useRef<string | null>(null);+ const scrubEnd = useRef<(() => void) | null>(null);+ const onDraftChange = useCallback(({ value: next }: ChakraNumberInput.ValueChangeDetails) => {+ draftRef.current = next;+ setDraft(next);+ }, []);+ const onDraftCommit = useCallback(+ (details: ChakraNumberInput.ValueChangeDetails) => {+ const edited = draftRef.current !== null;+ draftRef.current = null;+ setDraft(null);+ if (edited && details.value !== value) {+ onValueCommit?.(details);+ }+ },+ [onValueCommit, value]+ );+ // The number input commits on blur and Enter only; a scrub ends with the+ // mouse button, so the draft it produced is committed when the button lifts.+ // The listener reads the ref: a release in the same frame as the last move+ // must not commit a draft one step behind.+ const onScrubStart = useCallback(() => {+ scrubEnd.current?.();+ const scrub = new AbortController();+ scrubEnd.current = () => scrub.abort();+ window.addEventListener(+ 'mouseup',+ () => {+ scrub.abort();+ scrubEnd.current = null;+ const next = draftRef.current;+ if (next !== null) {+ onDraftCommit({ value: next, valueAsNumber: Number.parseFloat(next) });+ }+ },+ { signal: scrub.signal }+ );+ }, [onDraftCommit]);+ useEffect(() => () => scrubEnd.current?.(), []);+ const live = onValueChange !== undefined;+ return (+ <NumberInput.Root+ disabled={disabled}+ flexShrink={0}+ max={max}+ min={min}+ size="xs"+ step={step}+ value={live ? value : (draft ?? value)}+ w={`${TOOLBAR_NUMBER_FIELD_WIDTH_PX}px`}+ onValueChange={live ? onValueChange : onDraftChange}+ onValueCommit={live ? undefined : onDraftCommit}+ >+ <InputGroup+ endElement={suffix ? <span aria-hidden>{suffix}</span> : undefined}+ endElementProps={END_ELEMENT_PROPS}+ endOffset={suffix ? affixOffset(suffix.length) : undefined}+ startElement={+ <NumberInput.Scrubber aria-hidden onMouseDownCapture={live ? undefined : onScrubStart}>+ {label ?? <Icon as={MoveHorizontalIcon} boxSize="3" />}+ </NumberInput.Scrubber>+ }+ startElementProps={START_ELEMENT_PROPS}+ startOffset={label ? affixOffset(label.length) : affixOffset(2)}+ >+ <NumberInput.Input aria-label={ariaLabel} fontSize="xs" fontVariantNumeric="tabular-nums" textAlign="end" />+ </InputGroup>+ </NumberInput.Root>+ );+};++/** Commit-mode handler: applies a finite number and ignores the rest. */+export const useNumberCommit = (apply: (value: number) => void) =>+ useCallback(+ ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {+ if (Number.isFinite(valueAsNumber)) {+ apply(valueAsNumber);+ }+ },+ [apply]+ );++interface ToolbarSliderProps {+ 'aria-label': string;+ disabled?: boolean;+ formatValue?: (value: number) => string;+ getAriaValueText?: (value: number) => string;+ max: number;+ min: number;+ step?: number;+ value: number;+ onKeyDownCapture?: (event: KeyboardEvent<HTMLDivElement>) => void;+ onValueChange: (value: number) => void;+}++/** A slider that fills its region; pairs with a {@link ToolbarNumberField}. */+export const ToolbarSlider = ({+ 'aria-label': ariaLabel,+ disabled,+ formatValue,+ getAriaValueText,+ max,+ min,+ step,+ value,+ onKeyDownCapture,+ onValueChange,+}: ToolbarSliderProps) => {+ const labels = useMemo(() => [ariaLabel], [ariaLabel]);+ const values = useMemo(() => [value], [value]);+ const valueText = useMemo(+ () => (getAriaValueText ? ({ value: current }: { value: number }) => getAriaValueText(current) : undefined),+ [getAriaValueText]+ );+ const handleChange = useCallback(+ ({ value: next }: SliderValueChangeDetails) => {+ const first = next[0];+ if (first !== undefined && Number.isFinite(first)) {+ onValueChange(first);+ }+ },+ [onValueChange]+ );+ return (+ <Slider+ aria-label={labels}+ disabled={disabled}+ flex="1"+ formatValue={formatValue}+ getAriaValueText={valueText}+ max={max}+ min={min}+ minW="0"+ size="sm"+ step={step}+ value={values}+ onKeyDownCapture={onKeyDownCapture}+ onValueChange={handleChange}+ />+ );+};++/** Apply and Cancel for a pending operation, session or float, after whatever the owner shows about it. */+export const ToolbarStatus = ({+ applyDisabled = true,+ applyLoading = false,+ cancelDisabled = true,+ children,+ onApply,+ onCancel,+}: {+ applyDisabled?: boolean;+ applyLoading?: boolean;+ cancelDisabled?: boolean;+ children?: ReactNode;+ onApply?: () => void;+ onCancel?: () => void;+}) => {+ const { t } = useTranslation();+ return (+ <Flex align="center" gap="1" minW="0" w="full">+ <Box flex="1" minW="0" overflow="hidden" whiteSpace="nowrap">+ {children}+ </Box>+ <Button+ data-toolbar-action="apply"+ disabled={applyDisabled}+ flexShrink={0}+ loading={applyLoading}+ size="xs"+ variant="solid"+ onClick={onApply}+ >+ {t('common.apply')}+ </Button>+ <Button+ data-toolbar-action="cancel"+ disabled={cancelDisabled}+ flexShrink={0}+ size="xs"+ variant="ghost"+ onClick={onCancel}+ >+ {t('common.cancel')}+ </Button>+ </Flex>+ );+};++/** Muted guidance for tools and states without a control to show. */+export const ToolbarHint = ({ children }: { children: string }) => (+ <Text color="fg.muted" data-toolbar-hint="" fontSize="xs" minW="0">+ {children}+ </Text>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.tsnew file mode 100644index 0000000000..b780b28e9d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.test.ts@@ -0,0 +1,72 @@+import type { ToolId } from '@workbench/canvas-engine/api';++import { describe, expect, it } from 'vitest';++import { hasToolRegions, OPERATION_PRESENTATION_ADAPTERS, TOOL_PRESENTATION_ADAPTERS } from './toolAdapters';++const TOOL_IDS = Object.keys({+ bbox: true,+ brush: true,+ colorPicker: true,+ eraser: true,+ gradient: true,+ lasso: true,+ marquee: true,+ move: true,+ sam: true,+ shape: true,+ text: true,+ transform: true,+ view: true,+} satisfies Record<ToolId, true>) as ToolId[];++const englishCatalogModules = import.meta.glob('../../../../../public/locales/en.json', {+ eager: true,+ import: 'default',+});+const en = Object.values(englishCatalogModules)[0] as {+ widgets: {+ canvas: {+ toolHints: Record<string, string>;+ tools: Record<string, string>;+ };+ properties: { rows: Record<string, string>; sections: Record<string, string> };+ };+};++describe('tool presentation adapters', () => {+ it('registers every tool under its own id with a name in the English catalog', () => {+ for (const toolId of TOOL_IDS) {+ const adapter = TOOL_PRESENTATION_ADAPTERS[toolId];+ expect(adapter.id, toolId).toBe(toolId);+ expect(en.widgets.canvas.tools[toolId], toolId).toEqual(expect.any(String));+ }+ });++ it('hints exactly the tools without a control', () => {+ for (const toolId of TOOL_IDS) {+ const adapter = TOOL_PRESENTATION_ADAPTERS[toolId];+ if (hasToolRegions(adapter)) {+ expect(en.widgets.canvas.toolHints[toolId], toolId).toBeUndefined();+ } else {+ expect(en.widgets.canvas.toolHints[toolId], toolId).toEqual(expect.any(String));+ }+ }+ });++ it('names every Properties row and section in the catalog', () => {+ for (const row of ['geometry', 'intensity', 'color', 'modes', 'more']) {+ expect(en.widgets.properties.rows[row], row).toEqual(expect.any(String));+ }+ expect(en.widgets.properties.sections.tool).toEqual(expect.any(String));+ expect(en.widgets.properties.sections.operation).toEqual(expect.any(String));+ });++ it('gives both guarded operations a status region so Apply and Cancel stay in place', () => {+ expect(Object.keys(OPERATION_PRESENTATION_ADAPTERS).sort()).toEqual(['filter', 'select-object']);+ for (const adapter of Object.values(OPERATION_PRESENTATION_ADAPTERS)) {+ expect(adapter.status).toBeDefined();+ expect(adapter.modes).toBeDefined();+ }+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolAdapters.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.tssimilarity index 86%rename from invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolAdapters.tsrename to invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.tsindex e60b279ed5..523575fdd7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolAdapters.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolAdapters.ts@@ -12,31 +12,26 @@ import { selectObjectOperationAdapter } from '@workbench/widgets/canvas/tool-optimport { shapeAdapter } from '@workbench/widgets/canvas/tool-options/ShapeOptions';import { textAdapter } from '@workbench/widgets/canvas/tool-options/TextOptions';import { transformAdapter } from '@workbench/widgets/canvas/tool-options/TransformOptions';-import { HandIcon, PipetteIcon, ScanSearchIcon } from 'lucide-react';import type { CanvasOperationKind, OperationPresentationAdapter, ToolPresentationAdapter } from './toolbarContracts';/** Tools with no primary settings show their name and hint; the shell never unmounts for them. */-const hintOnly = (id: ToolId, icon: ToolPresentationAdapter['icon']): ToolPresentationAdapter => ({- icon,- id,- primary: null,-});+const hintOnly = (id: ToolId): ToolPresentationAdapter => ({ id });export const TOOL_PRESENTATION_ADAPTERS: Readonly<Record<ToolId, ToolPresentationAdapter>> = {bbox: bboxAdapter,brush: brushAdapter,- colorPicker: hintOnly('colorPicker', PipetteIcon),+ colorPicker: hintOnly('colorPicker'),eraser: eraserAdapter,gradient: gradientAdapter,lasso: lassoAdapter,marquee: marqueeAdapter,move: moveAdapter,- sam: hintOnly('sam', ScanSearchIcon),+ sam: hintOnly('sam'),shape: shapeAdapter,text: textAdapter,transform: transformAdapter,- view: hintOnly('view', HandIcon),+ view: hintOnly('view'),};export const OPERATION_PRESENTATION_ADAPTERS: Readonly<Record<CanvasOperationKind, OperationPresentationAdapter>> = {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarContracts.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolbarContracts.tssimilarity index 59%rename from invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarContracts.tsrename to invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolbarContracts.tsindex f4de95def6..d09c1976be 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/context-toolbar/toolbarContracts.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-presentation/toolbarContracts.ts@@ -3,8 +3,6 @@ import type { CanvasOperationState } from '@workbench/canvas-operations/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { ComponentType } from 'react';-import type { ToolbarRegionId, ToolbarRegionPlacement } from './toolbarLayout';-export type CanvasToolOptionsEngine = Pick<CanvasEngineHandle,'document' | 'interaction' | 'layers' | 'projectId' | 'selection' | 'tools' | 'viewport'@@ -12,52 +10,45 @@ export type CanvasToolOptionsEngine = Pick<export type CanvasOperationKind = Extract<CanvasOperationState, { status: 'active' }>['identity']['kind'];+export type ToolbarRegionId = 'geometry' | 'intensity' | 'color' | 'modes';+export interface ToolbarRegionProps {engine: CanvasToolOptionsEngine;/** Staging or generation owns the surface: mutating controls disable, Cancel stays. */isSurfaceInteractionLocked: boolean;- /** Inside the bar, or stacked inside the More menu when the bar is too narrow. */- placement: ToolbarRegionPlacement;}export interface ToolbarStatusProps {- compact: boolean;engine: CanvasToolOptionsEngine;isExternalInteractionLocked: boolean;}export type ToolbarRegionComponent = ComponentType<ToolbarRegionProps>;-/** The flexible modes region declares the bar width its content needs; the layout demotes it when that does not fit. */-export interface ToolbarModesRegion {- component: ToolbarRegionComponent;- width: number;-}-/**- * One tool's presentation in the context toolbar: which region each of its- * primary controls renders in, what only the More menu shows, and which region- * stays in the bar at every width. The adapter is a presentation seam over the- * engine's option stores and document transactions; it owns no state.+ * One tool's presentation: a component per region of its settings (geometry,+ * intensity, color, modes, and what only the full form shows), rendered by the+ * Properties widget. The adapter is a presentation seam over the engine's+ * option stores and document transactions; it owns no state.*/export interface ToolPresentationAdapter {id: ToolId;- icon: ComponentType;- primary: ToolbarRegionId | null;/** Paints into one leaf: a selected group gets the "select a layer" notice instead of strokes. */paintsLeaf?: boolean;+ /** Translation keys naming the rows where the generic region name would mislead (brush "Size", not "Geometry"). */+ rowLabels?: Partial<Record<ToolbarRegionId | 'more', string>>;geometry?: ToolbarRegionComponent;intensity?: ToolbarRegionComponent;color?: ToolbarRegionComponent;- modes?: ToolbarModesRegion;+ modes?: ToolbarRegionComponent;more?: ToolbarRegionComponent;status?: ComponentType<ToolbarStatusProps>;}-/** A guarded operation takes over the modes, More and status slots while it is active; the tool's own regions stay. */+/** A guarded operation's presentation: its inputs, its secondary controls and its status with Apply / Cancel. */export interface OperationPresentationAdapter {kind: CanvasOperationKind;- modes?: ToolbarModesRegion;+ modes?: ToolbarRegionComponent;more?: ToolbarRegionComponent;status: ComponentType<ToolbarStatusProps>;}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/properties/GroupSelectedNotice.tsx b/invokeai/frontend/webv2/src/workbench/widgets/properties/GroupSelectedNotice.tsxnew file mode 100644index 0000000000..67bdd057b0--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/properties/GroupSelectedNotice.tsx@@ -0,0 +1,42 @@+import { Flex, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui';+import { collectSubtreeLeaves, getDocumentNode } from '@workbench/canvas-engine/api';+import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++/** Leaf tools and editors cannot act on a group: name the way out instead of silently refusing. */+export const GroupSelectedNotice = ({ hint }: { hint?: string }) => {+ const { t } = useTranslation();+ const dispatch = useCanvasProjectMutationDispatch();+ const group = useActiveProjectSelector(+ (project) => {+ const { document } = project.canvas;+ const node = getDocumentNode(document, document.selectedLayerId);+ return node?.type === 'group' ? { firstLeafId: collectSubtreeLeaves(node)[0]?.id ?? null, id: node.id } : null;+ },+ (a, b) => a?.id === b?.id && a?.firstLeafId === b?.firstLeafId+ );+ const selectFirstLeaf = useCallback(() => {+ if (group?.firstLeafId) {+ dispatch({ id: group.firstLeafId, type: 'setCanvasSelectedLayer' });+ }+ }, [dispatch, group]);++ if (!group) {+ return null;+ }+ return (+ <Flex align="center" gap="2">+ <Text color="fg.muted" fontSize="xs" minW="0">+ {hint ?? t('widgets.layers.groupSelectedHint')}+ </Text>+ {group.firstLeafId ? (+ <Button flexShrink={0} size="2xs" variant="subtle" onClick={selectFirstLeaf}>+ {t('widgets.layers.actions.selectFirstChild')}+ </Button>+ ) : null}+ </Flex>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesSection.tsxnew file mode 100644index 0000000000..f02e294440--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesSection.tsx@@ -0,0 +1,59 @@+import type { ReactNode, Ref } from 'react';++import { Flex, Stack, Text } from '@chakra-ui/react';+import { FieldLabel } from '@platform/ui';++/** A headed group of rows in the Properties widget: Operation, Tool, Layer. */+export const PropertiesSection = ({+ children,+ disabled = false,+ ref,+ subtitle,+ title,+}: {+ children: ReactNode;+ /** The surface is busy elsewhere (staging, generation, an operation): the rows stay in place but cannot act. */+ disabled?: boolean;+ ref?: Ref<HTMLDivElement>;+ subtitle?: string;+ title: string;+}) => {+ return (+ <Stack+ ref={ref}+ aria-label={title}+ borderBottomWidth="1px"+ borderColor="border.subtle"+ gap="2"+ inert={disabled || undefined}+ opacity={disabled ? 0.5 : 1}+ px="3"+ py="2.5"+ role="group"+ >+ <Flex align="baseline" gap="2" minW="0">+ <FieldLabel>{title}</FieldLabel>+ {subtitle ? (+ <Text color="fg.muted" fontSize="xs" minW="0" truncate>+ {subtitle}+ </Text>+ ) : null}+ </Flex>+ {children}+ </Stack>+ );+};++/** One labelled row: a fixed label column and the controls packed after it, wrapping when the dock is narrow. */+export const PropertiesRow = ({ children, label }: { children: ReactNode; label: string }) => (+ <Flex align="flex-start" gap="2" minW="0">+ <Flex align="center" flexShrink={0} minH="8" w="20">+ <Text color="fg.muted" fontSize="xs">+ {label}+ </Text>+ </Flex>+ <Flex align="center" flex="1" flexWrap="wrap" gap="2" minH="8" minW="0">+ {children}+ </Flex>+ </Flex>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesWidgetView.tsxnew file mode 100644index 0000000000..a171ec97d3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesWidgetView.tsx@@ -0,0 +1,129 @@+import type { WidgetViewProps } from '@workbench/widgetContracts';++import { Flex, Stack, Text } from '@chakra-ui/react';+import { Scrollable } from '@platform/ui';+import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';+import { useCanvasActiveTool, useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';+import {+ hasToolRegions,+ OPERATION_PRESENTATION_ADAPTERS,+ TOOL_PRESENTATION_ADAPTERS,+} from '@workbench/widgets/canvas/tool-presentation/toolAdapters';+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useLayoutEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import { GroupSelectedNotice } from './GroupSelectedNotice';+import { PropertiesRow, PropertiesSection } from './PropertiesSection';++const REGION_LABEL_KEYS = {+ color: 'widgets.properties.rows.color',+ geometry: 'widgets.properties.rows.geometry',+ intensity: 'widgets.properties.rows.intensity',+ modes: 'widgets.properties.rows.modes',+ more: 'widgets.properties.rows.more',+} as const;++/**+ * Full editors for what the canvas is doing: the running operation first, then+ * the active tool's settings. Reads and writes the engine's option stores and+ * document transactions through the same adapters the canvas registers; it+ * mirrors no state of its own.+ */+export const PropertiesWidgetView = (_props: WidgetViewProps) => {+ const { t } = useTranslation();+ const engine = useCanvasEngine();+ const isSurfaceInteractionLocked = useActiveProjectSelector((project) =>+ isCanvasInteractionLocked(project.canvas, project.queue.items)+ );++ if (!engine) {+ return (+ <Flex align="center" color="fg.muted" fontSize="xs" h="full" justify="center" p="4">+ {t('widgets.properties.noCanvas')}+ </Flex>+ );+ }++ return (+ <Scrollable h="full">+ <ConnectedProperties engine={engine} isSurfaceInteractionLocked={isSurfaceInteractionLocked} />+ </Scrollable>+ );+};++const ConnectedProperties = ({+ engine,+ isSurfaceInteractionLocked,+}: {+ engine: CanvasEngineHandle;+ isSurfaceInteractionLocked: boolean;+}) => {+ const { t } = useTranslation();+ const activeTool = useCanvasActiveTool(engine);+ const operation = useCanvasOperation(engine);+ const running = operation.status === 'active' ? OPERATION_PRESENTATION_ADAPTERS[operation.identity.kind] : null;+ const tool = TOOL_PRESENTATION_ADAPTERS[activeTool];+ const toolName = t(`widgets.canvas.tools.${tool.id}`);+ const ToolStatus = tool.status;+ const regionProps = { engine, isSurfaceInteractionLocked };+ const rows = (+ [+ ['geometry', tool.geometry],+ ['intensity', tool.intensity],+ ['color', tool.color],+ ['modes', tool.modes],+ ['more', tool.more],+ ] as const+ ).filter((entry): entry is [keyof typeof REGION_LABEL_KEYS, NonNullable<(typeof entry)[1]>] => !!entry[1]);++ // `inert` will blur a focused tool control once an operation starts; hand focus to the operation's Cancel first.+ const root = useRef<HTMLDivElement>(null);+ const toolSection = useRef<HTMLDivElement>(null);+ useLayoutEffect(() => {+ if (running && toolSection.current?.contains(document.activeElement)) {+ root.current?.querySelector<HTMLElement>('[data-toolbar-action="cancel"]')?.focus();+ }+ }, [running]);++ return (+ <Stack ref={root} gap="0">+ {running ? (+ <PropertiesSection+ subtitle={t(+ running.kind === 'filter' ? 'widgets.layers.rasterFilter.title' : 'widgets.layers.selectObject.title'+ )}+ title={t('widgets.properties.sections.operation')}+ >+ {running.modes ? <running.modes {...regionProps} /> : null}+ {running.more ? <running.more {...regionProps} /> : null}+ <running.status engine={engine} isExternalInteractionLocked={isSurfaceInteractionLocked} />+ </PropertiesSection>+ ) : null}+ <PropertiesSection+ ref={toolSection}+ disabled={isSurfaceInteractionLocked || running !== null}+ subtitle={toolName}+ title={t('widgets.properties.sections.tool')}+ >+ {tool.paintsLeaf && !running ? <GroupSelectedNotice /> : null}+ {hasToolRegions(tool) ? (+ rows.map(([region, Region]) => (+ <PropertiesRow+ key={`${tool.id}:${region}`}+ label={t(tool.rowLabels?.[region] ?? REGION_LABEL_KEYS[region])}+ >+ <Region {...regionProps} />+ </PropertiesRow>+ ))+ ) : (+ <Text color="fg.muted" fontSize="xs">+ {t(`widgets.canvas.toolHints.${tool.id}`)}+ </Text>+ )}+ {ToolStatus ? <ToolStatus engine={engine} isExternalInteractionLocked={isSurfaceInteractionLocked} /> : null}+ </PropertiesSection>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesWidgets.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesWidgets.browser.test.tsxnew file mode 100644index 0000000000..abb91ccac8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/properties/PropertiesWidgets.browser.test.tsx@@ -0,0 +1,297 @@+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */+import type { CanvasOperationState } from '@workbench/canvas-operations/api';+import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';+import type { FilterOperationSessionState } from '@workbench/canvas-operations/filterOperationSession';+import type { CanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';+import type { Project } from '@workbench/projectContracts';+import type { WidgetViewProps } from '@workbench/widgetContracts';++import { ChakraProvider } from '@chakra-ui/react';+import { system } from '@theme/system';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import {+ createEngineRegistry,+ type EngineDeps,+ type EngineRegistry,+} from '@workbench/canvas-operations/engineRegistry';+import { attachCanvasOperations } from '@workbench/canvas-operations/operationAccess';+import { createEmptyCanvasDocument, createEmptyCanvasState } from '@workbench/canvasMigration';+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';+import { createInitialWorkbenchState } from '@workbench/workbenchState';+import { createInstance } from 'i18next';+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { I18nextProvider } from 'react-i18next';+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';+import { page, userEvent } from 'vitest/browser';++const harness = vi.hoisted(() => ({ engine: null as unknown, project: null as Project | null }));++vi.mock('@workbench/WorkbenchContext', () => ({+ useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project!),+ useOptionalWorkbenchCommands: () => null,+}));+vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({+ useCanvasProjectMutationDispatch: () => () => true,+}));+vi.mock('@workbench/widgets/canvas/useCanvasEngine', () => ({ useCanvasEngine: () => harness.engine }));++import { TransformWidgetView } from '@workbench/widgets/transform/TransformWidgetView';++import { PropertiesWidgetView } from './PropertiesWidgetView';++const i18n = createInstance();+beforeAll(async () => {+ const translation = (await (await fetch('/locales/en.json')).json()) as Record<string, unknown>;+ await i18n.init({ initAsync: false, lng: 'en', resources: { en: { translation } } });+});++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++/** The engine reads the harness project's canvas, so document edits resolve against the layers the views show. */+const createEngineDeps = (): EngineDeps => {+ const mutationPort: CanvasProjectMutationPort = {+ commitEdit: () => undefined,+ dispatch: () => false,+ getCanvasState: () => harness.project?.canvas ?? createEmptyCanvasState(64, 64),+ subscribe: () => () => undefined,+ };+ return {+ getMainModelBase: () => null,+ imageResolver: () => Promise.resolve(new Blob()),+ mutationPort,+ reportError: () => undefined,+ };+};++const filterSession = (): FilterOperationSessionState => ({+ autoProcess: true,+ draft: { settings: { high_threshold: 200, low_threshold: 100 }, type: 'canny_edge_detection' },+ error: null,+ initialFilter: null,+ layerId: 'layer-1',+ layerName: 'Portrait',+ layerType: 'raster',+ preview: null,+ status: 'ready',+});++const createFakeOperations = () => {+ const listeners = new Set<() => void>();+ const subscribe = (listener: () => void) => {+ listeners.add(listener);+ return () => listeners.delete(listener);+ };+ let filter: FilterOperationSessionState | null = null;+ let state: CanvasOperationState = { status: 'idle' };+ return {+ cancelFilterOperation: vi.fn(),+ commitFilterOperation: vi.fn(),+ getFilterSessionState: () => filter,+ getOperationState: () => state,+ getSamSessionState: () => null,+ processFilterOperation: vi.fn(),+ resetFilterOperation: vi.fn(),+ setFilterOperationAutoProcess: vi.fn(),+ start: (running: boolean) => {+ filter = running ? filterSession() : null;+ state = running+ ? {+ error: null,+ identity: { kind: 'filter', layerId: 'layer-1', projectId: 'p' },+ phase: 'ready',+ status: 'active',+ }+ : { status: 'idle' };+ listeners.forEach((listener) => listener());+ },+ subscribeFilterSession: subscribe,+ subscribeOperation: subscribe,+ subscribeSamSession: subscribe,+ updateFilterOperation: vi.fn(),+ };+};++let host: HTMLDivElement | null = null;+let root: Root | null = null;+let registry: EngineRegistry | null = null;+let engine: CanvasEngine | null = null;+let operations: ReturnType<typeof createFakeOperations> | null = null;++const settle = () =>+ act(+ () =>+ new Promise<void>((resolve) => {+ requestAnimationFrame(() => requestAnimationFrame(() => resolve()));+ })+ );++const viewProps = {} as WidgetViewProps;+const IDENTITY = { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 };++type Selection = 'none' | 'layer' | 'group';++const mount = async (View: typeof PropertiesWidgetView, selection: Selection = 'none') => {+ const base = { ...createInitialWorkbenchState().projects[0]!, id: 'p' };+ const nodes =+ selection === 'none'+ ? []+ : selection === 'layer'+ ? [layerContract('l0', 'raster', { name: 'Paint', transform: { ...IDENTITY, rotation: 0.5, x: 10.4 } })]+ : [groupContract('g0', [layerContract('l0', 'raster', { name: 'Paint' })], { name: 'Folder' })];+ harness.project = applyCanvasProjectMutation(base, {+ document: {+ ...createEmptyCanvasDocument(),+ selectedLayerId: selection === 'none' ? null : selection === 'layer' ? 'l0' : 'g0',+ stacks: stacksFrom(nodes),+ },+ type: 'replaceCanvasDocument',+ });+ host = document.createElement('div');+ host.style.cssText = 'width:450px;height:600px;';+ document.body.append(host);+ root = createRoot(host);+ registry = createEngineRegistry({ gracePeriodMs: 0 });+ engine = registry.getOrCreateEngine('p', createEngineDeps());+ operations = createFakeOperations();+ attachCanvasOperations(engine, operations as never);+ harness.engine = engine;+ await act(() => {+ root?.render(+ <I18nextProvider i18n={i18n}>+ <ChakraProvider value={system}>+ <View {...viewProps} />+ </ChakraProvider>+ </I18nextProvider>+ );+ });+ await settle();+};++afterEach(async () => {+ await act(() => root?.unmount());+ host?.remove();+ registry?.releaseEngine('p');+ host = null;+ root = null;+ registry = null;+ engine = null;+ harness.engine = null;+});++describe('Properties widget', () => {+ it('shows the active tool as labelled rows and swaps them with the tool', async () => {+ await mount(PropertiesWidgetView);+ await act(() => engine!.tools.setTool('brush'));+ await settle();+ expect(host!.textContent).toContain('Brush');+ await expect.element(page.getByRole('slider', { exact: true, name: 'Brush size' })).toBeVisible();+ await expect.element(page.getByRole('slider', { exact: true, name: 'Opacity' })).toBeVisible();+ await expect.element(page.getByRole('button', { exact: true, name: 'Brush color' })).toBeVisible();+ await expect.element(page.getByRole('button', { exact: true, name: 'Pen pressure affects width' })).toBeVisible();++ await act(() => engine!.tools.setTool('view'));+ await settle();+ expect(page.getByRole('slider', { exact: true, name: 'Brush size' }).query()).toBeNull();+ expect(host!.textContent).toContain('Drag to pan and scroll to zoom.');+ });++ it('puts a running operation first with Cancel, locks the tool rows in place and hands them focus over', async () => {+ await mount(PropertiesWidgetView);+ await act(() => engine!.tools.setTool('brush'));+ await settle();+ await act(() => page.getByRole('slider', { exact: true, name: 'Brush size' }).element().focus());+ await act(() => operations!.start(true));+ await settle();+ expect(host!.textContent?.indexOf('Operation')).toBeLessThan(host!.textContent?.indexOf('Tool') ?? -1);+ const cancel = page.getByRole('button', { exact: true, name: 'Cancel' });+ await expect.element(cancel).toBeEnabled();+ await expect.element(page.getByRole('button', { exact: true, name: 'Apply' })).toBeDisabled();+ expect(document.activeElement).toBe(cancel.element());+ expect(host!.querySelector('[role="group"][inert]')?.getAttribute('aria-label')).toBe('Tool');+ await act(() => operations!.start(false));+ await settle();+ expect(host!.querySelector('[inert]')).toBeNull();+ });+});++describe('Transform widget', () => {+ it('disables its fields with nothing selected and commits one patch per field for a selected layer', async () => {+ await mount(TransformWidgetView);+ expect(host!.textContent).toContain('No layer selected');+ await expect.element(page.getByRole('spinbutton', { exact: true, name: 'X' })).toBeDisabled();++ await act(() => root?.unmount());+ host?.remove();+ registry?.releaseEngine('p');+ await mount(TransformWidgetView, 'layer');+ const commit = vi.spyOn(engine!.layers, 'commitPrepared');+ const x = page.getByRole('spinbutton', { exact: true, name: 'X' });+ await expect.element(x).toBeEnabled();+ await expect.element(x).toHaveValue('10');+ await act(async () => {+ await userEvent.click(x);+ await userEvent.tab();+ await userEvent.tab();+ });+ expect(commit, 'focus and blur must not commit the rounded display over 10.4').not.toHaveBeenCalled();+ await act(async () => {+ await userEvent.fill(x, '40');+ await userEvent.keyboard('{Enter}');+ });+ expect(commit).toHaveBeenCalledTimes(1);+ expect(commit.mock.calls[0]?.[1]).toMatchObject({ forward: expect.anything() });+ expect(host!.textContent).toContain('Paint');+ expect(page.getByRole('button', { exact: true, name: 'Apply' }).query()).toBeNull();+ });++ it('wraps rotation into a half turn and names a selected group instead of editing it', async () => {+ await mount(TransformWidgetView, 'layer');+ const commit = vi.spyOn(engine!.layers, 'commitPrepared');+ const rotation = page.getByRole('spinbutton', { exact: true, name: 'Rotation' });+ await expect.element(rotation).toHaveValue('28.65');+ await act(async () => {+ await userEvent.fill(rotation, '270');+ await userEvent.keyboard('{Enter}');+ });+ expect(commit).toHaveBeenCalledTimes(1);+ expect(JSON.stringify(commit.mock.calls[0]?.[1])).toContain(String(-Math.PI / 2));++ await act(() => root?.unmount());+ host?.remove();+ registry?.releaseEngine('p');+ await mount(TransformWidgetView, 'group');+ expect(host!.textContent).toContain('Folder');+ expect(host!.textContent).toContain('Select a layer inside this group to transform.');+ await expect.element(page.getByRole('spinbutton', { exact: true, name: 'X' })).toBeDisabled();+ });++ it('scrubs a field from its label and commits the result once when the mouse button lifts', async () => {+ await mount(TransformWidgetView, 'layer');+ // The scrubber locks the pointer once a real click has activated the page; the harness lock steals focus.+ vi.spyOn(Element.prototype, 'requestPointerLock').mockImplementation(() => Promise.resolve());+ const commit = vi.spyOn(engine!.layers, 'commitPrepared');+ const scrubber = host!.querySelector<HTMLElement>('[data-scope="number-input"][data-part="scrubber"]')!;+ const x = page.getByRole('spinbutton', { exact: true, name: 'X' });+ await act(() =>+ scrubber.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 100, clientY: 100 }))+ );+ for (let step = 1; step <= 5; step += 1) {+ await act(() =>+ document.dispatchEvent(+ new MouseEvent('mousemove', { bubbles: true, clientX: 100 + step * 4, clientY: 100, movementX: 4 })+ )+ );+ }+ await expect.element(x).toHaveValue('15');+ expect(commit).not.toHaveBeenCalled();+ await act(() =>+ document.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 120, clientY: 100 }))+ );+ expect(commit).toHaveBeenCalledTimes(1);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/properties/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/properties/implementation.tsnew file mode 100644index 0000000000..a5b2b5baca--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/properties/implementation.ts@@ -0,0 +1,7 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { PropertiesWidgetView } from './PropertiesWidgetView';++export const widgetImplementation = {+ view: PropertiesWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/properties/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/properties/manifest.tsnew file mode 100644index 0000000000..02dbfb2012--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/properties/manifest.ts@@ -0,0 +1,15 @@+import type { WidgetManifest } from '@workbench/widgetContracts';++import { SlidersHorizontalIcon } from 'lucide-react';++export const propertiesWidgetManifest: WidgetManifest = {+ allowMultiple: false,+ allowedRegions: ['right'],+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },+ icon: SlidersHorizontalIcon,+ id: 'properties',+ label: (t) => t('widgets.labels.properties'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),+ rightDock: 'rightBottom',+ version: 1,+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/transform/TransformWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/transform/TransformWidgetView.tsxnew file mode 100644index 0000000000..7de5e30f39--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/transform/TransformWidgetView.tsx@@ -0,0 +1,184 @@+import type { LayerTransform } from '@workbench/canvas-engine/api';+import type { WidgetViewProps } from '@workbench/widgetContracts';++import { Flex, Stack, Text } from '@chakra-ui/react';+import { Button } from '@platform/ui';+import { getDocumentNode, lookupDocumentLeaf } from '@workbench/canvas-engine/api';+import { useCanvasHasFloatingSelection, useTransformSession } from '@workbench/widgets/canvas/engineStoreHooks';+import { ToolbarNumberField, useNumberCommit } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';+import { useCanvasEngine, type CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { GroupSelectedNotice } from '@workbench/widgets/properties/GroupSelectedNotice';+import { PropertiesRow, PropertiesSection } from '@workbench/widgets/properties/PropertiesSection';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';+import { useTranslation } from 'react-i18next';++const RAD_TO_DEG = 180 / Math.PI;+const DEG_TO_RAD = Math.PI / 180;+const MIN_SCALE_PERCENT = 1;+const round2 = (n: number): number => Math.round(n * 100) / 100;+/** Degrees in (-180, 180], so 270 reads and stores as -90. */+const wrapDegrees = (degrees: number): number => {+ const wrapped = ((((degrees + 180) % 360) + 360) % 360) - 180;+ return wrapped === -180 ? 180 : wrapped;+};+/** A flip is a negative scale; a zero or near-zero one is not a transform anyone can undo by eye. */+const clampScalePercent = (percent: number): number =>+ percent < 0 ? Math.min(percent, -MIN_SCALE_PERCENT) : Math.max(percent, MIN_SCALE_PERCENT);++interface SelectedNode {+ id: string;+ isGroup: boolean;+ locked: boolean;+ name: string;+ transform: LayerTransform | null;+}++/**+ * The selected layer's transform, editable without picking a tool: each field+ * commits one undoable document patch. While the Transform tool holds a+ * session, the same fields drive its preview and Apply / Cancel land or drop+ * it; a floating selection offers Apply / Cancel alone, since its transform is+ * layer-local rather than document space.+ */+export const TransformWidgetView = (_props: WidgetViewProps) => {+ const { t } = useTranslation();+ const engine = useCanvasEngine();++ if (!engine) {+ return (+ <Flex align="center" color="fg.muted" fontSize="xs" h="full" justify="center" p="4">+ {t('widgets.properties.noCanvas')}+ </Flex>+ );+ }+ return <ConnectedTransform engine={engine} />;+};++const ConnectedTransform = ({ engine }: { engine: CanvasEngineHandle }) => {+ const { t } = useTranslation();+ const commitPrepared = usePreparedCommit(engine);+ const session = useTransformSession(engine);+ const hasFloat = useCanvasHasFloatingSelection(engine);+ const selected = useActiveProjectSelector(+ (project): SelectedNode | null => {+ const { document } = project.canvas;+ const node = getDocumentNode(document, document.selectedLayerId);+ if (node?.type === 'group') {+ return { id: node.id, isGroup: true, locked: true, name: node.name, transform: null };+ }+ const leaf = node ? lookupDocumentLeaf(document, node.id) : null;+ return leaf+ ? {+ id: leaf.id,+ isGroup: false,+ locked: leaf.effectiveLocked,+ name: leaf.layer.name,+ transform: leaf.layer.transform,+ }+ : null;+ },+ (a, b) => a?.id === b?.id && a?.locked === b?.locked && a?.name === b?.name && a?.transform === b?.transform+ );++ const transform = session?.transform ?? selected?.transform ?? null;+ const editable = session !== null || (selected !== null && !selected.locked);+ const patch = useCallback(+ (next: Partial<LayerTransform>) => {+ if (session) {+ engine.layers.updateTransformSession({ ...session.transform, ...next });+ return;+ }+ if (!selected || selected.locked) {+ return;+ }+ commitPrepared(t('widgets.transform.edit'), (model) =>+ model.prepare({ id: selected.id, patch: { transform: next }, type: 'patch' })+ );+ },+ [commitPrepared, engine, selected, session, t]+ );+ const onX = useNumberCommit(useCallback((value: number) => patch({ x: Math.round(value) }), [patch]));+ const onY = useNumberCommit(useCallback((value: number) => patch({ y: Math.round(value) }), [patch]));+ const onScaleX = useNumberCommit(+ useCallback((value: number) => patch({ scaleX: clampScalePercent(value) / 100 }), [patch])+ );+ const onScaleY = useNumberCommit(+ useCallback((value: number) => patch({ scaleY: clampScalePercent(value) / 100 }), [patch])+ );+ const onRotation = useNumberCommit(+ useCallback((value: number) => patch({ rotation: wrapDegrees(value) * DEG_TO_RAD }), [patch])+ );+ const onApply = useCallback(() => engine.layers.applyTransform(), [engine]);+ const onCancel = useCallback(() => engine.layers.cancelTransform(), [engine]);+ const pending = session !== null || hasFloat;+ const field = (props: Omit<Parameters<typeof ToolbarNumberField>[0], 'disabled'>) => (+ <ToolbarNumberField {...props} disabled={!editable} />+ );++ return (+ <Stack gap="0">+ <PropertiesSection+ // A draft typed for one layer must not commit to the next selection.+ key={session ? 'session' : (selected?.id ?? '')}+ subtitle={session ? t('widgets.transform.session') : (selected?.name ?? t('widgets.transform.noSelection'))}+ title={t('widgets.transform.title')}+ >+ {selected?.isGroup && !session ? <GroupSelectedNotice hint={t('widgets.transform.groupSelected')} /> : null}+ <PropertiesRow label={t('widgets.transform.position')}>+ {field({+ 'aria-label': t('widgets.canvas.toolOptions.positionX'),+ label: t('widgets.canvas.toolOptions.positionX'),+ value: transform ? String(Math.round(transform.x)) : '',+ onValueCommit: onX,+ })}+ {field({+ 'aria-label': t('widgets.canvas.toolOptions.positionY'),+ label: t('widgets.canvas.toolOptions.positionY'),+ value: transform ? String(Math.round(transform.y)) : '',+ onValueCommit: onY,+ })}+ </PropertiesRow>+ <PropertiesRow label={t('widgets.transform.scale')}>+ {field({+ 'aria-label': t('widgets.canvas.toolOptions.scaleWidth'),+ label: t('widgets.canvas.toolOptions.frameWidth'),+ suffix: '%',+ value: transform ? String(round2(transform.scaleX * 100)) : '',+ onValueCommit: onScaleX,+ })}+ {field({+ 'aria-label': t('widgets.canvas.toolOptions.scaleHeight'),+ label: t('widgets.canvas.toolOptions.frameHeight'),+ suffix: '%',+ value: transform ? String(round2(transform.scaleY * 100)) : '',+ onValueCommit: onScaleY,+ })}+ </PropertiesRow>+ <PropertiesRow label={t('widgets.transform.rotation')}>+ {field({+ 'aria-label': t('widgets.canvas.toolOptions.rotation'),+ suffix: '°',+ value: transform ? String(round2(wrapDegrees(transform.rotation * RAD_TO_DEG))) : '',+ onValueCommit: onRotation,+ })}+ </PropertiesRow>+ {pending ? (+ <Flex gap="2" justify="flex-end">+ <Button size="xs" variant="ghost" onClick={onCancel}>+ {t('common.cancel')}+ </Button>+ <Button size="xs" onClick={onApply}>+ {t('common.apply')}+ </Button>+ </Flex>+ ) : (+ <Text color="fg.subtle" fontSize="2xs">+ {t('widgets.transform.hint')}+ </Text>+ )}+ </PropertiesSection>+ </Stack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/transform/implementation.ts b/invokeai/frontend/webv2/src/workbench/widgets/transform/implementation.tsnew file mode 100644index 0000000000..ffb8dda430--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/transform/implementation.ts@@ -0,0 +1,7 @@+import type { WidgetImplementation } from '@workbench/widgetContracts';++import { TransformWidgetView } from './TransformWidgetView';++export const widgetImplementation = {+ view: TransformWidgetView,+} satisfies WidgetImplementation;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/transform/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/transform/manifest.tsnew file mode 100644index 0000000000..b94d334fdd--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/transform/manifest.ts@@ -0,0 +1,15 @@+import type { WidgetManifest } from '@workbench/widgetContracts';++import { Rotate3dIcon } from 'lucide-react';++export const transformWidgetManifest: WidgetManifest = {+ allowMultiple: false,+ allowedRegions: ['right'],+ failurePolicy: { isolateRenderFailure: true, onRegistrationFailure: 'disable' },+ icon: Rotate3dIcon,+ id: 'transform',+ label: (t) => t('widgets.labels.transform'),+ load: () => import('./implementation').then((module) => module.widgetImplementation),+ rightDock: 'rightBottom',+ version: 1,+};diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 513e94e655..7b70780cfe 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -555,7 +555,7 @@ describe('workbench widget region defaults', () => {}});- it('moves Image Map into the bottom dock for an untouched pre-dock Edit rail and leaves other rails alone', () => {+ it('adds the bottom dock to an untouched pre-dock Edit rail and leaves other rails alone', () => {const initial = createInitialWorkbenchState();const preDock = (instanceIds: Project['widgetRegions']['right']['instanceIds']): WorkbenchState => ({...initial,@@ -574,12 +574,20 @@ describe('workbench widget region defaults', () => {const custom = preDock(['image-map', 'layers']);const hydratedEdit = getActiveProject(workbenchReducer(initial, { state: editRail, type: 'hydrateWorkbench' }));- expect(hydratedEdit.widgetRegions.right.instanceIds).toEqual(['layers', 'preview', 'gallery', 'queue']);+ expect(hydratedEdit.widgetRegions.right.instanceIds).toEqual([+ 'layers',+ 'preview',+ 'gallery',+ 'image-map',+ 'queue',+ ]);expect(hydratedEdit.widgetRegions.rightBottom).toMatchObject({- activeInstanceId: 'image-map',- instanceIds: ['image-map'],+ activeInstanceId: 'properties',+ instanceIds: ['properties', 'transform'],isCollapsed: false,});+ expect(hydratedEdit.widgetInstances.properties?.typeId).toBe('properties');+ expect(hydratedEdit.widgetInstances.transform?.typeId).toBe('transform');expect(hydratedEdit.widgetRegions.rightTop).toMatchObject({ instanceIds: [], isCollapsed: true });const hydratedCustom = getActiveProject(workbenchReducer(initial, { state: custom, type: 'hydrateWorkbench' }));diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 68f8f299a8..ca61c4b43d 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -1437,7 +1437,7 @@ const ensureRightRegion = (rightRegion: WidgetRegionState | undefined): WidgetRereturn rightRegion;};-/** The Edit rail as it shipped before the right rail had docks; Image Map now lives in the bottom dock. */+/** The Edit rail as it shipped before the right rail had docks; the bottom dock (Properties, Transform) joins it. */const PRE_DOCK_EDIT_RIGHT_REGION_WIDGET_IDS: readonly WidgetInstanceId[] = ['layers','preview',@@ -1446,11 +1446,12 @@ const PRE_DOCK_EDIT_RIGHT_REGION_WIDGET_IDS: readonly WidgetInstanceId[] = ['queue',];-/**- * Projects persisted before the right rail had docks carry none. An untouched- * pre-dock Edit rail adopts the shipped docks (Image Map moves to the bottom- * one); anything else gets empty, collapsed docks and keeps its rail as is.- */+/** One unreleased build docked Image Map alone at the bottom; that rail becomes the shipped one too. */+const INTERIM_EDIT_RIGHT_REGION_WIDGET_IDS: readonly WidgetInstanceId[] = ['layers', 'preview', 'gallery', 'queue'];++const sameInstanceIds = (region: WidgetRegionState, ids: readonly WidgetInstanceId[]): boolean =>+ region.instanceIds.length === ids.length && region.instanceIds.every((id, index) => id === ids[index]);+const isDockShape = (value: unknown): value is WidgetRegionState =>!!value &&typeof value === 'object' &&@@ -1459,43 +1460,41 @@ const isDockShape = (value: unknown): value is WidgetRegionState =>typeof (value as WidgetRegionState).isCollapsed === 'boolean' &&typeof (value as WidgetRegionState).sizePx === 'number';+/**+ * Projects persisted before the right rail had docks carry none, and one+ * unreleased build docked Image Map alone. An untouched rail of either shape+ * adopts the shipped Edit docks; anything else gets empty, collapsed docks for+ * the ones it lacks and keeps its rail as is.+ */const ensureRightRailDocks = (regions: Partial<Record<WidgetRegion, WidgetRegionState>> | undefined,right: WidgetRegionState-): {- docks: Pick<Record<WidgetRegion, WidgetRegionState>, 'right' | 'rightTop' | 'rightBottom'>;- /** Instances the migration moved from `right` into `rightBottom`. */- movedToBottom: readonly WidgetInstanceId[];-} => {+): Pick<Record<WidgetRegion, WidgetRegionState>, 'right' | 'rightTop' | 'rightBottom'> => {const dock = (name: 'rightTop' | 'rightBottom'): WidgetRegionState =>isDockShape(regions?.[name]) ? regions[name] : { ...EMPTY_DOCK_REGION, sizePx: createWidgetRegions()[name].sizePx };+ const top = dock('rightTop');+ const bottom = dock('rightBottom');const isPreDock = regions?.rightTop === undefined && regions?.rightBottom === undefined;- const isPreDockEditRail =- right.instanceIds.length === PRE_DOCK_EDIT_RIGHT_REGION_WIDGET_IDS.length &&- right.instanceIds.every((id, index) => id === PRE_DOCK_EDIT_RIGHT_REGION_WIDGET_IDS[index]);+ const isInterim =+ top.instanceIds.length === 0 &&+ sameInstanceIds(bottom, ['image-map']) &&+ sameInstanceIds(right, INTERIM_EDIT_RIGHT_REGION_WIDGET_IDS);- if (isPreDock && isPreDockEditRail) {+ if ((isPreDock && sameInstanceIds(right, PRE_DOCK_EDIT_RIGHT_REGION_WIDGET_IDS)) || isInterim) {const edit = getLayoutPreset('edit').snapshot.widgetRegions;return {- docks: {- right: {- ...right,- activeInstanceId: right.activeInstanceId === 'image-map' ? 'layers' : right.activeInstanceId,- instanceIds: [...edit.right.instanceIds],- },- // A rail the user had shut stays shut; the new dock opens with it.- rightBottom: {- ...edit.rightBottom,- instanceIds: [...edit.rightBottom.instanceIds],- isCollapsed: right.isCollapsed,- },- rightTop: dock('rightTop'),+ right: { ...right, instanceIds: [...edit.right.instanceIds] },+ // A rail the user had shut stays shut; the new dock opens with it.+ rightBottom: {+ ...edit.rightBottom,+ instanceIds: [...edit.rightBottom.instanceIds],+ isCollapsed: right.isCollapsed,},- movedToBottom: edit.rightBottom.instanceIds,+ rightTop: top,};}- return { docks: { right, rightBottom: dock('rightBottom'), rightTop: dock('rightTop') }, movedToBottom: [] };+ return { right, rightBottom: bottom, rightTop: top };};// The shipped bottom-region default before 'queue-status' was added — a@@ -1818,26 +1817,23 @@ const assembleWorkbenchProject = (project: Project, canvas: CanvasStateContractVlegacyWidgetRegions,ensureRightRegion(legacyWidgetRegions?.right ?? legacyWidgetRegions?.['right-panel']));- const floatingWidgets = normalizeFloatingWidgets((project as Partial<Project>).floatingWidgets, widgetInstances);- // A window floated out of the old rail docks back where the migration now keeps its widget.- const rehomedFloating = floatingWidgets- ? Object.fromEntries(- Object.entries(floatingWidgets).map(([instanceId, floating]) => [- instanceId,- rail.movedToBottom.includes(instanceId) && floating.returnRegion === 'right'- ? { ...floating, returnRegion: 'rightBottom' as const }- : floating,- ])- )- : floatingWidgets;+ // The bottom dock's widgets are new to a migrated project; every dock member needs an instance to render.+ const editInstances = getLayoutPreset('edit').snapshot.widgetInstances;+ for (const instanceId of rail.rightBottom.instanceIds) {+ const typeId = editInstances[instanceId]?.typeId;+ if (!widgetInstances[instanceId] && typeId) {+ widgetInstances[instanceId] = createWidgetInstance(typeId, instanceId);+ }+ }+const placement = reconcileFloatingWidgets({left: leftRegion,- ...rail.docks,+ ...rail,bottom: bottomRegion,center: ensureCenterRegion(legacyWidgetRegions?.center, project.layout.centerViewId),},- rehomedFloating+ normalizeFloatingWidgets((project as Partial<Project>).floatingWidgets, widgetInstances));return {