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(layers): tree panel with groups
Josh Corbett7bb25779ed55
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex 1c80ba2103..e14b969bc7 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -2197,7 +2197,9 @@"selectTransformTool": "Select transform tool","selectViewTool": "Select view tool","toggleNonRasterLayers": "Hide control, guidance and mask layers",- "undo": "Undo canvas edit"+ "undo": "Undo canvas edit",+ "groupLayers": "Group selected layers",+ "ungroupLayers": "Ungroup selected layers"},"contextMenu": {"createError": "Couldn't create from BBox",@@ -2308,7 +2310,11 @@"reverted": "The edit could not be verified and was reverted.","stale": "The canvas changed before this edit landed. Try again.","unmirrored": "The edit was reverted, but the canvas view may be out of date.",- "unverified": "The edit could not be verified or reverted. Check the canvas before continuing."+ "unverified": "The edit could not be verified or reverted. Check the canvas before continuing.",+ "refusedNotSiblings": "Only items that share the same group can be grouped together.",+ "refusedDepth": "Groups can nest at most 10 levels deep.",+ "refusedCycle": "A group can't be moved into itself.",+ "refusedNodeLimit": "The canvas can't hold more than 10,000 layers and groups."},"surface": "Canvas surface","toolHints": {@@ -2537,7 +2543,18 @@"transform": "Transform","unsupported": "This action is not supported for this layer.","unlock": "Unlock layer",- "unlockSelected": "Unlock selected layers"+ "unlockSelected": "Unlock selected layers",+ "group": "Group layers",+ "groupSelected": "Group selected layers",+ "ungroup": "Ungroup",+ "ungroupSelected": "Ungroup selected groups",+ "newGroup": "New group",+ "expandGroup": "Expand group",+ "collapseGroup": "Collapse group",+ "selectFirstChild": "Select first layer in group",+ "groupLocked": "Locked by a group",+ "groupDisabled": "Disabled by a group",+ "groupHidden": "Hidden by a group"},"control": {"apply": "Apply",@@ -2893,8 +2910,13 @@"image": "Image","inpaint_mask": "Inpaint","paint": "Paint",- "regional_guidance": "Region"- }+ "regional_guidance": "Region",+ "group": "Group"+ },+ "groupSummary_one": "{{count}} layer",+ "groupSummary_other": "{{count}} layers",+ "groupEmpty": "Empty group",+ "groupSelectedHint": "Select a layer inside this group to paint."},"gallery": {"alwaysShowDimensions": "Always show dimensions",diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.tsindex 6975719540..208814aae4 100644--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.test.ts@@ -1,5 +1,11 @@import type { CanvasLayerContract } from '@workbench/canvas-engine/api';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { indexStacks } from '@workbench/canvas-engine/document/documentIndex';import { beforeEach, describe, expect, it } from 'vitest';import {@@ -16,6 +22,7 @@ import {} from './layerPanelState';const ids = ['a', 'b', 'c', 'd'];+const indexOf = (nodeIds: readonly string[]) => indexStacks(stacksFrom(nodeIds.map((id) => layerContract(id))));const plain = { additive: false, range: false };const toggle = { additive: true, range: false };const range = { additive: false, range: true };@@ -84,38 +91,38 @@ describe('layer panel selection', () => {it('drops duplicate ids while reconciling', () => {const state = { ...createLayerPanelState('project', 'a'), selectedIds: ['a', 'a', 'b'] };- expect(reconcileLayerPanelState(state, 'project', ids, 'a').selectedIds).toEqual(['a', 'b']);+ expect(reconcileLayerPanelState(state, 'project', indexOf(ids), 'a').selectedIds).toEqual(['a', 'b']);});it('prunes removed secondaries without collapsing an unchanged primary', () => {const multi = { ...createLayerPanelState('project', 'a'), anchorId: 'c', selectedIds: ['a', 'b', 'c'] };- expect(reconcileLayerPanelState(multi, 'project', ['a', 'b', 'd'], 'a')).toEqual({+ expect(reconcileLayerPanelState(multi, 'project', indexOf(['a', 'b', 'd']), 'a')).toEqual({...multi,anchorId: 'a',selectedIds: ['a', 'b'],});- expect(reconcileLayerPanelState(multi, 'project', ids, 'a')).toBe(multi);+ expect(reconcileLayerPanelState(multi, 'project', indexOf(ids), 'a')).toBe(multi);});it('carries collapsed stacks through a same-project primary change only', () => {const collapsed = { ...createLayerPanelState('project', 'a'), collapsedStacks: ['control' as const] };- expect(reconcileLayerPanelState(collapsed, 'project', ids, 'b')).toMatchObject({+ expect(reconcileLayerPanelState(collapsed, 'project', indexOf(ids), 'b')).toMatchObject({collapsedStacks: ['control'],primaryId: 'b',});- expect(reconcileLayerPanelState(collapsed, 'other', ids, 'b').collapsedStacks).toEqual([]);+ expect(reconcileLayerPanelState(collapsed, 'other', indexOf(ids), 'b').collapsedStacks).toEqual([]);});it('collapses to a new primary selected outside the panel and resets between projects', () => {const multi = selectLayerInPanel(createLayerPanelState('project', 'a'), 'c', ids, toggle);- expect(reconcileLayerPanelState(multi, 'project', ids, 'd').selectedIds).toEqual(['d']);- expect(reconcileLayerPanelState(multi, 'other-project', ids, 'a').selectedIds).toEqual(['a']);+ expect(reconcileLayerPanelState(multi, 'project', indexOf(ids), 'd').selectedIds).toEqual(['d']);+ expect(reconcileLayerPanelState(multi, 'other-project', indexOf(ids), 'a').selectedIds).toEqual(['a']);});it('does not resurrect secondaries after an A to B to A project round trip', () => {let selection = selectLayerInPanel(createLayerPanelState('project-a', 'a'), 'c', ids, toggle);- selection = reconcileLayerPanelState(selection, 'project-b', ids, 'b');- selection = reconcileLayerPanelState(selection, 'project-a', ids, 'a');+ selection = reconcileLayerPanelState(selection, 'project-b', indexOf(ids), 'b');+ selection = reconcileLayerPanelState(selection, 'project-a', indexOf(ids), 'a');expect(selection.selectedIds).toEqual(['a']);});});@@ -126,7 +133,7 @@ describe('layer panel state store', () => {const project = (id: string, layerIds: readonly string[], selectedLayerId: string | null): LayerPanelProjectView => ({canvas: {document: {- layers: layerIds.map((layerId) => ({ id: layerId }) as CanvasLayerContract),+ stacks: stacksFrom(layerIds.map((layerId) => ({ id: layerId }) as CanvasLayerContract)),selectedLayerId,},},@@ -193,3 +200,18 @@ describe('layer panel state store', () => {expect(isSameLayerPanelState(readLayerPanelState('p1', 'a'), readLayerPanelState('p1', 'b'))).toBe(false);});});++describe('revealing an external primary', () => {+ it('expands every group above a primary that arrived from outside the panel', () => {+ const index = indexStacks(+ stacksFrom([groupContract('g', [groupContract('h', [layerContract('a')])]), layerContract('b')])+ );+ expect(reconcileLayerPanelState(createLayerPanelState('project', 'b'), 'project', index, 'a')).toMatchObject({+ expandedGroupIds: ['g', 'h'],+ primaryId: 'a',+ selectedIds: ['a'],+ });+ const collapsedByUser = createLayerPanelState('project', 'a');+ expect(reconcileLayerPanelState(collapsedByUser, 'project', index, 'a')).toBe(collapsedByUser);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts b/invokeai/frontend/webv2/src/workbench/layerPanelState.tsindex 5bd24805a3..31354f29fe 100644--- a/invokeai/frontend/webv2/src/workbench/layerPanelState.ts+++ b/invokeai/frontend/webv2/src/workbench/layerPanelState.ts@@ -1,7 +1,8 @@-import type { CanvasDocumentContractV2, LayerStackKind } from '@workbench/canvas-engine/api';+import type { CanvasDocumentContractV3, CanvasDocumentIndex, LayerStackKind } from '@workbench/canvas-engine/api';import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';+import { getDocumentIndex } from '@workbench/canvas-engine/api';/*** Transient Layers-panel state, kept per project and outside the document, its snapshots and@@ -14,6 +15,8 @@ export interface LayerPanelState {readonly anchorId: string | null;readonly selectedIds: readonly string[];readonly collapsedStacks: readonly LayerStackKind[];+ /** Groups whose children the panel shows; every other group is collapsed. */+ readonly expandedGroupIds: readonly string[];}export interface LayerSelectionModifiers {@@ -37,10 +40,12 @@ const store = createExternalStore<LayerPanelStore>({ byProject: {} });export const createLayerPanelState = (projectId: string,primaryId: string | null,- collapsedStacks: readonly LayerStackKind[] = []+ collapsedStacks: readonly LayerStackKind[] = [],+ expandedGroupIds: readonly string[] = []): LayerPanelState => ({anchorId: primaryId,collapsedStacks,+ expandedGroupIds,primaryId,projectId,selectedIds: primaryId ? [primaryId] : [],@@ -54,14 +59,17 @@ export const isSameLayerPanelState = (left: LayerPanelState, right: LayerPanelStleft.primaryId === right.primaryId &&left.anchorId === right.anchorId &&sameIds(left.selectedIds, right.selectedIds) &&- sameIds(left.collapsedStacks, right.collapsedStacks);+ sameIds(left.collapsedStacks, right.collapsedStacks) &&+ sameIds(left.expandedGroupIds, right.expandedGroupIds);const stateFor = (snapshot: LayerPanelStore, projectId: string, primaryId: string | null): LayerPanelState => {const stored = snapshot.byProject[projectId];if (!stored) {return createLayerPanelState(projectId, primaryId);}- return stored.primaryId === primaryId ? stored : createLayerPanelState(projectId, primaryId, stored.collapsedStacks);+ return stored.primaryId === primaryId+ ? stored+ : createLayerPanelState(projectId, primaryId, stored.collapsedStacks, stored.expandedGroupIds);};export const readLayerPanelState = (projectId: string, primaryId: string | null): LayerPanelState =>@@ -81,9 +89,11 @@ const write = (state: LayerPanelState): void => {/** Records a panel-originated selection; publish before dispatching a new primary so reconciliation keeps it. */export const publishLayerPanelSelection = (selection: LayerPanelSelectionUpdate): void => {+ const stored = store.getSnapshot().byProject[selection.projectId];write({anchorId: selection.anchorId ?? selection.primaryId,- collapsedStacks: store.getSnapshot().byProject[selection.projectId]?.collapsedStacks ?? [],+ collapsedStacks: stored?.collapsedStacks ?? [],+ expandedGroupIds: stored?.expandedGroupIds ?? [],primaryId: selection.primaryId,projectId: selection.projectId,selectedIds: [...selection.selectedIds],@@ -98,27 +108,59 @@ export const toggleLayerStackCollapsed = (projectId: string, primaryId: string |write({ ...current, collapsedStacks });};-/** Keeps a state valid after an external primary change, a project switch, or a layer removal. */+/** Shows or hides a group's children; `expanded` forces a state instead of toggling. */+export const setLayerGroupExpanded = (+ projectId: string,+ primaryId: string | null,+ groupIds: readonly string[],+ expanded?: boolean+): void => {+ const current = readLayerPanelState(projectId, primaryId);+ const next = new Set(current.expandedGroupIds);+ for (const groupId of groupIds) {+ if (expanded ?? !next.has(groupId)) {+ next.add(groupId);+ } else {+ next.delete(groupId);+ }+ }+ write({ ...current, expandedGroupIds: [...next] });+};++/**+ * Keeps a state valid after an external primary change, a project switch, or a node removal. A+ * primary that arrived from outside the panel (a hotkey, an undo, a new layer) is revealed: every+ * group above it expands so the row it names is on screen.+ */export const reconcileLayerPanelState = (state: LayerPanelState,projectId: string,- orderedIds: readonly string[],+ index: CanvasDocumentIndex,primaryId: string | null): LayerPanelState => {- const existing = new Set(orderedIds);- const validPrimaryId = primaryId && existing.has(primaryId) ? primaryId : null;+ const primary = primaryId ? index.byId.get(primaryId) : undefined;+ const validPrimaryId = primary ? primary.node.id : null;+ const expandedGroupIds = state.expandedGroupIds.filter((id) => index.byId.has(id));if (state.projectId !== projectId || state.primaryId !== validPrimaryId) {- return createLayerPanelState(projectId, validPrimaryId, state.projectId === projectId ? state.collapsedStacks : []);+ const revealed = primary ? [...new Set([...expandedGroupIds, ...primary.path])] : expandedGroupIds;+ return state.projectId === projectId+ ? createLayerPanelState(projectId, validPrimaryId, state.collapsedStacks, revealed)+ : createLayerPanelState(projectId, validPrimaryId, [], primary ? [...primary.path] : []);}+ const existing = index.byId;const selectedIds = [...new Set(state.selectedIds)].filter((id) => existing.has(id));if (validPrimaryId && !selectedIds.includes(validPrimaryId)) {selectedIds.push(validPrimaryId);}const anchorId = state.anchorId && existing.has(state.anchorId) ? state.anchorId : validPrimaryId;- if (anchorId === state.anchorId && sameIds(selectedIds, state.selectedIds)) {+ if (+ anchorId === state.anchorId &&+ sameIds(selectedIds, state.selectedIds) &&+ sameIds(expandedGroupIds, state.expandedGroupIds)+ ) {return state;}- return { ...state, anchorId, selectedIds };+ return { ...state, anchorId, expandedGroupIds, selectedIds };};/**@@ -169,7 +211,7 @@ export const selectLayerInPanel = (export interface LayerPanelProjectView {readonly id: string;- readonly canvas: { readonly document: Pick<CanvasDocumentContractV2, 'layers' | 'selectedLayerId'> };+ readonly canvas: { readonly document: Pick<CanvasDocumentContractV3, 'stacks' | 'selectedLayerId'> };}const reconciledDocuments = new Map<string, LayerPanelProjectView['canvas']['document']>();@@ -180,10 +222,7 @@ export const reconcileLayerPanelStates = (projects: readonly LayerPanelProjectViconst next: Record<string, LayerPanelState> = {};let changed = false;for (const project of projects) {- const stored = byProject[project.id];- if (!stored) {- continue;- }+ const stored = byProject[project.id] ?? createLayerPanelState(project.id, null);const { document } = project.canvas;if (reconciledDocuments.get(project.id) === document) {next[project.id] = stored;@@ -193,11 +232,11 @@ export const reconcileLayerPanelStates = (projects: readonly LayerPanelProjectViconst reconciled = reconcileLayerPanelState(stored,project.id,- document.layers.map((layer) => layer.id),+ getDocumentIndex(document),document.selectedLayerId);next[project.id] = reconciled;- changed ||= reconciled !== stored;+ changed ||= reconciled !== byProject[project.id];}for (const id of reconciledDocuments.keys()) {if (!(id in next)) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex ae6100708e..9ca53c912b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -433,6 +433,8 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {['canvas.nudgeDownLarge', t('widgets.canvas.commands.nudgeDownLarge'), ['shift+arrowdown']],// Layer management.['canvas.duplicateLayer', t('widgets.canvas.commands.duplicateLayer'), ['mod+j']],+ ['canvas.groupLayers', t('widgets.canvas.commands.groupLayers'), ['mod+g']],+ ['canvas.ungroupLayers', t('widgets.canvas.commands.ungroupLayers'), ['mod+shift+g']],['canvas.mergeDown', t('widgets.canvas.commands.mergeDown'), ['mod+e']],['canvas.layerForward', t('widgets.canvas.commands.layerForward'), ['mod+]']],['canvas.layerBackward', t('widgets.canvas.commands.layerBackward'), ['mod+[']],@@ -500,7 +502,6 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {beforeDangerItems={compositeSubmenus}dispatch={canvasDispatch}engine={engine}- layers={document.layers}showGroupLabelstarget={layerContextMenuTarget}onClose={closeContextMenu}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.tsindex 23e630840e..8af4789c28 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts@@ -1,13 +1,16 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasEngine,CanvasInteractionState,CanvasLayerContract,+ CanvasNodeContract,} from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import { createFlatDocumentModel } from '@workbench/canvas-engine/api';+import { createDocumentModel } from '@workbench/canvas-engine/api';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';+import { createControlLayer } from '@workbench/widgets/layers/layerOps';import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';@@ -26,14 +29,14 @@ const rasterLayer = (id: string, overrides: Partial<CanvasLayerContract> = {}):...overrides,}) as CanvasLayerContract;-const documentOf = (layers: readonly CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV2 =>+const documentOf = (layers: readonly CanvasLayerContract[], selectedLayerId: string | null): CanvasDocumentContractV3 =>({bbox: { height: 64, width: 64, x: 0, y: 0 },height: 64,- layers,+ stacks: stacksFrom(layers),selectedLayerId,width: 64,- }) as CanvasDocumentContractV2;+ }) as CanvasDocumentContractV3;/*** A recording engine double. Interaction state is a plain bag so tests can put@@ -113,7 +116,7 @@ const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyCoconst run = (commandId: string, overrides: Partial<CanvasHotkeyContext> = {}) => {const ctx = contextOf(overrides);(ctx.engine!.document.model as Mock).mockImplementation(() =>- createFlatDocumentModel(ctx.document, { editRevision: 0, projectId: 'project' })+ createDocumentModel(ctx.document, { editRevision: 0, projectId: 'project' }));executeCanvasHotkeyCommand(commandId, ctx);return ctx.engine as ReturnType<typeof createEngine>;@@ -218,7 +221,7 @@ describe('layer reorder', () => {});expect(engine.layers.commitPrepared).toHaveBeenCalledWith('widgets.canvas.commands.reorderLayer',- expect.objectContaining({ forward: expect.objectContaining({ type: 'reorderCanvasLayerStacks' }) })+ expect.objectContaining({ forward: expect.objectContaining({ type: 'reorderCanvasSiblings' }) }));});@@ -253,11 +256,11 @@ describe('layer reorder', () => {'widgets.canvas.commands.reorderLayer',expect.objectContaining({forward: {- stacks: [- { orderedIds: ['c2', 'c1'], stack: 'control' },- { orderedIds: ['r2', 'r1'], stack: 'raster' },+ orders: [+ { orderedIds: ['c2', 'c1'], parentId: null, stack: 'control' },+ { orderedIds: ['r2', 'r1'], parentId: null, stack: 'raster' },],- type: 'reorderCanvasLayerStacks',+ type: 'reorderCanvasSiblings',},}));@@ -289,7 +292,7 @@ describe('delete: pixels vs layer', () => {expect.objectContaining({forward: { ids: ['a', 'c'], type: 'removeCanvasLayers' },inverse: expect.objectContaining({- add: [expect.objectContaining({ layers: [layers[0]] }), expect.objectContaining({ layers: [layers[2]] })],+ add: [expect.objectContaining({ nodes: [layers[0]] }), expect.objectContaining({ nodes: [layers[2]] })],selectedLayerId: 'a',}),})@@ -516,3 +519,79 @@ describe('robustness', () => {}});});++describe('group selection', () => {+ const nodeDocument = (nodes: CanvasNodeContract[], selectedLayerId: string | null): CanvasDocumentContractV3 => ({+ ...documentOf([], selectedLayerId),+ stacks: stacksFrom(nodes),+ });+ const control = (id: string): CanvasLayerContract => createControlLayer(id, id);++ it('reorders, deletes and duplicates a selected group', () => {+ const document = nodeDocument([groupContract('g', [rasterLayer('a')]), rasterLayer('b')], 'g');+ const reorder = run('canvas.layerToBack', { document, selectedLayerIds: ['g'] });+ expect(reorder.layers.commitPrepared).toHaveBeenCalledWith(+ 'widgets.canvas.commands.reorderLayer',+ expect.objectContaining({ forward: expect.objectContaining({ type: 'reorderCanvasSiblings' }) })+ );+ const remove = run('canvas.deleteSelected', { document, selectedLayerIds: ['g'] });+ expect(remove.layers.commitPrepared).toHaveBeenCalledWith(+ 'widgets.canvas.commands.deleteLayer',+ expect.objectContaining({ forward: { ids: ['g'], type: 'removeCanvasLayers' } })+ );+ const duplicate = run('canvas.duplicateLayer', { document, selectedLayerIds: ['g'] });+ expect(duplicate.layers.duplicateLayers).toHaveBeenCalledWith(['g']);+ });++ it('refuses to delete a leaf frozen by a locked group', () => {+ const document = nodeDocument([groupContract('g', [rasterLayer('a')], { isLocked: true })], 'a');+ const engine = run('canvas.deleteSelected', { document, selectedLayerIds: ['a'] });+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();+ });++ it('shows overlays hidden behind a hidden group, and hides them again from the roots', () => {+ const hidden = nodeDocument([{ ...groupContract('g', [control('c1')]), isHidden: true }, control('c2')], 'c2');+ const shown = run('canvas.toggleNonRasterLayers', { document: hidden });+ expect(shown.layers.commitPrepared).toHaveBeenCalledWith(+ 'widgets.canvas.commands.toggleNonRasterLayers',+ expect.objectContaining({ forward: { type: 'setCanvasLayersHidden', updates: [{ id: 'g', isHidden: false }] } })+ );+ const visible = nodeDocument([groupContract('g', [control('c1')]), control('c2')], 'c2');+ const hide = run('canvas.toggleNonRasterLayers', { document: visible });+ expect(hide.layers.commitPrepared).toHaveBeenCalledWith(+ 'widgets.canvas.commands.toggleNonRasterLayers',+ expect.objectContaining({+ forward: {+ type: 'setCanvasLayersHidden',+ updates: [+ { id: 'g', isHidden: true },+ { id: 'c2', isHidden: true },+ ],+ },+ })+ );+ });++ it('groups and ungroups the selection', () => {+ const grouped = run('canvas.groupLayers', {+ document: nodeDocument([rasterLayer('a'), rasterLayer('b')], 'a'),+ selectedLayerIds: ['a', 'b'],+ });+ expect(grouped.layers.commitPrepared).toHaveBeenCalledWith(+ 'widgets.canvas.commands.groupLayers',+ expect.objectContaining({+ forward: expect.objectContaining({+ add: [expect.objectContaining({ nodes: [expect.objectContaining({ type: 'group' })] })],+ }),+ })+ );+ const ungrouped = run('canvas.ungroupLayers', {+ document: nodeDocument([groupContract('g', [rasterLayer('a')])], 'g'),+ selectedLayerIds: ['g'],+ });+ expect(ungrouped.layers.commitPrepared).toHaveBeenCalledWith(+ 'widgets.canvas.commands.ungroupLayers',+ expect.objectContaining({ forward: expect.objectContaining({ removeIds: ['g'] }) })+ );+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.tsindex 2bd9ea6162..9ca84ef1a7 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts@@ -1,14 +1,26 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasEngine,LayerStackMoveKind,StructuralCommitResult,} from '@workbench/canvas-engine/api';import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';-import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';+import {+ compileDocumentLeaves,+ getDocumentIndex,+ isGroupNode,+ isNodeHidden,+ isOverlayStack,+} from '@workbench/canvas-engine/api';import { publishLayerPanelSelection } from '@workbench/layerPanelState';import { commitPreparedEdit, type PreparedCommitOutcome } from '@workbench/widgets/canvas/useStructuralCommit';+import {+ canGroupNodes,+ canUngroupNodes,+ groupLayers,+ ungroupLayers,+} from '@workbench/widgets/layers/layerGroupCommands';import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';/** Command id → document-space nudge delta (shift variants are ×10). */@@ -37,7 +49,7 @@ const REORDER_KINDS: Record<string, LayerStackMoveKind> = {* makes the ~35-command dispatch table testable without mounting React.*/export interface CanvasHotkeyContext {- readonly document: CanvasDocumentContractV2;+ readonly document: CanvasDocumentContractV3;readonly engine: CanvasEngine | null;/** Any staging slot exists, so left/right cycle candidates instead of nudging. */readonly hasStagingSlots: boolean;@@ -64,9 +76,11 @@ export interface CanvasHotkeyContext {*/export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyContext): void => {const { dispatch, document, engine, t } = ctx;- const { layers, selectedLayerId } = document;- const selectedIndex = selectedLayerId ? layers.findIndex((layer) => layer.id === selectedLayerId) : -1;- const selectedLayer = selectedIndex >= 0 ? layers[selectedIndex] : undefined;+ const { selectedLayerId } = document;+ const index = getDocumentIndex(document);+ const selected = selectedLayerId ? index.byId.get(selectedLayerId) : undefined;+ const selectedLayer = selected && !isGroupNode(selected.node) ? selected.node : undefined;+ const selectedFrozen = !!selected && (selected.ancestorsLocked || selected.node.isLocked);if ((commandId === 'canvas.prevEntity' || commandId === 'canvas.nudgeLeft') && ctx.hasStagingSlots) {dispatch({ direction: -1, type: 'cycleStagedImage' });@@ -104,7 +118,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC// Layer z-reorder: the same prepared move the layers panel commits.const reorderKind = REORDER_KINDS[commandId];if (reorderKind) {- if (!engine || selectedIndex < 0) {+ if (!engine || !selected) {return;}ctx.reportPreparedCommit(@@ -120,7 +134,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC// Photoshop meaning. Only with no selection does it delete the layer.if (engine?.interaction.get('hasSelection')) {engine.selection.eraseSelection();- } else if (engine && selectedLayer && selectedIndex >= 0 && !selectedLayer.isLocked) {+ } else if (engine && selected && !selectedFrozen) {ctx.reportPreparedCommit(commitPreparedEdit(engine, t('widgets.canvas.commands.deleteLayer'), (model) =>model.prepare({ ids: ctx.selectedLayerIds, type: 'remove' })@@ -132,16 +146,21 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC} else if (commandId === 'canvas.pasteImage') {ctx.pasteFromClipboard();} else if (commandId === 'canvas.toggleNonRasterLayers') {- // Hide, never disable: this is the "get the overlays out of my way"- // shortcut, and it must leave the generated image untouched.- const hideable = layers.filter(isHideableLayer);- if (engine && hideable.length > 0) {- const nextHidden = hideable.every((layer) => !isLayerHidden(layer));+ // Hide, never disable: this is the "get the overlays out of my way" shortcut, and it must+ // leave the generated image untouched. Hiding turns off the overlay roots; showing turns on+ // every node hidden in its own right, so nothing stays gated behind a hidden group.+ const overlays = index.nodes.filter((entry) => isOverlayStack(entry.stack));+ const leaves = compileDocumentLeaves(document).filter((leaf) => isOverlayStack(leaf.stack));+ if (engine && leaves.length > 0) {+ const nextHidden = leaves.every((leaf) => !leaf.documentHidden);+ const targets = nextHidden+ ? overlays.filter((entry) => entry.parentId === null)+ : overlays.filter((entry) => isNodeHidden(entry.node));ctx.reportPreparedCommit(commitPreparedEdit(engine, t('widgets.canvas.commands.toggleNonRasterLayers'), (model) =>model.prepare({type: 'set-hidden',- updates: hideable.map((layer) => ({ id: layer.id, isHidden: nextHidden })),+ updates: targets.map((entry) => ({ id: entry.node.id, isHidden: nextHidden })),})));@@ -220,7 +239,7 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC// the selected pixels. With none, it duplicates the whole layer.if (engine?.interaction.get('hasSelection')) {engine.selection.liftSelectionToLayer();- } else if (engine && selectedLayer) {+ } else if (engine && selected) {void engine.layers.duplicateLayers(ctx.selectedLayerIds).then((result) => {@@ -243,6 +262,16 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyCctx.notifyLayerDuplicateFailed();});}+ } else if (commandId === 'canvas.groupLayers') {+ if (engine && selected && canGroupNodes(document, ctx.selectedLayerIds)) {+ ctx.reportPreparedCommit(+ groupLayers(engine, engine.projectId, ctx.selectedLayerIds, t('widgets.canvas.commands.groupLayers'))+ );+ }+ } else if (commandId === 'canvas.ungroupLayers') {+ if (engine && selected && canUngroupNodes(document, ctx.selectedLayerIds)) {+ ctx.reportPreparedCommit(ungroupLayers(engine, ctx.selectedLayerIds, t('widgets.canvas.commands.ungroupLayers')));+ }} else if (commandId === 'canvas.mergeDown') {// Gate on the SAME predicate the layers panel's context menu uses to// enable/disable its "Merge Down" item (`canMergeLayerDown`), so the hotkeydiff --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 33f1f6b8f3..47095d47ce 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,6 +1,7 @@import type { NumberInput as ChakraNumberInput } from '@chakra-ui/react';import { HStack, NumberInput, Text } from '@chakra-ui/react';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import { useCallback } from 'react';@@ -26,10 +27,10 @@ export const MoveOptions = ({ engine }: ToolOptionsComponentProps) => {const selected = useActiveProjectSelector((project): SelectedTransform | null => {const { document } = project.canvas;- const layer = document.selectedLayerId- ? document.layers.find((entry) => entry.id === document.selectedLayerId)- : undefined;- return layer ? { id: layer.id, x: layer.transform.x, y: layer.transform.y } : null;+ const leaf = document.selectedLayerId ? lookupDocumentLeaf(document, document.selectedLayerId) : null;+ return leaf && !leaf.effectiveLocked+ ? { id: leaf.id, x: leaf.layer.transform.x, y: leaf.layer.transform.y }+ : null;},(a, b) => a?.id === b?.id && a?.x === b?.x && a?.y === b?.y);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsxindex 4679780426..6b2b9c1c6a 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ToolOptionsBar.tsx@@ -3,10 +3,14 @@ import type { CanvasOperationState } from '@workbench/canvas-operations/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import type { ComponentType } from 'react';-import { HStack, Text } from '@chakra-ui/react';+import { Button, HStack, Text } from '@chakra-ui/react';+import { collectSubtreeLeaves, getDocumentNode } from '@workbench/canvas-engine/api';+import { useCanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';import { BboxDetailsBar } from '@workbench/widgets/canvas/BboxDetailsBar';import { CanvasFloatingBarDivider } from '@workbench/widgets/canvas/CanvasFloatingBar';import { useCanvasActiveTool, useCanvasOperation } from '@workbench/widgets/canvas/engineStoreHooks';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useCallback } from 'react';import { useTranslation } from 'react-i18next';import { BboxOptions } from './BboxOptions';@@ -32,6 +36,9 @@ export interface ToolOptionsComponentProps {engine: CanvasToolOptionsEngine;}+/** Tools that paint into one leaf; a selected group cannot take their strokes. */+const LEAF_TOOLS: ReadonlySet<ToolId> = new Set(['brush', 'eraser', 'gradient', 'shape', 'text']);+/** Contextual options content per active tool; tools without an entry show their hint instead. */export const TOOL_OPTIONS_COMPONENTS: Partial<Record<ToolId, ComponentType<ToolOptionsComponentProps>>> = {bbox: BboxOptions,@@ -91,7 +98,9 @@ export const ToolOptionsBar = ({ engine }: { engine: CanvasToolOptionsEngine })<CanvasFloatingBarDivider />{hasBboxDetails ? <BboxDetailsBar engine={engine} /> : null}{hasBboxDetails && OptionsComponent ? <CanvasFloatingBarDivider /> : null}- {OptionsComponent ? (+ {OptionsComponent && LEAF_TOOLS.has(activeTool) ? (+ <LeafToolOptions component={OptionsComponent} engine={engine} />+ ) : OptionsComponent ? (<OptionsComponent engine={engine} />) : (<Text color="fg.subtle" fontSize="xs" minW="0" truncate>@@ -102,3 +111,44 @@ export const ToolOptionsBar = ({ engine }: { engine: CanvasToolOptionsEngine })</CanvasOptionsBar>);};++/** A leaf tool's options, or the way out when the selection is a group those tools cannot paint into. */+const LeafToolOptions = ({+ component: OptionsComponent,+ engine,+}: {+ component: ComponentType<ToolOptionsComponentProps>;+ engine: CanvasToolOptionsEngine;+}) => {+ const { t } = useTranslation();+ const dispatch = useCanvasProjectMutationDispatch();+ const selectedGroup = 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 (selectedGroup?.firstLeafId) {+ dispatch({ id: selectedGroup.firstLeafId, type: 'setCanvasSelectedLayer' });+ }+ }, [dispatch, selectedGroup]);++ if (!selectedGroup) {+ return <OptionsComponent engine={engine} />;+ }+ return (+ <HStack gap="2" minW="0">+ <Text color="fg.subtle" fontSize="xs" minW="0" truncate>+ {t('widgets.layers.groupSelectedHint')}+ </Text>+ {selectedGroup.firstLeafId ? (+ <Button size="2xs" variant="subtle" onClick={selectFirstLeaf}>+ {t('widgets.layers.actions.selectFirstChild')}+ </Button>+ ) : null}+ </HStack>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsxindex 55e8cd1117..61d960c84c 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentsPopover.browser.test.tsx@@ -1,12 +1,13 @@-import type { CanvasRasterLayerContractV2, PreparedFlatEdit } from '@workbench/canvas-engine/api';+import type { CanvasRasterLayerContractV2, PreparedDocumentEdit } from '@workbench/canvas-engine/api';/* oxlint-disable react-perf/jsx-no-new-function-as-prop */import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { ChakraProvider } from '@chakra-ui/react';import { applyThemeToRoot } from '@theme/applyTheme';import { system } from '@theme/system';-import { createFlatDocumentModel } from '@workbench/canvas-engine/api';-import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';+import { createDocumentModel } from '@workbench/canvas-engine/api';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { createInstance } from 'i18next';import { act, useMemo, useState } from 'react';import { createRoot, type Root } from 'react-dom/client';@@ -42,7 +43,7 @@ const createLayer = (): CanvasRasterLayerContractV2 =>type: 'raster',}) as unknown as CanvasRasterLayerContractV2;-const commits: PreparedFlatEdit[] = [];+const commits: PreparedDocumentEdit[] = [];let latestAdjustments: unknown = 'untouched';const Harness = () => {@@ -63,14 +64,14 @@ const Harness = () => {return {document: {model: () =>- createFlatDocumentModel(- { ...createEmptyCanvasDocumentV2(), layers: [layer], selectedLayerId: layer.id },+ createDocumentModel(+ { ...createEmptyCanvasDocument(), stacks: stacksFrom([layer]), selectedLayerId: layer.id },{ editRevision: 0, projectId: 'test-project' }),},layers: {applyStructuralPreview: apply,- commitPrepared: (_label: string, edit: PreparedFlatEdit) => {+ commitPrepared: (_label: string, edit: PreparedDocumentEdit) => {commits.push(edit);return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };},diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsxindex e9ac9cc8c7..6ec4a3a16e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerSettings.tsx@@ -7,6 +7,7 @@ import type {CanvasControlAdapterContract,CanvasControlLayerContract,CanvasDocumentCapability,+ CanvasLayerContract,} from '@workbench/canvas-engine/api';import type { LayerFilterOperationEngine } from '@workbench/widgets/layers/LayerFilterOperationButton';import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';@@ -19,6 +20,7 @@ import {} from '@features/generation/graph';import { useModelsSelector } from '@features/models';import { Field, Select, Slider } from '@platform/ui';+import { lookupDocumentLeaf } from '@workbench/canvas-engine/api';import { getCanvasOperations, resolveDefaultFilterForModel } from '@workbench/canvas-operations/api';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';import { useCallback, useMemo, useRef } from 'react';@@ -67,6 +69,21 @@ interface ControlLayerSettingsProps {* undo stack (`updateCanvasLayerConfig`); the filter preview runs on the utility* queue and never mutates the document until "Apply".*/+/** Contributing control leaves of one adapter kind with content, in generation order. */+const contributingControlLayers = (+ engine: CanvasStructuralEngine & LayerFilterOperationEngine & { readonly document: CanvasDocumentCapability },+ kind: CanvasControlAdapterContract['kind']+): CanvasLayerContract[] =>+ (engine.document.model()?.compileLeaves() ?? [])+ .filter(+ (leaf) =>+ leaf.contributionEnabled &&+ leaf.layer.type === 'control' &&+ leaf.layer.adapter.kind === kind &&+ engine.exports.hasExportableLayerContent(leaf.id)+ )+ .map((leaf) => leaf.layer);+export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: ControlLayerSettingsProps) => {const { t } = useTranslation();const commitPrepared = usePreparedCommit(engine);@@ -287,32 +304,17 @@ export const ControlLayerSettings = ({ engine, layer, onOperationStarted }: Contconst hasContent = engine?.exports.hasExportableLayerContent(layer.id) ?? false;const controlLoraIndex =adapter.kind === 'control_lora' && engine- ? (engine.document- .getDocument()- ?.layers.filter(- (candidate) =>- candidate.isEnabled &&- candidate.type === 'control' &&- candidate.adapter.kind === 'control_lora' &&- engine.exports.hasExportableLayerContent(candidate.id)- )- .findIndex((candidate) => candidate.id === layer.id) ?? 0)+ ? contributingControlLayers(engine, 'control_lora').findIndex((candidate) => candidate.id === layer.id): 0;const zImageControlIndex =adapter.kind === 'z_image_control' && engine- ? (engine.document- .getDocument()- ?.layers.filter(- (candidate) =>- candidate.isEnabled &&- candidate.type === 'control' &&- candidate.adapter.kind === 'z_image_control' &&- engine.exports.hasExportableLayerContent(candidate.id)- )- .findIndex((candidate) => candidate.id === layer.id) ?? 0)+ ? contributingControlLayers(engine, 'z_image_control').findIndex((candidate) => candidate.id === layer.id): 0;+ const contributing = engine+ ? (lookupDocumentLeaf(engine.document.model()?.document, layer.id)?.contributionEnabled ?? false)+ : layer.isEnabled;const validationReason =- layer.isEnabled && mainModel+ contributing && mainModel? getControlValidationReason({adapterModel: adapterModel ? { base: adapterModel.base, type: adapterModel.type } : null,beginEndStepPct: adapter.beginEndStepPct,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsxindex fbeea6d2c6..3fb61cacfa 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/ControlLayerWarningIcon.tsx@@ -14,12 +14,19 @@ import { useSelectedMainModel } from './useSelectedMainModel';* generation time (no model, incompatible adapter, …). Renders nothing for* other layer types and healthy control layers.*/-export const ControlLayerWarningIcon = ({ layer }: { layer: CanvasLayerContract }) => {+/** `contributing` is the effective enablement; a layer gated by a group is not validated. */+export const ControlLayerWarningIcon = ({+ layer,+ contributing = layer.isEnabled,+}: {+ layer: CanvasLayerContract;+ contributing?: boolean;+}) => {const { t } = useTranslation();const models = useModelsSelector((snapshot) => snapshot.models);const mainModel = useSelectedMainModel();- if (layer.type !== 'control' || !layer.isEnabled || !mainModel) {+ if (layer.type !== 'control' || !contributing || !mainModel) {return null;}const reason = getControlLayerAttentionReason(layer, mainModel.base, models);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 2dfff805b1..4ccd3ab2a8 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -1,5 +1,5 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasMaskContract,BooleanRasterOperation,@@ -15,9 +15,9 @@ import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { galleryTransfers } from '@features/gallery';import { useModelsSelector } from '@features/models';import { IconButton, MenuContent, RenameDialog, Tooltip } from '@platform/ui';-import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/api';+import { getDocumentLayer, getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/api';import { getCanvasOperations } from '@workbench/canvas-operations/api';-import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';+import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';import { useNotify } from '@workbench/useNotify';import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';@@ -51,6 +51,7 @@ import type { LayerPropertiesSection } from './layerPropertiesRequestStore';import { resolveDefaultControlModelForBase } from './controlModelOptions';import {+ actionTargets,getLayerContextActions,type LayerConfigPatchKind,type LayerContextAction,@@ -66,6 +67,7 @@ import {getLayerContextMenuRenderEntries,} from './layerContextMenuLayout';import { copyBlobToClipboard, saveLayerToAssets } from './layerExportActions';+import { groupLayers } from './layerGroupCommands';import { resolveMenuTargetForRender } from './layerMenuState';import {convertRasterToControl,@@ -140,7 +142,7 @@ const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {unsupported: 'widgets.layers.actions.unsupported',};-const hasPureExportableLayerContent = (layer: CanvasLayerContract, document: CanvasDocumentContractV2): boolean => {+const hasPureExportableLayerContent = (layer: CanvasLayerContract, document: CanvasDocumentContractV3): boolean => {if (!renderableSourceOf(layer)) {return false;}@@ -220,6 +222,7 @@ const LayerMenu = ({[document.height, document.width]);const documentEditingLocked = useCanvasDocumentEditingLocked(engine);+ const { selectedIds } = useLayerPanelState(projectId, document.selectedLayerId);const interactionLocked = isCanvasInteractionLocked(canvas, queueItems) || documentEditingLocked;// Re-render when live, not-yet-persisted paint/mask pixels change.useLayerThumbnailVersion(engine, layer.id);@@ -268,6 +271,7 @@ const LayerMenu = ({hasWorkflowBindings: workflowAvailability.hasWorkflowBindings,interactionLocked,layer,+ selectedIds,}),[document,@@ -275,6 +279,7 @@ const LayerMenu = ({hasSupportedContent,interactionLocked,layer,+ selectedIds,workflowAvailability.canRunWorkflow,workflowAvailability.hasWorkflowBindings,]@@ -326,7 +331,7 @@ const LayerMenu = ({return;}commitPrepared(t('widgets.layers.actions.duplicate'), (model) =>- model.prepare({ newId: createLayerId(), sourceId: layer.id, type: 'duplicate' })+ model.prepare({ createId: createLayerId, ids: [layer.id], type: 'duplicate' }));}, [commitPrepared, document.selectedLayerId, engine, layer.id, notify, projectId, t]);@@ -334,6 +339,14 @@ const LayerMenu = ({commitPrepared(t('widgets.layers.actions.delete'), (model) => model.prepare({ ids: [layer.id], type: 'remove' }));}, [commitPrepared, layer.id, t]);+ const handleGroup = useCallback(() => {+ const ids = actionTargets({ layer, selectedIds });+ const outcome = groupLayers(engine, projectId, ids, t('widgets.layers.actions.group'));+ if (outcome.status === 'refused') {+ throw makeStatusError(outcome.refusal.status === 'locked' ? 'locked' : 'unsupported');+ }+ }, [engine, layer, makeStatusError, projectId, selectedIds, t]);+const handleMerge = useCallback(() => {// Pixel work: engine-only, and not recorded on the undo history.engine?.layers.mergeLayerDown(layer.id);@@ -630,6 +643,7 @@ const LayerMenu = ({delete: handleDelete,duplicate: handleDuplicate,extractMaskedArea: handleExtractMaskedArea,+ group: handleGroup,fitToBbox: handleFitToBbox,mergeDown: handleMerge,openProperties: handleOpenProperties,@@ -656,6 +670,7 @@ const LayerMenu = ({handleDuplicate,handleExtractMaskedArea,handleFitToBbox,+ handleGroup,handleLayerConfigAction,handleMerge,handleOpenProperties,@@ -769,7 +784,6 @@ interface LayerRowMenuProps {dispatch: Dispatch<CanvasProjectMutation>;engine: LayerContextMenuEngine | null;layer: CanvasLayerContract;- layers: readonly CanvasLayerContract[];}/** The layers-panel per-row context menu: a ⋯ trigger button, opened below it. */@@ -788,9 +802,9 @@ export interface CanvasLayerContextMenuTarget {* The canvas-surface right-click menu: the SAME {@link LayerMenu}, anchored at the* cursor via a 1×1 virtual rect (no trigger DOM), controlled by `target`. The* canvas widget sets `target` to the hit layer + pointer position after selecting- * it; `null` closes the menu. The layer is resolved from- * `target.layerId` against the live layer list, so the shared items get the exact- * same inputs the panel passes. Keyed by layer id so switching target resets the+ * it; `null` closes the menu. The layer is resolved from `target.layerId`+ * against the live document, so the shared items get the exact same inputs the+ * panel passes. Keyed by layer id so switching target resets the* menu's sibling-dialog state.** Choosing a sibling-dialog action closes the menu, which nulls `target`. The@@ -801,7 +815,6 @@ export const CanvasLayerContextMenu = ({beforeDangerItems,dispatch,engine,- layers,target,showGroupLabels,onClose,@@ -809,7 +822,6 @@ export const CanvasLayerContextMenu = ({beforeDangerItems?: ReactNode;dispatch: Dispatch<CanvasProjectMutation>;engine: LayerContextMenuEngine | null;- layers: readonly CanvasLayerContract[];target: CanvasLayerContextMenuTarget | null;showGroupLabels?: boolean;onClose: () => void;@@ -819,7 +831,10 @@ export const CanvasLayerContextMenu = ({const [dialogState, setDialogState] = useState<LayerMenuDialogState | null>(null);const renderTarget = resolveMenuTargetForRender(target, dialogState);- const layer = renderTarget ? layers.find((entry) => entry.id === renderTarget.layerId) : undefined;+ const layerId = renderTarget?.layerId ?? null;+ const layer = useActiveProjectSelector((project) =>+ layerId ? (getDocumentLayer(project.canvas.document, layerId) ?? undefined) : undefined+ );const anchorX = renderTarget?.x ?? 0;const anchorY = renderTarget?.y ?? 0;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsxindex 44439a400f..1dd9fce494 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerFilterOperationDelegation.test.tsx@@ -25,7 +25,7 @@ const { operations, renderSharedLaunch } = vi.hoisted(() => ({renderSharedLaunch: vi.fn(),}));const ENGINE = {- document: { getDocument: vi.fn(() => ({ layers: [] })) },+ document: { getDocument: vi.fn(() => ({ layers: [] })), model: () => null },exports: { hasExportableLayerContent: vi.fn(() => false) },} as unknown as CanvasEngine;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsxnew file mode 100644index 0000000000..de3feb6e37--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx@@ -0,0 +1,273 @@+import type { CanvasGroupContract, LayerStackKind, LayerStackMoveKind } from '@workbench/canvas-engine/api';+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { LucideIcon } from 'lucide-react';+import type { ComponentProps } from 'react';++import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { IconButton, MenuContent, RenameDialog } from '@platform/ui';+import { collectSubtree, getDocumentIndex, isOverlayStack } from '@workbench/canvas-engine/api';+import { publishLayerPanelSelection, useLayerPanelState } from '@workbench/layerPanelState';+import { useNotify } from '@workbench/useNotify';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';+import {+ ArrowDownIcon,+ ArrowDownToLineIcon,+ ArrowUpIcon,+ ArrowUpToLineIcon,+ CopyIcon,+ EyeIcon,+ EyeOffIcon,+ FolderPlusIcon,+ LockIcon,+ LockOpenIcon,+ MoreVerticalIcon,+ PencilIcon,+ Trash2Icon,+ UngroupIcon,+} from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { canGroupNodes, groupLayers, ungroupLayers } from './layerGroupCommands';++export type LayerGroupContextMenuEngine = Pick<CanvasEngineHandle, 'document' | 'layers' | 'projectId'>;++type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];++const MENU_POSITIONING: MenuPositioning = { placement: 'bottom-end' };++const ARRANGE: readonly { icon: LucideIcon; key: string; kind: LayerStackMoveKind }[] = [+ { icon: ArrowUpToLineIcon, key: 'moveToFront', kind: 'front' },+ { icon: ArrowUpIcon, key: 'moveForward', kind: 'forward' },+ { icon: ArrowDownIcon, key: 'moveBackward', kind: 'backward' },+ { icon: ArrowDownToLineIcon, key: 'moveToBack', kind: 'back' },+];++const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();++interface LayerGroupContextMenuProps {+ editingLocked: boolean;+ engine: LayerGroupContextMenuEngine | null;+ group: CanvasGroupContract;+ stack: LayerStackKind;+ /** A right-click point that opens the same menu there; `null` shows only the trigger. */+ anchor?: { x: number; y: number } | null;+ onAnchorClose?: () => void;+}++const MenuRow = ({ icon, label }: { icon: LucideIcon; label: string }) => (+ <HStack gap="2" minW="0" w="full">+ <Icon as={icon} boxSize="3.5" color="fg.subtle" flexShrink={0} />+ <Text flex="1" fontSize="xs">+ {label}+ </Text>+ </HStack>+);++/** The per-group menu: naming, grouping, arrangement, and state edits, all through prepared edits. */+export const LayerGroupContextMenu = ({+ anchor = null,+ editingLocked,+ engine,+ group,+ onAnchorClose,+ stack,+}: LayerGroupContextMenuProps) => {+ const { t } = useTranslation();+ const commitPrepared = usePreparedCommit(engine);+ const notify = useNotify();+ const projectId = useActiveProjectId();+ const document = useActiveProjectSelector((project) => project.canvas.document);+ const { selectedIds } = useLayerPanelState(projectId, document.selectedLayerId);+ const [renaming, setRenaming] = useState(false);++ const selection = useCallback(+ (): readonly string[] => (selectedIds.includes(group.id) ? selectedIds : [group.id]),+ [group.id, selectedIds]+ );+ // What a locked ancestor or a locked descendant takes off the table, so no item leads to a refusal.+ const entry = getDocumentIndex(document).byId.get(group.id);+ const frozen = entry?.ancestorsLocked ?? false;+ const holdsLocked =+ frozen || group.isLocked || (entry ? collectSubtree(entry.node).some((node) => node.isLocked) : false);+ const groupable = !frozen && canGroupNodes(document, selection());+ const anchorX = anchor?.x ?? 0;+ const anchorY = anchor?.y ?? 0;+ const anchoredPositioning = useMemo<MenuPositioning>(+ () => ({ getAnchorRect: () => ({ height: 1, width: 1, x: anchorX, y: anchorY }), placement: 'bottom-start' }),+ [anchorX, anchorY]+ );+ const handleAnchoredOpenChange = useCallback(+ (details: { open: boolean }) => {+ if (!details.open) {+ onAnchorClose?.();+ }+ },+ [onAnchorClose]+ );++ const patch = useCallback(+ (label: string, forward: Partial<Pick<CanvasGroupContract, 'name' | 'isEnabled' | 'isLocked'>>) =>+ commitPrepared(label, (model) => model.prepare({ id: group.id, patch: forward, type: 'patch' })),+ [commitPrepared, group.id]+ );++ const handleRename = useCallback(+ (name: string) => {+ patch(t('widgets.layers.actions.rename'), { name });+ },+ [patch, t]+ );+ const openRename = useCallback(() => setRenaming(true), []);+ const closeRename = useCallback(() => setRenaming(false), []);+ const handleToggleEnabled = useCallback(+ () => patch(t('widgets.layers.actions.toggleVisibility'), { isEnabled: !group.isEnabled }),+ [group.isEnabled, patch, t]+ );+ const handleToggleLock = useCallback(+ () => patch(t('widgets.layers.actions.toggleLock'), { isLocked: !group.isLocked }),+ [group.isLocked, patch, t]+ );+ const handleToggleHidden = useCallback(+ () =>+ commitPrepared(t('widgets.layers.actions.toggleHidden'), (model) =>+ model.prepare({ type: 'set-hidden', updates: [{ id: group.id, isHidden: group.isHidden !== true }] })+ ),+ [commitPrepared, group.id, group.isHidden, t]+ );+ const handleGroup = useCallback(+ () => groupLayers(engine, projectId, selection(), t('widgets.layers.actions.group')),+ [engine, projectId, selection, t]+ );+ const handleUngroup = useCallback(+ () => ungroupLayers(engine, selection(), t('widgets.layers.actions.ungroup')),+ [engine, selection, t]+ );+ const handleDuplicate = useCallback(async () => {+ if (!engine) {+ return;+ }+ try {+ const result = await engine.layers.duplicateLayers(selection());+ if (result.status === 'duplicated') {+ publishLayerPanelSelection({ primaryId: result.selectedLayerId, projectId, selectedIds: result.duplicateIds });+ return;+ }+ if (result.status === 'busy') {+ return;+ }+ } catch {+ // The engine leaves the document unchanged on a rejected transaction.+ }+ notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.copyFailed'));+ }, [engine, notify, projectId, selection, t]);+ const handleDelete = useCallback(+ () =>+ commitPrepared(t('widgets.layers.actions.delete'), (model) =>+ model.prepare({ ids: selection(), type: 'remove' })+ ),+ [commitPrepared, selection, t]+ );+ const handleArrange = useCallback(+ (kind: LayerStackMoveKind, label: string) => () =>+ commitPrepared(label, (model) => model.prepare({ ids: selection(), kind, type: 'move' })),+ [commitPrepared, selection]+ );++ const locked = editingLocked;+ const hideable = isOverlayStack(stack);++ const items = (+ <MenuContent minW="13rem" py="1">+ {ARRANGE.map((entry) => (+ <Menu.Item+ key={entry.kind}+ disabled={locked || frozen}+ value={entry.kind}+ onSelect={handleArrange(entry.kind, t(`widgets.layers.actions.${entry.key}`))}+ >+ <MenuRow icon={entry.icon} label={t(`widgets.layers.actions.${entry.key}`)} />+ </Menu.Item>+ ))}+ <Menu.Separator borderColor="border.subtle" />+ <Menu.Item disabled={locked} value="rename" onSelect={openRename}>+ <MenuRow icon={PencilIcon} label={t('widgets.layers.actions.rename')} />+ </Menu.Item>+ <Menu.Item disabled={locked || !engine || frozen} value="duplicate" onSelect={handleDuplicate}>+ <MenuRow icon={CopyIcon} label={t('widgets.layers.actions.duplicate')} />+ </Menu.Item>+ <Menu.Item disabled={locked || !groupable} value="group" onSelect={handleGroup}>+ <MenuRow icon={FolderPlusIcon} label={t('widgets.layers.actions.group')} />+ </Menu.Item>+ <Menu.Item disabled={locked || frozen || group.isLocked} value="ungroup" onSelect={handleUngroup}>+ <MenuRow icon={UngroupIcon} label={t('widgets.layers.actions.ungroup')} />+ </Menu.Item>+ <Menu.Separator borderColor="border.subtle" />+ <Menu.Item disabled={locked} value="enabled" onSelect={handleToggleEnabled}>+ <MenuRow+ icon={group.isEnabled ? EyeOffIcon : EyeIcon}+ label={t(group.isEnabled ? 'widgets.layers.actions.hide' : 'widgets.layers.actions.show')}+ />+ </Menu.Item>+ {hideable ? (+ <Menu.Item disabled={locked} value="hidden" onSelect={handleToggleHidden}>+ <MenuRow icon={group.isHidden ? EyeIcon : EyeOffIcon} label={t('widgets.layers.actions.toggleHidden')} />+ </Menu.Item>+ ) : null}+ <Menu.Item disabled={locked} value="lock" onSelect={handleToggleLock}>+ <MenuRow+ icon={group.isLocked ? LockOpenIcon : LockIcon}+ label={t(group.isLocked ? 'widgets.layers.actions.unlock' : 'widgets.layers.actions.lock')}+ />+ </Menu.Item>+ <Menu.Separator borderColor="border.subtle" />+ <Menu.Item color="fg.error" disabled={locked || holdsLocked} value="delete" onSelect={handleDelete}>+ <MenuRow icon={Trash2Icon} label={t('widgets.layers.actions.delete')} />+ </Menu.Item>+ </MenuContent>+ );++ return (+ <>+ <Menu.Root lazyMount positioning={MENU_POSITIONING} unmountOnExit>+ <Menu.Trigger asChild>+ <IconButton+ aria-label={t('widgets.layers.options')}+ color="fg.muted"+ size="2xs"+ variant="ghost"+ onClick={stopPropagation}+ >+ <MoreVerticalIcon />+ </IconButton>+ </Menu.Trigger>+ <Portal>+ <Menu.Positioner>{items}</Menu.Positioner>+ </Portal>+ </Menu.Root>+ {anchor ? (+ <Menu.Root+ lazyMount+ open+ positioning={anchoredPositioning}+ unmountOnExit+ onOpenChange={handleAnchoredOpenChange}+ >+ <Portal>+ <Menu.Positioner>{items}</Menu.Positioner>+ </Portal>+ </Menu.Root>+ ) : null}+ <RenameDialog+ initialName={group.name}+ isOpen={renaming}+ label={t('widgets.layers.actions.rename')}+ submitLabel={t('widgets.layers.actions.rename')}+ title={t('widgets.layers.actions.rename')}+ onClose={closeRename}+ onSubmit={handleRename}+ />+ </>+ );+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsxdeleted file mode 100644index 868280484e..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx+++ /dev/null@@ -1,343 +0,0 @@-import type { DragEndEvent } from '@dnd-kit/core';-import type { CanvasLayerContract, LayerStackKind } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { LayerSelectionModifiers } from '@workbench/layerPanelState';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import type { LucideIcon } from 'lucide-react';-import type { Dispatch } from 'react';--import { Collapsible, HStack, Icon, Stack, Text } from '@chakra-ui/react';-import { closestCenter, DndContext, KeyboardSensor, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';-import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifiers';-import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';-import { IconButton, toaster, Tooltip } from '@platform/ui';-import { canMergeVisibleRasters } from '@workbench/canvas-engine/api';-import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';-import { useActiveProjectName } from '@workbench/WorkbenchContext';-import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';-import { useCallback, useMemo } from 'react';-import { useTranslation } from 'react-i18next';--import { groupAddItemId } from './addLayerMenu';-import { LAYER_KEYBOARD_SENSOR_OPTIONS } from './layerDndConfig';-import {- canExportRasterPsd,- getGroupActions,- groupVisibilityAxis,- isGroupAllVisible,- planGroupHiddenToggle,- planGroupVisibilityToggle,-} from './layerGroupActions';-import { reorderSelectionWithinGroup } from './layerGroups';-import { LayerListItem, type LayerListItemEngine } from './LayerListItem';-import { getPsdExportNoticeKey } from './psdExportNotice';-import { useAddLayer } from './useAddLayer';--type LayerGroupEngine = LayerListItemEngine & Pick<CanvasEngineHandle, 'exports' | 'interaction' | 'layers'>;--const DND_MODIFIERS = [restrictToVerticalAxis, restrictToParentElement];-const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } } as const;--interface LayerGroupSectionProps {- dispatch: Dispatch<CanvasProjectMutation>;- engine: LayerGroupEngine | null;- groupKey: LayerStackKind;- groupLayers: readonly CanvasLayerContract[];- isCollapsed: boolean;- layers: readonly CanvasLayerContract[];- onSelectLayer: (layerId: string, modifiers: LayerSelectionModifiers) => void;- onToggleCollapse: (groupKey: LayerStackKind) => void;- selectedIds: readonly string[];- selectedLayerId: string | null;-}--/**- * One collapsible type-group section: a header (chevron + name + count + a- * right-aligned action cluster) and, when expanded, the group's rows in a- * self-contained `DndContext`. Scoping DnD to the group means a drag can never see- * (or drop onto) another group's rows — cross-group moves are structurally- * impossible. Collapsing a group unmounts only its own rows, so drag-and-drop in- * the other (still-expanded) groups is unaffected.- */-export const LayerGroupSection = ({- dispatch,- engine,- groupKey,- groupLayers,- isCollapsed,- layers,- onSelectLayer,- onToggleCollapse,- selectedIds,- selectedLayerId,-}: LayerGroupSectionProps) => {- const commitPrepared = usePreparedCommit(engine);- const { t } = useTranslation();- const editingLocked = useCanvasDocumentEditingLocked(engine);-- const sensors = useSensors(- useSensor(PointerSensor, POINTER_SENSOR_OPTIONS),- useSensor(KeyboardSensor, LAYER_KEYBOARD_SENSOR_OPTIONS)- );-- const groupIds = useMemo(() => groupLayers.map((layer) => layer.id), [groupLayers]);-- const handleDragEnd = useCallback(- (event: DragEndEvent) => {- if (editingLocked) {- return;- }- const { active, over } = event;- if (!over) {- return;- }- const next = reorderSelectionWithinGroup(layers, String(active.id), String(over.id), selectedIds);- if (!next) {- return;- }- commitPrepared(t('widgets.layers.actions.reorder'), (model) =>- model.prepare({ stacks: [next], type: 'reorder' })- );- },- [commitPrepared, editingLocked, layers, selectedIds, t]- );-- const handleToggleCollapse = useCallback(() => onToggleCollapse(groupKey), [groupKey, onToggleCollapse]);-- return (- <Stack gap="1">- {/*- `px` matches a row's own content edge (the list's `px="1"` plus each- row's `p="1.5"`), so the header chevron and its action cluster sit in- the same columns as the rows below.- */}- <HStack gap="1" px="2.5">- <IconButton- aria-label={t(isCollapsed ? 'widgets.layers.groupActions.expand' : 'widgets.layers.groupActions.collapse')}- color="fg.subtle"- size="2xs"- variant="ghost"- onClick={handleToggleCollapse}- >- <Icon- as={ChevronDownIcon}- boxSize="3.5"- transform={isCollapsed ? 'rotate(-90deg)' : undefined}- transitionDuration="fast"- transitionProperty="transform"- />- </IconButton>- <Text- // `fg.subtle` at this size reaches only 3.56:1 on the panel surface,- // short of WCAG AA. The axe gate catches it intermittently, because- // the header has to be scrolled into view to be scanned.- color="fg.muted"- cursor="pointer"- flex="1"- fontSize="2xs"- fontWeight="700"- textTransform="uppercase"- truncate- userSelect="none"- onClick={handleToggleCollapse}- >- {t(`widgets.layers.groups.${groupKey}`)} ({groupLayers.length})- </Text>- <GroupActions- engine={engine}- editingLocked={editingLocked}- groupKey={groupKey}- groupLayers={groupLayers}- layers={layers}- />- </HStack>- {/* unmountOnExit: collapsing must UNMOUNT the rows (not just hide them) so an- open per-row properties popover — and any control-layer filter preview it- hosts — is torn down with them (Task 38/39 cleanup contract). */}- <Collapsible.Root lazyMount open={!isCollapsed} unmountOnExit>- <Collapsible.Content>- <DndContext- collisionDetection={closestCenter}- modifiers={DND_MODIFIERS}- sensors={sensors}- onDragEnd={handleDragEnd}- >- <SortableContext items={groupIds} strategy={verticalListSortingStrategy}>- <Stack gap="0.5" px="1">- {groupLayers.map((layer) => (- <LayerListItem- key={layer.id}- dispatch={dispatch}- editingLocked={editingLocked}- engine={engine}- isPrimarySelected={layer.id === selectedLayerId}- isSelected={selectedIds.includes(layer.id)}- layer={layer}- layers={layers}- onSelect={onSelectLayer}- />- ))}- </Stack>- </SortableContext>- </DndContext>- </Collapsible.Content>- </Collapsible.Root>- </Stack>- );-};--/**- * The right-aligned group-header action cluster. The set of actions is data- * (`getGroupActions`), so Task 44's PSD export button drops in by extending that- * array + this switch — no new prop wiring.- */-const GroupActions = ({- editingLocked,- engine,- groupKey,- groupLayers,- layers,-}: {- editingLocked: boolean;- engine: LayerGroupEngine | null;- groupKey: LayerStackKind;- groupLayers: readonly CanvasLayerContract[];- layers: readonly CanvasLayerContract[];-}) => {- const commitPrepared = usePreparedCommit(engine);- const { t } = useTranslation();- const addLayer = useAddLayer();- const projectName = useActiveProjectName();- const allVisible = isGroupAllVisible(groupLayers, groupVisibilityAxis(groupKey));- // Enablement and execution share the same contributor selector and the- // engine's live-content predicate, so empty paint layers do not enable an op.- const canMerge =- !editingLocked &&- !!engine &&- groupKey === 'raster' &&- canMergeVisibleRasters(layers, engine.exports.hasExportableLayerContent);- const canExport = !!engine && groupKey === 'raster' && canExportRasterPsd(layers);-- const handleNew = useCallback(() => addLayer(groupAddItemId(groupKey)), [addLayer, groupKey]);-- const handleToggleVisibility = useCallback(() => {- // Overlay groups toggle the DISPLAY axis — "get these out of my way" must- // not change the generated image. The raster group has no display axis, so- // it keeps toggling enablement.- if (groupVisibilityAxis(groupKey) === 'hidden') {- const { updates } = planGroupHiddenToggle(groupLayers);- if (updates.length === 0) {- return;- }- commitPrepared(t('widgets.layers.groupActions.toggleHidden'), (model) =>- model.prepare({ type: 'set-hidden', updates })- );- return;- }- const { updates } = planGroupVisibilityToggle(groupLayers);- commitPrepared(t('widgets.layers.groupActions.toggleVisibility'), (model) =>- model.prepare({ type: 'set-enabled', updates })- );- }, [commitPrepared, groupKey, groupLayers, t]);-- const handleMergeVisible = useCallback(() => {- if (!engine) {- return;- }- void engine.layers.mergeVisibleRasterLayers().then((result) => {- if (result === 'not-ready') {- toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });- } else if (result === 'over-budget') {- toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });- }- });- }, [engine, t]);-- const handleExportPsd = useCallback(async () => {- if (!engine) {- return;- }- // Read-only: no dispatch, no history. The engine lazily loads `ag-psd`,- // bakes the raster layers, and triggers the download. Surface the refusal- // cases (still-loading caches / oversized bounds / nothing to export).- try {- const result = await engine.exports.exportRasterLayersToPsd(projectName);- const noticeKey = getPsdExportNoticeKey(result);- if (noticeKey) {- toaster.create({ title: t(noticeKey), type: 'warning' });- }- } catch {- toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' });- }- }, [engine, projectName, t]);-- const actions = getGroupActions(groupKey);-- return (- <HStack gap="0.5">- {actions.map((action) => {- switch (action) {- case 'mergeVisible':- return (- <GroupActionButton- key={action}- disabled={!canMerge}- icon={LayersIcon}- label={t('widgets.layers.groupActions.mergeVisible')}- onClick={handleMergeVisible}- />- );- case 'exportPsd':- return (- <GroupActionButton- key={action}- disabled={editingLocked || !canExport}- icon={FileDownIcon}- label={t('widgets.layers.groupActions.exportPsd')}- onClick={handleExportPsd}- />- );- case 'toggleVisibility':- return (- <GroupActionButton- key={action}- disabled={editingLocked}- icon={allVisible ? EyeIcon : EyeOffIcon}- label={t(allVisible ? 'widgets.layers.groupActions.hideAll' : 'widgets.layers.groupActions.showAll')}- onClick={handleToggleVisibility}- />- );- case 'new':- return (- <GroupActionButton- key={action}- disabled={editingLocked}- icon={PlusIcon}- label={t('widgets.layers.groupActions.new')}- onClick={handleNew}- />- );- }- })}- </HStack>- );-};--const GroupActionButton = ({- disabled,- icon,- label,- onClick,-}: {- disabled?: boolean;- icon: LucideIcon;- label: string;- onClick: () => void;-}) => (- <Tooltip content={label}>- <IconButton aria-label={label} color="fg.subtle" disabled={disabled} size="2xs" variant="ghost" onClick={onClick}>- <Icon as={icon} boxSize="3.5" />- </IconButton>- </Tooltip>-);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.test.tsdeleted file mode 100644index d3a63a7f57..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.test.ts+++ /dev/null@@ -1,25 +0,0 @@-import { describe, expect, it } from 'vitest';--import { getLayerListItemInteractionState } from './LayerListItem';--describe('getLayerListItemInteractionState', () => {- it('keeps selection available while disabling document edits and sorting during an operation', () => {- expect(getLayerListItemInteractionState(true)).toEqual({- canRename: false,- canSelect: true,- canToggleLock: false,- canToggleVisibility: false,- sortableDisabled: true,- });- });-- it('enables ordinary row editing and sorting when document editing is unlocked', () => {- expect(getLayerListItemInteractionState(false)).toEqual({- canRename: true,- canSelect: true,- canToggleLock: true,- canToggleVisibility: true,- sortableDisabled: false,- });- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsxdeleted file mode 100644index 70d0e13afe..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx+++ /dev/null@@ -1,406 +0,0 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/api';-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';-import type { LayerSelectionModifiers } from '@workbench/layerPanelState';-import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';-import type { Dispatch, KeyboardEvent, MouseEvent } from 'react';--import { Badge, Box, chakra, HStack, Input, Stack } from '@chakra-ui/react';-import { useSortable } from '@dnd-kit/sortable';-import { CSS } from '@dnd-kit/utilities';-import { IconButton, Row, ToggleDot } from '@platform/ui';-import { MiddleTruncate } from '@platform/ui/MiddleTruncate';-import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';-import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';-import { EyeIcon, EyeOffIcon, LockIcon, LockOpenIcon } from 'lucide-react';-import { useCallback, useMemo, useState } from 'react';-import { useTranslation } from 'react-i18next';--import { ControlLayerWarningIcon } from './ControlLayerWarningIcon';-import {- CanvasLayerContextMenu,- type CanvasLayerContextMenuTarget,- LayerContextMenu,- type LayerContextMenuEngine,-} from './LayerContextMenu';-import { createLayerMenuTargetFromContextEvent } from './layerMenuState';-import { LayerPropertiesPopover, type LayerPropertiesEngine } from './LayerPropertiesPopover';-import { LayerThumbnail } from './LayerThumbnail';--const ROW_INTERACTIVE_DESCENDANTS = {- '& button, & input': {- pointerEvents: 'auto',- },-};-const ROW_SELECTION_FOCUS = {- outline: '2px solid',- outlineColor: 'accent.solid',- outlineOffset: '-2px',-};-const LAYER_ROW_BACKGROUND_TRANSITION = 'background min(40ms, var(--wb-motion-duration-fast)) ease-out';-const VISIBILITY_DOT_BASE = {- borderRadius: 'full',- borderWidth: '1px',- content: '""',- h: '3',- inset: '50% auto auto 50%',- position: 'absolute',- transform: 'translate(-50%, -50%)',- transition: 'background var(--wb-motion-duration-fast), border-color var(--wb-motion-duration-fast)',- w: '3',-};-const VISIBILITY_DOT_CHECKED = {- ...VISIBILITY_DOT_BASE,- bg: 'accent.solid',- borderColor: 'accent.solid',-};-const VISIBILITY_DOT_UNCHECKED = {- ...VISIBILITY_DOT_BASE,- bg: 'transparent',- borderColor: 'border.emphasized',-};-const VISIBILITY_DOT_CHECKED_HOVER = {- _before: {- bg: 'accent.emphasized',- borderColor: 'accent.emphasized',- },-};-const VISIBILITY_DOT_UNCHECKED_HOVER = {- _before: {- borderColor: 'fg.muted',- },-};--export type LayerListItemEngine = LayerContextMenuEngine & LayerPropertiesEngine & Pick<CanvasEngineHandle, 'previews'>;--const layerBadgeKey = (layer: CanvasLayerContract): string => {- if (layer.type === 'raster') {- return layer.source.type === 'image' ? 'widgets.layers.types.image' : 'widgets.layers.types.paint';- }- return `widgets.layers.types.${layer.type}`;-};--interface LayerListItemProps {- dispatch: Dispatch<CanvasProjectMutation>;- editingLocked: boolean;- engine: LayerListItemEngine | null;- isPrimarySelected: boolean;- isSelected: boolean;- layer: CanvasLayerContract;- layers: readonly CanvasLayerContract[];- onSelect: (layerId: string, modifiers: LayerSelectionModifiers) => void;-}--export const getLayerListItemInteractionState = (editingLocked: boolean) => ({- canRename: !editingLocked,- canSelect: true,- canToggleLock: !editingLocked,- canToggleVisibility: !editingLocked,- sortableDisabled: editingLocked,-});--export const LayerListItem = ({- dispatch,- editingLocked,- engine,- isPrimarySelected,- isSelected,- layer,- layers,- onSelect,-}: LayerListItemProps) => {- const commitPrepared = usePreparedCommit(engine);- const { t } = useTranslation();- const interaction = getLayerListItemInteractionState(editingLocked);- const { attributes, isDragging, listeners, setActivatorNodeRef, setNodeRef, transform, transition } = useSortable({- disabled: interaction.sortableDisabled,- id: layer.id,- });- const [isEditing, setIsEditing] = useState(false);- const [draftName, setDraftName] = useState(layer.name);- const [contextMenuTarget, setContextMenuTarget] = useState<CanvasLayerContextMenuTarget | null>(null);-- const dndStyle = useMemo(- () => ({- opacity: isDragging ? 0.4 : undefined,- position: 'relative' as const,- transform: CSS.Translate.toString(transform),- transition,- zIndex: isDragging ? 1 : undefined,- }),- [isDragging, transform, transition]- );-- const handleSelect = useCallback(- (event: MouseEvent<HTMLButtonElement>) => {- if (interaction.canSelect) {- onSelect(layer.id, { additive: event.metaKey || event.ctrlKey, range: event.shiftKey });- }- },- [interaction.canSelect, layer.id, onSelect]- );-- const selectForContextMenu = useCallback(() => {- if (!isSelected) {- onSelect(layer.id, { additive: false, range: false });- }- }, [isSelected, layer.id, onSelect]);-- const patchBase = useCallback(- (label: string, forward: Partial<CanvasLayerContract>) => {- commitPrepared(label, (model) => model.prepare({ id: layer.id, patch: forward, type: 'patch' }));- },- [commitPrepared, layer.id]- );-- const handleToggleVisible = useCallback(- (checked: boolean) => {- patchBase(t('widgets.layers.actions.toggleVisibility'), { isEnabled: checked });- },- [patchBase, t]- );-- const handleToggleHidden = useCallback(- (event: { stopPropagation: () => void }) => {- event.stopPropagation();- const isHidden = !isLayerHidden(layer);- commitPrepared(t('widgets.layers.actions.toggleHidden'), (model) =>- model.prepare({ type: 'set-hidden', updates: [{ id: layer.id, isHidden }] })- );- },- [commitPrepared, layer, t]- );-- const handleToggleLock = useCallback(- (event: { stopPropagation: () => void }) => {- event.stopPropagation();- patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked });- },- [layer.isLocked, patchBase, t]- );-- const startEditing = useCallback(() => {- setDraftName(layer.name);- setIsEditing(true);- }, [layer.name]);-- const commitName = useCallback(() => {- setIsEditing(false);- const name = draftName.trim();- if (name && name !== layer.name) {- patchBase(t('widgets.layers.actions.rename'), { name });- }- }, [draftName, layer.name, patchBase, t]);-- const handleNameKeyDown = useCallback(- (event: KeyboardEvent<HTMLInputElement>) => {- // Stop ONLY the two keys the rename owns. A blanket stop would also stop- // the native event reaching the window, killing every global hotkey while- // renaming; the hotkey runtime already refuses to fire non-`allowInEditable`- // bindings for a focused input, so nothing else needs suppressing here.- // Escape does need it: the engine's own window listener would otherwise- // take it as a canvas deselect.- if (event.key === 'Enter') {- event.stopPropagation();- commitName();- } else if (event.key === 'Escape') {- event.stopPropagation();- setIsEditing(false);- }- },- [commitName]- );-- const handleNameChange = useCallback((event: { target: { value: string } }) => setDraftName(event.target.value), []);-- const handleContextMenu = useCallback(- (event: MouseEvent<HTMLElement>) => {- if (!isSelected) {- selectForContextMenu();- }- setContextMenuTarget(createLayerMenuTargetFromContextEvent(layer.id, event));- },- [isSelected, layer.id, selectForContextMenu]- );-- const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);-- /**- * Pointer listeners only. dnd-kit starts a keyboard drag on Enter and- * inspects nothing but the key code, so with no grip to own that gesture the- * activator is left unattached — Enter on a row belongs to selection, and- * `mod+Enter` (Invoke) can no longer begin an invisible drag that leaves the- * row at drag opacity. Keyboard reordering is the context menu's Move actions.- */- const sortableRowListeners = useMemo(() => {- if (interaction.sortableDisabled || !listeners) {- return {};- }- const { onKeyDown: _onKeyDown, ...rest } = listeners;- return rest;- }, [interaction.sortableDisabled, listeners]);-- // The selection button carries them, and owns its own role, focus, and- // pressed state — dnd-kit's versions of those would overwrite it.- const sortableAttributes = useMemo(() => {- if (interaction.sortableDisabled) {- return {};- }- const { role: _role, tabIndex: _tabIndex, 'aria-pressed': _ariaPressed, ...rest } = attributes;- return rest;- }, [attributes, interaction.sortableDisabled]);-- return (- <Box ref={setNodeRef} style={dndStyle}>- <Row- {...sortableRowListeners}- active={isSelected ? 'muted' : undefined}- borderStartColor={isPrimarySelected ? 'accent.solid' : 'transparent'}- borderStartWidth="2px"- cursor={isDragging ? 'grabbing' : 'default'}- display="flex"- gap="1.5"- p="1.5"- position="relative"- transition={LAYER_ROW_BACKGROUND_TRANSITION}- onContextMenu={handleContextMenu}- >- {/*- No grip: the row itself is the pointer drag target, and the- row-covering selection button carries the sortable role description so- the affordance is still announced. dnd-kit's `role` / `tabIndex` /- `aria-pressed` are dropped so the button keeps its own selection- semantics — notably Enter, which selects rather than starting a drag.- Keyboard reordering is the context menu's Move actions.- */}- <chakra.button- ref={setActivatorNodeRef}- {...sortableAttributes}- aria-current={isPrimarySelected ? 'true' : undefined}- aria-label={t('widgets.layers.actions.select', { name: layer.name })}- aria-pressed={isSelected}- data-primary={isPrimarySelected || undefined}- cursor={isDragging ? 'grabbing' : undefined}- inset="0"- position="absolute"- rounded="sm"- type="button"- _focusVisible={ROW_SELECTION_FOCUS}- onClick={handleSelect}- onDoubleClick={interaction.canRename ? startEditing : undefined}- />- <HStack css={ROW_INTERACTIVE_DESCENDANTS} gap="1.5" pointerEvents="none" position="relative" w="full">- <LayerThumbnail engine={engine} layer={layer} />- <Stack flex="1" gap="0.5" minW="0">- {isEditing ? (- <Input- autoFocus- aria-label={t('widgets.layers.actions.rename')}- disabled={!interaction.canRename}- size="2xs"- value={draftName}- onBlur={commitName}- onChange={handleNameChange}- onKeyDown={handleNameKeyDown}- onPointerDown={stopPropagation}- />- ) : (- <MiddleTruncate- aria-disabled={!interaction.canRename}- fontSize="2xs"- fontWeight="700"- text={layer.name}- />- )}- <HStack alignSelf="flex-start" gap="1">- <Badge colorPalette="gray" size="xs" variant="subtle">- {t(layerBadgeKey(layer))}- </Badge>- <ControlLayerWarningIcon layer={layer} />- </HStack>- </Stack>- {/*- One control cluster on the same 0.5 rhythm as the group header's, so- every row's trailing icons land in the same columns as each other and- as the header above. Raster layers have no display axis, so their- hide slot is held open rather than collapsed — otherwise their- remaining controls would shift out of column against masks.- */}- <HStack flexShrink="0" gap="0.5">- {isHideableLayer(layer) ? (- <IconButton- aria-label={t('widgets.layers.actions.toggleHidden')}- aria-pressed={!isLayerHidden(layer)}- color={isLayerHidden(layer) ? 'fg.subtle' : 'fg'}- disabled={!interaction.canToggleVisibility}- size="2xs"- variant="ghost"- onClick={handleToggleHidden}- onPointerDown={stopPropagation}- >- {isLayerHidden(layer) ? <EyeOffIcon /> : <EyeIcon />}- </IconButton>- ) : (- <Box boxSize="6" />- )}- {/*- `display="flex"` is load bearing, not cosmetic: as a block box this- wrapper lays its button out on a text baseline, and the descender- space below made it 30px tall and pushed the control 3px above the- centre line its sibling icon buttons sit on.- */}- <Box display="flex" flexShrink="0" onClick={stopPropagation} onPointerDown={stopPropagation}>- <ToggleDot- _before={layer.isEnabled ? VISIBILITY_DOT_CHECKED : VISIBILITY_DOT_UNCHECKED}- _focusVisible={ROW_SELECTION_FOCUS}- _hover={layer.isEnabled ? VISIBILITY_DOT_CHECKED_HOVER : VISIBILITY_DOT_UNCHECKED_HOVER}- bg="transparent"- borderWidth="0"- checked={layer.isEnabled}- cursor={interaction.canToggleVisibility ? 'pointer' : 'not-allowed'}- disabled={!interaction.canToggleVisibility}- h="6"- label={t('widgets.layers.actions.toggleVisibility')}- position="relative"- transition="none"- w="6"- onCheckedChange={handleToggleVisible}- />- </Box>- <IconButton- aria-label={t('widgets.layers.actions.toggleLock')}- color={layer.isLocked ? 'fg' : 'fg.subtle'}- disabled={!interaction.canToggleLock}- size="2xs"- variant="ghost"- onClick={handleToggleLock}- onPointerDown={stopPropagation}- >- {layer.isLocked ? <LockIcon /> : <LockOpenIcon />}- </IconButton>- <Box- display="flex"- flexShrink="0"- onClick={stopPropagation}- onContextMenu={stopPropagation}- onPointerDown={stopPropagation}- >- <LayerPropertiesPopover engine={engine} layer={layer} />- </Box>- <Box display="flex" flexShrink="0" onPointerDown={stopPropagation}>- <LayerContextMenu dispatch={dispatch} engine={engine} layer={layer} layers={layers} />- </Box>- </HStack>- </HStack>- </Row>- <CanvasLayerContextMenu- dispatch={dispatch}- engine={engine}- layers={layers}- target={contextMenuTarget}- onClose={closeContextMenu}- />- </Box>- );-};--const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsxindex 21cf2a9524..779eb21a81 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx@@ -1,14 +1,11 @@+import type { CanvasDocumentContractV3, LayerStackMoveKind } from '@workbench/canvas-engine/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { HStack, Text } from '@chakra-ui/react';import { toaster } from '@platform/ui';import { IconButton } from '@platform/ui/Button';import { Tooltip } from '@platform/ui/Tooltip';-import {- canMergeSelectedRasters,- type CanvasLayerContract,- type LayerStackMoveKind,-} from '@workbench/canvas-engine/api';+import { canMergeSelectedRasters, collectSubtree, getDocumentIndex } from '@workbench/canvas-engine/api';import { publishLayerPanelSelection } from '@workbench/layerPanelState';import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';@@ -20,6 +17,8 @@ import {CopyIcon,EyeIcon,EyeOffIcon,+ FolderMinusIcon,+ FolderPlusIcon,LockIcon,LockOpenIcon,MergeIcon,@@ -28,21 +27,23 @@ import {import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';+import { canGroupNodes, canUngroupNodes, groupLayers, ungroupLayers } from './layerGroupCommands';+type MultiSelectionEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;const BULK_TOOLTIP_POSITIONING = { placement: 'top' } as const;interface LayerMultiSelectionActionsProps {+ document: CanvasDocumentContractV3;editingLocked: boolean;engine: MultiSelectionEngine | null;- layers: readonly CanvasLayerContract[];projectId: string;selectedIds: readonly string[];}export const LayerMultiSelectionActions = ({+ document,editingLocked,engine,- layers,projectId,selectedIds,}: LayerMultiSelectionActionsProps) => {@@ -50,15 +51,21 @@ export const LayerMultiSelectionActions = ({const { t } = useTranslation();useCanvasRasterContentEpoch(engine);const selected = useMemo(() => {- const ids = new Set(selectedIds);- return layers.filter((layer) => ids.has(layer.id));- }, [layers, selectedIds]);- const allEnabled = selected.every((layer) => layer.isEnabled);- const allLocked = selected.every((layer) => layer.isLocked);- const hasLocked = selected.some((layer) => layer.isLocked);+ const index = getDocumentIndex(document);+ return selectedIds.map((id) => index.byId.get(id)).filter((entry) => entry !== undefined);+ }, [document, selectedIds]);+ const allEnabled = selected.every((entry) => entry.node.isEnabled);+ const allLocked = selected.every((entry) => entry.node.isLocked);+ const anyFrozen = selected.some(+ (entry) => entry.ancestorsLocked || collectSubtree(entry.node).some((node) => node.isLocked)+ );+ const canGroup = canGroupNodes(document, selectedIds);+ const canUngroup = canUngroupNodes(document, selectedIds);+ const model = engine?.document.model() ?? null;const canMergeSelected =!!engine &&- canMergeSelectedRasters(layers, new Set(selectedIds), (layerId) =>+ !!model &&+ canMergeSelectedRasters(model.document, model.compileLeaves(), new Set(selectedIds), (layerId) =>engine.exports.hasExportableLayerContent(layerId));@@ -77,8 +84,7 @@ export const LayerMultiSelectionActions = ({return;}} catch {- // Reducer rejection is failure-atomic; surface the same actionable result- // as a preflight refusal instead of leaking an event-handler exception.+ // Reducer rejection is failure-atomic; surface the same actionable result as a refusal.}if (engine) {toaster.create({ title: t('widgets.layers.actions.copyFailed'), type: 'warning' });@@ -123,17 +129,26 @@ export const LayerMultiSelectionActions = ({const isEnabled = !allEnabled;commitPrepared(t(isEnabled ? 'widgets.layers.actions.enableSelected' : 'widgets.layers.actions.disableSelected'),- (model) => model.prepare({ type: 'set-enabled', updates: selected.map((layer) => ({ id: layer.id, isEnabled })) })+ (model) => model.prepare({ type: 'set-enabled', updates: selectedIds.map((id) => ({ id, isEnabled })) }));- }, [allEnabled, commitPrepared, selected, t]);+ }, [allEnabled, commitPrepared, selectedIds, t]);const toggleLocked = useCallback(() => {const isLocked = !allLocked;commitPrepared(t(isLocked ? 'widgets.layers.actions.lockSelected' : 'widgets.layers.actions.unlockSelected'),- (model) => model.prepare({ type: 'set-locked', updates: selected.map((layer) => ({ id: layer.id, isLocked })) })+ (model) => model.prepare({ type: 'set-locked', updates: selectedIds.map((id) => ({ id, isLocked })) }));- }, [allLocked, commitPrepared, selected, t]);+ }, [allLocked, commitPrepared, selectedIds, t]);++ const groupSelected = useCallback(+ () => groupLayers(engine, projectId, selectedIds, t('widgets.layers.actions.groupSelected')),+ [engine, projectId, selectedIds, t]+ );+ const ungroupSelected = useCallback(+ () => ungroupLayers(engine, selectedIds, t('widgets.layers.actions.ungroupSelected')),+ [engine, selectedIds, t]+ );const deleteSelected = useCallback(() => {commitPrepared(t('widgets.layers.actions.deleteSelected'), (model) =>@@ -176,6 +191,18 @@ export const LayerMultiSelectionActions = ({label={t('widgets.layers.actions.moveSelectedToBack')}onClick={moveToBack}/>+ <BulkActionButton+ disabled={editingLocked || !engine || !canGroup}+ icon={FolderPlusIcon}+ label={t('widgets.layers.actions.groupSelected')}+ onClick={groupSelected}+ />+ <BulkActionButton+ disabled={editingLocked || !engine || !canUngroup}+ icon={FolderMinusIcon}+ label={t('widgets.layers.actions.ungroupSelected')}+ onClick={ungroupSelected}+ /><BulkActionButtondisabled={editingLocked}icon={allEnabled ? EyeOffIcon : EyeIcon}@@ -202,7 +229,7 @@ export const LayerMultiSelectionActions = ({/><BulkActionButtoncolorPalette="red"- disabled={editingLocked || hasLocked}+ disabled={editingLocked || anyFrozen}icon={Trash2Icon}label={t('widgets.layers.actions.deleteSelected')}onClick={deleteSelected}diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.browser.test.tsxsimilarity index 72%rename from invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsxrename to invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.browser.test.tsxindex a4ef766398..327d317b63 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.browser.test.tsx@@ -1,21 +1,14 @@/* oxlint-disable react-perf/jsx-no-new-function-as-prop */-import type { PreparedFlatEdit } from '@workbench/canvas-engine/api';+import type { CanvasNodeContract, PreparedDocumentEdit } from '@workbench/canvas-engine/api';import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';import { ChakraProvider } from '@chakra-ui/react';-import {- closestCenter,- DndContext,- KeyboardSensor,- PointerSensor,- useSensor,- useSensors,- type DragEndEvent,-} from '@dnd-kit/core';+import { closestCenter, DndContext, PointerSensor, useSensor, useSensors, type DragEndEvent } from '@dnd-kit/core';import { arrayMove, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';import { system } from '@theme/system';-import { createFlatDocumentModel } from '@workbench/canvas-engine/api';-import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';+import { createDocumentModel } from '@workbench/canvas-engine/api';+import { groupContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';import { createLayerPanelState, selectLayerInPanel } from '@workbench/layerPanelState';import { createInstance } from 'i18next';import { act, useCallback, useMemo, useState } from 'react';@@ -24,9 +17,9 @@ import { I18nextProvider, initReactI18next } from 'react-i18next';import { afterEach, describe, expect, it, vi } from 'vitest';import { userEvent } from 'vitest/browser';-import { LAYER_KEYBOARD_SENSOR_OPTIONS } from './layerDndConfig';-import { LayerListItem, type LayerListItemEngine } from './LayerListItem';import { createEmptyPaintLayer } from './layerOps';+import { LayerRow, type LayerRowEngine } from './LayerRow';+import { buildLayerStackRows } from './layerTreeRows';vi.mock('./ControlLayerWarningIcon', () => ({ControlLayerWarningIcon: () => null,@@ -53,6 +46,10 @@ vi.mock('./LayerContextMenu', () => ({LayerContextMenu: () => <button aria-label="Layer menu" type="button" />,}));+vi.mock('./LayerGroupContextMenu', () => ({+ LayerGroupContextMenu: () => <button aria-label="Group menu" type="button" />,+}));+const i18n = createInstance();void i18n.use(initReactI18next).init({fallbackLng: 'en',@@ -64,11 +61,16 @@ void i18n.use(initReactI18next).init({widgets: {layers: {actions: {+ collapseGroup: 'Collapse group',+ expandGroup: 'Expand group',+ groupLocked: 'Locked by a group',reorder: 'Reorder layer',select: 'Select {{name}}',toggleLock: 'Toggle lock',toggleVisibility: 'Toggle visibility',},+ groupSummary_one: '{{count}} layer',+ groupSummary_other: '{{count}} layers',types: { paint: 'Paint' },},},@@ -77,47 +79,60 @@ void i18n.use(initReactI18next).init({},});-const INITIAL_LAYERS = [createEmptyPaintLayer('First layer', 'first'), createEmptyPaintLayer('Second layer', 'second')];+const INITIAL_NODES: CanvasNodeContract[] = [+ createEmptyPaintLayer('First layer', 'first'),+ createEmptyPaintLayer('Second layer', 'second'),+];const requestLayerThumbnail = vi.fn();-const Harness = () => {- const [layers, setLayers] = useState(INITIAL_LAYERS);+const Harness = ({ initialNodes = INITIAL_NODES }: { initialNodes?: CanvasNodeContract[] }) => {+ const [nodes, setNodes] = useState(initialNodes);+ const [expanded, setExpanded] = useState<ReadonlySet<string>>(() => new Set());const [selection, setSelection] = useState(() => createLayerPanelState('test-project', null));- const sensors = useSensors(- useSensor(PointerSensor, { activationConstraint: { distance: 6 } }),- useSensor(KeyboardSensor, LAYER_KEYBOARD_SENSOR_OPTIONS)- );- const layerIds = useMemo(() => layers.map((layer) => layer.id), [layers]);+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));const selectedLayerId = selection.primaryId;+ const document = useMemo(+ () => ({ ...createEmptyCanvasDocument(), stacks: stacksFrom(nodes), selectedLayerId }),+ [nodes, selectedLayerId]+ );+ const rows = useMemo(() => buildLayerStackRows(document, expanded).raster.rows, [document, expanded]);+ const rowIds = useMemo(() => rows.map((row) => row.id), [rows]);const dispatch = useCallback((mutation: CanvasProjectMutation) => {if (mutation.type === 'setCanvasSelectedLayer') {setSelection(createLayerPanelState('test-project', mutation.id));} else if (mutation.type === 'updateCanvasLayer' && mutation.patch.isEnabled !== undefined) {- setLayers((current) =>- current.map((layer) =>- layer.id === mutation.id ? { ...layer, isEnabled: mutation.patch.isEnabled ?? layer.isEnabled } : layer+ setNodes((current) =>+ current.map((node) =>+ node.id === mutation.id ? { ...node, isEnabled: mutation.patch.isEnabled ?? node.isEnabled } : node));}}, []);const handleSelect = useCallback((id: string, modifiers: { additive: boolean; range: boolean }) => {- setSelection((current) => selectLayerInPanel(current, id, layerIds, modifiers));+ setSelection((current) => selectLayerInPanel(current, id, rowIds, modifiers));},- [layerIds]+ [rowIds]);+ const handleToggleExpanded = useCallback((groupId: string) => {+ setExpanded((current) => {+ const next = new Set(current);+ if (next.has(groupId)) {+ next.delete(groupId);+ } else {+ next.add(groupId);+ }+ return next;+ });+ }, []);const engine = useMemo(() =>({document: {- model: () =>- createFlatDocumentModel(- { ...createEmptyCanvasDocumentV2(), layers, selectedLayerId: selection.primaryId },- { editRevision: 0, projectId: 'test-project' }- ),+ model: () => createDocumentModel(document, { editRevision: 0, projectId: 'test-project' }),},layers: {- commitPrepared: (_label: string, edit: PreparedFlatEdit) => {+ commitPrepared: (_label: string, edit: PreparedDocumentEdit) => {dispatch(edit.forward);return { status: 'committed' as const };},@@ -131,40 +146,42 @@ const Harness = () => {requestLayerThumbnail,},projectId: 'test-project',- }) as unknown as LayerListItemEngine,- [dispatch, layers, selection.primaryId]+ }) as unknown as LayerRowEngine,+ [dispatch, document]);const handleDragEnd = useCallback((event: DragEndEvent) => {if (!event.over || event.active.id === event.over.id) {return;}- setLayers((current) => {- const from = current.findIndex((layer) => layer.id === event.active.id);- const to = current.findIndex((layer) => layer.id === event.over?.id);+ setNodes((current) => {+ const from = current.findIndex((node) => node.id === event.active.id);+ const to = current.findIndex((node) => node.id === event.over?.id);return from === -1 || to === -1 ? current : arrayMove(current, from, to);});}, []);return (<DndContext collisionDetection={closestCenter} sensors={sensors} onDragEnd={handleDragEnd}>- <SortableContext items={layerIds} strategy={verticalListSortingStrategy}>- {layers.map((layer) => (- <LayerListItem- key={layer.id}+ <SortableContext items={rowIds} strategy={verticalListSortingStrategy}>+ {rows.map((row) => (+ <LayerRow+ key={row.id}dispatch={dispatch}+ drag={null}editingLocked={false}engine={engine}- isPrimarySelected={selectedLayerId === layer.id}- isSelected={selection.selectedIds.includes(layer.id)}- layer={layer}- layers={layers}+ isPrimarySelected={selectedLayerId === row.id}+ isSelected={selection.selectedIds.includes(row.id)}+ row={row}onSelect={handleSelect}+ onToggleExpanded={handleToggleExpanded}/>))}</SortableContext><output data-testid="selected-layer">{selectedLayerId ?? 'none'}</output><output data-testid="selected-layers">{selection.selectedIds.join(',') || 'none'}</output>- <output data-testid="layer-order">{layers.map((layer) => layer.id).join(',')}</output>+ <output data-testid="layer-order">{nodes.map((node) => node.id).join(',')}</output>+ <output data-testid="row-order">{rowIds.join(',')}</output></DndContext>);};@@ -173,7 +190,7 @@ let host: HTMLDivElement | null = null;let root: Root | null = null;(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;-const renderHarness = async () => {+const renderHarness = async (initialNodes?: CanvasNodeContract[]) => {host = document.createElement('div');host.style.width = '480px';document.body.append(host);@@ -183,12 +200,13 @@ const renderHarness = async () => {root?.render(<I18nextProvider i18n={i18n}><ChakraProvider value={system}>- <Harness />+ <Harness initialNodes={initialNodes} /></ChakraProvider></I18nextProvider>);});};+const rowOrder = (): string => host!.querySelector<HTMLOutputElement>('[data-testid="row-order"]')!.value;const pointer = (type: string, target: EventTarget, clientX: number, clientY: number): void => {target.dispatchEvent(@@ -211,7 +229,7 @@ afterEach(async () => {vi.clearAllMocks();});-describe('LayerListItem accessibility', () => {+describe('LayerRow accessibility', () => {it('keeps layer-row background feedback nearly immediate', async () => {await renderHarness();@@ -279,7 +297,7 @@ describe('LayerListItem accessibility', () => {);expect(selectedLayers()).toBe('first,second');expect(selectedLayer()).toBe('second');- expect(selectionButton('First layer')).toHaveAttribute('aria-pressed', 'true');+ expect(selectionButton('First layer')).toHaveAttribute('aria-selected', 'true');expect(selectionButton('First layer')).not.toHaveAttribute('aria-current');expect(selectionButton('Second layer')).toHaveAttribute('aria-current', 'true');expect(selectionButton('Second layer')).toHaveAttribute('data-primary', 'true');@@ -409,18 +427,33 @@ describe('LayerListItem accessibility', () => {expect(layerOrder()).toBe('second,first');});- // With no grip there is no keyboard drag gesture to claim Enter, so the- // Enter/Arrow/Enter sequence that used to reorder now moves nothing. Enter- // still selects (covered above); keyboard reordering is the context menu's- // Move actions.- it('no longer starts a keyboard drag from a focused row', async () => {- await renderHarness();- selectionButton('First layer').focus();+ it('expands and collapses a group from its chevron and arrow keys, indenting its children', async () => {+ await renderHarness([+ groupContract('g', [createEmptyPaintLayer('Inner layer', 'inner')], { name: 'Group' }),+ createEmptyPaintLayer('Outer layer', 'outer'),+ ]);+ expect(rowOrder()).toBe('g,outer');+ expect(selectionButton('Group')).toHaveAttribute('aria-expanded', 'false');++ await act(() => userEvent.click(host!.querySelector<HTMLButtonElement>('button[aria-label="Expand group"]')!));+ expect(rowOrder()).toBe('g,inner,outer');+ expect(selectionButton('Group')).toHaveAttribute('aria-expanded', 'true');+ expect(selectionButton('Inner layer')).toHaveAttribute('aria-level', '2');+ expect(getComputedStyle(selectionButton('Inner layer').parentElement!).paddingLeft).toBe('16px');++ selectionButton('Group').focus();+ await act(() => userEvent.keyboard('{ArrowLeft}'));+ expect(rowOrder()).toBe('g,outer');+ });- await act(() => userEvent.keyboard('{Enter}'));- await act(() => userEvent.keyboard('{ArrowDown}'));- await act(() => userEvent.keyboard('{Enter}'));+ it('reports a lock inherited from a group on the child row', async () => {+ await renderHarness([+ groupContract('g', [createEmptyPaintLayer('Inner layer', 'inner')], { isLocked: true, name: 'Group' }),+ ]);+ await act(() => userEvent.click(host!.querySelector<HTMLButtonElement>('button[aria-label="Expand group"]')!));- expect(layerOrder()).toBe('first,second');+ const locks = host!.querySelectorAll<HTMLButtonElement>('button[aria-label="Toggle lock"]');+ expect(locks).toHaveLength(2);+ expect(locks[1]!.querySelector('svg.lucide-lock')).not.toBeNull();});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsxnew file mode 100644index 0000000000..1dd44b7f84--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRow.tsx@@ -0,0 +1,552 @@+import type { CanvasGroupContract, CanvasLayerContract } from '@workbench/canvas-engine/api';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { LayerSelectionModifiers } from '@workbench/layerPanelState';+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { Dispatch, KeyboardEvent, MouseEvent } from 'react';++import { Badge, Box, chakra, HStack, Icon, Input, Stack, Text } from '@chakra-ui/react';+import { useSortable } from '@dnd-kit/sortable';+import { CSS } from '@dnd-kit/utilities';+import { IconButton, Row, ToggleDot, Tooltip } from '@platform/ui';+import { MiddleTruncate } from '@platform/ui/MiddleTruncate';+import { isHideableLayer, isNodeHidden, isOverlayStack } from '@workbench/canvas-engine/api';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import {+ ChevronRightIcon,+ EyeIcon,+ EyeOffIcon,+ FolderIcon,+ FolderOpenIcon,+ LockIcon,+ LockOpenIcon,+} from 'lucide-react';+import { memo, useCallback, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { LayerTreeRow } from './layerTreeRows';++import { ControlLayerWarningIcon } from './ControlLayerWarningIcon';+import {+ CanvasLayerContextMenu,+ type CanvasLayerContextMenuTarget,+ LayerContextMenu,+ type LayerContextMenuEngine,+} from './LayerContextMenu';+import { LayerGroupContextMenu, type LayerGroupContextMenuEngine } from './LayerGroupContextMenu';+import { createLayerMenuTargetFromContextEvent } from './layerMenuState';+import { LayerPropertiesPopover, type LayerPropertiesEngine } from './LayerPropertiesPopover';+import { LayerThumbnail } from './LayerThumbnail';++/** Horizontal offset per nesting level, in CSS pixels; the drag projection uses the same step. */+export const LAYER_TREE_INDENT_PX = 16;++const ROW_INTERACTIVE_DESCENDANTS = {+ '& button, & input': {+ pointerEvents: 'auto',+ },+};+const ROW_SELECTION_FOCUS = {+ outline: '2px solid',+ outlineColor: 'accent.solid',+ outlineOffset: '-2px',+};+const LAYER_ROW_BACKGROUND_TRANSITION = 'background min(40ms, var(--wb-motion-duration-fast)) ease-out';+const VISIBILITY_DOT_BASE = {+ borderRadius: 'full',+ borderWidth: '1px',+ content: '""',+ h: '3',+ inset: '50% auto auto 50%',+ position: 'absolute',+ transform: 'translate(-50%, -50%)',+ transition: 'background var(--wb-motion-duration-fast), border-color var(--wb-motion-duration-fast)',+ w: '3',+};+const VISIBILITY_DOT_CHECKED = { ...VISIBILITY_DOT_BASE, bg: 'accent.solid', borderColor: 'accent.solid' };+/** Enabled on its own, but an ancestor keeps it out of the composite. */+const VISIBILITY_DOT_GATED = { ...VISIBILITY_DOT_BASE, bg: 'transparent', borderColor: 'accent.solid' };+const VISIBILITY_DOT_UNCHECKED = { ...VISIBILITY_DOT_BASE, bg: 'transparent', borderColor: 'border.emphasized' };+const VISIBILITY_DOT_CHECKED_HOVER = { _before: { bg: 'accent.emphasized', borderColor: 'accent.emphasized' } };+const VISIBILITY_DOT_UNCHECKED_HOVER = { _before: { borderColor: 'fg.muted' } };+const INDICATOR_STYLE = { bg: 'accent.solid', borderRadius: 'full', h: '2px', my: '1px' };++export type LayerRowEngine = LayerContextMenuEngine &+ LayerGroupContextMenuEngine &+ LayerPropertiesEngine &+ Pick<CanvasEngineHandle, 'previews'>;++const layerBadgeKey = (layer: CanvasLayerContract): string => {+ if (layer.type === 'raster') {+ return layer.source.type === 'image' ? 'widgets.layers.types.image' : 'widgets.layers.types.paint';+ }+ return `widgets.layers.types.${layer.type}`;+};++export interface LayerRowDragState {+ /** The row travels with the current drag. */+ readonly isDragSource: boolean;+ /** The row stands in for the dragged block: draw the insertion line at this depth instead. */+ readonly indicatorDepth: number | null;+}++interface LayerRowProps {+ dispatch: Dispatch<CanvasProjectMutation>;+ drag: LayerRowDragState | null;+ editingLocked: boolean;+ engine: LayerRowEngine | null;+ isPrimarySelected: boolean;+ isSelected: boolean;+ row: LayerTreeRow;+ onSelect: (id: string, modifiers: LayerSelectionModifiers) => void;+ onToggleExpanded: (groupId: string) => void;+}++export const getLayerRowInteractionState = (editingLocked: boolean) => ({+ canRename: !editingLocked,+ canSelect: true,+ canToggleLock: !editingLocked,+ canToggleVisibility: !editingLocked,+ sortableDisabled: editingLocked,+});++const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();++const LayerRowComponent = ({+ dispatch,+ drag,+ editingLocked,+ engine,+ isPrimarySelected,+ isSelected,+ row,+ onSelect,+ onToggleExpanded,+}: LayerRowProps) => {+ const commitPrepared = usePreparedCommit(engine);+ const { t } = useTranslation();+ const interaction = getLayerRowInteractionState(editingLocked);+ const { node } = row;+ const group = node.type === 'group' ? (node as CanvasGroupContract) : null;+ const layer = node.type === 'group' ? null : (node as CanvasLayerContract);+ const { attributes, isDragging, listeners, setActivatorNodeRef, setNodeRef, transform, transition } = useSortable({+ disabled: interaction.sortableDisabled,+ id: row.id,+ });+ const [isEditing, setIsEditing] = useState(false);+ const [draftName, setDraftName] = useState(node.name);+ const [contextMenuTarget, setContextMenuTarget] = useState<CanvasLayerContextMenuTarget | null>(null);+ const [groupMenuAnchor, setGroupMenuAnchor] = useState<{ x: number; y: number } | null>(null);+ const selectRef = useRef<HTMLButtonElement | null>(null);++ const dndStyle = useMemo(+ () => ({+ opacity: isDragging || drag?.isDragSource ? 0.4 : undefined,+ position: 'relative' as const,+ transform: CSS.Translate.toString(transform),+ transition,+ zIndex: isDragging ? 1 : undefined,+ }),+ [drag?.isDragSource, isDragging, transform, transition]+ );+ const indentStyle = useMemo(() => ({ paddingLeft: `${row.depth * LAYER_TREE_INDENT_PX}px` }), [row.depth]);+ // The insertion line stands in for the block at full strength; only the block itself fades.+ const indicatorHostStyle = useMemo(() => ({ ...dndStyle, opacity: undefined }), [dndStyle]);+ const indicatorStyle = useMemo(+ () => ({ marginLeft: `${(drag?.indicatorDepth ?? 0) * LAYER_TREE_INDENT_PX}px` }),+ [drag?.indicatorDepth]+ );++ const handleSelect = useCallback(+ (event: MouseEvent<HTMLButtonElement>) => {+ if (interaction.canSelect) {+ onSelect(row.id, { additive: event.metaKey || event.ctrlKey, range: event.shiftKey });+ }+ },+ [interaction.canSelect, row.id, onSelect]+ );++ const handleToggleExpanded = useCallback(+ (event: { stopPropagation: () => void }) => {+ event.stopPropagation();+ onToggleExpanded(row.id);+ },+ [onToggleExpanded, row.id]+ );++ const handleSelectKeyDown = useCallback(+ (event: KeyboardEvent<HTMLButtonElement>) => {+ if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {+ const tree = event.currentTarget.closest('[role="tree"]');+ const items = tree ? Array.from(tree.querySelectorAll<HTMLElement>('[role="treeitem"]')) : [];+ const next = items[items.indexOf(event.currentTarget) + (event.key === 'ArrowDown' ? 1 : -1)];+ if (next) {+ event.preventDefault();+ next.focus();+ }+ return;+ }+ if (!group) {+ return;+ }+ if ((event.key === 'ArrowRight' && !row.expanded) || (event.key === 'ArrowLeft' && row.expanded)) {+ event.preventDefault();+ onToggleExpanded(row.id);+ }+ },+ [group, onToggleExpanded, row.expanded, row.id]+ );++ const patchBase = useCallback(+ (label: string, forward: Partial<Pick<CanvasLayerContract, 'name' | 'isEnabled' | 'isLocked'>>) => {+ commitPrepared(label, (model) => model.prepare({ id: row.id, patch: forward, type: 'patch' }));+ },+ [commitPrepared, row.id]+ );++ const handleToggleVisible = useCallback(+ (checked: boolean) => patchBase(t('widgets.layers.actions.toggleVisibility'), { isEnabled: checked }),+ [patchBase, t]+ );++ const handleToggleHidden = useCallback(+ (event: { stopPropagation: () => void }) => {+ event.stopPropagation();+ const isHidden = !isNodeHidden(node);+ commitPrepared(t('widgets.layers.actions.toggleHidden'), (model) =>+ model.prepare({ type: 'set-hidden', updates: [{ id: row.id, isHidden }] })+ );+ },+ [commitPrepared, node, row.id, t]+ );++ const handleToggleLock = useCallback(+ (event: { stopPropagation: () => void }) => {+ event.stopPropagation();+ patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !node.isLocked });+ },+ [node.isLocked, patchBase, t]+ );++ const startEditing = useCallback(() => {+ setDraftName(node.name);+ setIsEditing(true);+ }, [node.name]);++ const finishEditing = useCallback(() => {+ setIsEditing(false);+ selectRef.current?.focus();+ }, []);++ const commitName = useCallback(() => {+ finishEditing();+ const name = draftName.trim();+ if (name && name !== node.name) {+ patchBase(t('widgets.layers.actions.rename'), { name });+ }+ }, [draftName, finishEditing, node.name, patchBase, t]);++ const handleNameKeyDown = useCallback(+ (event: KeyboardEvent<HTMLInputElement>) => {+ // Stop only the two keys the rename owns; the hotkey runtime already refuses non-editable+ // bindings for a focused input, and Escape would otherwise reach the engine as a deselect.+ if (event.key === 'Enter') {+ event.stopPropagation();+ commitName();+ } else if (event.key === 'Escape') {+ event.stopPropagation();+ finishEditing();+ }+ },+ [commitName, finishEditing]+ );++ const handleNameChange = useCallback((event: { target: { value: string } }) => setDraftName(event.target.value), []);+ const focusOnMount = useCallback((input: HTMLInputElement | null) => {+ input?.focus();+ input?.select();+ }, []);++ const handleContextMenu = useCallback(+ (event: MouseEvent<HTMLElement>) => {+ if (!isSelected) {+ onSelect(row.id, { additive: false, range: false });+ }+ if (layer) {+ setContextMenuTarget(createLayerMenuTargetFromContextEvent(row.id, event));+ } else {+ event.preventDefault();+ setGroupMenuAnchor({ x: event.clientX, y: event.clientY });+ }+ },+ [isSelected, layer, onSelect, row.id]+ );++ const closeContextMenu = useCallback(() => setContextMenuTarget(null), []);+ const closeGroupMenu = useCallback(() => setGroupMenuAnchor(null), []);+ const setSelectRef = useCallback(+ (element: HTMLButtonElement | null) => {+ setActivatorNodeRef(element);+ selectRef.current = element;+ },+ [setActivatorNodeRef]+ );++ // Pointer listeners only: Enter on a row belongs to selection, and keyboard reordering is the+ // menu's Move actions, so dnd-kit's keyboard activator stays unattached.+ const sortableRowListeners = useMemo(() => {+ if (interaction.sortableDisabled || !listeners) {+ return {};+ }+ const { onKeyDown: _onKeyDown, ...rest } = listeners;+ return rest;+ }, [interaction.sortableDisabled, listeners]);++ // The selection button owns its role, focus, and pressed state.+ const sortableAttributes = useMemo(() => {+ if (interaction.sortableDisabled) {+ return {};+ }+ const { role: _role, tabIndex: _tabIndex, 'aria-pressed': _ariaPressed, ...rest } = attributes;+ return rest;+ }, [attributes, interaction.sortableDisabled]);++ const hideable = group ? isOverlayStack(row.stack) : isHideableLayer(layer!);+ const ownHidden = isNodeHidden(node);+ const hiddenByAncestor = row.documentHidden && !ownHidden;+ const lockedByAncestor = row.effectiveLocked && !node.isLocked;+ const disabledByAncestor = !row.contributionEnabled && node.isEnabled;++ if (drag?.indicatorDepth !== null && drag?.indicatorDepth !== undefined) {+ return (+ <Box ref={setNodeRef} aria-hidden style={indicatorHostStyle}>+ <Box style={indicatorStyle} {...INDICATOR_STYLE} />+ </Box>+ );+ }++ return (+ <Box ref={setNodeRef} style={dndStyle}>+ <Row+ {...sortableRowListeners}+ active={isSelected ? 'muted' : undefined}+ borderStartColor={isPrimarySelected ? 'accent.solid' : 'transparent'}+ borderStartWidth="2px"+ cursor={isDragging ? 'grabbing' : 'default'}+ display="flex"+ gap="1.5"+ p="1.5"+ position="relative"+ style={indentStyle}+ transition={LAYER_ROW_BACKGROUND_TRANSITION}+ onContextMenu={handleContextMenu}+ >+ {/* No grip: the row is the pointer drag target; the row-covering selection button carries+ the sortable description and keeps Enter as selection. */}+ <chakra.button+ ref={setSelectRef}+ {...sortableAttributes}+ aria-current={isPrimarySelected ? 'true' : undefined}+ aria-expanded={group ? row.expanded : undefined}+ aria-label={t('widgets.layers.actions.select', { name: node.name })}+ aria-level={row.depth + 1}+ aria-selected={isSelected}+ role="treeitem"+ data-primary={isPrimarySelected || undefined}+ cursor={isDragging ? 'grabbing' : undefined}+ inset="0"+ position="absolute"+ rounded="sm"+ type="button"+ _focusVisible={ROW_SELECTION_FOCUS}+ onClick={handleSelect}+ onDoubleClick={interaction.canRename ? startEditing : undefined}+ onKeyDown={handleSelectKeyDown}+ />+ <HStack css={ROW_INTERACTIVE_DESCENDANTS} gap="1.5" pointerEvents="none" position="relative" w="full">+ {group ? (+ <>+ <IconButton+ aria-label={t(+ row.expanded ? 'widgets.layers.actions.collapseGroup' : 'widgets.layers.actions.expandGroup'+ )}+ color="fg.subtle"+ size="2xs"+ variant="ghost"+ onClick={handleToggleExpanded}+ onPointerDown={stopPropagation}+ >+ <Icon+ as={ChevronRightIcon}+ boxSize="3.5"+ transform={row.expanded ? 'rotate(90deg)' : undefined}+ transitionDuration="fast"+ transitionProperty="transform"+ />+ </IconButton>+ <Box+ alignItems="center"+ bg="bg.muted"+ borderColor="border.subtle"+ borderWidth="1px"+ boxSize="8"+ color="fg.muted"+ display="flex"+ flexShrink={0}+ justifyContent="center"+ rounded="sm"+ >+ <Icon as={row.expanded ? FolderOpenIcon : FolderIcon} boxSize="4" />+ </Box>+ </>+ ) : (+ <LayerThumbnail engine={engine} layer={layer!} />+ )}+ <Stack flex="1" gap="0.5" minW="0">+ {isEditing ? (+ <Input+ ref={focusOnMount}+ aria-label={t('widgets.layers.actions.rename')}+ disabled={!interaction.canRename}+ size="2xs"+ value={draftName}+ onBlur={commitName}+ onChange={handleNameChange}+ onKeyDown={handleNameKeyDown}+ onPointerDown={stopPropagation}+ />+ ) : (+ <MiddleTruncate+ aria-disabled={!interaction.canRename}+ color={row.contributionEnabled ? undefined : 'fg.muted'}+ fontSize="2xs"+ fontWeight="700"+ text={node.name}+ />+ )}+ <HStack alignSelf="flex-start" gap="1">+ {group ? (+ <Text color="fg.subtle" fontSize="2xs">+ {row.leafCount === 0+ ? t('widgets.layers.groupEmpty')+ : t('widgets.layers.groupSummary', { count: row.leafCount })}+ </Text>+ ) : (+ <>+ <Badge colorPalette="gray" size="xs" variant="subtle">+ {t(layerBadgeKey(layer!))}+ </Badge>+ <ControlLayerWarningIcon contributing={row.contributionEnabled} layer={layer!} />+ </>+ )}+ </HStack>+ </Stack>+ {/* One control cluster on the same rhythm as the stack header so every row's trailing+ icons share columns; slots a row cannot use are held open. */}+ <HStack flexShrink="0" gap="0.5">+ {hideable ? (+ <Tooltip+ content={+ hiddenByAncestor ? t('widgets.layers.actions.groupHidden') : t('widgets.layers.actions.toggleHidden')+ }+ >+ <IconButton+ aria-label={t('widgets.layers.actions.toggleHidden')}+ aria-pressed={!ownHidden}+ color={row.documentHidden ? 'fg.subtle' : 'fg'}+ disabled={!interaction.canToggleVisibility || hiddenByAncestor}+ size="2xs"+ variant="ghost"+ onClick={handleToggleHidden}+ onPointerDown={stopPropagation}+ >+ {row.documentHidden ? <EyeOffIcon /> : <EyeIcon />}+ </IconButton>+ </Tooltip>+ ) : (+ <Box boxSize="6" />+ )}+ <Box display="flex" flexShrink="0" onClick={stopPropagation} onPointerDown={stopPropagation}>+ <ToggleDot+ _before={+ node.isEnabled+ ? disabledByAncestor+ ? VISIBILITY_DOT_GATED+ : VISIBILITY_DOT_CHECKED+ : VISIBILITY_DOT_UNCHECKED+ }+ _focusVisible={ROW_SELECTION_FOCUS}+ _hover={node.isEnabled ? VISIBILITY_DOT_CHECKED_HOVER : VISIBILITY_DOT_UNCHECKED_HOVER}+ bg="transparent"+ borderWidth="0"+ checked={node.isEnabled}+ cursor={interaction.canToggleVisibility ? 'pointer' : 'not-allowed'}+ disabled={!interaction.canToggleVisibility}+ h="6"+ label={t('widgets.layers.actions.toggleVisibility')}+ position="relative"+ transition="none"+ w="6"+ tooltip={disabledByAncestor ? t('widgets.layers.actions.groupDisabled') : undefined}+ onCheckedChange={handleToggleVisible}+ />+ </Box>+ <Tooltip+ content={+ lockedByAncestor ? t('widgets.layers.actions.groupLocked') : t('widgets.layers.actions.toggleLock')+ }+ >+ <IconButton+ aria-label={t('widgets.layers.actions.toggleLock')}+ color={node.isLocked ? 'fg' : row.effectiveLocked ? 'fg.muted' : 'fg.subtle'}+ disabled={!interaction.canToggleLock || lockedByAncestor}+ size="2xs"+ variant="ghost"+ onClick={handleToggleLock}+ onPointerDown={stopPropagation}+ >+ {row.effectiveLocked ? <LockIcon /> : <LockOpenIcon />}+ </IconButton>+ </Tooltip>+ {layer ? (+ <Box+ display="flex"+ flexShrink="0"+ onClick={stopPropagation}+ onContextMenu={stopPropagation}+ onPointerDown={stopPropagation}+ >+ <LayerPropertiesPopover engine={engine} layer={layer} />+ </Box>+ ) : (+ <Box boxSize="6" />+ )}+ <Box display="flex" flexShrink="0" onPointerDown={stopPropagation}>+ {group ? (+ <LayerGroupContextMenu+ anchor={groupMenuAnchor}+ editingLocked={editingLocked}+ engine={engine}+ group={group}+ stack={row.stack}+ onAnchorClose={closeGroupMenu}+ />+ ) : (+ <LayerContextMenu dispatch={dispatch} engine={engine} layer={layer!} />+ )}+ </Box>+ </HStack>+ </HStack>+ </Row>+ {layer ? (+ <CanvasLayerContextMenu+ dispatch={dispatch}+ engine={engine}+ target={contextMenuTarget}+ onClose={closeContextMenu}+ />+ ) : null}+ </Box>+ );+};++export const LayerRow = memo(LayerRowComponent);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackSection.tsxnew file mode 100644index 0000000000..737781b067--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerStackSection.tsx@@ -0,0 +1,454 @@+import type { DragEndEvent, DragMoveEvent, DragOverEvent, DragStartEvent } from '@dnd-kit/core';+import type { CanvasDocumentContractV3, LayerStackKind } from '@workbench/canvas-engine/api';+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';+import type { LayerSelectionModifiers } from '@workbench/layerPanelState';+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';+import type { LucideIcon } from 'lucide-react';+import type { Dispatch } from 'react';++import { Badge, Collapsible, HStack, Icon, Stack, Text } from '@chakra-ui/react';+import { closestCenter, DndContext, DragOverlay, PointerSensor, useSensor, useSensors } from '@dnd-kit/core';+import { restrictToVerticalAxis } from '@dnd-kit/modifiers';+import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';+import { IconButton, toaster, Tooltip } from '@platform/ui';+import { canMergeVisibleRasters, getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';+import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';+import { useActiveProjectName } from '@workbench/WorkbenchContext';+import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, FolderIcon, LayersIcon, PlusIcon } from 'lucide-react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';++import type { LayerStackRows, LayerTreeRow } from './layerTreeRows';++import { stackAddItemId } from './addLayerMenu';+import { LAYER_TREE_INDENT_PX, LayerRow, type LayerRowEngine } from './LayerRow';+import {+ canExportRasterPsd,+ getStackActions,+ isStackAllVisible,+ planStackVisibilityToggle,+ stackVisibilityAxis,+} from './layerStackActions';+import { projectLayerDrop, type LayerDropTarget } from './layerTreeDrop';+import { getPsdExportNoticeKey } from './psdExportNotice';+import { useAddLayer } from './useAddLayer';++export type LayerStackEngine = LayerRowEngine &+ Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;++const POINTER_SENSOR_OPTIONS = { activationConstraint: { distance: 6 } } as const;+const OVERLAY_MODIFIERS = [restrictToVerticalAxis];+/** How long the pointer rests on a collapsed group before it opens to accept the drop. */+const HOVER_EXPAND_DELAY_MS = 600;++interface DragState {+ readonly activeId: string;+ /** Every selected row that travels with the drag, outermost only. */+ readonly activeIds: readonly string[];+ readonly overId: string | null;+ readonly depthOffset: number;+}++interface LayerStackSectionProps {+ dispatch: Dispatch<CanvasProjectMutation>;+ document: CanvasDocumentContractV3;+ engine: LayerStackEngine | null;+ isCollapsed: boolean;+ onExpandGroup: (groupId: string) => void;+ onSelect: (id: string, modifiers: LayerSelectionModifiers) => void;+ onToggleCollapse: (stack: LayerStackKind) => void;+ onToggleExpanded: (groupId: string) => void;+ selectedIds: readonly string[];+ selectedLayerId: string | null;+ stack: LayerStackRows;+}++/** The descendants a rendered row carries: the following rows with a greater depth. */+const subtreeIds = (rows: readonly LayerTreeRow[], id: string): string[] => {+ const start = rows.findIndex((row) => row.id === id);+ if (start < 0) {+ return [];+ }+ const ids = [id];+ for (let index = start + 1; index < rows.length && rows[index]!.depth > rows[start]!.depth; index += 1) {+ ids.push(rows[index]!.id);+ }+ return ids;+};++/**+ * One collapsible stack: a header (chevron + name + count + action cluster) and, when expanded,+ * the stack's tree rows in a self-contained `DndContext`, so a drag can never land in another+ * stack. Dropping projects the pointer onto a sortable-tree target (gap + depth) and commits one+ * `reparent`; rows that travel with the block leave the list for the duration of the drag.+ */+export const LayerStackSection = ({+ dispatch,+ document,+ engine,+ isCollapsed,+ onExpandGroup,+ onSelect,+ onToggleCollapse,+ onToggleExpanded,+ selectedIds,+ selectedLayerId,+ stack,+}: LayerStackSectionProps) => {+ const commitPrepared = usePreparedCommit(engine);+ const { t } = useTranslation();+ const editingLocked = useCanvasDocumentEditingLocked(engine);+ const sensors = useSensors(useSensor(PointerSensor, POINTER_SENSOR_OPTIONS));+ const [drag, setDrag] = useState<DragState | null>(null);+ const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const { rows } = stack;++ const clearHoverTimer = useCallback(() => {+ if (hoverTimer.current !== null) {+ clearTimeout(hoverTimer.current);+ hoverTimer.current = null;+ }+ }, []);+ useEffect(() => clearHoverTimer, [clearHoverTimer]);++ // Rows that travel with the drag leave the list; the active row stays as the insertion mark.+ const sortableRows = useMemo(() => {+ if (!drag) {+ return rows;+ }+ const travelling = new Set(drag.activeIds.flatMap((id) => subtreeIds(rows, id)));+ return rows.filter((row) => row.id === drag.activeId || !travelling.has(row.id));+ }, [drag, rows]);+ const sortableIds = useMemo(() => sortableRows.map((row) => row.id), [sortableRows]);++ const target = useMemo((): LayerDropTarget | null => {+ if (!drag) {+ return null;+ }+ const activeIndex = sortableRows.findIndex((row) => row.id === drag.activeId);+ let overId = drag.overId ?? drag.activeId;+ let edge: 'above' | 'below' = 'above';+ if (overId === drag.activeId) {+ const neighbour = sortableRows[activeIndex + 1] ?? sortableRows[activeIndex - 1];+ if (!neighbour) {+ return null;+ }+ overId = neighbour.id;+ edge = neighbour === sortableRows[activeIndex + 1] ? 'above' : 'below';+ } else {+ edge = sortableRows.findIndex((row) => row.id === overId) > activeIndex ? 'below' : 'above';+ }+ return projectLayerDrop({ activeIds: drag.activeIds, depthOffset: drag.depthOffset, edge, overId, rows });+ }, [drag, rows, sortableRows]);++ // Only rendered, outermost selected rows travel: a row hidden in a collapsed group or under another+ // selected row is not a separate block, so it is neither counted nor moved on its own.+ const handleDragStart = useCallback(+ (event: DragStartEvent) => {+ const activeId = String(event.active.id);+ const selected = new Set(selectedIds.includes(activeId) ? selectedIds : [activeId]);+ const covered = new Set<string>();+ const activeIds: string[] = [];+ for (const row of rows) {+ if (!selected.has(row.id) || covered.has(row.id)) {+ continue;+ }+ activeIds.push(row.id);+ for (const id of subtreeIds(rows, row.id)) {+ covered.add(id);+ }+ }+ setDrag({ activeId, activeIds, depthOffset: 0, overId: null });+ },+ [rows, selectedIds]+ );++ const handleDragMove = useCallback((event: DragMoveEvent) => {+ const depthOffset = Math.round(event.delta.x / LAYER_TREE_INDENT_PX);+ setDrag((current) => (current && current.depthOffset !== depthOffset ? { ...current, depthOffset } : current));+ }, []);++ const handleDragOver = useCallback(+ (event: DragOverEvent) => {+ const overId = event.over ? String(event.over.id) : null;+ setDrag((current) => (current && current.overId !== overId ? { ...current, overId } : current));+ clearHoverTimer();+ const over = overId && overId !== String(event.active.id) ? rows.find((row) => row.id === overId) : undefined;+ if (over && over.kind === 'group' && !over.expanded && over.childCount > 0) {+ hoverTimer.current = setTimeout(() => onExpandGroup(over.id), HOVER_EXPAND_DELAY_MS);+ }+ },+ [clearHoverTimer, onExpandGroup, rows]+ );++ const handleDragEnd = useCallback(+ (_event: DragEndEvent) => {+ clearHoverTimer();+ setDrag(null);+ if (editingLocked || !target) {+ return;+ }+ commitPrepared(t('widgets.layers.actions.reorder'), (model) =>+ model.prepare({ beforeId: target.beforeId, ids: target.ids, parentId: target.parentId, type: 'reparent' })+ );+ },+ [clearHoverTimer, commitPrepared, editingLocked, t, target]+ );++ const handleDragCancel = useCallback(() => {+ clearHoverTimer();+ setDrag(null);+ }, [clearHoverTimer]);++ const handleToggleCollapse = useCallback(() => onToggleCollapse(stack.stack), [onToggleCollapse, stack.stack]);++ const activeRow = drag ? rows.find((row) => row.id === drag.activeId) : undefined;+ const activeDrag = useMemo(+ () => (drag ? { indicatorDepth: target?.depth ?? null, isDragSource: true } : null),+ [drag, target?.depth]+ );++ return (+ <Stack gap="1">+ {/* `px` matches a row's own content edge (the list's `px="1"` plus each row's `p="1.5"`), so+ the header chevron and its action cluster sit in the same columns as the rows below. */}+ <HStack gap="1" px="2.5">+ <IconButton+ aria-label={t(isCollapsed ? 'widgets.layers.groupActions.expand' : 'widgets.layers.groupActions.collapse')}+ color="fg.subtle"+ size="2xs"+ variant="ghost"+ onClick={handleToggleCollapse}+ >+ <Icon+ as={ChevronDownIcon}+ boxSize="3.5"+ transform={isCollapsed ? 'rotate(-90deg)' : undefined}+ transitionDuration="fast"+ transitionProperty="transform"+ />+ </IconButton>+ <Text+ color="fg.muted"+ cursor="pointer"+ flex="1"+ fontSize="2xs"+ fontWeight="700"+ textTransform="uppercase"+ truncate+ userSelect="none"+ onClick={handleToggleCollapse}+ >+ {t(`widgets.layers.groups.${stack.stack}`)} ({stack.leafCount})+ </Text>+ <StackActions document={document} editingLocked={editingLocked} engine={engine} stack={stack.stack} />+ </HStack>+ {/* unmountOnExit: collapsing must UNMOUNT the rows so an open per-row properties popover — and+ any control-layer filter preview it hosts — is torn down with them. */}+ <Collapsible.Root lazyMount open={!isCollapsed} unmountOnExit>+ <Collapsible.Content>+ <DndContext+ collisionDetection={closestCenter}+ sensors={sensors}+ onDragCancel={handleDragCancel}+ onDragEnd={handleDragEnd}+ onDragMove={handleDragMove}+ onDragOver={handleDragOver}+ onDragStart={handleDragStart}+ >+ <SortableContext items={sortableIds} strategy={verticalListSortingStrategy}>+ <Stack aria-label={t(`widgets.layers.groups.${stack.stack}`)} gap="0.5" px="1" role="tree">+ {sortableRows.map((row) => (+ <LayerRow+ key={row.id}+ dispatch={dispatch}+ drag={row.id === drag?.activeId ? activeDrag : null}+ editingLocked={editingLocked}+ engine={engine}+ isPrimarySelected={row.id === selectedLayerId}+ isSelected={selectedIds.includes(row.id)}+ row={row}+ onSelect={onSelect}+ onToggleExpanded={onToggleExpanded}+ />+ ))}+ </Stack>+ </SortableContext>+ <DragOverlay dropAnimation={null} modifiers={OVERLAY_MODIFIERS}>+ {activeRow && drag ? <LayerDragGhost count={drag.activeIds.length} row={activeRow} /> : null}+ </DragOverlay>+ </DndContext>+ </Collapsible.Content>+ </Collapsible.Root>+ </Stack>+ );+};++/** The compact card that follows the pointer: the grabbed row's name plus how many rows travel. */+const LayerDragGhost = ({ count, row }: { count: number; row: LayerTreeRow }) => (+ <HStack+ bg="bg.panel"+ borderColor="accent.solid"+ borderWidth="1px"+ boxShadow="lg"+ cursor="grabbing"+ gap="2"+ maxW="16rem"+ px="2"+ py="1.5"+ rounded="sm"+ >+ {row.kind === 'group' ? <Icon as={FolderIcon} boxSize="3.5" color="fg.muted" flexShrink={0} /> : null}+ <Text flex="1" fontSize="2xs" fontWeight="700" truncate>+ {row.node.name}+ </Text>+ {count > 1 ? (+ <Badge colorPalette="accent" size="xs" variant="solid">+ {count}+ </Badge>+ ) : null}+ </HStack>+);++/** The right-aligned stack-header action cluster; the set of actions is data (`getStackActions`). */+const StackActions = ({+ document,+ editingLocked,+ engine,+ stack,+}: {+ document: CanvasDocumentContractV3;+ editingLocked: boolean;+ engine: LayerStackEngine | null;+ stack: LayerStackKind;+}) => {+ const commitPrepared = usePreparedCommit(engine);+ const { t } = useTranslation();+ const addLayer = useAddLayer();+ const projectName = useActiveProjectName();+ const axis = stackVisibilityAxis(stack);+ const entries = getDocumentIndex(document).nodes.filter((entry) => entry.stack === stack);+ const allVisible = isStackAllVisible(entries, axis);+ // Enablement and execution share the same contributor selector and the engine's live-content+ // predicate, so empty paint layers do not enable an op.+ const canMerge =+ !editingLocked &&+ !!engine &&+ stack === 'raster' &&+ canMergeVisibleRasters(engine.document.model()?.compileLeaves() ?? [], engine.exports.hasExportableLayerContent);+ const canExport = !!engine && stack === 'raster' && canExportRasterPsd(getDocumentLeaves(document));++ const handleNew = useCallback(() => addLayer(stackAddItemId(stack)), [addLayer, stack]);++ const handleToggleVisibility = useCallback(() => {+ const { ids, nextVisible } = planStackVisibilityToggle(entries, axis);+ if (ids.length === 0) {+ return;+ }+ if (axis === 'hidden') {+ commitPrepared(t('widgets.layers.groupActions.toggleHidden'), (model) =>+ model.prepare({ type: 'set-hidden', updates: ids.map((id) => ({ id, isHidden: !nextVisible })) })+ );+ return;+ }+ commitPrepared(t('widgets.layers.groupActions.toggleVisibility'), (model) =>+ model.prepare({ type: 'set-enabled', updates: ids.map((id) => ({ id, isEnabled: nextVisible })) })+ );+ }, [axis, commitPrepared, entries, t]);++ const handleMergeVisible = useCallback(() => {+ if (!engine) {+ return;+ }+ void engine.layers.mergeVisibleRasterLayers().then((result) => {+ if (result === 'not-ready') {+ toaster.create({ title: t('widgets.layers.groupActions.mergeNotReady'), type: 'warning' });+ } else if (result === 'over-budget') {+ toaster.create({ title: t('widgets.layers.groupActions.mergeOverBudget'), type: 'warning' });+ }+ });+ }, [engine, t]);++ const handleExportPsd = useCallback(async () => {+ if (!engine) {+ return;+ }+ try {+ const result = await engine.exports.exportRasterLayersToPsd(projectName);+ const noticeKey = getPsdExportNoticeKey(result);+ if (noticeKey) {+ toaster.create({ title: t(noticeKey), type: 'warning' });+ }+ } catch {+ toaster.create({ title: t('widgets.layers.groupActions.exportFailed'), type: 'error' });+ }+ }, [engine, projectName, t]);++ return (+ <HStack gap="0.5">+ {getStackActions(stack).map((action) => {+ switch (action) {+ case 'mergeVisible':+ return (+ <StackActionButton+ key={action}+ disabled={!canMerge}+ icon={LayersIcon}+ label={t('widgets.layers.groupActions.mergeVisible')}+ onClick={handleMergeVisible}+ />+ );+ case 'exportPsd':+ return (+ <StackActionButton+ key={action}+ disabled={editingLocked || !canExport}+ icon={FileDownIcon}+ label={t('widgets.layers.groupActions.exportPsd')}+ onClick={handleExportPsd}+ />+ );+ case 'toggleVisibility':+ return (+ <StackActionButton+ key={action}+ disabled={editingLocked}+ icon={allVisible ? EyeIcon : EyeOffIcon}+ label={t(allVisible ? 'widgets.layers.groupActions.hideAll' : 'widgets.layers.groupActions.showAll')}+ onClick={handleToggleVisibility}+ />+ );+ case 'new':+ return (+ <StackActionButton+ key={action}+ disabled={editingLocked}+ icon={PlusIcon}+ label={t('widgets.layers.groupActions.new')}+ onClick={handleNew}+ />+ );+ }+ })}+ </HStack>+ );+};++const StackActionButton = ({+ disabled,+ icon,+ label,+ onClick,+}: {+ disabled?: boolean;+ icon: LucideIcon;+ label: string;+ onClick: () => void;+}) => (+ <Tooltip content={label}>+ <IconButton aria-label={label} color="fg.subtle" disabled={disabled} size="2xs" variant="ghost" onClick={onClick}>+ <Icon as={icon} boxSize="3.5" />+ </IconButton>+ </Tooltip>+);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsxindex ab3ec2dfbc..f0241394f3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersHeaderActions.tsx@@ -4,6 +4,7 @@ import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { IconButton, MenuContent } from '@platform/ui';import {BrushIcon,+ FolderPlusIcon,ImagePlusIcon,MapPinIcon,PlusIcon,@@ -24,6 +25,7 @@ const MENU_POSITIONING = { placement: 'bottom-end' } as const;/** Icon per add-layer item (kept in the view; the menu structure itself is pure data). */const ADD_LAYER_ICONS: Record<AddLayerItemId, LucideIcon> = {control: SlidersHorizontalIcon,+ group: FolderPlusIcon,inpaint_mask: SquareDashedBottomIcon,raster: BrushIcon,regional_guidance: MapPinIcon,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsxindex cbf2659456..bd61a4ee0d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx@@ -3,12 +3,18 @@ import type {SelectValueChangeDetails,SliderValueChangeDetails,} from '@chakra-ui/react';-import type { CanvasBlendMode, CanvasLayerContract, CanvasMaskFillContract } from '@workbench/canvas-engine/api';+import type {+ CanvasBlendMode,+ CanvasDocumentContractV3,+ CanvasLayerContract,+ CanvasMaskFillContract,+} from '@workbench/canvas-engine/api';import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';import { Box, createListCollection, Flex, HStack, NumberInput, Stack } from '@chakra-ui/react';import { useDebouncedDraftValue, useRegisterGenerateDraftFlusher } from '@features/generation/react';import { ColorPicker, Field, Select, Slider } from '@platform/ui';+import { getDocumentLayer } from '@workbench/canvas-engine/api';import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';import {CANVAS_DENOISING_STRENGTH_KEY,@@ -42,11 +48,8 @@ const isMaskLayer = (layer: CanvasLayerContract | null): layer is MaskLayer =>layer !== null && (layer.type === 'inpaint_mask' || layer.type === 'regional_guidance');const selectSelectedLayer = (project: {- canvas: { document: { layers: readonly CanvasLayerContract[]; selectedLayerId: string | null } };-}): CanvasLayerContract | null => {- const { layers, selectedLayerId } = project.canvas.document;- return layers.find((layer) => layer.id === selectedLayerId) ?? null;-};+ canvas: { document: Pick<CanvasDocumentContractV3, 'stacks' | 'selectedLayerId'> };+}): CanvasLayerContract | null => getDocumentLayer(project.canvas.document, project.canvas.document.selectedLayerId);export const isSameSelection = (left: CanvasLayerContract | null, right: CanvasLayerContract | null): boolean => {if (left?.id !== right?.id || left?.opacity !== right?.opacity || left?.blendMode !== right?.blendMode) {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsxindex d91d044073..645c8f9799 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx@@ -1,9 +1,11 @@import type { LayerStackKind } from '@workbench/canvas-engine/api';import { Flex, Icon, Stack, Text } from '@chakra-ui/react';+import { LAYER_STACKS_TOP_FIRST } from '@workbench/canvas-engine/api';import {publishLayerPanelSelection,selectLayerInPanel,+ setLayerGroupExpanded,toggleLayerStackCollapsed,useLayerPanelState,type LayerSelectionModifiers,@@ -16,20 +18,16 @@ import { LayersIcon } from 'lucide-react';import { useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';-import type { LayerGroup } from './layerGroups';--import { groupLayers } from './layerGroups';-import { LayerGroupSection } from './LayerGroupSection';import { LayerMultiSelectionActions } from './LayerMultiSelectionActions';-import { isLayerPropertiesGroupRequested, useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';+import { isLayerPropertiesRequestedWithin, useCurrentLayerPropertiesRequest } from './layerPropertiesRequestStore';import { LayersPanelHeader } from './LayersPanelHeader';+import { LayerStackSection } from './LayerStackSection';+import { buildLayerStackRows } from './layerTreeRows';/**- * The layers panel: a fixed Photoshop-style header region (selected layer's- * opacity + blend mode, global denoising strength) above the layer list, which- * is split into type groups (inpaint masks / regional guidance / control /- * raster — legacy display order). Each group is a within-group drag-to-reorder- * list mapped onto the single global z-ordered `layers` array.+ * The layers panel: a fixed Photoshop-style header region (selected layer's opacity + blend mode,+ * global denoising strength) above the four stacks (inpaint masks / regional guidance / control /+ * raster), each a tree of groups and layers rendered top first.*/export const LayersWidgetView = () => {const { t } = useTranslation();@@ -38,51 +36,65 @@ export const LayersWidgetView = () => {const dispatch = useCanvasProjectMutationDispatch();const editingLocked = useCanvasDocumentEditingLocked(engine);const propertiesRequest = useCurrentLayerPropertiesRequest();- const { layers, selectedLayerId } = useActiveProjectSelector(- (project) => ({- layers: project.canvas.document.layers,- selectedLayerId: project.canvas.document.selectedLayerId,- }),- (left, right) => left.layers === right.layers && left.selectedLayerId === right.selectedLayerId- );+ const document = useActiveProjectSelector((project) => project.canvas.document);+ const { selectedLayerId } = document;- const groups = useMemo(() => groupLayers(layers), [layers]);const panelState = useLayerPanelState(projectId, selectedLayerId);- const isCollapsed = (group: LayerGroup): boolean =>- panelState.collapsedStacks.includes(group.key) && !isLayerPropertiesGroupRequested(propertiesRequest, group.layers);- const allLayerIds = useMemo(() => groups.flatMap((group) => group.layers.map((layer) => layer.id)), [groups]);- const visibleLayerIds = groups.flatMap((group) => (isCollapsed(group) ? [] : group.layers.map((layer) => layer.id)));- const selectedIds = panelState.selectedIds;+ const expandedGroupIds = useMemo(() => new Set(panelState.expandedGroupIds), [panelState.expandedGroupIds]);+ const stacks = useMemo(() => buildLayerStackRows(document, expandedGroupIds), [document, expandedGroupIds]);+ const visibleStacks = useMemo(+ () => LAYER_STACKS_TOP_FIRST.map((kind) => stacks[kind]).filter((stack) => stack.nodeIds.length > 0),+ [stacks]+ );+ const { collapsedStacks, selectedIds } = panelState;+ const isCollapsed = useCallback(+ (stack: LayerStackKind): boolean =>+ collapsedStacks.includes(stack) && !isLayerPropertiesRequestedWithin(propertiesRequest, stacks[stack].nodeIds),+ [collapsedStacks, propertiesRequest, stacks]+ );+ const allNodeIds = useMemo(() => visibleStacks.flatMap((stack) => stack.nodeIds), [visibleStacks]);+ const visibleRowIds = useMemo(+ () => visibleStacks.flatMap((stack) => (isCollapsed(stack.stack) ? [] : stack.rows.map((row) => row.id))),+ [isCollapsed, visibleStacks]+ );- const handleSelectLayer = useCallback(- (layerId: string, modifiers: LayerSelectionModifiers) => {- const next = selectLayerInPanel(panelState, layerId, modifiers.range ? visibleLayerIds : allLayerIds, modifiers);+ const handleSelect = useCallback(+ (id: string, modifiers: LayerSelectionModifiers) => {+ const next = selectLayerInPanel(panelState, id, modifiers.range ? visibleRowIds : allNodeIds, modifiers);publishLayerPanelSelection(next);if (next.primaryId !== selectedLayerId) {dispatch({ id: next.primaryId, type: 'setCanvasSelectedLayer' });}},- [allLayerIds, dispatch, panelState, selectedLayerId, visibleLayerIds]+ [allNodeIds, dispatch, panelState, selectedLayerId, visibleRowIds]);const handleToggleCollapse = useCallback((stack: LayerStackKind) => toggleLayerStackCollapsed(projectId, selectedLayerId, stack),[projectId, selectedLayerId]);+ const handleToggleExpanded = useCallback(+ (groupId: string) => setLayerGroupExpanded(projectId, selectedLayerId, [groupId]),+ [projectId, selectedLayerId]+ );+ const handleExpandGroup = useCallback(+ (groupId: string) => setLayerGroupExpanded(projectId, selectedLayerId, [groupId], true),+ [projectId, selectedLayerId]+ );return (<Stack h="full"><LayersPanelHeader />{selectedIds.length > 1 ? (<LayerMultiSelectionActions+ document={document}editingLocked={editingLocked}engine={engine}- layers={layers}projectId={projectId}selectedIds={selectedIds}/>) : null}- {groups.length === 0 ? (+ {visibleStacks.length === 0 ? (<Flexalign="center"borderColor="border.subtle"@@ -103,19 +115,20 @@ export const LayersWidgetView = () => {</Flex>) : (<Stack gap="3">- {groups.map((group) => (- <LayerGroupSection- key={group.key}+ {visibleStacks.map((stack) => (+ <LayerStackSection+ key={stack.stack}dispatch={dispatch}+ document={document}engine={engine}- groupKey={group.key}- groupLayers={group.layers}- isCollapsed={isCollapsed(group)}- layers={layers}- onSelectLayer={handleSelectLayer}- onToggleCollapse={handleToggleCollapse}+ isCollapsed={isCollapsed(stack.stack)}selectedIds={selectedIds}selectedLayerId={selectedLayerId}+ stack={stack}+ onExpandGroup={handleExpandGroup}+ onSelect={handleSelect}+ onToggleCollapse={handleToggleCollapse}+ onToggleExpanded={handleToggleExpanded}/>))}</Stack>diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.tsindex 9c4e20630b..05d3739417 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { ADD_LAYER_MENU, groupAddItemId, isAddLayerItemAvailable } from './addLayerMenu';+import { ADD_LAYER_MENU, isAddLayerItemAvailable, stackAddItemId } from './addLayerMenu';describe('ADD_LAYER_MENU', () => {it('splits into the legacy Regional / Layers groups in order', () => {@@ -19,7 +19,7 @@ describe('ADD_LAYER_MENU', () => {});it('lists control + raster under Layers', () => {- expect(ADD_LAYER_MENU[1]?.items.map((item) => item.id)).toEqual(['control', 'raster']);+ expect(ADD_LAYER_MENU[1]?.items.map((item) => item.id)).toEqual(['control', 'raster', 'group']);});it('gives every item a widgets.layers i18n label key', () => {@@ -39,12 +39,12 @@ describe('isAddLayerItemAvailable', () => {});});-describe('groupAddItemId', () => {+describe('stackAddItemId', () => {it('maps a group key to its own add-layer item', () => {- expect(groupAddItemId('raster')).toBe('raster');- expect(groupAddItemId('control')).toBe('control');- expect(groupAddItemId('inpaint_mask')).toBe('inpaint_mask');+ expect(stackAddItemId('raster')).toBe('raster');+ expect(stackAddItemId('control')).toBe('control');+ expect(stackAddItemId('inpaint_mask')).toBe('inpaint_mask');// A group header's "New" creates a plain region, not the ref-image variant.- expect(groupAddItemId('regional_guidance')).toBe('regional_guidance');+ expect(stackAddItemId('regional_guidance')).toBe('regional_guidance');});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.tsindex 2c2f74201b..5d6811b01b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/addLayerMenu.ts@@ -1,13 +1,19 @@/*** Pure data for the layers-panel add-layer surfaces (kept free of React so the* grouping is unit-testable). The header menu renders {@link ADD_LAYER_MENU}; each- * group header's "New" button uses {@link groupAddItemId} to add its own type.+ * stack header's "New" button uses {@link stackAddItemId} to add its own type.*/import type { LayerStackKind } from '@workbench/canvas-engine/api';/** The distinct "add a layer" actions offered across the panel's add surfaces. */-export type AddLayerItemId = 'inpaint_mask' | 'regional_guidance' | 'regional_reference_image' | 'control' | 'raster';+export type AddLayerItemId =+ | 'inpaint_mask'+ | 'regional_guidance'+ | 'regional_reference_image'+ | 'control'+ | 'raster'+ | 'group';/** A single add-layer menu entry (label is an i18n key; the icon lives in the view). */export interface AddLayerMenuItem {@@ -39,6 +45,7 @@ export const ADD_LAYER_MENU: readonly AddLayerMenuGroup[] = [items: [{ id: 'control', labelKey: 'widgets.layers.actions.addControlLayer' },{ id: 'raster', labelKey: 'widgets.layers.actions.addRasterLayer' },+ { id: 'group', labelKey: 'widgets.layers.actions.newGroup' },],titleKey: 'widgets.layers.menuGroups.layers',},@@ -48,5 +55,5 @@ export const ADD_LAYER_MENU: readonly AddLayerMenuGroup[] = [export const isAddLayerItemAvailable = (id: AddLayerItemId, base: string | null): boolean =>id !== 'regional_reference_image' || base !== 'flux2';-/** The add-layer action a group-header "New" button triggers for its type. */-export const groupAddItemId = (groupKey: LayerStackKind): AddLayerItemId => groupKey;+/** The add-layer action a stack-header "New" button triggers for its type. */+export const stackAddItemId = (stack: LayerStackKind): AddLayerItemId => stack;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 5e8e28da8a..ac0bedc21e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -1,9 +1,10 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import {@@ -54,13 +55,13 @@ const makeLayer = (type: CanvasLayerContract['type']): CanvasLayerContract => {}};-const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 512, width: 512, x: 0, y: 0 },height: 512,- layers,+ stacks: stacksFrom(layers),selectedLayerId: layers[0]?.id ?? null,- version: 2,+ version: 3,width: 512,});@@ -77,6 +78,7 @@ const makeState = (hasWorkflowBindings: true,interactionLocked: false,layer,+ selectedIds: [layer.id],...overrides,};};@@ -90,6 +92,7 @@ const makeEffects = (): LayerContextActionEffects => ({duplicate: vi.fn(),extractMaskedArea: vi.fn(() => Promise.resolve()),fitToBbox: vi.fn(),+ group: vi.fn(),mergeDown: vi.fn(),openProperties: vi.fn(),openRename: vi.fn(),@@ -432,6 +435,7 @@ describe('getLayerContextActions', () => {'move-backward','move-to-back','duplicate',+ 'group','rename','transform','fit-to-bbox',diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex ae38bc6c81..1a08e88540 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -1,12 +1,17 @@import type {BooleanRasterOperation,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,LayerStackMoveKind,} from '@workbench/canvas-engine/api';import type { LucideIcon } from 'lucide-react';-import { getSourceContentRect, isPixelBackedLayer, lookupLayerBelow } from '@workbench/canvas-engine/api';+import {+ getDocumentIndex,+ getSourceContentRect,+ isPixelBackedLayer,+ lookupLayerBelow,+} from '@workbench/canvas-engine/api';import {ArrowDownIcon,ArrowDownToLineIcon,@@ -16,6 +21,7 @@ import {CropIcon,EyeIcon,EyeOffIcon,+ FolderPlusIcon,ImageIcon,LockIcon,LockOpenIcon,@@ -30,7 +36,7 @@ import {import type { LayerPropertiesSection } from './layerPropertiesRequestStore';-import { getGroupPosition } from './layerGroups';+import { canGroupNodes } from './layerGroupCommands';import { canConvertRasterControl, canMergeLayerDown } from './layerOps';export type LayerContextActionId =@@ -39,6 +45,7 @@ export type LayerContextActionId =| 'move-backward'| 'move-to-back'| 'duplicate'+ | 'group'| 'rename'| 'transform'| 'fit-to-bbox'@@ -81,17 +88,20 @@ export type LayerContextSubmenuId = 'arrange' | 'add-modifiers' | 'add-regional'export interface LayerContextActionState {canRunWorkflow: boolean;- document: CanvasDocumentContractV2;+ document: CanvasDocumentContractV3;hasEngine: boolean;hasSupportedContent: boolean;hasWorkflowBindings: boolean;interactionLocked: boolean;layer: CanvasLayerContract;+ /** The panel's selection; an action on a selected layer applies to every selected node. */+ selectedIds: readonly string[];}export interface LayerContextActionEffects {reorder(kind: LayerStackMoveKind, actionId: LayerContextActionId): void;duplicate(): void;+ group(): void;openRename(): void;openRunWorkflow(): void;startSelectObject(layerId: string): void;@@ -167,8 +177,15 @@ const REGIONAL_ONLY = ['regional_guidance'] as const;const alwaysVisible = (): boolean => true;const isInteractionFree = (context: LayerContextActionState): boolean => !context.interactionLocked;+const layerEntry = (context: LayerContextActionState) => getDocumentIndex(context.document).byId.get(context.layer.id);+/** The nodes a selection-wide action applies to: the whole selection when the layer is in it. */+export const actionTargets = (context: Pick<LayerContextActionState, 'layer' | 'selectedIds'>): readonly string[] =>+ context.selectedIds.includes(context.layer.id) ? context.selectedIds : [context.layer.id];+/** Locked in its own right or by a group above it: content edits are refused either way. */+const isLayerFrozen = (context: LayerContextActionState): boolean =>+ context.layer.isLocked || (layerEntry(context)?.ancestorsLocked ?? false);const isLayerMutable = (context: LayerContextActionState): boolean =>- isInteractionFree(context) && !context.layer.isLocked;+ isInteractionFree(context) && !isLayerFrozen(context);const hasReadablePixels = (context: LayerContextActionState): boolean =>context.hasEngine && context.hasSupportedContent && !context.interactionLocked;const hasMutablePixels = (context: LayerContextActionState): boolean =>@@ -206,15 +223,26 @@ const hasFilterableLayerContent = (context: LayerContextActionState): boolean =>);};-const groupPosition = (context: LayerContextActionState) => getGroupPosition(context.document.layers, context.layer.id);+/** Where the layer sits among its siblings (index 0 = top), or null when absent. */+const siblingPosition = (context: LayerContextActionState): { index: number; count: number } | null => {+ const index = getDocumentIndex(context.document);+ const entry = index.byId.get(context.layer.id);+ if (!entry) {+ return null;+ }+ const parent = entry.parentId === null ? null : index.byId.get(entry.parentId)!.node;+ const count =+ parent && parent.type === 'group' ? parent.children.length : context.document.stacks[entry.stack].length;+ return { count, index: entry.siblingIndex };+};const canMoveForward = (context: LayerContextActionState): boolean => {- const position = groupPosition(context);+ const position = siblingPosition(context);return isInteractionFree(context) && !!position && position.index > 0;};const canMoveBackward = (context: LayerContextActionState): boolean => {- const position = groupPosition(context);+ const position = siblingPosition(context);return isInteractionFree(context) && !!position && position.index < position.count - 1;};@@ -292,6 +320,21 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinisection: 'quick',supportedLayerTypes: ALL_LAYER_TYPES,},+ {+ defaultLabel: 'Group layers',+ handler: ({ effects }) => effects.group(),+ icon: FolderPlusIcon,+ id: 'group',+ isEnabled: (context) =>+ isInteractionFree(context) &&+ !(layerEntry(context)?.ancestorsLocked ?? false) &&+ canGroupNodes(context.document, actionTargets(context)),+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.group',+ order: 20,+ section: 'quick',+ supportedLayerTypes: ALL_LAYER_TYPES,+ },{defaultLabel: 'Add image noise',handler: ({ effects }) => effects.patchConfig('inpaint-noise'),diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex 9ec35a4e6e..0fe3aafa43 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -1,9 +1,10 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it } from 'vitest';import { getLayerContextActions } from './layerContextActions';@@ -27,13 +28,13 @@ const paintLayer = (id: string, patch: Partial<CanvasRasterLayerContractV2> = {}...patch,});-const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 512, width: 512, x: 0, y: 0 },height: 512,- layers,+ stacks: stacksFrom(layers),selectedLayerId: layers[0]?.id ?? null,- version: 2,+ version: 3,width: 512,});@@ -45,6 +46,7 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerConthasSupportedContent: true,hasWorkflowBindings: true,interactionLocked: false,+ selectedIds: [layer.id],layer,});@@ -71,7 +73,7 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(upper, [upper, below])).toEqual([{id: 'quick',- items: ['arrange(move-to-front,move-forward,move-backward,move-to-back)', 'duplicate'],+ items: ['arrange(move-to-front,move-forward,move-backward,move-to-back)', 'duplicate', 'group'],presentation: 'row',},{diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerDndConfig.browser.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerDndConfig.browser.test.tsdeleted file mode 100644index ded3a08b23..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerDndConfig.browser.test.ts+++ /dev/null@@ -1,60 +0,0 @@-import { describe, expect, it } from 'vitest';--import { shouldStartLayerKeyboardDrag } from './layerDndConfig';--const keyEvent = (target: EventTarget | null) => ({- altKey: false,- ctrlKey: false,- metaKey: false,- shiftKey: false,- target,-});--/** A layer row containing a button, plus a portalled panel outside it. */-const buildTree = () => {- const row = document.createElement('div');- const button = document.createElement('button');- const input = document.createElement('input');- row.append(button, input);-- const portal = document.createElement('div');- const portalTextarea = document.createElement('textarea');- portal.append(portalTextarea);-- document.body.append(row, portal);- return { button, input, portal, portalTextarea, row };-};--describe('shouldStartLayerKeyboardDrag — DOM rules', () => {- it('allows a plain Enter on the row itself', () => {- const { row } = buildTree();- expect(shouldStartLayerKeyboardDrag(keyEvent(row), row)).toBe(true);- });-- it('allows a plain Enter on a non-editable child of the row', () => {- const { button, row } = buildTree();- expect(shouldStartLayerKeyboardDrag(keyEvent(button), row)).toBe(true);- });-- it('refuses Enter typed in the row own rename input', () => {- const { input, row } = buildTree();- expect(shouldStartLayerKeyboardDrag(keyEvent(input), row)).toBe(false);- });-- it('refuses Enter from a PORTALLED textarea that bubbled in through the React tree', () => {- // The layer-properties popover renders through a Portal, so its DOM node is- // not inside the row even though React events reach the row.- const { portalTextarea, row } = buildTree();- expect(shouldStartLayerKeyboardDrag(keyEvent(portalTextarea), row)).toBe(false);- });-- it('refuses Enter from any node outside the row, editable or not', () => {- const { portal, row } = buildTree();- expect(shouldStartLayerKeyboardDrag(keyEvent(portal), row)).toBe(false);- });-- it('refuses a modified Enter even on the row itself', () => {- const { row } = buildTree();- expect(shouldStartLayerKeyboardDrag({ ...keyEvent(row), ctrlKey: true }, row)).toBe(false);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerDndConfig.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerDndConfig.tsdeleted file mode 100644index 1d2bc328fd..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerDndConfig.ts+++ /dev/null@@ -1,62 +0,0 @@-import type { KeyboardSensorOptions } from '@dnd-kit/core';--import { sortableKeyboardCoordinates } from '@dnd-kit/sortable';--export const LAYER_KEYBOARD_SENSOR_OPTIONS = {- coordinateGetter: sortableKeyboardCoordinates,- keyboardCodes: {- cancel: ['Escape'],- end: ['Enter'],- start: ['Enter'],- },-} satisfies KeyboardSensorOptions;--/** The shape of a keyboard event this guard inspects (DOM or React synthetic). */-export interface LayerDragKeyEvent {- target: EventTarget | null;- altKey: boolean;- ctrlKey: boolean;- metaKey: boolean;- shiftKey: boolean;-}--/**- * Whether a key event may start a keyboard drag of a layer row.- *- * dnd-kit claims `Enter` to start a drag and inspects only `event.code`, and the- * whole row is the drag handle (no separate activator node, so dnd-kit's own- * `event.target !== activator` guard never engages). That let two unrelated- * Enter presses start a drag nobody asked for:- *- * - **A MODIFIED Enter.** `mod+Enter` is Invoke. Pressing it with a row focused- * also began an invisible keyboard drag, leaving the row stuck at drag opacity- * — which reads as the layer having been disabled, though nothing about the- * layer changed.- * - **An Enter from a PORTALLED descendant.** React events bubble through the- * component tree, not the DOM, so keystrokes in the layer-properties popover- * (portalled to the body, and holding multi-line prompt textareas where Enter- * is a newline) reached the row. The popover defended itself by stopping- * propagation wholesale, which also stopped the event reaching the window —- * killing every global hotkey inside it, including the prompt-attention keys.- *- * Guarding the activator fixes both at the source, so no portalled panel has to- * remember to stop propagation — and none of them has to break global hotkeys to- * do it.- */-export const shouldStartLayerKeyboardDrag = (event: LayerDragKeyEvent, rowNode: HTMLElement | null): boolean => {- // An unmodified Enter is the drag gesture; every modified one belongs to a- // command (Invoke, and anything a user rebinds onto mod+Enter).- if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {- return false;- }- if (typeof HTMLElement === 'undefined' || !(event.target instanceof HTMLElement)) {- return true;- }- // Typing Enter in a field is never a request to reorder layers.- if (event.target.closest('input, textarea, select, [contenteditable="true"]')) {- return false;- }- // Portal bleed: the event reached this row through the React tree, but its- // DOM node lives elsewhere.- return !rowNode || rowNode.contains(event.target);-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.tsdeleted file mode 100644index 45bbaf76c3..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts+++ /dev/null@@ -1,189 +0,0 @@-import type {- CanvasInpaintMaskLayerContract,- CanvasLayerContract,- CanvasLayerSourceContract,- CanvasRasterLayerContractV2,-} from '@workbench/canvas-engine/contracts';--import { describe, expect, it } from 'vitest';--import {- canExportRasterPsd,- getGroupActions,- groupVisibilityAxis,- isGroupAllVisible,- planGroupHiddenToggle,- planGroupVisibilityToggle,-} from './layerGroupActions';--const raster = (source: CanvasLayerSourceContract, id = 'r'): CanvasRasterLayerContractV2 => ({- blendMode: 'normal',- id,- isEnabled: true,- isLocked: false,- name: id,- opacity: 1,- source,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',-});--const imageRef = { height: 10, imageName: 'img', width: 10 };--const inpaint = (id: string, isEnabled = true): CanvasInpaintMaskLayerContract => ({- blendMode: 'normal',- id,- isEnabled,- isLocked: false,- mask: { bitmap: null, fill: { color: '#f00', style: 'solid' } },- name: id,- opacity: 1,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'inpaint_mask',-});--describe('getGroupActions', () => {- it('offers merge-visible + export-psd only for the raster group, with new + toggle everywhere', () => {- expect(getGroupActions('raster')).toEqual(['mergeVisible', 'exportPsd', 'toggleVisibility', 'new']);- expect(getGroupActions('control')).toEqual(['toggleVisibility', 'new']);- expect(getGroupActions('inpaint_mask')).toEqual(['toggleVisibility', 'new']);- expect(getGroupActions('regional_guidance')).toEqual(['toggleVisibility', 'new']);- });-- it('renders "new" rightmost', () => {- for (const key of ['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const) {- const actions = getGroupActions(key);- expect(actions[actions.length - 1]).toBe('new');- }- });-});--describe('canExportRasterPsd', () => {- it('is false with no exportable raster content', () => {- expect(canExportRasterPsd([])).toBe(false);- expect(canExportRasterPsd([inpaint('m')])).toBe(false);- // A brand-new paint layer (no bitmap) still counts — its live cache may hold- // unflushed strokes the export bakes.- expect(canExportRasterPsd([raster({ bitmap: null, type: 'paint' })])).toBe(true);- });-- it('counts image/paint/gradient/text and non-polygon shapes as content', () => {- expect(canExportRasterPsd([raster({ image: imageRef, type: 'image' })])).toBe(true);- expect(canExportRasterPsd([raster({ bitmap: imageRef, type: 'paint' })])).toBe(true);- expect(- canExportRasterPsd([- raster({ fill: null, height: 10, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 10 }),- ])- ).toBe(true);- });-- it('excludes polygon shapes (no rasterizer)', () => {- expect(- canExportRasterPsd([- raster({ fill: null, height: 10, kind: 'polygon', stroke: null, strokeWidth: 0, type: 'shape', width: 10 }),- ])- ).toBe(false);- });-});--describe('isGroupAllVisible', () => {- it('is true only when every layer is enabled (empty ⇒ true)', () => {- expect(isGroupAllVisible([])).toBe(true);- expect(isGroupAllVisible([inpaint('a', true), inpaint('b', true)])).toBe(true);- expect(isGroupAllVisible([inpaint('a', true), inpaint('b', false)])).toBe(false);- });-});--describe('planGroupVisibilityToggle', () => {- it('hides all when every layer is visible', () => {- const layers = [inpaint('a', true), inpaint('b', true)];- const { updates, nextVisible } = planGroupVisibilityToggle(layers);- expect(nextVisible).toBe(false);- expect(updates).toEqual([- { id: 'a', isEnabled: false },- { id: 'b', isEnabled: false },- ]);- // Inverse restores each layer's prior visibility verbatim (single undo entry).- });-- it('shows all when any layer is hidden, toggling every layer to the shared target', () => {- const layers = [inpaint('a', true), inpaint('b', false)];- const { updates, nextVisible } = planGroupVisibilityToggle(layers);- expect(nextVisible).toBe(true);- expect(updates).toEqual([- { id: 'a', isEnabled: true },- { id: 'b', isEnabled: true },- ]);- });-});--// Merge-visible contributor selection is tested where it lives:-// `canvas-engine/document/mergeVisible.test.ts` (the selector the engine op runs).--describe('planGroupHiddenToggle', () => {- const control = (id: string, isHidden?: boolean): CanvasLayerContract => ({- adapter: { beginEndStepPct: [0, 1], controlMode: 'balanced', kind: 'controlnet', model: null, weight: 1 },- blendMode: 'normal',- id,- isEnabled: true,- isHidden,- isLocked: false,- name: id,- opacity: 1,- source: { image: { height: 10, imageName: id, width: 10 }, type: 'image' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'control',- withTransparencyEffect: false,- });-- it('hides every layer when all are currently shown', () => {- const plan = planGroupHiddenToggle([control('a'), control('b')]);- expect(plan.nextVisible).toBe(false);- expect(plan.updates).toEqual([- { id: 'a', isHidden: true },- { id: 'b', isHidden: true },- ]);- });-- it('shows every layer when any is currently hidden', () => {- const plan = planGroupHiddenToggle([control('a', true), control('b')]);- expect(plan.nextVisible).toBe(true);- expect(plan.updates).toEqual([- { id: 'a', isHidden: false },- { id: 'b', isHidden: false },- ]);- });-- it('never touches enablement — hiding must not change the generated image', () => {- const plan = planGroupHiddenToggle([control('a')]);- expect(JSON.stringify(plan)).not.toContain('isEnabled');- });-- it('skips layers that cannot be hidden', () => {- const raster: CanvasLayerContract = {- blendMode: 'normal',- id: 'r',- isEnabled: true,- isLocked: false,- name: 'r',- opacity: 1,- source: { bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' },- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },- type: 'raster',- };- const plan = planGroupHiddenToggle([raster, control('a')]);- expect(plan.updates.map((update) => update.id)).toEqual(['a']);- });-});--describe('groupVisibilityAxis', () => {- it('drives display visibility for the overlay groups', () => {- expect(groupVisibilityAxis('control')).toBe('hidden');- expect(groupVisibilityAxis('regional_guidance')).toBe('hidden');- expect(groupVisibilityAxis('inpaint_mask')).toBe('hidden');- });-- it('drives enablement for the raster group, which has no display axis', () => {- expect(groupVisibilityAxis('raster')).toBe('enabled');- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.tsdeleted file mode 100644index 6e8c7cd9b6..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts+++ /dev/null@@ -1,83 +0,0 @@-import type { CanvasLayerContract, LayerStackKind } from '@workbench/canvas-engine/api';--import { isExportableRasterLayer, isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';--/** A group-header action id. Extend this + `getGroupActions` to add a new action. */-export type GroupActionId = 'mergeVisible' | 'exportPsd' | 'toggleVisibility' | 'new';--/**- * The right-aligned actions for a group, in left-to-right render order (the "New"- * action sits rightmost, nearest the panel's own add-layer menu). Only the raster- * group offers "merge visible" + "export to PSD"; every group offers- * hide/show-all + new.- */-export const getGroupActions = (groupKey: LayerStackKind): GroupActionId[] => {- const actions: GroupActionId[] = [];- if (groupKey === 'raster') {- actions.push('mergeVisible', 'exportPsd');- }- actions.push('toggleVisibility', 'new');- return actions;-};--/** Whether the raster group's "export to PSD" action has anything to export. */-export const canExportRasterPsd = (layers: readonly CanvasLayerContract[]): boolean =>- layers.some(isExportableRasterLayer);--/** A single layer's target enablement, for the bulk `setCanvasLayersEnabled` action. */-export interface LayerVisibilityUpdate {- id: string;- isEnabled: boolean;-}--/** A single layer's target display visibility, for the bulk `setCanvasLayersHidden` action. */-export interface LayerHiddenUpdate {- id: string;- isHidden: boolean;-}--/**- * Which axis a group's show/hide-all button drives.- *- * The three overlay groups drive the DISPLAY axis: their layers are drawn to- * show you where an effect applies, so getting them out of the way must not- * change the image. The raster group has no display axis — the raster stack IS- * the generation input, so hiding a raster layer and disabling it are the same- * act — and drives enablement.- */-export const groupVisibilityAxis = (groupKey: LayerStackKind): 'enabled' | 'hidden' =>- groupKey === 'raster' ? 'enabled' : 'hidden';--/** True when every layer in the group is currently visible on the group's own axis. Empty ⇒ true. */-export const isGroupAllVisible = (- groupLayers: readonly CanvasLayerContract[],- axis: 'enabled' | 'hidden' = 'enabled'-): boolean =>- axis === 'hidden'- ? groupLayers.every((layer) => !isLayerHidden(layer))- : groupLayers.every((layer) => layer.isEnabled);--/**- * Plans a group show/hide-all toggle as ONE reversible bulk action: if every- * layer is currently visible, hide them all; otherwise show them all (legacy- * `CanvasEntityType` toggle semantics); the prepared edit restores each- * layer's prior state on undo.- */-export const planGroupVisibilityToggle = (- groupLayers: readonly CanvasLayerContract[]-): { updates: LayerVisibilityUpdate[]; nextVisible: boolean } => {- const nextVisible = !isGroupAllVisible(groupLayers);- return { nextVisible, updates: groupLayers.map((layer) => ({ id: layer.id, isEnabled: nextVisible })) };-};--/** The display-axis counterpart of {@link planGroupVisibilityToggle}. */-export const planGroupHiddenToggle = (- groupLayers: readonly CanvasLayerContract[]-): { updates: LayerHiddenUpdate[]; nextVisible: boolean } => {- const hideable = groupLayers.filter(isHideableLayer);- const nextVisible = !isGroupAllVisible(hideable, 'hidden');- return { nextVisible, updates: hideable.map((layer) => ({ id: layer.id, isHidden: !nextVisible })) };-};--// Merge-visible contributor selection lives in the engine's document layer-// Canvas execution uses the same legacy-parity eligibility rules.diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.tsnew file mode 100644index 0000000000..bf09fce8e4--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts@@ -0,0 +1,82 @@+import type { CanvasDocumentContractV3 } from '@workbench/canvas-engine/api';+import type { CanvasPreparedEngine, PreparedCommitOutcome } from '@workbench/widgets/canvas/useStructuralCommit';++import { getDocumentIndex, isGroupNode } from '@workbench/canvas-engine/api';+import { publishLayerPanelSelection, readLayerPanelState, setLayerGroupExpanded } from '@workbench/layerPanelState';+import { commitPreparedEdit } from '@workbench/widgets/canvas/useStructuralCommit';++import { createLayerId, nextGroupName } from './layerOps';++/** Whether `ids` name siblings the model can wrap in one group. */+export const canGroupNodes = (document: CanvasDocumentContractV3, ids: readonly string[]): boolean => {+ const index = getDocumentIndex(document);+ const entries = ids.map((id) => index.byId.get(id)).filter((entry) => entry !== undefined);+ if (entries.length === 0 || entries.length !== ids.length) {+ return false;+ }+ const selected = new Set(ids);+ const outer = entries.filter((entry) => !entry.path.some((ancestor) => selected.has(ancestor)));+ const first = outer[0]!;+ return outer.every((entry) => entry.stack === first.stack && entry.parentId === first.parentId);+};++/** Whether any of `ids` is a group the model can dissolve. */+export const canUngroupNodes = (document: CanvasDocumentContractV3, ids: readonly string[]): boolean =>+ ids.some((id) => {+ const node = getDocumentIndex(document).byId.get(id)?.node;+ return !!node && isGroupNode(node);+ });++/**+ * Wraps `ids` in a new group, selects it, and shows its children. The selection is published only+ * for an edit the model accepted, before the commit so reconciliation keeps it, and rolled back if+ * the commit does not land.+ */+export const groupLayers = (+ engine: CanvasPreparedEngine | null,+ projectId: string,+ ids: readonly string[],+ label: string+): PreparedCommitOutcome => {+ const model = engine?.document.model() ?? null;+ if (!engine || !model) {+ return { status: 'not-ready' };+ }+ const groupId = createLayerId();+ const names = getDocumentIndex(model.document).nodes.map((entry) => entry.node.name);+ const result = model.prepare({ groupId, ids, name: nextGroupName(names), type: 'group' });+ if (result.status === 'unchanged') {+ return result;+ }+ if (result.status !== 'prepared') {+ return { refusal: result, status: 'refused' };+ }+ const previous = readLayerPanelState(projectId, model.document.selectedLayerId);+ setLayerGroupExpanded(projectId, model.document.selectedLayerId, [groupId], true);+ publishLayerPanelSelection({ primaryId: groupId, projectId, selectedIds: [groupId] });+ const outcome = engine.layers.commitPrepared(label, result.edit);+ if (outcome.status !== 'committed') {+ publishLayerPanelSelection({+ anchorId: previous.anchorId,+ primaryId: previous.primaryId,+ projectId,+ selectedIds: previous.selectedIds,+ });+ setLayerGroupExpanded(projectId, previous.primaryId, [groupId], false);+ }+ return outcome;+};++/** Dissolves every group among `ids`; nothing to dissolve is a quiet no-op. */+export const ungroupLayers = (+ engine: CanvasPreparedEngine | null,+ ids: readonly string[],+ label: string+): PreparedCommitOutcome =>+ commitPreparedEdit(engine, label, (model) => {+ const groupIds = ids.filter((id) => {+ const node = model.getNode(id);+ return !!node && isGroupNode(node);+ });+ return groupIds.length === 0 ? { status: 'unchanged' } : model.prepare({ ids: groupIds, type: 'ungroup' });+ });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.tsdeleted file mode 100644index ee10042d05..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts+++ /dev/null@@ -1,148 +0,0 @@-import type {- CanvasControlLayerContract,- CanvasInpaintMaskLayerContract,- CanvasLayerContract,- CanvasRegionalGuidanceLayerContract,-} from '@workbench/canvas-engine/contracts';--import { describe, expect, it } from 'vitest';--import { getGroupPosition, groupLayers, reorderSelectionWithinGroup, reorderWithinGroup } from './layerGroups';-import { createEmptyPaintLayer } from './layerOps';--const raster = (id: string): CanvasLayerContract => createEmptyPaintLayer(id, id);--const base = (id: string) => ({- blendMode: 'normal' as const,- id,- isEnabled: true,- isLocked: false,- name: id,- opacity: 1,- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },-});--const mask = (): { bitmap: null; fill: { color: string; style: 'solid' } } => ({- bitmap: null,- fill: { color: '#f00', style: 'solid' },-});--const control = (id: string): CanvasControlLayerContract => ({- ...base(id),- adapter: { beginEndStepPct: [0, 1], controlMode: null, kind: 'controlnet', model: null, weight: 1 },- source: { bitmap: null, type: 'paint' },- type: 'control',- withTransparencyEffect: true,-});--const regional = (id: string): CanvasRegionalGuidanceLayerContract => ({- ...base(id),- autoNegative: false,- mask: mask(),- negativePrompt: null,- positivePrompt: null,- referenceImages: [],- type: 'regional_guidance',-});--const inpaint = (id: string): CanvasInpaintMaskLayerContract => ({- ...base(id),- mask: mask(),- type: 'inpaint_mask',-});--const ids = (layers: CanvasLayerContract[]): string[] => layers.map((layer) => layer.id);--describe('groupLayers', () => {- it('partitions into non-empty groups in display order, preserving global order within a group', () => {- // Global z-order (index 0 = top) with interleaved types.- const layers = [inpaint('i1'), raster('r1'), regional('g1'), raster('r2'), control('c1'), inpaint('i2')];- const groups = groupLayers(layers);- expect(groups.map((group) => group.key)).toEqual(['inpaint_mask', 'regional_guidance', 'control', 'raster']);- expect(ids(groups[0]!.layers)).toEqual(['i1', 'i2']);- expect(ids(groups[1]!.layers)).toEqual(['g1']);- expect(ids(groups[2]!.layers)).toEqual(['c1']);- expect(ids(groups[3]!.layers)).toEqual(['r1', 'r2']);- });-- it('drops empty groups', () => {- const groups = groupLayers([raster('r1'), raster('r2')]);- expect(groups).toHaveLength(1);- expect(groups[0]!.key).toBe('raster');- });-- it('returns nothing for an empty document', () => {- expect(groupLayers([])).toEqual([]);- });-});--describe('getGroupPosition', () => {- const layers = [inpaint('i1'), raster('r1'), raster('r2'), raster('r3')];-- it('reports index within the group and the group count', () => {- expect(getGroupPosition(layers, 'r1')).toEqual({ count: 3, index: 0 });- expect(getGroupPosition(layers, 'r3')).toEqual({ count: 3, index: 2 });- expect(getGroupPosition(layers, 'i1')).toEqual({ count: 1, index: 0 });- });-- it('returns null for an absent id', () => {- expect(getGroupPosition(layers, 'ghost')).toBeNull();- });-});--describe('reorderWithinGroup', () => {- // Interleaved: raster r1/r2/r3 sit at global slots 1, 3, 4.- const layers = [inpaint('i1'), raster('r1'), regional('g1'), raster('r2'), raster('r3')];-- it('moves a raster below another raster, keeping other-group layers in place', () => {- // r1 (slot 1) dropped onto r3 (slot 4): raster subsequence r1,r2,r3 -> r2,r3,r1- // written back into slots [1,3,4]; i1 and g1 keep slots 0 and 2.- expect(reorderWithinGroup(layers, 'r1', 'r3')).toEqual({ orderedIds: ['r2', 'r3', 'r1'], stack: 'raster' });- });-- it('moves a raster up', () => {- expect(reorderWithinGroup(layers, 'r3', 'r1')).toEqual({ orderedIds: ['r3', 'r1', 'r2'], stack: 'raster' });- });-- it('rejects a cross-group drop (raster onto regional)', () => {- expect(reorderWithinGroup(layers, 'r1', 'g1')).toBeNull();- });-- it('rejects a no-op (active equals over)', () => {- expect(reorderWithinGroup(layers, 'r1', 'r1')).toBeNull();- });-- it('rejects when an id is absent', () => {- expect(reorderWithinGroup(layers, 'ghost', 'r1')).toBeNull();- expect(reorderWithinGroup(layers, 'r1', 'ghost')).toBeNull();- });-});--describe('reorderSelectionWithinGroup', () => {- const layers = [inpaint('i1'), raster('r1'), regional('g1'), raster('r2'), raster('r3'), raster('r4')];-- it('drags selected members of the active group as one ordered block', () => {- expect(reorderSelectionWithinGroup(layers, 'r1', 'r4', ['r1', 'r3'])).toEqual({- orderedIds: ['r2', 'r4', 'r1', 'r3'],- stack: 'raster',- });- });-- it('moves the selected block toward the front', () => {- expect(reorderSelectionWithinGroup(layers, 'r3', 'r1', ['r2', 'r3'])).toEqual({- orderedIds: ['r2', 'r3', 'r1', 'r4'],- stack: 'raster',- });- });-- it('falls back to a single-layer drag when the active row is not selected', () => {- expect(reorderSelectionWithinGroup(layers, 'r1', 'r3', ['r2', 'r4'])).toEqual({- orderedIds: ['r2', 'r3', 'r1', 'r4'],- stack: 'raster',- });- });-- it('does not reorder when the block is dropped on one of its own members', () => {- expect(reorderSelectionWithinGroup(layers, 'r1', 'r3', ['r1', 'r3'])).toBeNull();- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.tsdeleted file mode 100644index bd509f5bc6..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts+++ /dev/null@@ -1,121 +0,0 @@-import type { CanvasLayerContract, LayerStackKind, ReorderFlatStackCommand } from '@workbench/canvas-engine/api';--import { getStackOrder, LAYER_STACKS_TOP_FIRST, layerStackOf } from '@workbench/canvas-engine/api';--import { moveItem } from './layersDnd';--/** A non-empty Layers panel section: one stack plus its members in flat order. */-export interface LayerGroup {- key: LayerStackKind;- layers: CanvasLayerContract[];-}--/**- * Partitions layers into the non-empty type groups, in display order. Each- * group's members keep their global relative order; empty groups are dropped.- */-export const groupLayers = (layers: readonly CanvasLayerContract[]): LayerGroup[] =>- LAYER_STACKS_TOP_FIRST.map((key) => ({- key,- layers: layers.filter((layer) => layerStackOf(layer) === key),- })).filter((group) => group.layers.length > 0);--/** A layer's position within its own group (index 0 = top of the group). */-export interface GroupPosition {- index: number;- count: number;-}--/** Where `layerId` sits inside its type group, or null when it is absent. */-export const getGroupPosition = (layers: readonly CanvasLayerContract[], layerId: string): GroupPosition | null => {- const layer = layers.find((entry) => entry.id === layerId);- if (!layer) {- return null;- }- const key = layerStackOf(layer);- const index = layers.filter((entry) => layerStackOf(entry) === key).findIndex((entry) => entry.id === layerId);- const count = layers.filter((entry) => layerStackOf(entry) === key).length;- return { count, index };-};--const sameOrder = (a: readonly string[], b: readonly string[]): boolean =>- a.length === b.length && a.every((id, index) => id === b[index]);--/**- * Reorders one stack: `reorderGroup` receives the stack's ids (top-to-bottom) and returns their new- * order (or null for a no-op). Returns the stack-scoped command, or null when nothing moved.- */-const remapGroupOrder = (- layers: readonly CanvasLayerContract[],- key: LayerStackKind,- reorderGroup: (groupIds: string[]) => string[] | null-): ReorderFlatStackCommand | null => {- const groupIds = [...getStackOrder(layers, key).orderedIds];- const reordered = reorderGroup(groupIds);- if (!reordered || sameOrder(reordered, groupIds)) {- return null;- }- return { orderedIds: reordered, stack: key };-};--/**- * Maps a drag-to-reorder (drop `activeId` onto same-group `overId`) to a stack command. Returns- * null — a no-op — when the ids are equal, either is absent, they live in different stacks, or- * nothing moved.- */-export const reorderWithinGroup = (- layers: readonly CanvasLayerContract[],- activeId: string,- overId: string-): ReorderFlatStackCommand | null => {- if (activeId === overId) {- return null;- }- const active = layers.find((layer) => layer.id === activeId);- const over = layers.find((layer) => layer.id === overId);- if (!active || !over || layerStackOf(active) !== layerStackOf(over)) {- return null;- }- return remapGroupOrder(layers, layerStackOf(active), (groupIds) => {- const from = groupIds.indexOf(activeId);- const to = groupIds.indexOf(overId);- return moveItem(groupIds, from, to);- });-};--/**- * Drag-reorders the selected members of the active layer's group as one block.- * Selections in other type groups stay put. Dragging an unselected row retains- * the normal single-row behaviour.- */-export const reorderSelectionWithinGroup = (- layers: readonly CanvasLayerContract[],- activeId: string,- overId: string,- selectedIds: readonly string[]-): ReorderFlatStackCommand | null => {- const active = layers.find((layer) => layer.id === activeId);- const over = layers.find((layer) => layer.id === overId);- if (!active || !over || layerStackOf(active) !== layerStackOf(over)) {- return null;- }- const selected = new Set(selectedIds);- if (!selected.has(activeId)) {- return reorderWithinGroup(layers, activeId, overId);- }- return remapGroupOrder(layers, layerStackOf(active), (groupIds) => {- const moving = groupIds.filter((id) => selected.has(id));- if (moving.length < 2) {- return moveItem(groupIds, groupIds.indexOf(activeId), groupIds.indexOf(overId));- }- if (selected.has(overId)) {- return null;- }- const activeIndex = groupIds.indexOf(activeId);- const overIndex = groupIds.indexOf(overId);- const remaining = groupIds.filter((id) => !selected.has(id));- const remainingOverIndex = remaining.indexOf(overId);- const insertAt = activeIndex < overIndex ? remainingOverIndex + 1 : remainingOverIndex;- return [...remaining.slice(0, insertAt), ...moving, ...remaining.slice(insertAt)];- });-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex 77ed01230f..cd9ca32563 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -1,9 +1,10 @@import type {- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasLayerContract,CanvasRasterLayerContractV2,} from '@workbench/canvas-engine/contracts';+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';import { describe, expect, it, vi } from 'vitest';import {@@ -143,13 +144,13 @@ describe('isMergeableRasterLayer', () => {});describe('canMergeLayerDown', () => {- const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+ const documentOf = (layers: CanvasLayerContract[]): CanvasDocumentContractV3 => ({background: 'transparent',bbox: { height: 100, width: 100, x: 0, y: 0 },height: 100,- layers,+ stacks: stacksFrom(layers),selectedLayerId: null,- version: 2,+ version: 3,width: 100,});const document = documentOf([paintLayer('top'), imageLayer('mid'), maskLayer('bottom')]);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 1a2f9e5008..92b4c236d2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -6,7 +6,7 @@import type {CanvasBlendMode,CanvasControlLayerContract,- CanvasDocumentContractV2,+ CanvasDocumentContractV3,CanvasImageRef,CanvasInpaintMaskLayerContract,CanvasLayerBaseContract,@@ -109,6 +109,25 @@ export const nextInpaintMaskName = (existingNames: readonly string[]): string =>return `Inpaint Mask ${n}`;};+/** The next free "Group N" name given the existing node names (N ≥ 1, first gap). */+export const nextGroupName = (existingNames: readonly string[]): string => {+ const used = new Set<number>();+ for (const name of existingNames) {+ const match = /^Group (\d+)$/.exec(name.trim());+ if (match) {+ const n = Number(match[1]);+ if (Number.isInteger(n) && n > 0) {+ used.add(n);+ }+ }+ }+ let n = 1;+ while (used.has(n)) {+ n += 1;+ }+ return `Group ${n}`;+};+/** Builds an empty inpaint mask layer with the legacy-default fill (no bitmap yet). */export const createInpaintMaskLayer = (name: string, id: string = createLayerId()): CanvasInpaintMaskLayerContract => ({blendMode: 'normal',@@ -352,7 +371,7 @@ export const fitLayerTransformToBbox = (bbox: Rect,documentRect: Rect = bbox): LayerTransform | null => {- const doc = { height: documentRect.height, width: documentRect.width } as CanvasDocumentContractV2;+ const doc = { height: documentRect.height, width: documentRect.width } as CanvasDocumentContractV3;const contentRect = getSourceContentRect(layer, doc);if (contentRect.width <= 0 || contentRect.height <= 0) {return null;@@ -610,7 +629,7 @@ export const convertRasterControlLayer = (};/** Whether the layers panel may offer merge-down for `layerId`; merging is pixel work, so it needs an engine. */-export const canMergeLayerDown = (document: CanvasDocumentContractV2, layerId: string, hasEngine: boolean): boolean =>+export const canMergeLayerDown = (document: CanvasDocumentContractV3, layerId: string, hasEngine: boolean): boolean =>hasEngine && mergeDownEligibility(document, layerId).status === 'eligible';/** Applies a guarded live edit without recording history until the interaction ends. */diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.tsindex 824069031e..5c769e43ae 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.ts@@ -1,10 +1,10 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { createControlLayer, createEmptyPaintLayer } from './layerOps';+import { createControlLayer } from './layerOps';import {clearLayerPropertiesRequest,getLayerPropertiesRequest,- isLayerPropertiesGroupRequested,+ isLayerPropertiesRequestedWithin,layerPropertiesRequestStore,requestLayerProperties,} from './layerPropertiesRequestStore';@@ -59,7 +59,7 @@ describe('layerPropertiesRequestStore', () => {requestLayerProperties(control.id, 'filter');const request = getLayerPropertiesRequest();- expect(isLayerPropertiesGroupRequested(request, [control])).toBe(true);- expect(isLayerPropertiesGroupRequested(request, [createEmptyPaintLayer('Raster', 'raster-1')])).toBe(false);+ expect(isLayerPropertiesRequestedWithin(request, [control.id])).toBe(true);+ expect(isLayerPropertiesRequestedWithin(request, ['raster-1'])).toBe(false);});});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.tsindex 837ca11ce8..f4f15ecc88 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts@@ -1,5 +1,3 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/api';-import { registerAccountOwnedResource } from '@platform/state/accountLifecycle';import { createExternalStore } from '@platform/state/externalStore';@@ -48,7 +46,8 @@ export const useLayerPropertiesRequest = (layerId: string): LayerPropertiesRequeexport const useCurrentLayerPropertiesRequest = (): LayerPropertiesRequest | null =>layerPropertiesRequestStore.useSelector((snapshot) => snapshot.request, Object.is);-export const isLayerPropertiesGroupRequested = (+/** Whether the pending request targets one of `nodeIds`, so its stack must stay expanded to honour it. */+export const isLayerPropertiesRequestedWithin = (request: LayerPropertiesRequest | null,- layers: readonly CanvasLayerContract[]-): boolean => !!request && layers.some((layer) => layer.id === request.layerId);+ nodeIds: readonly string[]+): boolean => !!request && nodeIds.includes(request.layerId);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.test.tsnew file mode 100644index 0000000000..db29f65c0d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.test.ts@@ -0,0 +1,80 @@+import type { CanvasLayerContract, CanvasLayerSourceContract, CanvasNodeContract } from '@workbench/canvas-engine/api';++import { getDocumentIndex } from '@workbench/canvas-engine/api';+import {+ groupContract,+ layerContract,+ stacksFrom,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { describe, expect, it } from 'vitest';++import { canExportRasterPsd, getStackActions, isStackAllVisible, planStackVisibilityToggle } from './layerStackActions';++const raster = (source: CanvasLayerSourceContract, id = 'r'): CanvasLayerContract =>+ layerContract(id, 'raster', { source });+const imageRef = { height: 10, imageName: 'img', width: 10 };+const entriesOf = (nodes: CanvasNodeContract[]) => getDocumentIndex({ stacks: stacksFrom(nodes) }).nodes;++describe('getStackActions', () => {+ it('offers merge-visible + export-psd only for the raster stack, with new rightmost everywhere', () => {+ expect(getStackActions('raster')).toEqual(['mergeVisible', 'exportPsd', 'toggleVisibility', 'new']);+ for (const stack of ['control', 'inpaint_mask', 'regional_guidance'] as const) {+ expect(getStackActions(stack)).toEqual(['toggleVisibility', 'new']);+ }+ });+});++describe('canExportRasterPsd', () => {+ it('counts pixel-backed and rasterizable sources, not masks or polygons', () => {+ expect(canExportRasterPsd([])).toBe(false);+ expect(canExportRasterPsd([layerContract('m', 'inpaint_mask')])).toBe(false);+ expect(canExportRasterPsd([raster({ bitmap: null, type: 'paint' })])).toBe(true);+ expect(canExportRasterPsd([raster({ image: imageRef, type: 'image' })])).toBe(true);+ expect(+ canExportRasterPsd([+ raster({+ fill: null,+ height: 10,+ kind: 'polygon',+ points: [],+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 10,+ }),+ ])+ ).toBe(false);+ });+});++describe('planStackVisibilityToggle', () => {+ it('turns the roots off when every leaf is visible', () => {+ const entries = entriesOf([+ raster({ bitmap: null, type: 'paint' }, 'a'),+ groupContract('g', [raster({ bitmap: null, type: 'paint' }, 'b')]),+ ]);+ expect(isStackAllVisible(entries, 'enabled')).toBe(true);+ expect(planStackVisibilityToggle(entries, 'enabled')).toEqual({ ids: ['a', 'g'], nextVisible: false });+ });++ it('turns every node that is off in its own right back on, so a disabled group cannot keep its leaves dark', () => {+ const entries = entriesOf([+ groupContract(+ 'g',+ [raster({ bitmap: null, type: 'paint' }, 'b'), layerContract('c', 'raster', { isEnabled: false })],+ { isEnabled: false }+ ),+ ]);+ expect(isStackAllVisible(entries, 'enabled')).toBe(false);+ expect(planStackVisibilityToggle(entries, 'enabled')).toEqual({ ids: ['g', 'c'], nextVisible: true });+ });++ it('drives the display axis of overlay stacks through group hidden flags', () => {+ const hiddenGroup = { ...groupContract('g', [layerContract('c1', 'control')]), isHidden: true };+ const entries = entriesOf([hiddenGroup, layerContract('c2', 'control')]);+ expect(isStackAllVisible(entries, 'hidden')).toBe(false);+ expect(planStackVisibilityToggle(entries, 'hidden')).toEqual({ ids: ['g'], nextVisible: true });+ const shown = entriesOf([groupContract('g', [layerContract('c1', 'control')]), layerContract('c2', 'control')]);+ expect(planStackVisibilityToggle(shown, 'hidden')).toEqual({ ids: ['g', 'c2'], nextVisible: false });+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.tsnew file mode 100644index 0000000000..6e8c5f6255--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerStackActions.ts@@ -0,0 +1,62 @@+import type { CanvasLayerContract, CanvasNodeEntry, LayerStackKind } from '@workbench/canvas-engine/api';++import { isExportableRasterLayer, isGroupNode, isNodeHidden } from '@workbench/canvas-engine/api';++/** A stack-header action id. Extend this + `getStackActions` to add a new action. */+export type StackActionId = 'mergeVisible' | 'exportPsd' | 'toggleVisibility' | 'new';++/**+ * The right-aligned actions for a stack, in left-to-right render order (the "New" action sits+ * rightmost, nearest the panel's own add-layer menu). Only the raster stack offers "merge+ * visible" + "export to PSD"; every stack offers hide/show-all + new.+ */+export const getStackActions = (stack: LayerStackKind): StackActionId[] => {+ const actions: StackActionId[] = [];+ if (stack === 'raster') {+ actions.push('mergeVisible', 'exportPsd');+ }+ actions.push('toggleVisibility', 'new');+ return actions;+};++/** Whether the raster stack's "export to PSD" action has anything to export. */+export const canExportRasterPsd = (leaves: readonly CanvasLayerContract[]): boolean =>+ leaves.some(isExportableRasterLayer);++export type StackVisibilityAxis = 'enabled' | 'hidden';++/**+ * Which axis a stack's show/hide-all button drives. The three overlay stacks drive the DISPLAY+ * axis: their layers are drawn to show where an effect applies, so getting them out of the way+ * must not change the image. The raster stack IS the generation input, so it drives enablement.+ */+export const stackVisibilityAxis = (stack: LayerStackKind): StackVisibilityAxis =>+ stack === 'raster' ? 'enabled' : 'hidden';++const isEntryVisible = (entry: CanvasNodeEntry, axis: StackVisibilityAxis): boolean =>+ axis === 'hidden'+ ? !entry.ancestorsHidden && !isNodeHidden(entry.node)+ : entry.ancestorsEnabled && entry.node.isEnabled;++const isOwnVisible = (entry: CanvasNodeEntry, axis: StackVisibilityAxis): boolean =>+ axis === 'hidden' ? !isNodeHidden(entry.node) : entry.node.isEnabled;++/** True when every leaf of the stack is effectively visible on `axis`. Empty ⇒ true. */+export const isStackAllVisible = (entries: readonly CanvasNodeEntry[], axis: StackVisibilityAxis): boolean =>+ entries.every((entry) => isGroupNode(entry.node) || isEntryVisible(entry, axis));++/**+ * Plans a stack show/hide-all toggle as ONE reversible bulk edit. When every leaf is visible the+ * roots alone are turned off, so descendants keep their own flags; otherwise every node that is+ * off in its own right is turned on, so nothing stays gated behind an ancestor.+ */+export const planStackVisibilityToggle = (+ entries: readonly CanvasNodeEntry[],+ axis: StackVisibilityAxis+): { ids: string[]; nextVisible: boolean } => {+ const nextVisible = !isStackAllVisible(entries, axis);+ const targets = nextVisible+ ? entries.filter((entry) => !isOwnVisible(entry, axis))+ : entries.filter((entry) => entry.parentId === null);+ return { ids: targets.map((entry) => entry.node.id), nextVisible };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.tsnew file mode 100644index 0000000000..7ad96798b3--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeDrop.ts@@ -0,0 +1,111 @@+import type { LayerStackKind } from '@workbench/canvas-engine/api';++import { CANVAS_MAX_NODE_DEPTH } from '@workbench/canvas-engine/api';++import type { LayerTreeRow } from './layerTreeRows';++/** Where a dragged block lands, expressed as the model's `reparent` target. */+export interface LayerDropTarget {+ readonly stack: LayerStackKind;+ readonly parentId: string | null;+ /** The sibling the block lands above, or `null` for the bottom of `parentId`. */+ readonly beforeId: string | null;+ /** The depth the preview draws the block at. */+ readonly depth: number;+ /** Ids that move, outermost only, in document order. */+ readonly ids: readonly string[];+}++export interface LayerDropInput {+ /** The stack's rendered rows, top first. */+ readonly rows: readonly LayerTreeRow[];+ /** Every selected id that drags along; descendants of another dragged id are folded in. */+ readonly activeIds: readonly string[];+ readonly overId: string;+ /** Whether the pointer sits in the upper or lower half of the row it is over. */+ readonly edge: 'above' | 'below';+ /** How many indent steps the pointer has moved horizontally since the drag began. */+ readonly depthOffset: number;+}++/** The descendants of a rendered row are the following rows with a greater depth. */+const subtreeEnd = (rows: readonly LayerTreeRow[], start: number): number => {+ const depth = rows[start]!.depth;+ let end = start + 1;+ while (end < rows.length && rows[end]!.depth > depth) {+ end += 1;+ }+ return end;+};++/**+ * Projects a drag onto the sortable-tree target it describes: the dragged block leaves the list,+ * the pointer's vertical position picks the gap, and its horizontal offset picks the depth+ * between the shallowest and deepest parent that gap allows. Returns `null` when nothing valid+ * is under the pointer, when the pointer is over the block itself, or when the move would exceed+ * the depth limit. Locks, cycles across stacks, and other document refusals stay with the model.+ */+export const projectLayerDrop = (input: LayerDropInput): LayerDropTarget | null => {+ const { rows } = input;+ const selected = new Set(input.activeIds);+ const outer = rows.filter(+ (row, index) =>+ selected.has(row.id) &&+ !rows.slice(0, index).some((candidate) => selected.has(candidate.id) && isAncestorRow(rows, candidate, row))+ );+ if (outer.length === 0) {+ return null;+ }+ const moving = new Set<string>();+ let deepestSubtree = 0;+ for (const row of outer) {+ const start = rows.indexOf(row);+ const end = subtreeEnd(rows, start);+ for (let index = start; index < end; index += 1) {+ moving.add(rows[index]!.id);+ }+ deepestSubtree = Math.max(deepestSubtree, row.subtreeDepth);+ }+ if (moving.has(input.overId)) {+ return null;+ }+ const remaining = rows.filter((row) => !moving.has(row.id));+ const overIndex = remaining.findIndex((row) => row.id === input.overId);+ if (overIndex < 0) {+ return null;+ }+ const insertAt = input.edge === 'above' ? overIndex : overIndex + 1;+ const previous = remaining[insertAt - 1];+ const next = remaining[insertAt];+ const maxDepth = Math.min(+ previous ? previous.depth + (previous.kind === 'group' && previous.expanded ? 1 : 0) : 0,+ CANVAS_MAX_NODE_DEPTH - deepestSubtree+ );+ const minDepth = next ? next.depth : 0;+ if (maxDepth < minDepth) {+ return null;+ }+ const depth = Math.max(minDepth, Math.min(maxDepth, outer[0]!.depth + input.depthOffset));+ let parentId: string | null = null;+ if (depth > 0 && previous) {+ if (previous.depth < depth) {+ parentId = previous.id;+ } else {+ for (let index = insertAt - 1; index >= 0; index -= 1) {+ const candidate = remaining[index]!;+ if (candidate.depth === depth - 1) {+ parentId = candidate.id;+ break;+ }+ }+ }+ }+ const beforeId = next && next.parentId === parentId && next.depth === depth ? next.id : null;+ return { beforeId, depth, ids: outer.map((row) => row.id), parentId, stack: rows[0]!.stack };+};++const isAncestorRow = (rows: readonly LayerTreeRow[], ancestor: LayerTreeRow, row: LayerTreeRow): boolean => {+ const start = rows.indexOf(ancestor);+ const index = rows.indexOf(row);+ return ancestor.kind === 'group' && index > start && index < subtreeEnd(rows, start);+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.tsnew file mode 100644index 0000000000..72843cf4a8--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.test.ts@@ -0,0 +1,189 @@+import {+ documentFrom,+ groupContract,+ layerContract,+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';+import { describe, expect, it } from 'vitest';++import { projectLayerDrop } from './layerTreeDrop';+import { buildLayerStackRows } from './layerTreeRows';++const layer = layerContract;+const group = groupContract;++/** raster: r1, G[r2, H[r3], r4], r5 · control: c1 */+const document = () =>+ documentFrom([+ layer('c1', 'control'),+ layer('r1'),+ group('G', [layer('r2'), group('H', [layer('r3')], { isLocked: true }), layer('r4')], { isEnabled: false }),+ layer('r5'),+ ]);++const outline = (rows: readonly { id: string; depth: number }[]) =>+ rows.map((row) => `${' '.repeat(row.depth)}${row.id}`);++describe('buildLayerStackRows', () => {+ it('lists rendered rows per stack, hiding the children of collapsed groups', () => {+ const collapsed = buildLayerStackRows(document(), new Set());+ expect(outline(collapsed.raster.rows)).toEqual(['r1', 'G', 'r5']);+ expect(collapsed.raster.nodeIds).toEqual(['r1', 'G', 'r2', 'H', 'r3', 'r4', 'r5']);+ expect(collapsed.raster.leafCount).toBe(5);+ expect(outline(collapsed.control.rows)).toEqual(['c1']);+ expect(collapsed.inpaint_mask.rows).toEqual([]);++ const expanded = buildLayerStackRows(document(), new Set(['G', 'H']));+ expect(outline(expanded.raster.rows)).toEqual(['r1', 'G', ' r2', ' H', ' r3', ' r4', 'r5']);+ expect(outline(buildLayerStackRows(document(), new Set(['H'])).raster.rows)).toEqual(['r1', 'G', 'r5']);+ });++ it('carries effective state and counts on each row', () => {+ const rows = buildLayerStackRows(document(), new Set(['G', 'H'])).raster.rows;+ const byId = Object.fromEntries(rows.map((row) => [row.id, row]));+ expect(byId.G).toMatchObject({+ childCount: 3,+ contributionEnabled: false,+ expanded: true,+ gatedByAncestor: false,+ kind: 'group',+ leafCount: 3,+ });+ expect(byId.r3).toMatchObject({+ contributionEnabled: false,+ depth: 2,+ effectiveLocked: true,+ gatedByAncestor: true,+ kind: 'leaf',+ parentId: 'H',+ });+ expect(byId.H).toMatchObject({ contributionEnabled: false, effectiveLocked: true, gatedByAncestor: true });+ expect(byId.r5).toMatchObject({ contributionEnabled: true, effectiveLocked: false, gatedByAncestor: false });+ });++ it('keeps row identity for untouched nodes across an unrelated edit and a toggle elsewhere', () => {+ const before = buildLayerStackRows(document(), new Set(['G'])).raster.rows;+ const renamed = documentFrom([+ layer('c1', 'control'),+ layer('r1', 'raster', { name: 'renamed' }),+ before[1]!.node,+ layer('r5'),+ ]);+ const after = buildLayerStackRows(renamed, new Set(['G'])).raster.rows;+ expect(after[1]).toBe(before[1]);+ expect(after[2]).toBe(before[2]);+ expect(after[0]).not.toBe(before[0]);+ const toggled = buildLayerStackRows(renamed, new Set(['G', 'H'])).raster.rows;+ expect(toggled.find((row) => row.id === 'G')).toBe(after[1]);+ expect(toggled.find((row) => row.id === 'H')).not.toBe(after.find((row) => row.id === 'H'));+ });+});++describe('projectLayerDrop', () => {+ const rows = () => buildLayerStackRows(document(), new Set(['G', 'H'])).raster.rows;++ it('drops between siblings at the same depth', () => {+ expect(projectLayerDrop({ activeIds: ['r5'], depthOffset: 0, edge: 'above', overId: 'r1', rows: rows() })).toEqual({+ beforeId: 'r1',+ depth: 0,+ ids: ['r5'],+ parentId: null,+ stack: 'raster',+ });+ expect(projectLayerDrop({ activeIds: ['r1'], depthOffset: 0, edge: 'below', overId: 'r5', rows: rows() })).toEqual({+ beforeId: null,+ depth: 0,+ ids: ['r1'],+ parentId: null,+ stack: 'raster',+ });+ });++ it('indents into the group above when dragged right, and outdents at a subtree end when dragged left', () => {+ expect(projectLayerDrop({ activeIds: ['r5'], depthOffset: 1, edge: 'below', overId: 'G', rows: rows() })).toEqual({+ beforeId: 'r2',+ depth: 1,+ ids: ['r5'],+ parentId: 'G',+ stack: 'raster',+ });+ expect(projectLayerDrop({ activeIds: ['r5'], depthOffset: 2, edge: 'below', overId: 'H', rows: rows() })).toEqual({+ beforeId: 'r3',+ depth: 2,+ ids: ['r5'],+ parentId: 'H',+ stack: 'raster',+ });+ expect(projectLayerDrop({ activeIds: ['r1'], depthOffset: 0, edge: 'below', overId: 'r4', rows: rows() })).toEqual({+ beforeId: 'r5',+ depth: 0,+ ids: ['r1'],+ parentId: null,+ stack: 'raster',+ });+ expect(projectLayerDrop({ activeIds: ['r1'], depthOffset: 1, edge: 'below', overId: 'r4', rows: rows() })).toEqual({+ beforeId: null,+ depth: 1,+ ids: ['r1'],+ parentId: 'G',+ stack: 'raster',+ });+ });++ it('clamps the depth to what the neighbours allow', () => {+ // Between r2 and H the only legal depth is 1.+ expect(+ projectLayerDrop({ activeIds: ['r5'], depthOffset: 5, edge: 'below', overId: 'r2', rows: rows() })+ ).toMatchObject({ depth: 1, parentId: 'G' });+ expect(+ projectLayerDrop({ activeIds: ['r5'], depthOffset: -5, edge: 'below', overId: 'r2', rows: rows() })+ ).toMatchObject({ depth: 1, parentId: 'G' });+ });++ it('moves a group with its descendants and refuses to drop into itself', () => {+ expect(+ projectLayerDrop({ activeIds: ['G', 'r3'], depthOffset: 0, edge: 'below', overId: 'r5', rows: rows() })+ ).toEqual({+ beforeId: null,+ depth: 0,+ ids: ['G'],+ parentId: null,+ stack: 'raster',+ });+ expect(+ projectLayerDrop({ activeIds: ['G'], depthOffset: 0, edge: 'above', overId: 'r3', rows: rows() })+ ).toBeNull();+ });++ it('keeps a multi-selection in document order', () => {+ expect(+ projectLayerDrop({ activeIds: ['r5', 'r1'], depthOffset: 0, edge: 'above', overId: 'r4', rows: rows() })+ ).toEqual({+ beforeId: 'r4',+ depth: 1,+ ids: ['r1', 'r5'],+ parentId: 'G',+ stack: 'raster',+ });+ });++ it('treats a collapsed group as a leaf for indentation and refuses past the depth limit', () => {+ const collapsed = buildLayerStackRows(document(), new Set()).raster.rows;+ expect(+ projectLayerDrop({ activeIds: ['r5'], depthOffset: 1, edge: 'below', overId: 'G', rows: collapsed })+ ).toMatchObject({ depth: 0, parentId: null });+ const nest = (depth: number): ReturnType<typeof layer> | ReturnType<typeof group> =>+ depth === 0 ? layer('leaf') : group(`n${depth}`, [nest(depth - 1)]);+ const deep = documentFrom([nest(10), group('S', [layer('s')])]);+ const ids = new Set(Array.from({ length: 10 }, (_, index) => `n${index + 1}`).concat(['S']));+ const deepRows = buildLayerStackRows(deep, ids).raster.rows;+ expect(+ projectLayerDrop({ activeIds: ['S'], depthOffset: 10, edge: 'below', overId: 'leaf', rows: deepRows })+ ).toMatchObject({ depth: 9, parentId: 'n2' });+ expect(+ projectLayerDrop({ activeIds: ['s'], depthOffset: 10, edge: 'below', overId: 'leaf', rows: deepRows })+ ).toMatchObject({ depth: 10, parentId: 'n1' });+ expect(+ projectLayerDrop({ activeIds: ['S'], depthOffset: 10, edge: 'below', overId: 'n1', rows: deepRows })+ ).toBeNull();+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.tsnew file mode 100644index 0000000000..3fdc5bb329--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerTreeRows.ts@@ -0,0 +1,128 @@+import type {+ CanvasDocumentContractV3,+ CanvasNodeContract,+ CanvasNodeEntry,+ LayerStackKind,+} from '@workbench/canvas-engine/api';++import {+ collectSubtreeLeaves,+ getDocumentIndex,+ isGroupNode,+ isNodeHidden,+ subtreeDepth,+} from '@workbench/canvas-engine/api';++/** One Layers-panel row: a node plus the tree and effective facts the row renders. */+export interface LayerTreeRow {+ readonly id: string;+ readonly kind: 'group' | 'leaf';+ readonly stack: LayerStackKind;+ readonly node: CanvasNodeContract;+ readonly parentId: string | null;+ readonly depth: number;+ /** Groups only: whether the row shows its children. */+ readonly expanded: boolean;+ readonly childCount: number;+ readonly leafCount: number;+ /** Levels below this node, rendered or not; 0 for a leaf or an empty group. */+ readonly subtreeDepth: number;+ /** The node and every ancestor are enabled. */+ readonly contributionEnabled: boolean;+ /** The node or an ancestor is locked. */+ readonly effectiveLocked: boolean;+ /** The node or an ancestor is display-hidden. */+ readonly documentHidden: boolean;+ /** An ancestor alone disables, locks, or hides this node. */+ readonly gatedByAncestor: boolean;+}++export interface LayerStackRows {+ readonly stack: LayerStackKind;+ /** Rows the panel renders, top first; children of collapsed groups are absent. */+ readonly rows: readonly LayerTreeRow[];+ /** Every node id in the stack, top first, whether rendered or not. */+ readonly nodeIds: readonly string[];+ readonly leafCount: number;+}++const rowsByNode = new WeakMap<CanvasNodeContract, LayerTreeRow>();++const isRowCurrent = (row: LayerTreeRow, entry: CanvasNodeEntry, expanded: boolean): boolean =>+ row.node === entry.node &&+ row.parentId === entry.parentId &&+ row.depth === entry.path.length &&+ row.expanded === expanded &&+ row.contributionEnabled === (entry.ancestorsEnabled && row.node.isEnabled) &&+ row.effectiveLocked === (entry.ancestorsLocked || entry.node.isLocked) &&+ row.documentHidden === (entry.ancestorsHidden || isNodeHidden(entry.node));++const rowFor = (entry: CanvasNodeEntry, expanded: boolean): LayerTreeRow => {+ const cached = rowsByNode.get(entry.node);+ if (cached && isRowCurrent(cached, entry, expanded)) {+ return cached;+ }+ const { node } = entry;+ const group = isGroupNode(node);+ const row: LayerTreeRow = {+ childCount: group ? node.children.length : 0,+ contributionEnabled: entry.ancestorsEnabled && node.isEnabled,+ depth: entry.path.length,+ documentHidden: entry.ancestorsHidden || isNodeHidden(node),+ effectiveLocked: entry.ancestorsLocked || node.isLocked,+ expanded: group && expanded,+ gatedByAncestor: !entry.ancestorsEnabled || entry.ancestorsLocked || entry.ancestorsHidden,+ id: node.id,+ kind: group ? 'group' : 'leaf',+ leafCount: group ? collectSubtreeLeaves(node).length : 1,+ node,+ parentId: entry.parentId,+ stack: entry.stack,+ subtreeDepth: group ? Math.max(1, subtreeDepth(node)) : 0,+ };+ rowsByNode.set(node, row);+ return row;+};++/**+ * The rows of every stack for a document and the set of expanded groups. Row objects keep their+ * identity while their node, place, effective state, and expansion are unchanged, so memoized row+ * components skip unaffected rows.+ */+export const buildLayerStackRows = (+ document: CanvasDocumentContractV3,+ expandedGroupIds: ReadonlySet<string>+): Record<LayerStackKind, LayerStackRows> => {+ const index = getDocumentIndex(document);+ const result: Record<LayerStackKind, { rows: LayerTreeRow[]; nodeIds: string[]; leafCount: number }> = {+ control: { leafCount: 0, nodeIds: [], rows: [] },+ inpaint_mask: { leafCount: 0, nodeIds: [], rows: [] },+ raster: { leafCount: 0, nodeIds: [], rows: [] },+ regional_guidance: { leafCount: 0, nodeIds: [], rows: [] },+ };+ const collapsed = new Set<string>();+ for (const entry of index.nodes) {+ const target = result[entry.stack];+ target.nodeIds.push(entry.node.id);+ if (!isGroupNode(entry.node)) {+ target.leafCount += 1;+ }+ if (entry.path.some((ancestor) => collapsed.has(ancestor))) {+ if (isGroupNode(entry.node) && !expandedGroupIds.has(entry.node.id)) {+ collapsed.add(entry.node.id);+ }+ continue;+ }+ const expanded = isGroupNode(entry.node) && expandedGroupIds.has(entry.node.id);+ if (isGroupNode(entry.node) && !expanded) {+ collapsed.add(entry.node.id);+ }+ target.rows.push(rowFor(entry, expanded));+ }+ return {+ control: { stack: 'control', ...result.control },+ inpaint_mask: { stack: 'inpaint_mask', ...result.inpaint_mask },+ raster: { stack: 'raster', ...result.raster },+ regional_guidance: { stack: 'regional_guidance', ...result.regional_guidance },+ };+};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersDnd.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layersDnd.test.tsdeleted file mode 100644index 25cf00f50f..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersDnd.test.ts+++ /dev/null@@ -1,70 +0,0 @@-import { describe, expect, it } from 'vitest';--import { LAYER_KEYBOARD_SENSOR_OPTIONS, shouldStartLayerKeyboardDrag } from './layerDndConfig';-import { moveItem } from './layersDnd';--describe('layer keyboard drag configuration', () => {- it('uses Enter alone to start and end, Escape to cancel, and never claims Space', () => {- expect(LAYER_KEYBOARD_SENSOR_OPTIONS.keyboardCodes).toEqual({- cancel: ['Escape'],- end: ['Enter'],- start: ['Enter'],- });- expect(Object.values(LAYER_KEYBOARD_SENSOR_OPTIONS.keyboardCodes).flat()).not.toContain('Space');- });-});--describe('moveItem', () => {- it('moves an item forward, shifting the rest', () => {- expect(moveItem(['a', 'b', 'c', 'd'], 0, 2)).toEqual(['b', 'c', 'a', 'd']);- });-- it('moves an item backward, shifting the rest', () => {- expect(moveItem(['a', 'b', 'c', 'd'], 3, 1)).toEqual(['a', 'd', 'b', 'c']);- });-- it('is a no-op (order preserved) when from equals to', () => {- expect(moveItem(['a', 'b', 'c'], 1, 1)).toEqual(['a', 'b', 'c']);- });-- it('does not mutate the input', () => {- const input = ['a', 'b', 'c'];- moveItem(input, 0, 2);- expect(input).toEqual(['a', 'b', 'c']);- });-});--describe('shouldStartLayerKeyboardDrag', () => {- const keyEvent = (- overrides: Partial<{- target: EventTarget | null;- altKey: boolean;- ctrlKey: boolean;- metaKey: boolean;- shiftKey: boolean;- }> = {}- ) => ({- altKey: false,- ctrlKey: false,- metaKey: false,- shiftKey: false,- target: null,- ...overrides,- });-- it('allows a plain Enter with no DOM context (the node-test path)', () => {- expect(shouldStartLayerKeyboardDrag(keyEvent(), null)).toBe(true);- });-- it.each([['ctrlKey'], ['metaKey'], ['shiftKey'], ['altKey']] as const)(- 'refuses a %s-modified Enter — those belong to commands, not reordering',- (modifier) => {- expect(shouldStartLayerKeyboardDrag(keyEvent({ [modifier]: true }), null)).toBe(false);- }- );-- it('refuses mod+Enter specifically, the Invoke binding that left rows stuck at drag opacity', () => {- expect(shouldStartLayerKeyboardDrag(keyEvent({ ctrlKey: true }), null)).toBe(false);- expect(shouldStartLayerKeyboardDrag(keyEvent({ metaKey: true }), null)).toBe(false);- });-});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersDnd.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layersDnd.tsdeleted file mode 100644index 1328ea5c45..0000000000--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layersDnd.ts+++ /dev/null@@ -1,18 +0,0 @@-/**- * Pure array move used by the layers panel's grouped drag-to-reorder and its- * context-menu z-arrange commands (see `layerGroups.ts`, which maps a- * within-group move back onto the single global z-ordered `layers` array).- *- * Kept free of dnd-kit and React so the mapping is unit-testable in node.- */--/** Moves the item at `fromIndex` to `toIndex`, shifting the others. Returns a new array. */-export const moveItem = <T>(items: readonly T[], fromIndex: number, toIndex: number): T[] => {- const next = [...items];- const [moved] = next.splice(fromIndex, 1);- if (moved === undefined) {- return next;- }- next.splice(toIndex, 0, moved);- return next;-};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.tsindex cbb9466a12..916cc27973 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts@@ -1,9 +1,11 @@-import type { CanvasLayerContract } from '@workbench/canvas-engine/api';+import type { CanvasNodeContract } from '@workbench/canvas-engine/api';import { useModelsSelector } from '@features/models';+import { getDocumentIndex, getDocumentLeaves } from '@workbench/canvas-engine/api';+import { setLayerGroupExpanded } from '@workbench/layerPanelState';import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';-import { useActiveProjectSelector } from '@workbench/WorkbenchContext';+import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';import { nextLayerName } from '@workbench/workbenchState';import { useCallback } from 'react';import { useTranslation } from 'react-i18next';@@ -16,9 +18,11 @@ import {createControlLayer,createEmptyPaintLayer,createInpaintMaskLayer,+ createLayerId,createRegionalGuidanceLayer,createRegionalGuidanceLayerWithRefImage,nextControlLayerName,+ nextGroupName,nextInpaintMaskName,nextRegionalGuidanceName,} from './layerOps';@@ -27,21 +31,23 @@ import { useSelectedModelBase } from './useSelectedModelBase';/*** Returns a single `addLayer(id)` callback that creates a new layer of the given* kind through the guarded structural commit (one undoable history entry per- * add). Reused by the panel's add-layer menu AND each group header's "New"- * button so both surfaces stay in lockstep.+ * add). Reused by the panel's add-layer menu AND each stack header's "New"+ * button so both surfaces stay in lockstep. A new node lands directly above the+ * selection, inside its group when the selection is a leaf of one.*/export const useAddLayer = (): ((id: AddLayerItemId) => void) => {const { t } = useTranslation();const engine = useCanvasEngine();+ const projectId = useActiveProjectId();const commitPrepared = usePreparedCommit(engine);const base = useSelectedModelBase();const models = useModelsSelector((snapshot) => snapshot.models);const layerNames = useActiveProjectSelector(- (project) => project.canvas.document.layers.map((layer) => layer.name),+ (project) => getDocumentIndex(project.canvas.document).nodes.map((entry) => entry.node.name),(left, right) => left.length === right.length && left.every((name, index) => name === right[index]));const regionalGuidanceCount = useActiveProjectSelector(- (project) => project.canvas.document.layers.filter((layer) => layer.type === 'regional_guidance').length+ (project) => getDocumentLeaves(project.canvas.document).filter((layer) => layer.type === 'regional_guidance').length);return useCallback(@@ -49,12 +55,39 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {if (!isAddLayerItemAvailable(id, base)) {return;}- const add = (label: string, layer: CanvasLayerContract): void => {+ const add = (label: string, node: CanvasNodeContract): void => {commitPrepared(label, (model) =>- model.prepare({ aboveId: model.document.selectedLayerId, layers: [layer], type: 'insert' })+ model.prepare({ aboveId: model.document.selectedLayerId, nodes: [node], type: 'insert' }));};switch (id) {+ case 'group': {+ // An empty group has no stack of its own: it joins the selected node's stack, else raster.+ const groupId = createLayerId();+ const outcome = commitPrepared(t('widgets.layers.actions.newGroup'), (model) => {+ const selectedId = model.document.selectedLayerId;+ const selected = selectedId ? getDocumentIndex(model.document).byId.get(selectedId) : undefined;+ return model.prepare({+ aboveId: selectedId,+ nodes: [+ {+ children: [],+ id: groupId,+ isEnabled: true,+ isLocked: false,+ name: nextGroupName(layerNames),+ type: 'group',+ },+ ],+ stack: selected?.stack ?? 'raster',+ type: 'insert',+ });+ });+ if (outcome.status === 'committed') {+ setLayerGroupExpanded(projectId, groupId, [groupId], true);+ }+ return;+ }case 'raster': {const layer = createEmptyPaintLayer(nextLayerName(layerNames));add(t('widgets.layers.actions.addRasterLayer'), layer);@@ -91,6 +124,6 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {}}},- [base, commitPrepared, layerNames, models, regionalGuidanceCount, t]+ [base, commitPrepared, layerNames, models, projectId, regionalGuidanceCount, t]);};