Skip to content

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

refactor(layers): give layer duplicate, delete, group and ungroup one owner (#10307)

Josh Corbett6322a7372083
diff --git a/invokeai/frontend/webv2/performance/browser-baseline.json b/invokeai/frontend/webv2/performance/browser-baseline.json
index 6ddcf7639f..00fbf3482d 100644
--- a/invokeai/frontend/webv2/performance/browser-baseline.json
+++ b/invokeai/frontend/webv2/performance/browser-baseline.json
@@ -159,12 +159,12 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 344531,
+ "largestAssetRawBytes": 347117,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 602779,
+ "scriptRawBytes": 613179,
"scriptRequestCount": 7,
- "totalRawBytes": 602779
+ "totalRawBytes": 613179
},
"domContentLoadedMedianMs": 117.5,
"id": "editor-canvas",
@@ -197,12 +197,12 @@
"cssRawBytes": 0,
"fontRawBytes": 0,
"imageRawBytes": 0,
- "largestAssetRawBytes": 344531,
+ "largestAssetRawBytes": 347117,
"otherRawBytes": 0,
"requestCount": 7,
- "scriptRawBytes": 602779,
+ "scriptRawBytes": 613179,
"scriptRequestCount": 7,
- "totalRawBytes": 602779
+ "totalRawBytes": 613179
},
"domContentLoadedMedianMs": 117.60000000149012,
"id": "editor-canvas",
@@ -3194,10 +3194,10 @@
"source:src/workbench/widgets/layers/layerActionSession.ts",
"source:src/workbench/widgets/layers/layerChildRows.ts",
"source:src/workbench/widgets/layers/layerChildSelection.ts",
+ "source:src/workbench/widgets/layers/layerCommands.ts",
"source:src/workbench/widgets/layers/layerContextActions.ts",
"source:src/workbench/widgets/layers/layerContextMenuLayout.ts",
"source:src/workbench/widgets/layers/layerExportActions.ts",
- "source:src/workbench/widgets/layers/layerGroupCommands.ts",
"source:src/workbench/widgets/layers/layerMenuState.ts",
"source:src/workbench/widgets/layers/layerOps.ts",
"source:src/workbench/widgets/layers/layerPanelDiagnostics.ts",
@@ -3231,7 +3231,6 @@
"source:src/workbench/widgets/layers/useAddLayer.ts",
"source:src/workbench/widgets/layers/useCanvasCompanionHotkeys.ts",
"source:src/workbench/widgets/layers/useControlSourceActions.ts",
- "source:src/workbench/widgets/layers/useLayerSelectionCommands.ts",
"source:src/workbench/widgets/layers/useLayerStackActions.ts",
"source:src/workbench/widgets/layers/useSelectedMainModel.ts",
"source:src/workbench/widgets/layers/useSelectedModelBase.ts",
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 599e2f7fb8..dbe16173a4 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -4425,7 +4425,6 @@
"copySelection": "Copy selection",
"cutSelection": "Cut selection",
"decreaseBrushSize": "Decrease brush/eraser size",
- "deleteLayer": "Delete layer",
"deleteSelected": "Delete selected canvas item",
"deselect": "Deselect",
"duplicateLayer": "Duplicate layer",
@@ -5155,10 +5154,12 @@
"groupExcluded": "Left out of generation by a group. Use the group in generation to bring it back.",
"duplicateCount_one": "Duplicate layer",
"duplicateCount_other": "Duplicate {{count}} layers",
+ "duplicateGroup": "Duplicate group",
"groupCount_one": "Group layer",
"groupCount_other": "Group {{count}} layers",
"deleteCount_one": "Delete layer",
"deleteCount_other": "Delete {{count}} layers",
+ "deleteGroup": "Delete group",
"toggleActive": "Show or hide layer",
"hideModifiers": "Hide modifiers",
"showModifiers": "Show modifiers",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
index 881ef8fc66..cc4bf52f54 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/ARCHITECTURE.md
@@ -31,7 +31,7 @@ Paint persistence clears dirty result only after intended layer accepts bitmap r
`document/documentIndex.ts` builds one index per `stacks` identity (parent, path, sibling index, document order, ancestor-effective enabled/locked/hidden per node). Selection and bbox edits keep `stacks` and cost no index. Value edit (transform, opacity, blend, name, source, config, or a flag) goes through `updateNodeValues`, which finds each edited node via index and copies only sibling arrays on its path (cost: sibling counts along edited paths, never the forest), so `stacks` changes; it then registers a derived index for new forests extending previous one, and records the edit's replaced nodes (before and after; ancestors rebuilt only for a new child array are not listed) against new forests: `byId` is a layered map reading through to previous index for every untouched id, `nodes` and `leaves` materialize only when a consumer reads them (`leaves` keeps identity when no leaf object changed), and only entries constructed are edited path plus subtree under a group whose flags changed. After eight derivations chain flattens onto its plain root: one override layer holding newest entry of every id chain touched, still pointing consumers at root's cached compile so flattening recompiles only what chain changed; only when overrides cover more than a quarter of root is a plain index rebuilt. So lookups read through at most nine layers; nothing older than root is retained. `document-model/documentModel.budget.test.ts` pins this at 10,000 nodes: leaf edit revisits and constructs `depth + 1` entries, compiles `depth + 1` semantic nodes (ancestors keep counts without walking subtrees) and one leaf, answers `lookupDocumentLeaf`/`lookupDocumentNodeState` without materializing node list; complete reducer → mirror value edit does same with no forest diff.
-`document-model/documentModel.ts` compiles `SemanticLeaf`s and `SemanticNode`s from that index: `contributionEnabled`, `effectiveLocked`, `documentHidden` fold in every ancestor; leaf or node keeps identity while its contract object, place, and ancestor-effective state are unchanged. Every consumer deciding visibility, contribution, editability, export, or what a panel row shows reads these (or `isLeaf*` predicates), not node's own flags; `model.refusalFor(command)` is the single eligibility authority for enabling a command before it runs; for `reparent`, `group`, `ungroup`, `remove` it runs same validator `prepare` uses without materializing an edit (`editsMaterialized` stays zero), so drag hover or toolbar render never builds an inverse or postconditions. Locks are all-or-nothing over subtrees: no command edits, moves, groups, ungroups, or inserts into a subtree that holds a locked node or sits under one, while name, enablement, and lock flips stay open so a locked node can be unlocked.
+`document-model/documentModel.ts` compiles `SemanticLeaf`s and `SemanticNode`s from that index: `contributionEnabled`, `effectiveLocked`, `documentHidden` fold in every ancestor; leaf or node keeps identity while its contract object, place, and ancestor-effective state are unchanged. Every consumer deciding visibility, contribution, editability, export, or what a panel row shows reads these (or `isLeaf*` predicates), not node's own flags; `model.refusalFor(command)` is the single eligibility authority for enabling a command before it runs; for `reparent`, `group`, `ungroup`, `remove`, `duplicate` it runs same validator `prepare` uses without materializing an edit (`editsMaterialized` stays zero), so drag hover or toolbar render never builds an inverse or postconditions. Locks are all-or-nothing over subtrees: no command edits, moves, groups, ungroups, or inserts into a subtree that holds a locked node or sits under one, while name, enablement, and lock flips stay open so a locked node can be unlocked. Duplicate inserts its copy beside the source, so only a locked ancestor refuses it: a locked node, or a group holding one, copies with its locks. The engine's duplicate commits its own pixel copies rather than the model's prepared edit, and asks the same check of the document it commits, so a group locked while source pixels load still refuses it.
Model prepares structural edits (`insert`, `remove`, `duplicate`, `move`, `reorder`, `reparent`, `group`, `ungroup`, `patch*`, `set-*`, `translate`, `select`); `commitPrepared` commits them. Restructuring lands as one `applyCanvasLayerStackMutation`; reducer applies it as `add`, then `move`, then `removeIds`, then flag and selection updates, refusing whole mutation when any step is invalid or result exceeds limits. Insertion anchors are exact: before a surviving sibling under its current parent, after a surviving sibling, top of captured parent, nearest surviving group on captured path, then stack top. Inverses restore removed or moved nodes as maximal sibling runs anchored to their unmoved neighbours, so undo reproduces previous structure exactly.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 625f9d3ca8..2487f13864 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -828,7 +828,8 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {
*/
cropAllLayersToBbox(): Promise<CropAllLayersResult>;
cropLayerToBbox(layerId: string): Promise<CropLayerResult>;
- duplicateLayers(layerIds: readonly string[]): Promise<DuplicateLayersResult>;
+ /** Copies the outermost of `layerIds` with their pixels as one undo step named `label`, selecting the copies. */
+ duplicateLayers(label: string, layerIds: readonly string[]): Promise<DuplicateLayersResult>;
/** Unions the masks' coverage into one new inpaint mask above the topmost source, removing the sources. */
mergeInpaintMasks(layerIds: readonly string[]): Promise<MergeInpaintMasksResult>;
mergeLayerDown(upperLayerId: string): Promise<MergeDownResult>;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
index 8e65a19eb0..470fcd4462 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
@@ -10,7 +10,7 @@ import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/ren
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
-import { lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
+import { createDocumentModel, lookupDocumentLeaf } from '@workbench/canvas-engine/document-model/documentModel';
import {
getDocumentIndex,
getDocumentLayer,
@@ -87,6 +87,7 @@ export interface LayerMutationControllerOptions {
| 'isGestureActive'
| 'isPermitCurrent'
| 'preparePixels'
+ | 'projectId'
| 'reserveRaster'
>;
readonly backend: RasterBackend;
@@ -144,7 +145,7 @@ export class LayerMutationController {
constructor(private readonly options: LayerMutationControllerOptions) {}
- async duplicate(layerIds: readonly string[]): Promise<DuplicateLayersResult> {
+ async duplicate(label: string, layerIds: readonly string[]): Promise<DuplicateLayersResult> {
const { ctx, ...o } = this.options;
const permit = ctx.capturePermit();
if (this.duplicateInFlight || !permit || ctx.isGestureActive()) {
@@ -162,7 +163,7 @@ export class LayerMutationController {
const plans = sources.map((source) => o.getDuplicateRasterPlan(source, document));
const notReadySources = sources.filter((_source, index) => plans[index]?.type === 'not-ready');
if (notReadySources.length === 0) {
- return this.commitDuplicate(layerIds);
+ return this.commitDuplicate(label, layerIds);
}
this.duplicateInFlight = true;
@@ -196,14 +197,14 @@ export class LayerMutationController {
) {
return { status: 'stale' };
}
- return this.commitDuplicate(layerIds);
+ return this.commitDuplicate(label, layerIds);
} finally {
pinLease.release();
this.duplicateInFlight = false;
}
}
- private commitDuplicate(layerIds: readonly string[]): DuplicateLayersResult {
+ private commitDuplicate(label: string, layerIds: readonly string[]): DuplicateLayersResult {
const { ctx, ...o } = this.options;
const document = ctx.getDocument();
if (!document) {
@@ -213,6 +214,15 @@ export class LayerMutationController {
if (!roots) {
return { status: 'nothing' };
}
+ // Asked of the document being committed: callers check first, so a refusal here means a group was locked or the
+ // tree outgrew its limits while source pixels were prepared.
+ const refusal = createDocumentModel(document, {
+ editRevision: ctx.getEditRevision(),
+ projectId: ctx.projectId,
+ }).refusalFor({ createId: ctx.createLayerId, ids: layerIds, type: 'duplicate' });
+ if (refusal) {
+ return { status: 'stale' };
+ }
const sources = roots.flatMap((entry) => collectSubtreeLeaves(entry.node));
const plans = sources.map((source) => o.getDuplicateRasterPlan(source, document));
let retainedBytes = 0;
@@ -365,22 +375,18 @@ export class LayerMutationController {
)
);
};
- const result = txn.publish(
- duplicates.length === 1 ? 'Duplicate layer' : 'Duplicate layers',
- added(initialPrepared),
- {
- bytes: historyBytes,
- dispose: () => detachedLease?.release(),
- heldAssetRefs: collectHistoryMediaRefs(duplicates),
- redo,
- undo: () =>
- ctx.applyStep(
- stackStep(removeDuplicates, hasOriginals, addDuplicates, hasDuplicates, {
- notify: () => o.publishSelectedLayerIds(previousSelectedLayerId, previousSelectedIds),
- })
- ),
- }
- );
+ const result = txn.publish(label, added(initialPrepared), {
+ bytes: historyBytes,
+ dispose: () => detachedLease?.release(),
+ heldAssetRefs: collectHistoryMediaRefs(duplicates),
+ redo,
+ undo: () =>
+ ctx.applyStep(
+ stackStep(removeDuplicates, hasOriginals, addDuplicates, hasDuplicates, {
+ notify: () => o.publishSelectedLayerIds(previousSelectedLayerId, previousSelectedIds),
+ })
+ ),
+ });
if (result.status !== 'committed') {
return { status: guardedResultRefusal(result) };
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
index e52c7b1c45..5bd6e2372d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.budget.test.ts
@@ -426,7 +426,7 @@ describe('reducer → mirror value edits at the 10,000-node limit', () => {
describe('eligibility without materialization', () => {
beforeEach(resetCounters);
- it('answers reparent, group, ungroup and remove eligibility without building an edit', () => {
+ it('answers reparent, group, ungroup, remove and duplicate eligibility without building an edit', () => {
const document = createLargeTreeDocument(NODE_COUNT);
const model = createDocumentModel(document, context);
const index = getDocumentIndex(document);
@@ -440,6 +440,7 @@ describe('eligibility without materialization', () => {
expect(model.refusalFor({ groupId: '\0probe', ids: ['l0', 'l1'], name: '', type: 'group' })).toBeDefined();
expect(model.refusalFor({ ids: [groupId], type: 'ungroup' })).toBeNull();
expect(model.refusalFor({ ids: ['l0'], type: 'remove' })).toBeNull();
+ expect(model.refusalFor({ createId: () => '\0copy', ids: [groupId, 'l0'], type: 'duplicate' })).toBeNull();
expect(counters().editsMaterialized).toBe(0);
expect(model.prepare({ ids: ['l0'], type: 'remove' }).status).toBe('prepared');
expect(counters().editsMaterialized).toBe(1);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
index 476b529423..5136e2782a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
@@ -356,6 +356,37 @@ describe('createDocumentModel', () => {
expect(copy).toMatchObject({ adjustments });
});
+ it('duplicates a locked node and a group holding one beside themselves, but copies nothing into a locked group', () => {
+ let next = 0;
+ const createId = () => `d${next++}`;
+ const project = projectWith(
+ [
+ layer('r1', 'raster', { isLocked: true }),
+ group('G', [layer('r2', 'raster', { isLocked: true })]),
+ group('L', [layer('r3')], { isLocked: true }),
+ ],
+ 'r1'
+ );
+
+ const { after } = roundTrip(project, { createId, ids: ['r1', 'G', 'L'], type: 'duplicate' });
+ expect(outline(after.canvas.document)).toEqual([
+ 'd0',
+ 'r1',
+ 'd1',
+ ' d2',
+ 'G',
+ ' r2',
+ 'd3',
+ ' d4',
+ 'L',
+ ' r3',
+ ]);
+ expect(modelOf(project).prepare({ createId, ids: ['r3'], type: 'duplicate' })).toEqual({
+ ids: ['L'],
+ status: 'locked',
+ });
+ });
+
it('moves within sibling lists, keeping a selected group and its descendants together', () => {
const project = projectWith(tree(), 'r3');
const moved = roundTrip(project, { ids: ['G', 'r3'], kind: 'front', type: 'move' });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
index 806c447e5b..54ce3a8beb 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.ts
@@ -684,7 +684,13 @@ export const createDocumentModel = (
);
};
- const prepareDuplicate = (command: Extract<DocumentCommand, { type: 'duplicate' }>): PrepareEditResult => {
+ /**
+ * Every refusal a duplicate can meet from the document, decided before an id is minted: asking is free of side
+ * effects and costs no copy. Only a `createId` that returns an id the document holds is refused later.
+ */
+ const checkDuplicate = (
+ command: Extract<DocumentCommand, { type: 'duplicate' }>
+ ): DocumentRefusal | { outer: CanvasNodeEntry[] } => {
const ids = unique(command.ids);
if (ids.length === 0) {
return { operation: 'duplicate nothing', status: 'unsupported' };
@@ -694,11 +700,12 @@ export const createDocumentModel = (
return found;
}
const outer = outermostNodes(index, ids);
- const locked = unique(outer.flatMap((entry) => lockedWithin(index, entry)));
+ // A copy lands beside its source, so only a locked ancestor refuses it: copying a locked node (or one holding
+ // locked nodes) inserts nothing into a locked subtree, and the copy keeps its locks.
+ const locked = unique(outer.flatMap((entry) => lockedAlong(index, entry.path)));
if (locked.length > 0) {
return { ids: locked, status: 'locked' };
}
- // Every refusal is decided before an id is minted, so asking is free of side effects.
let budgeted = 0;
for (const entry of outer) {
const refusal = limits([entry.node], entry.path.length, budgeted);
@@ -707,6 +714,16 @@ export const createDocumentModel = (
}
budgeted += collectSubtree(entry.node).length;
}
+ return { outer };
+ };
+
+ // Production duplicates commit through the engine (pixel copies), which asks `refusalFor`; model tests use this edit.
+ const prepareDuplicate = (command: Extract<DocumentCommand, { type: 'duplicate' }>): PrepareEditResult => {
+ const checked = checkDuplicate(command);
+ if ('status' in checked) {
+ return checked;
+ }
+ const { outer } = checked;
const add: CanvasNodeInsertion[] = [];
const createdIds: string[] = [];
const rootIds: string[] = [];
@@ -1582,7 +1599,9 @@ export const createDocumentModel = (
? checkUngroup(command)
: command.type === 'remove'
? checkRemove(command)
- : null;
+ : command.type === 'duplicate'
+ ? checkDuplicate(command)
+ : null;
if (checked) {
return 'status' in checked && checked.status !== 'unchanged' ? (checked as DocumentRefusal) : null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts
index 206a7d0f35..b8d13626c0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.heldAssets.test.ts
@@ -283,7 +283,7 @@ const cases: HeldCase[] = [
{
act: async ({ engine }) => {
await warmCaches(engine, ['a']);
- return engine.layers.duplicateLayers(['a']);
+ return engine.layers.duplicateLayers('Duplicate', ['a']);
},
heldAfterOp: ['original-duplicate.png'],
heldAfterUndo: ['original-duplicate.png'],
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index da2506fa95..c2177d76e8 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -50,7 +50,7 @@ import {
} from '@workbench/canvas-operations/createCanvasEngine';
import { FILTER_AUTO_PROCESS_DEBOUNCE_MS } from '@workbench/canvas-operations/filterOperationSession';
import { getCanvasOperationImplementation as getCanvasOperations } from '@workbench/canvas-operations/operationAccess';
-import { executeCanvasHotkeyCommand } from '@workbench/widgets/canvas/canvasHotkeyCommands';
+import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from '@workbench/widgets/canvas/canvasHotkeyCommands';
import { createInitialWorkbenchState, workbenchReducer } from '@workbench/workbenchState.testing';
import { afterEach, describe, expect, it, type Mock, vi } from 'vitest';
@@ -8191,7 +8191,7 @@ describe('mergeVisibleRasterLayers', () => {
expect(session.apply({ id: 'upper', patch: { blendMode: 'screen' }, type: 'updateCanvasLayer' })).toBe(true);
raf.flush();
- const result = await engine.layers.duplicateLayers(['upper']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper']);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
@@ -8209,7 +8209,7 @@ describe('mergeVisibleRasterLayers', () => {
const blendModeOf = (id: string) =>
getDocumentLeaves(engine.document.getDocument()!).find((layer) => layer.id === id)?.blendMode;
- const duplicate = engine.layers.duplicateLayers(['upper']);
+ const duplicate = engine.layers.duplicateLayers('Duplicate', ['upper']);
const session = engine.layers.beginStructuralPreview()!;
expect(session.apply({ id: 'below', patch: { blendMode: 'screen' }, type: 'updateCanvasLayer' })).toBe(true);
raf.flush();
@@ -8234,6 +8234,25 @@ describe('mergeVisibleRasterLayers', () => {
engine.lifecycle.dispose();
});
+ it('refuses a duplicate whose parent group was locked while its source pixels loaded', async () => {
+ const base = twoPaintDoc();
+ const [upper, below] = getDocumentLeaves(base) as [CanvasLayerContract, CanvasLayerContract];
+ const { engine, store } = setup({ ...base, stacks: stacksFrom([groupContract('g', [upper]), below]) });
+
+ const duplicate = engine.layers.duplicateLayers('Duplicate', ['upper']);
+ store.dispatch({
+ enabledUpdates: [],
+ lockedUpdates: [{ id: 'g', isLocked: true }],
+ type: 'applyCanvasLayerStackMutation',
+ });
+ const locked = engine.document.getDocument();
+
+ expect(await duplicate).toEqual({ status: 'stale' });
+ expect(engine.document.getDocument()).toBe(locked);
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.lifecycle.dispose();
+ });
+
it('lands a selected merge past a preview of another layer opened while it exported', async () => {
const { engine, raf, setPanelSelectedIds } = setup(selectedMergeDoc());
raf.flush();
@@ -8273,7 +8292,7 @@ describe('mergeVisibleRasterLayers', () => {
raf.flush();
setPanelSelectedIds(['upper', 'below']);
- const result = await engine.layers.duplicateLayers(['upper', 'below']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper', 'below']);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
throw new Error(`unexpected duplicate result: ${result.status}`);
@@ -8323,13 +8342,13 @@ describe('mergeVisibleRasterLayers', () => {
setPanelSelectedIds(['upper', 'below']);
setRejectMutations(true);
- expect(await engine.layers.duplicateLayers(['upper', 'below'])).toEqual({ status: 'stale' });
+ expect(await engine.layers.duplicateLayers('Duplicate', ['upper', 'below'])).toEqual({ status: 'stale' });
expect(getPanelSelectedIds()).toEqual(['upper', 'below']);
expect(selectionChanges).toHaveLength(0);
expect(engine.stores.canUndo.get()).toBe(false);
setRejectMutations(false);
- const result = await engine.layers.duplicateLayers(['upper', 'below']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper', 'below']);
if (result.status !== 'duplicated') {
throw new Error(`unexpected duplicate result: ${result.status}`);
}
@@ -8370,7 +8389,7 @@ describe('mergeVisibleRasterLayers', () => {
await flushMicrotasks();
raf.flush();
- const result = await engine.layers.duplicateLayers(['upper']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper']);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
throw new Error(`unexpected duplicate result: ${result.status}`);
@@ -8402,7 +8421,7 @@ describe('mergeVisibleRasterLayers', () => {
it('duplicates pending empty paint as empty instead of resurrecting its stale durable bitmap', async () => {
const { engine } = setup(twoPaintDoc(), new Set(['upper']));
- const result = await engine.layers.duplicateLayers(['upper']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper']);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
@@ -8425,7 +8444,7 @@ describe('mergeVisibleRasterLayers', () => {
const doc = { ...twoPaintDoc(), stacks: stacksFrom([mask]), selectedLayerId: mask.id };
const { engine } = setup(doc, new Set([mask.id]));
- const result = await engine.layers.duplicateLayers([mask.id]);
+ const result = await engine.layers.duplicateLayers('Duplicate', [mask.id]);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
@@ -8451,7 +8470,7 @@ describe('mergeVisibleRasterLayers', () => {
};
const { engine, surfaces } = setup(doc);
- const result = await engine.layers.duplicateLayers(['upper']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper']);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
@@ -8600,7 +8619,10 @@ describe('mergeVisibleRasterLayers', () => {
};
const { engine, raf, surfaces } = setup(doc);
- const result = await engine.layers.duplicateLayers(layers.map((layer) => layer.id));
+ const result = await engine.layers.duplicateLayers(
+ 'Duplicate',
+ layers.map((layer) => layer.id)
+ );
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
throw new Error(`unexpected duplicate result: ${result.status}`);
@@ -8625,8 +8647,8 @@ describe('mergeVisibleRasterLayers', () => {
it('reports a concurrent duplicate as busy while first-use source preparation is in flight', async () => {
const { engine } = setup(twoPaintDoc());
- const first = engine.layers.duplicateLayers(['upper']);
- expect(await engine.layers.duplicateLayers(['upper'])).toEqual({ status: 'busy' });
+ const first = engine.layers.duplicateLayers('Duplicate', ['upper']);
+ expect(await engine.layers.duplicateLayers('Duplicate', ['upper'])).toEqual({ status: 'busy' });
expect((await first).status).toBe('duplicated');
engine.lifecycle.dispose();
@@ -8653,7 +8675,10 @@ describe('mergeVisibleRasterLayers', () => {
width: size,
};
const { engine, surfaces } = setup(doc);
- const result = await engine.layers.duplicateLayers(layers.map((layer) => layer.id));
+ const result = await engine.layers.duplicateLayers(
+ 'Duplicate',
+ layers.map((layer) => layer.id)
+ );
if (result.status !== 'duplicated') {
throw new Error(`unexpected duplicate result: ${result.status}`);
}
@@ -8683,7 +8708,7 @@ describe('mergeVisibleRasterLayers', () => {
raf.flush();
const beforeDuplicate = surfaces.length;
- const result = await engine.layers.duplicateLayers(['upper']);
+ const result = await engine.layers.duplicateLayers('Duplicate', ['upper']);
expect(result.status).toBe('duplicated');
if (result.status !== 'duplicated') {
@@ -8724,7 +8749,12 @@ describe('mergeVisibleRasterLayers', () => {
raf.flush();
const afterRasterization = surfaces.length;
- expect(await engine.layers.duplicateLayers(layers.map((layer) => layer.id))).toEqual({ status: 'over-budget' });
+ expect(
+ await engine.layers.duplicateLayers(
+ 'Duplicate',
+ layers.map((layer) => layer.id)
+ )
+ ).toEqual({ status: 'over-budget' });
expect(surfaces).toHaveLength(afterRasterization);
expect(await engine.layers.mergeSelectedRasterLayers(layers.map((layer) => layer.id))).toBe('over-budget');
expect(getDocumentLeaves(engine.document.getDocument()!)).toEqual(layers);
@@ -20539,7 +20569,11 @@ describe('layer quick-switch memory', () => {
swapActiveColors: vi.fn(),
resetActiveColors: vi.fn(),
pasteFromClipboard: vi.fn(),
- notifyLayerDuplicateFailed: vi.fn(),
+ layerCommands: {
+ engine,
+ reportError: vi.fn(),
+ t: ((key: string) => key) as CanvasHotkeyContext['layerCommands']['t'],
+ },
reportStructuralCommit: vi.fn(),
reportPreparedCommit: vi.fn(),
reportLayerOperation: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
index 7cc0496aab..8f86e45d5f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
@@ -48,7 +48,7 @@ describe('layer restore through history on an interleaved document', () => {
[raster('r0'), createInpaintMaskLayer('m1', 'm1'), raster('r1')],
'r0'
);
- const duplicated = await engine.layers.duplicateLayers(['r0']);
+ const duplicated = await engine.layers.duplicateLayers('Duplicate', ['r0']);
expect(duplicated.status).toBe('duplicated');
const r0 = getDocumentLeaves(document()).find((layer) => layer.id === 'r0')!;
@@ -74,7 +74,7 @@ describe('layer restore through history on an interleaved document', () => {
[raster('r0'), createInpaintMaskLayer('m1', 'm1'), raster('r1')],
'r0'
);
- const duplicated = await engine.layers.duplicateLayers(['r0']);
+ const duplicated = await engine.layers.duplicateLayers('Duplicate', ['r0']);
if (duplicated.status !== 'duplicated') {
throw new Error('expected a duplicate');
}
@@ -108,7 +108,7 @@ describe('layer restore through history on an interleaved document', () => {
const outline = () =>
getDocumentIndex(document()).nodes.map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);
- const duplicated = await engine.layers.duplicateLayers(['g', 'r2']);
+ const duplicated = await engine.layers.duplicateLayers('Duplicate', ['g', 'r2']);
if (duplicated.status !== 'duplicated') {
throw new Error(`expected a duplicate, got ${duplicated.status}`);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index d28010df5c..423876c308 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -481,8 +481,7 @@ export const CanvasWidgetView = ({ runtime, instance }: WidgetViewProps) => {
document,
engine,
hasMultipleStagingSlots,
- notifyLayerDuplicateFailed: () =>
- notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),
+ layerCommands: { engine, reportError: notify.error, t },
pasteFromClipboard,
reportLayerOperation: (refusal) => reportLayerOperation(refusal, notify.error, t),
reportMergeDownRefusal: (refusal) => reportMergeDownRefusal(document, refusal, showCanvasRefusalNotice, t),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
index b13f1791ea..5377bb8206 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -9,14 +9,25 @@ import type {
NewRasterLayerResult,
} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type * as LayerCommandsModule from '@workbench/widgets/layers/layerCommands';
import type { TFunction } from 'i18next';
import { createControlLayer, 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 { firstPartyHotkeyCatalog } from '@workbench/hotkeys/catalog';
+import { deleteLayers, duplicateLayers, groupLayers, ungroupLayers } from '@workbench/widgets/layers/layerCommands';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
+// The layer commands own their eligibility, labels and feedback (see layerCommands tests); here only routing counts.
+vi.mock('@workbench/widgets/layers/layerCommands', async (importOriginal) => ({
+ ...(await importOriginal<typeof LayerCommandsModule>()),
+ deleteLayers: vi.fn(() => 'committed'),
+ duplicateLayers: vi.fn(() => Promise.resolve('committed')),
+ groupLayers: vi.fn(() => 'committed'),
+ ungroupLayers: vi.fn(() => 'committed'),
+}));
+
import { CANVAS_HEADER_HOTKEYS } from './canvasHeaderCommands';
import { CANVAS_ONLY_HOTKEYS, executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
import {
@@ -119,7 +130,7 @@ const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyCo
document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a'),
engine: createEngine(),
hasMultipleStagingSlots: false,
- notifyLayerDuplicateFailed: vi.fn(),
+ layerCommands: { engine: null, reportError: vi.fn(), t: ((key: string) => key) as TFunction },
pasteFromClipboard,
resetActiveColors: vi.fn(),
selectedLayerIds: ['a'],
@@ -138,6 +149,7 @@ const run = (commandId: string, overrides: Partial<CanvasHotkeyContext> = {}) =>
};
beforeEach(() => {
+ vi.clearAllMocks();
dispatch = vi.fn();
copySelection = vi.fn();
pasteFromClipboard = vi.fn();
@@ -203,8 +215,8 @@ describe('while results are staged', () => {
expect(erasing.selection.eraseSelection).toHaveBeenCalledOnce();
expect(dispatch).not.toHaveBeenCalled();
- const deleting = run('canvas.deleteSelected', { hasMultipleStagingSlots: true });
- expect(deleting.layers.commitPrepared).toHaveBeenCalledOnce();
+ run('canvas.deleteSelected', { hasMultipleStagingSlots: true });
+ expect(deleteLayers).toHaveBeenCalledOnce();
expect(dispatch).not.toHaveBeenCalled();
});
@@ -212,9 +224,8 @@ describe('while results are staged', () => {
expect(run('canvas.tool.brush', { hasMultipleStagingSlots: true }).tools.setTool).toHaveBeenCalledWith('brush');
expect(run('canvas.undo', { hasMultipleStagingSlots: true }).history.undo).toHaveBeenCalledOnce();
expect(run('canvas.selectAll', { hasMultipleStagingSlots: true }).selection.selectAll).toHaveBeenCalledOnce();
- expect(run('canvas.duplicateLayer', { hasMultipleStagingSlots: true }).layers.duplicateLayers).toHaveBeenCalledWith(
- ['a']
- );
+ run('canvas.duplicateLayer', { hasMultipleStagingSlots: true });
+ expect(duplicateLayers).toHaveBeenCalledOnce();
const crop = contextOf({ hasMultipleStagingSlots: true });
executeCanvasHotkeyCommand('canvas.cropAllLayersToFrame', crop);
expect(crop.cropAllLayers).toHaveBeenCalledOnce();
@@ -377,93 +388,29 @@ describe('layer reorder', () => {
});
});
-describe('delete: pixels vs layer', () => {
- it('erases the pixel selection when one exists', () => {
- const engine = run('canvas.deleteSelected', { engine: createEngine({ hasSelection: true }) });
- expect(engine.selection.eraseSelection).toHaveBeenCalled();
- expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
- });
-
- it('deletes the selected layer when there is no pixel selection', () => {
- const engine = run('canvas.deleteSelected');
- expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
- expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
- 'widgets.canvas.commands.deleteLayer',
- expect.objectContaining({ forward: { ids: ['a'], type: 'removeCanvasLayers' } })
- );
- });
-
- it('deletes the full Layers-panel selection as one history edit', () => {
- const layers = [rasterLayer('a'), rasterLayer('b'), rasterLayer('c')];
- const engine = run('canvas.deleteSelected', { document: documentOf(layers, 'a'), selectedLayerIds: ['a', 'c'] });
-
- expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
- 'widgets.canvas.commands.deleteLayer',
- expect.objectContaining({
- forward: { ids: ['a', 'c'], type: 'removeCanvasLayers' },
- inverse: expect.objectContaining({
- add: [expect.objectContaining({ nodes: [layers[0]] }), expect.objectContaining({ nodes: [layers[2]] })],
- selectedLayerId: 'a',
- }),
- })
- );
- });
-
- it('does not delete when any selected layer is locked', () => {
- const engine = run('canvas.deleteSelected', {
- document: documentOf([rasterLayer('a'), rasterLayer('b', { isLocked: true })], 'a'),
- selectedLayerIds: ['a', 'b'],
- });
-
- expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
+describe('layer commands', () => {
+ it.each([
+ ['canvas.deleteSelected', deleteLayers],
+ ['canvas.duplicateLayer', duplicateLayers],
+ ['canvas.groupLayers', groupLayers],
+ ['canvas.ungroupLayers', ungroupLayers],
+ ])('%s runs the shared layer command on the Layers-panel selection', (commandId, command) => {
+ const ctx = contextOf({ selectedLayerIds: ['a', 'b'] });
+ executeCanvasHotkeyCommand(commandId, ctx);
+ expect(command).toHaveBeenCalledExactlyOnceWith(ctx.layerCommands, ['a', 'b']);
});
- it('does nothing with neither a selection nor a selected layer', () => {
- const engine = run('canvas.deleteSelected', { document: documentOf([rasterLayer('a')], null) });
- expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
- expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
+ it('Delete erases a live pixel selection instead of deleting layers', () => {
+ const engine = run('canvas.deleteSelected', { engine: createEngine({ hasSelection: true }) });
+ expect(engine.selection.eraseSelection).toHaveBeenCalledOnce();
+ expect(deleteLayers).not.toHaveBeenCalled();
});
-});
-describe('duplicate: lift vs whole layer', () => {
- it('lifts the pixel selection into a new layer when one exists', () => {
+ it('mod+J lifts a live pixel selection into a new layer instead of duplicating layers', () => {
const engine = run('canvas.duplicateLayer', { engine: createEngine({ hasSelection: true }) });
- expect(engine.selection.liftSelectionToLayer).toHaveBeenCalled();
- expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
- });
-
- it('duplicates the whole layer with no pixel selection', () => {
- const engine = run('canvas.duplicateLayer');
- expect(engine.layers.duplicateLayers).toHaveBeenCalledWith(['a']);
- });
-
- it('duplicates every selected layer as one engine operation', () => {
- const engine = run('canvas.duplicateLayer', { selectedLayerIds: ['a', 'b'] });
- expect(engine.layers.duplicateLayers).toHaveBeenCalledWith(['a', 'b']);
+ expect(engine.selection.liftSelectionToLayer).toHaveBeenCalledOnce();
+ expect(duplicateLayers).not.toHaveBeenCalled();
});
-
- it('reports when whole-layer duplication throws', async () => {
- const engine = createEngine();
- engine.layers.duplicateLayers.mockImplementation(() => Promise.reject(new Error('rejected')));
- const notifyLayerDuplicateFailed = vi.fn();
-
- executeCanvasHotkeyCommand('canvas.duplicateLayer', contextOf({ engine, notifyLayerDuplicateFailed }));
-
- await vi.waitFor(() => expect(notifyLayerDuplicateFailed).toHaveBeenCalledOnce());
- });
-
- it.each(['not-ready', 'over-budget', 'stale'] as const)(
- 'explains a %s whole-layer duplication refusal',
- async (status) => {
- const engine = createEngine();
- engine.layers.duplicateLayers.mockImplementation(() => Promise.resolve({ status }));
- const reportLayerOperation = vi.fn();
-
- executeCanvasHotkeyCommand('canvas.duplicateLayer', contextOf({ engine, reportLayerOperation }));
-
- await vi.waitFor(() => expect(reportLayerOperation).toHaveBeenCalledExactlyOnceWith(status));
- }
- );
});
describe('clipboard', () => {
@@ -820,26 +767,13 @@ describe('group selection', () => {
});
const control = (id: string): CanvasLayerContract => createControlLayer({ id, name: id });
- it('reorders, deletes and duplicates a selected group', () => {
+ it('reorders 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', () => {
@@ -864,47 +798,6 @@ describe('group selection', () => {
})
);
});
-
- 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'] }) })
- );
- });
-
- it('ungroup on leaves of one group moves them out above it, and does nothing for a top-level leaf', () => {
- const document = nodeDocument([groupContract('g', [rasterLayer('a'), rasterLayer('b')]), rasterLayer('c')], 'a');
- const lifted = run('canvas.ungroupLayers', { document, selectedLayerIds: ['b', 'a'] });
- expect(lifted.layers.commitPrepared).toHaveBeenCalledExactlyOnceWith(
- 'widgets.layers.actions.removeFromGroup',
- expect.objectContaining({
- forward: expect.objectContaining({
- move: [{ anchor: expect.objectContaining({ beforeId: 'g', parentPath: [] }), ids: ['a', 'b'] }],
- }),
- })
- );
- const topLevel = run('canvas.ungroupLayers', {
- document: { ...document, selectedLayerId: 'c' },
- selectedLayerIds: ['c'],
- });
- expect(topLevel.layers.commitPrepared).not.toHaveBeenCalled();
- });
});
describe('active color pair commands', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index ac6780cd8d..5c4dee8068 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -17,7 +17,6 @@ import {
isNodeHidden,
isOverlayStack,
} from '@workbench/canvas-engine/api';
-import { publishLayerPanelSelection } from '@workbench/layerPanelState';
import {
CANVAS_HISTORY_HOTKEYS,
CANVAS_MERGE_DOWN_HOTKEY,
@@ -33,13 +32,12 @@ import {
type PreparedCommitOutcome,
} from '@workbench/widgets/canvas/useStructuralCommit';
import {
- canGroupSelection,
- canRemoveFromGroup,
- canUngroupSelection,
+ deleteLayers,
+ duplicateLayers,
groupLayers,
- removeFromGroup,
ungroupLayers,
-} from '@workbench/widgets/layers/layerGroupCommands';
+ type LayerCommandDeps,
+} from '@workbench/widgets/layers/layerCommands';
/** Keys that act only while the Canvas itself holds focus; rows and fields own them elsewhere. */
export const CANVAS_ONLY_HOTKEYS = [
@@ -161,8 +159,9 @@ export interface CanvasHotkeyContext extends Omit<CanvasToolCommandContext, 'eng
readonly copySelection: (cut: boolean) => void;
/** Crops every unlocked layer to the frame and reports the outcome, as the canvas menu does. */
readonly cropAllLayers: () => void;
+ /** Delete, duplicate, group and ungroup run on `selectedLayerIds` through these, as every layer surface does. */
+ readonly layerCommands: LayerCommandDeps;
readonly pasteFromClipboard: () => void;
- readonly notifyLayerDuplicateFailed: () => void;
readonly reportStructuralCommit: (result: StructuralCommitResult) => void;
readonly reportPreparedCommit: (outcome: PreparedCommitOutcome) => void;
readonly reportLayerOperation: (refusal: LayerOperationRefusal | AdjustmentRefusal | LayerUnreadable) => void;
@@ -182,7 +181,6 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
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);
const stepsResults =
commandId === 'canvas.prevEntity' ||
@@ -241,12 +239,8 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
// Delete clears selected pixels before falling back to layer deletion.
if (engine?.interaction.get('hasSelection')) {
engine.selection.eraseSelection();
- } else if (engine && selected && !selectedFrozen) {
- ctx.reportPreparedCommit(
- commitPreparedEdit(engine, t('widgets.canvas.commands.deleteLayer'), (model) =>
- model.prepare({ ids: ctx.selectedLayerIds, type: 'remove' })
- )
- );
+ } else {
+ deleteLayers(ctx.layerCommands, ctx.selectedLayerIds);
}
} else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {
ctx.copySelection(commandId === 'canvas.cutSelection');
@@ -298,49 +292,13 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
if (result.status !== 'created' && result.status !== 'empty') {
ctx.reportLayerOperation(result.status);
}
- } else if (engine && selected) {
- void engine.layers
- .duplicateLayers(ctx.selectedLayerIds)
- .then((result) => {
- if (result.status === 'duplicated') {
- publishLayerPanelSelection({
- primaryId: result.selectedLayerId,
- projectId: engine.projectId,
- selectedIds: result.duplicateIds,
- });
- return;
- }
- if (result.status === 'busy') {
- return;
- }
- if (result.status === 'nothing') {
- ctx.notifyLayerDuplicateFailed();
- return;
- }
- ctx.reportLayerOperation(result.status === 'unreadable' ? result : result.status);
- })
- .catch(() => {
- // The engine keeps rejected transactions atomic; route both rejection
- // and preflight refusal through the same user-facing command feedback.
- ctx.notifyLayerDuplicateFailed();
- });
+ } else {
+ void duplicateLayers(ctx.layerCommands, ctx.selectedLayerIds);
}
} else if (commandId === 'canvas.groupLayers') {
- if (engine && selected && canGroupSelection(engine.document.model(), ctx.selectedLayerIds)) {
- ctx.reportPreparedCommit(
- groupLayers(engine, engine.projectId, ctx.selectedLayerIds, t('widgets.canvas.commands.groupLayers'))
- );
- }
+ groupLayers(ctx.layerCommands, ctx.selectedLayerIds);
} else if (commandId === 'canvas.ungroupLayers') {
- // Groups dissolve; a selection of leaves of one group moves out above it instead.
- const model = engine?.document.model() ?? null;
- if (engine && selected && canUngroupSelection(model, ctx.selectedLayerIds)) {
- ctx.reportPreparedCommit(ungroupLayers(engine, ctx.selectedLayerIds, t('widgets.canvas.commands.ungroupLayers')));
- } else if (engine && selected && canRemoveFromGroup(model, ctx.selectedLayerIds)) {
- ctx.reportPreparedCommit(
- removeFromGroup(engine, ctx.selectedLayerIds, t('widgets.layers.actions.removeFromGroup'))
- );
- }
+ ungroupLayers(ctx.layerCommands, ctx.selectedLayerIds);
} else if (commandId === 'canvas.mergeDown') {
mergeSelectedLayerDown(engine, document, ctx.reportLayerOperation, ctx.reportMergeDownRefusal);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts
index 360c3bfd07..e797ad1799 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasSelectionEdits.browser.test.ts
@@ -17,7 +17,7 @@ import { createWorkbenchStore } from '@workbench/workbenchStore';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { copyCanvasSelection } from './canvasClipboard';
-import { executeCanvasHotkeyCommand } from './canvasHotkeyCommands';
+import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
const cleanups: (() => void | Promise<void>)[] = [];
afterEach(async () => {
@@ -136,7 +136,11 @@ const setup = async (layers: readonly Parameters<typeof stacksFrom>[0][number][]
document: doc(),
engine,
hasMultipleStagingSlots: false,
- notifyLayerDuplicateFailed: vi.fn(),
+ layerCommands: {
+ engine,
+ reportError: vi.fn(),
+ t: ((key: string) => key) as CanvasHotkeyContext['layerCommands']['t'],
+ },
pasteFromClipboard: vi.fn(),
reportLayerOperation: vi.fn(),
reportMergeDownRefusal: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
index 2ceb3b0a25..506d518fad 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/engineStoreHooks.ts
@@ -86,6 +86,21 @@ export const useCanvasEngineRead = <T extends boolean | number | string | null>(
return useSyncExternalStore(subscribe, read, read);
};
+/**
+ * A primitive read of the engine's document model, as `useCanvasEngineRead` but re-read only when the document
+ * changes: for answers pixels cannot change, such as command eligibility, so painting never re-runs them.
+ */
+export const useCanvasDocumentRead = <T extends boolean | number | string | null>(
+ engine: CanvasCoreStoreCapability | null,
+ read: () => T
+): T => {
+ const subscribe = useCallback(
+ (listener: () => void) => engine?.interaction.subscribe('documentEpoch', listener) ?? (() => undefined),
+ [engine]
+ );
+ return useSyncExternalStore(subscribe, read, read);
+};
+
/** Subscribes to one layer's thumbnail request state; an absent key is idle. */
export const useLayerThumbnailStatus = (
engine: CanvasCoreStoreCapability | null,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx
index f17b1624b7..dd9040a92b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/AdjustmentSettings.browser.test.tsx
@@ -125,7 +125,10 @@ const setUp = (owner: Owner, adjustments: CanvasAdjustmentEntry[]): void => {
},
});
adjustmentStatus = createFakeAdjustmentStatus();
- Object.assign(stub.engine, { interaction: adjustmentStatus.interaction });
+ // The group menu reads its commands' availability on every render; the stub's document never changes beneath it.
+ Object.assign(stub.engine, {
+ interaction: { ...adjustmentStatus.interaction, subscribe: () => () => undefined },
+ });
};
const mount = async (element: ReactElement): Promise<void> => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
index 29f4d577f6..37596a532b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.browser.test.tsx
@@ -364,3 +364,67 @@ describe('generation and canvas visibility in the layer menus', () => {
expect(engine.history.getEntries().past).toEqual([expected[0]]);
});
});
+
+describe('group menu commands follow the document model', () => {
+ /** Opens the group menu on `groupId` over a real engine for `nodes`. */
+ const openGroupMenu = async (nodes: CanvasNodeContract[], groupId: string, selectedIds: readonly string[] = []) => {
+ const harnessed = await renderMenu(nodes, selectedIds);
+ const group = getDocumentIndex(harnessed.document()).byId.get(groupId)!.node as CanvasGroupContract;
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <LayerGroupContextMenu
+ anchor={{ height: 1, width: 1, x: 40, y: 40 }}
+ editingLocked={false}
+ engine={harnessed.engine}
+ group={group}
+ stack="raster"
+ onClose={() => undefined}
+ />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+ await expect.element(page.getByRole('menu')).toBeVisible();
+ return harnessed;
+ };
+ const disabled = (name: string) => item(name).element().getAttribute('aria-disabled') === 'true';
+ const commandStates = () => ({
+ delete: disabled('Delete group'),
+ duplicate: disabled('Duplicate group'),
+ ungroup: disabled('Ungroup'),
+ });
+
+ it('offers every command on an unlocked group', async () => {
+ await openGroupMenu([groupContract('G', [imageLayer('child')])], 'G');
+ expect(commandStates()).toEqual({ delete: false, duplicate: false, ungroup: false });
+ });
+
+ it('keeps a locked group whole, yet copies it beside itself', async () => {
+ const { document, engine } = await openGroupMenu(
+ [groupContract('G', [imageLayer('child')], { isLocked: true })],
+ 'G'
+ );
+ expect(commandStates()).toEqual({ delete: true, duplicate: false, ungroup: true });
+
+ await act(() => item('Duplicate group').click());
+ await vi.waitFor(() => expect(engine.history.getEntries().past).toEqual(['Duplicate group']));
+ expect(document().stacks.raster.map((node) => [node.name, node.isLocked])).toEqual([
+ ['G copy', true],
+ ['G', true],
+ ]);
+ });
+
+ it('copies nothing into the locked group around a group', async () => {
+ await openGroupMenu([groupContract('L', [groupContract('H', [imageLayer('child')])], { isLocked: true })], 'H');
+ expect(commandStates()).toEqual({ delete: true, duplicate: true, ungroup: true });
+ });
+
+ it('names a group selected with its own child as the group, in the menu and in history', async () => {
+ const { engine } = await openGroupMenu([groupContract('G', [imageLayer('child')])], 'G', ['G', 'child']);
+
+ await act(() => item('Delete group').click());
+ await vi.waitFor(() => expect(engine.history.getEntries().past).toEqual(['Delete group']));
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index e88a657fd7..33179a9a95 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -39,7 +39,7 @@ import { getCanvasOperations } from '@workbench/canvas-operations/api';
import { useWorkbenchFocus } from '@workbench/focusRegions';
import { ShortcutKeycaps } from '@workbench/hotkeys/keyGlyphs';
import { formatHotkeyForPlatform } from '@workbench/hotkeys/keys';
-import { publishLayerPanelSelection, readLayerPanelState, useLayerPanelState } from '@workbench/layerPanelState';
+import { useLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { reportTransformRefusal, showCanvasRefusalNotice } from '@workbench/widgets/canvas/canvasToolCommands';
import {
@@ -79,6 +79,14 @@ import type {
} from './layerContextMenuLayout';
import type { LayerMenuDialogKind, LayerMenuDialogState } from './layerMenuState';
+import {
+ deleteLayers,
+ duplicateLayers,
+ groupLayers,
+ ungroupLayers,
+ useLayerCommandAvailability,
+ useLayerCommandDeps,
+} from './layerCommands';
import {
actionTargets,
enabledToggleLabel,
@@ -98,7 +106,6 @@ import {
getLayerContextMenuRenderEntries,
} from './layerContextMenuLayout';
import { copyLayerToClipboard, saveLayerToBoard } from './layerExportActions';
-import { canGroupSelection, canRemoveFromGroup, groupLayers, removeFromGroup } from './layerGroupCommands';
import { resolveMenuTargetForRender } from './layerMenuState';
import {
DEFAULT_INPAINT_MASK_FILL,
@@ -291,7 +298,8 @@ const LayerMenu = ({
);
const targets = actionTargets({ layer, selectedIds });
- const canGroup = useCanvasEngineRead(engine, () => canGroupSelection(engine?.document.model() ?? null, targets));
+ const commandDeps = useLayerCommandDeps(engine);
+ const available = useLayerCommandAvailability(engine, targets);
const canMerge = useCanvasEngineRead(engine, () => {
const model = engine?.document.model() ?? null;
return (
@@ -311,22 +319,17 @@ const LayerMenu = ({
)
: 'ineligible';
});
- const canRemoveTargetsFromGroup = useCanvasEngineRead(engine, () =>
- canRemoveFromGroup(engine?.document.model() ?? null, targets)
- );
- const canDeleteSelection = useCanvasEngineRead(
- engine,
- () => engine?.document.model()?.refusalFor({ ids: targets, type: 'remove' }) === null
- );
const hiddenByAncestor =
(lookupDocumentNodeState(document, layer.id)?.documentHidden ?? false) && !isNodeHidden(layer);
const isQuickSwitchBookmark = useLayerQuickSwitch(engine).bookmarkedLayerId === layer.id;
const actionState = useMemo<LayerContextActionState>(
() => ({
- canDeleteSelection,
- canGroupSelection: canGroup,
+ canDeleteSelection: available.delete,
+ canDuplicateSelection: available.duplicate,
+ canGroupSelection: available.group,
canMergeSelection: canMerge,
- canRemoveFromGroup: canRemoveTargetsFromGroup,
+ // The item shows only for leaves of one group, where ungroup is exactly that lift.
+ canRemoveFromGroup: available.ungroup,
hiddenByAncestor,
isQuickSwitchBookmark,
canRunWorkflow: workflowAvailability.canRunWorkflow,
@@ -345,10 +348,8 @@ const LayerMenu = ({
base,
hiddenByAncestor,
isQuickSwitchBookmark,
- canDeleteSelection,
- canGroup,
+ available,
canMerge,
- canRemoveTargetsFromGroup,
document,
engine,
hasSupportedContent,
@@ -377,57 +378,10 @@ const LayerMenu = ({
[t]
);
- const handleDuplicate = useCallback(async () => {
- if (engine) {
- const panelSelection = readLayerPanelState(projectId, document.selectedLayerId);
- const sourceIds = panelSelection.selectedIds.includes(layer.id) ? panelSelection.selectedIds : [layer.id];
- try {
- const result = await engine.layers.duplicateLayers(sourceIds);
- if (result.status === 'duplicated') {
- publishLayerPanelSelection({
- primaryId: result.selectedLayerId,
- projectId,
- selectedIds: result.duplicateIds,
- });
- return;
- }
- if (result.status === 'busy') {
- return;
- }
- if (result.status !== 'nothing') {
- reportLayerOperation(result.status === 'unreadable' ? result : result.status, notify.error, t);
- return;
- }
- } catch {
- // Report rejected transactions in the menu; the document remains unchanged.
- }
- notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.copyFailed'));
- return;
- }
- commitPrepared(t('widgets.layers.actions.duplicate'), (model) =>
- model.prepare({ createId: createLayerId, ids: [layer.id], type: 'duplicate' })
- );
- }, [commitPrepared, document.selectedLayerId, engine, layer.id, notify, projectId, t]);
-
- const handleDelete = useCallback(() => {
- const ids = actionTargets({ layer, selectedIds });
- commitPrepared(getActionLabel('delete'), (model) => model.prepare({ ids, type: 'remove' }));
- }, [commitPrepared, getActionLabel, layer, selectedIds]);
-
- 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 handleRemoveFromGroup = useCallback(() => {
- const outcome = removeFromGroup(engine, actionTargets({ layer, selectedIds }), getActionLabel('remove-from-group'));
- if (outcome.status === 'refused') {
- throw makeStatusError(outcome.refusal.status === 'locked' ? 'locked' : 'unsupported');
- }
- }, [engine, getActionLabel, layer, makeStatusError, selectedIds]);
+ const handleDuplicate = useCallback(() => duplicateLayers(commandDeps, targets), [commandDeps, targets]);
+ const handleDelete = useCallback(() => deleteLayers(commandDeps, targets), [commandDeps, targets]);
+ const handleGroup = useCallback(() => groupLayers(commandDeps, targets), [commandDeps, targets]);
+ const handleRemoveFromGroup = useCallback(() => ungroupLayers(commandDeps, targets), [commandDeps, targets]);
const handleMergeMasks = useCallback(async () => {
if (!engine) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
index 51e2099a14..f35bf41ba1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupContextMenu.tsx
@@ -11,10 +11,9 @@ import type { ComponentProps } from 'react';
import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';
import { MenuActionItem, 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 { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { getDocumentIndex, isOverlayStack } from '@workbench/canvas-engine/api';
+import { useLayerPanelState } from '@workbench/layerPanelState';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector } from '@workbench/WorkbenchContext';
import {
ArrowDownIcon,
@@ -40,15 +39,24 @@ import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { COLOR_LABEL_ITEMS } from './colorLabels';
+import {
+ deleteLayers,
+ duplicateLayers,
+ groupLayers,
+ layerCommandLabel,
+ layerCommandTargets,
+ ungroupLayers,
+ useLayerCommandAvailability,
+ useLayerCommandDeps,
+} from './layerCommands';
import { ADJUSTMENT_ADD_ITEMS, adjustmentAddActionId, enabledToggleLabel } from './layerContextActions';
-import { canGroupSelection, groupLayers, ungroupLayers } from './layerGroupCommands';
import { createAdjustmentEntry } from './layerOps';
const SUBMENU_POSITIONING = { placement: 'right-start' } as const;
const noop = (): void => undefined;
-export type LayerGroupContextMenuEngine = Pick<CanvasEngineHandle, 'document' | 'layers' | 'projectId'>;
+export type LayerGroupContextMenuEngine = Pick<CanvasEngineHandle, 'document' | 'interaction' | 'layers' | 'projectId'>;
type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];
@@ -80,7 +88,7 @@ export const LayerGroupContextMenu = ({
}: LayerGroupContextMenuProps) => {
const { t } = useTranslation();
const commitPrepared = usePreparedCommit(engine);
- const notify = useNotify();
+ const commandDeps = useLayerCommandDeps(engine);
const projectId = useActiveProjectId();
const document = useActiveProjectSelector((project) => project.canvas.document);
const { selectedIds } = useLayerPanelState(projectId, document.selectedLayerId);
@@ -96,16 +104,12 @@ export const LayerGroupContextMenu = ({
setMenuOpen(true);
}
- 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 = canGroupSelection(engine?.document.model() ?? null, selection());
+ const targets = layerCommandTargets(selectedIds, group.id);
+ const available = useLayerCommandAvailability(engine, targets);
+ const duplicateLabel = layerCommandLabel(document, 'duplicate', targets);
+ const deleteLabel = layerCommandLabel(document, 'delete', targets);
+ // What a locked ancestor takes off the table for arrangement and adjustments, so no item leads to a refusal.
+ const frozen = getDocumentIndex(document).byId.get(group.id)?.ancestorsLocked ?? false;
const positioning = useMemo<MenuPositioning>(
() => ({ getAnchorRect: () => anchor, placement: 'bottom-start' }),
[anchor]
@@ -165,47 +169,14 @@ export const LayerGroupContextMenu = ({
),
[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;
- }
- if (result.status !== 'nothing') {
- reportLayerOperation(result.status === 'unreadable' ? result : result.status, notify.error, t);
- 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 handleGroup = useCallback(() => groupLayers(commandDeps, targets), [commandDeps, targets]);
+ const handleUngroup = useCallback(() => ungroupLayers(commandDeps, targets), [commandDeps, targets]);
+ const handleDuplicate = useCallback(() => duplicateLayers(commandDeps, targets), [commandDeps, targets]);
+ const handleDelete = useCallback(() => deleteLayers(commandDeps, targets), [commandDeps, targets]);
const handleArrange = useCallback(
(kind: LayerStackMoveKind, label: string) => () =>
- commitPrepared(label, (model) => model.prepare({ ids: selection(), kind, type: 'move' })),
- [commitPrepared, selection]
+ commitPrepared(label, (model) => model.prepare({ ids: targets, kind, type: 'move' })),
+ [commitPrepared, targets]
);
const locked = editingLocked;
@@ -256,21 +227,21 @@ export const LayerGroupContextMenu = ({
onSelect={openRename}
/>
<MenuActionItem
- disabled={locked || !engine || frozen}
+ disabled={locked || !available.duplicate}
icon={CopyIcon}
- label={t('widgets.layers.actions.duplicate')}
+ label={t(duplicateLabel.key, { count: duplicateLabel.count })}
value="duplicate"
onSelect={handleDuplicate}
/>
<MenuActionItem
- disabled={locked || !groupable}
+ disabled={locked || !available.group}
icon={FolderPlusIcon}
label={t('widgets.layers.actions.group')}
value="group"
onSelect={handleGroup}
/>
<MenuActionItem
- disabled={locked || frozen || group.isLocked}
+ disabled={locked || !available.ungroup}
icon={UngroupIcon}
label={t('widgets.layers.actions.ungroup')}
value="ungroup"
@@ -386,9 +357,9 @@ export const LayerGroupContextMenu = ({
)}
<Menu.Separator borderColor="border.subtle" />
<MenuActionItem
- disabled={locked || holdsLocked}
+ disabled={locked || !available.delete}
icon={Trash2Icon}
- label={t('widgets.layers.actions.delete')}
+ label={t(deleteLabel.key, { count: deleteLabel.count })}
tone="danger"
value="delete"
onSelect={handleDelete}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx
index 6a19024e14..ec405552a5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelFooter.tsx
@@ -1,3 +1,4 @@
+import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
import type { LucideIcon } from 'lucide-react';
import { HStack, Input, Text } from '@chakra-ui/react';
@@ -7,23 +8,44 @@ import { CopyIcon, FolderPlusIcon, Trash2Icon } from 'lucide-react';
import { memo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
-import type { LayerSelectionCommands } from './useLayerSelectionCommands';
+import {
+ deleteLayers,
+ duplicateLayers,
+ groupLayers,
+ useLayerCommandAvailability,
+ useLayerCommandDeps,
+} from './layerCommands';
const ACTION_TOOLTIP_POSITIONING = { placement: 'top' } as const;
interface LayersPanelFooterProps {
- commands: LayerSelectionCommands;
degraded: boolean;
+ editingLocked: boolean;
+ engine: CanvasEngineHandle | null;
filter: string;
+ /** The panel's selection, which the footer's commands act on. */
+ selectedIds: readonly string[];
onFilterChange: (filter: string) => void;
}
-const LayersPanelFooterComponent = ({ commands, degraded, filter, onFilterChange }: LayersPanelFooterProps) => {
+const LayersPanelFooterComponent = ({
+ degraded,
+ editingLocked,
+ engine,
+ filter,
+ selectedIds,
+ onFilterChange,
+}: LayersPanelFooterProps) => {
const { t } = useTranslation();
+ const deps = useLayerCommandDeps(engine);
+ const available = useLayerCommandAvailability(engine, selectedIds);
const handleFilter = useCallback(
(event: { target: { value: string } }) => onFilterChange(event.target.value),
[onFilterChange]
);
+ const handleDuplicate = useCallback(() => void duplicateLayers(deps, selectedIds), [deps, selectedIds]);
+ const handleGroup = useCallback(() => groupLayers(deps, selectedIds), [deps, selectedIds]);
+ const handleDelete = useCallback(() => deleteLayers(deps, selectedIds), [deps, selectedIds]);
return (
<HStack borderColor="border.subtle" borderTopWidth="1px" gap="2" minH="10" px="2" py="1">
<Input
@@ -41,23 +63,23 @@ const LayersPanelFooterComponent = ({ commands, degraded, filter, onFilterChange
) : null}
<HStack gap="0.5">
<FooterAction
- disabled={!commands.canDuplicate}
+ disabled={editingLocked || !available.duplicate}
icon={CopyIcon}
label={t('widgets.layers.actions.duplicateSelected')}
- onRun={commands.duplicateSelected}
+ onRun={handleDuplicate}
/>
<FooterAction
- disabled={!commands.canGroup}
+ disabled={editingLocked || !available.group}
icon={FolderPlusIcon}
label={t('widgets.layers.actions.groupSelected')}
- onRun={commands.groupSelected}
+ onRun={handleGroup}
/>
<FooterAction
colorPalette="red"
- disabled={!commands.canDelete}
+ disabled={editingLocked || !available.delete}
icon={Trash2Icon}
label={t('widgets.layers.actions.deleteSelected')}
- onRun={commands.deleteSelected}
+ onRun={handleDelete}
/>
</HStack>
</HStack>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
index f71cd09701..614473c6c3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.browser.test.tsx
@@ -1244,7 +1244,11 @@ describe('LayersTree selection, surfaces and structure', () => {
swapActiveColors: vi.fn(),
resetActiveColors: vi.fn(),
pasteFromClipboard: vi.fn(),
- notifyLayerDuplicateFailed: vi.fn(),
+ layerCommands: {
+ engine: engine as CanvasEngine,
+ reportError: vi.fn(),
+ t: ((key: string) => key) as CanvasHotkeyContext['layerCommands']['t'],
+ },
reportStructuralCommit: vi.fn(),
reportPreparedCommit: vi.fn(),
reportLayerOperation: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index 18f97c3fb9..5ce863c2a0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -46,6 +46,7 @@ import {
type ProjectedChildRow,
} from './layerChildRows';
import { clearLayerChildSelection, selectLayerChild, useLayerChildSelection } from './layerChildSelection';
+import { deleteLayers, layerCommandTargets, useLayerCommandDeps } from './layerCommands';
import { enabledToggleLabel } from './layerContextActions';
import { copyLayerToClipboard } from './layerExportActions';
import { createAdjustmentId, createNoiseSeed } from './layerOps';
@@ -184,6 +185,7 @@ export const LayersTree = ({
}: LayersTreeProps) => {
const { t } = useTranslation();
const commitPrepared = usePreparedCommit(engine);
+ const layerCommands = useLayerCommandDeps(engine);
const propertiesRequest = useCurrentLayerPropertiesRequest();
const operation = useCanvasOperation(engine);
const operationLayerId = operation.status === 'active' ? operation.identity.layerId : null;
@@ -318,6 +320,7 @@ export const LayersTree = ({
document,
editingLocked,
engine,
+ layerCommands,
onRevealProperties,
panel,
panelRows,
@@ -335,6 +338,7 @@ export const LayersTree = ({
document,
editingLocked,
engine,
+ layerCommands,
onRevealProperties,
panel,
panelRows,
@@ -437,17 +441,12 @@ export const LayersTree = ({
// After deletion, focus the nearest surviving row below, otherwise above.
const removeRows = useCallback(
(key: string) => {
- const { document: currentDocument, engine: currentEngine, panel: current, visibleRowIds: rows } = latest.current;
+ const { document: currentDocument, layerCommands, panel: current, visibleRowIds: rows } = latest.current;
const vm = lookupDocumentNodeState(currentDocument, key);
if (!vm) {
return;
}
- // The menu's rule: the selection when the row is part of it, else the row alone.
- const ids = current.selectedIds.includes(key) ? current.selectedIds : [key];
- // A stray key on a locked row is ignored, as the menu disables its Delete.
- if (currentEngine?.document.model()?.refusalFor({ ids, type: 'remove' })) {
- return;
- }
+ const ids = layerCommandTargets(current.selectedIds, key);
const removed = new Set(ids);
const survives = (id: string): boolean => {
const state = lookupDocumentNodeState(currentDocument, id);
@@ -455,15 +454,12 @@ export const LayersTree = ({
};
const index = rows.indexOf(key);
const next = rows.slice(index + 1).find(survives) ?? rows.slice(0, Math.max(0, index)).reverse().find(survives);
- const outcome = runStructural(
- t(ids.length > 1 ? 'widgets.layers.actions.deleteSelected' : 'widgets.layers.actions.delete'),
- { ids, type: 'remove' }
- );
- if (outcome.status === 'committed' && next) {
+ // A locked row's Delete is a quiet no-op, as the menu disables its Delete.
+ if (deleteLayers(layerCommands, ids) === 'committed' && next) {
focusItem(next);
}
},
- [focusItem, runStructural, t]
+ [focusItem]
);
const commands = useMemo<LayerRowCommands>(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index a59830cfe1..77fa7be0a3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -39,7 +39,6 @@ import {
import { HistoryPane } from './panes/HistoryPane';
import { LayerColorPane, LayerEditorPanes } from './panes/LayerEditorPanes';
import { useCanvasCompanionHotkeys } from './useCanvasCompanionHotkeys';
-import { useLayerSelectionCommands } from './useLayerSelectionCommands';
const TREE_TABS_ID_BASE = 'layer-tree';
const TREE_TABS: ReadonlyArray<{ id: LayerTreeTabId; labelKey: string }> = [
@@ -66,7 +65,6 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {
const nodeCount = getDocumentIndex(document).nodes.length;
const degraded = nodeCount > LAYER_PANEL_DEGRADE_THRESHOLD;
- const selectionCommands = useLayerSelectionCommands(engine, projectId, panel.selectedIds, editingLocked);
useCanvasCompanionHotkeys(runtime, engine);
const handleFilter = useCallback(
(filter: string) => setLayerPanelFilter(projectId, selectedLayerId, filter),
@@ -186,9 +184,11 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {
</Flex>
)}
<LayersPanelFooter
- commands={selectionCommands}
degraded={degraded}
+ editingLocked={editingLocked}
+ engine={engine}
filter={panel.filter}
+ selectedIds={panel.selectedIds}
onFilterChange={handleFilter}
/>
{addMenuAnchor ? <AddLayerContextMenu anchor={addMenuAnchor} onClose={closeAddMenu} /> : null}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.browser.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.browser.test.ts
new file mode 100644
index 0000000000..f2312f9301
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.browser.test.ts
@@ -0,0 +1,76 @@
+/**
+ * The layer commands over a real engine wired as the app wires it: the labels they give reach the engine's undo
+ * history, and a duplicate leaves its copies selected in the Layers panel.
+ */
+
+import { getDocumentIndex } from '@workbench/canvas-engine/api';
+import { layerContract, stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createCanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
+import { clearLayerPanelStates, publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { createInstance } from 'i18next';
+import { afterEach, beforeAll, describe, expect, it } from 'vitest';
+
+import { deleteLayers, duplicateLayers, groupLayers, type LayerCommandDeps } from './layerCommands';
+
+const i18n = createInstance();
+const cleanups: (() => void)[] = [];
+
+beforeAll(async () => {
+ const translation = await fetch('/locales/en.json').then((response) => response.json());
+ await i18n.init({ initAsync: false, lng: 'en', resources: { en: { translation } } });
+});
+
+afterEach(() => {
+ for (const cleanup of cleanups.splice(0).reverse()) {
+ cleanup();
+ }
+ clearLayerPanelStates();
+});
+
+const setup = (ids: readonly string[]) => {
+ const store = createWorkbenchStore();
+ const projectId = store.getState().activeProjectId;
+ store.commands.canvas.apply(projectId, {
+ document: {
+ ...createEmptyCanvasDocument(64, 64),
+ selectedLayerId: ids[0]!,
+ stacks: stacksFrom(ids.map((id) => layerContract(id))),
+ },
+ type: 'replaceCanvasDocument',
+ });
+ const engine = createCanvasEngine({
+ ensureProjectOnServer: () => Promise.resolve(),
+ imageResolver: () => Promise.reject(new Error('no images')),
+ mutationPort: createCanvasProjectMutationPort(store, projectId),
+ projectId,
+ reportError: () => undefined,
+ setSelectedLayerIds: (primaryId, selectedIds) => publishLayerPanelSelection({ primaryId, projectId, selectedIds }),
+ });
+ cleanups.push(() => engine.lifecycle.dispose());
+ const errors: [string, string][] = [];
+ const deps: LayerCommandDeps = { engine, reportError: (title, message) => errors.push([title, message]), t: i18n.t };
+ const document = () => store.getState().projects.find((project) => project.id === projectId)!.canvas.document;
+ const panel = () => readLayerPanelState(projectId, document().selectedLayerId);
+ return { deps, document, engine, errors, panel };
+};
+
+describe('layer commands on a real engine', () => {
+ it('records each command under its count label, and selects the copies a duplicate makes', async () => {
+ const h = setup(['a', 'b', 'c']);
+
+ expect(await duplicateLayers(h.deps, ['a', 'b'])).toBe('committed');
+ const copies = h.panel().selectedIds;
+ const byId = getDocumentIndex(h.document()).byId;
+ expect(copies.map((id) => byId.get(id)?.node.name).sort()).toEqual(['a copy', 'b copy']);
+ expect(h.document().selectedLayerId).toBe(h.panel().primaryId);
+
+ expect(groupLayers(h.deps, copies)).toBe('committed');
+ expect(deleteLayers(h.deps, ['c'])).toBe('committed');
+
+ expect(h.engine.history.getEntries().past).toEqual(['Duplicate 2 layers', 'Group 2 layers', 'Delete layer']);
+ expect(h.errors).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.test.ts
new file mode 100644
index 0000000000..57d2e9d9cf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.test.ts
@@ -0,0 +1,334 @@
+import type {
+ CanvasDocumentContractV3,
+ CanvasNodeContract,
+ DuplicateLayersResult,
+ StructuralCommitResult,
+} from '@workbench/canvas-engine/api';
+import type { Project } from '@workbench/projectContracts';
+
+import { createDocumentModel, getDocumentIndex } from '@workbench/canvas-engine/api';
+import {
+ groupContract as group,
+ layerContract as layer,
+ stacksFrom,
+} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { clearLayerPanelStates, publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';
+import { createInitialWorkbenchState } from '@workbench/workbenchState';
+import { createInstance } from 'i18next';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import {
+ canRunLayerCommand,
+ deleteLayers,
+ duplicateLayers,
+ groupLayers,
+ layerCommandTargets,
+ ungroupLayers,
+ type LayerCommand,
+ type LayerCommandDeps,
+ type LayerCommandEngine,
+ type LayerCommandOutcome,
+} from './layerCommands';
+
+const englishCatalog = Object.values(
+ import.meta.glob('../../../../public/locales/en.json', { eager: true, import: 'default' })
+)[0] as Record<string, unknown>;
+const i18n = createInstance();
+await i18n.init({ initAsync: false, lng: 'en', resources: { en: { translation: englishCatalog } } });
+
+afterEach(() => clearLayerPanelStates());
+
+/** Stacks top first, each node in preorder, indented by depth. */
+const outline = (document: CanvasDocumentContractV3): string[] =>
+ getDocumentIndex(document).nodes.map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);
+
+/**
+ * The commands over a real document model whose commits apply through the real reducer. The engine's pixel copy is
+ * the one double: it records its label and answers `duplicateResult`.
+ */
+const setup = (nodes: CanvasNodeContract[]) => {
+ let project: Project = applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
+ document: { ...createEmptyCanvasDocument(), selectedLayerId: 'r1', stacks: stacksFrom(nodes) },
+ type: 'replaceCanvasDocument',
+ });
+ const labels: string[] = [];
+ const errors: [string, string][] = [];
+ const control: {
+ commitResult: StructuralCommitResult | null;
+ duplicateResult: () => Promise<DuplicateLayersResult>;
+ previewEnds: number;
+ } = {
+ commitResult: null,
+ previewEnds: 0,
+ duplicateResult: () => Promise.resolve({ duplicateIds: ['copy'], selectedLayerId: 'copy', status: 'duplicated' }),
+ };
+ const engine: LayerCommandEngine = {
+ document: { model: () => createDocumentModel(project.canvas.document, { editRevision: 0, projectId: project.id }) },
+ layers: {
+ commitPrepared: (label, edit) => {
+ if (control.commitResult) {
+ return control.commitResult;
+ }
+ labels.push(label);
+ project = applyCanvasProjectMutation(project, edit.forward);
+ return { status: 'committed' };
+ },
+ duplicateLayers: (label) => {
+ labels.push(label);
+ return control.duplicateResult();
+ },
+ endStructuralPreview: () => {
+ control.previewEnds += 1;
+ },
+ },
+ projectId: project.id,
+ };
+ const deps: LayerCommandDeps = {
+ engine,
+ reportError: (title, message) => errors.push([title, message]),
+ t: i18n.t,
+ };
+ const run = (command: LayerCommand, ids: readonly string[]): Promise<LayerCommandOutcome> | LayerCommandOutcome => {
+ switch (command) {
+ case 'delete':
+ return deleteLayers(deps, ids);
+ case 'duplicate':
+ return duplicateLayers(deps, ids);
+ case 'group':
+ return groupLayers(deps, ids);
+ case 'ungroup':
+ return ungroupLayers(deps, ids);
+ }
+ };
+ return {
+ can: (command: LayerCommand, ids: readonly string[]) => canRunLayerCommand(engine.document.model(), command, ids),
+ control,
+ deps,
+ document: () => project.canvas.document,
+ errors,
+ labels,
+ panel: () => readLayerPanelState(project.id, project.canvas.document.selectedLayerId),
+ projectId: project.id,
+ run,
+ };
+};
+
+/** raster: r1, G[r2, r3], r4 */
+const tree = (locks: { G?: boolean; r1?: boolean; r3?: boolean } = {}): CanvasNodeContract[] => [
+ layer('r1', 'raster', { isLocked: locks.r1 ?? false }),
+ group('G', [layer('r2'), layer('r3', 'raster', { isLocked: locks.r3 ?? false })], { isLocked: locks.G ?? false }),
+ layer('r4'),
+];
+
+describe('layerCommandTargets', () => {
+ it('acts on the whole selection when the subject is part of it, else on the subject alone', () => {
+ expect(layerCommandTargets(['r1', 'r4'], 'r4')).toEqual(['r1', 'r4']);
+ expect(layerCommandTargets(['r1', 'r4'], 'r2')).toEqual(['r2']);
+ expect(layerCommandTargets([], 'r2')).toEqual(['r2']);
+ });
+});
+
+describe('eligibility', () => {
+ it.each<[LayerCommand, readonly string[], readonly string[]]>([
+ ['delete', ['r2', 'r3'], ['r1', 'r2']],
+ ['group', ['r2', 'r3'], ['r1', 'r4']],
+ ['ungroup', ['r3'], ['r2']],
+ ])(
+ '%s refuses a selection holding a locked layer, quietly and without touching anything',
+ async (command, locked, free) => {
+ const h = setup(tree({ r3: true }));
+ const before = h.document();
+
+ expect(h.can(command, free)).toBe(true);
+ expect(h.can(command, locked)).toBe(false);
+ expect(await h.run(command, locked)).toBe('skipped');
+
+ expect(h.document()).toBe(before);
+ expect(h.labels).toEqual([]);
+ expect(h.errors).toEqual([]);
+ }
+ );
+
+ it.each<[LayerCommand, readonly string[]]>([
+ ['delete', ['G']],
+ ['delete', ['r2']],
+ ['group', ['r2']],
+ ['ungroup', ['G']],
+ ['ungroup', ['r2']],
+ ])('%s %j refuses on or inside a locked group', async (command, ids) => {
+ const h = setup(tree({ G: true }));
+
+ expect(h.can(command, ids)).toBe(false);
+ expect(await h.run(command, ids)).toBe('skipped');
+ expect(h.labels).toEqual([]);
+ expect(h.errors).toEqual([]);
+ });
+
+ it('duplicates a locked layer or a locked group beside itself, but copies nothing into a locked group', async () => {
+ const lockedLayer = setup(tree({ r1: true }));
+ expect(lockedLayer.can('duplicate', ['r1'])).toBe(true);
+ expect(await lockedLayer.run('duplicate', ['r1'])).toBe('committed');
+
+ const lockedGroup = setup(tree({ G: true }));
+ expect(lockedGroup.can('duplicate', ['G'])).toBe(true);
+ expect(await lockedGroup.run('duplicate', ['G'])).toBe('committed');
+ expect([...lockedLayer.labels, ...lockedGroup.labels]).toEqual(['Duplicate layer', 'Duplicate group']);
+
+ expect(lockedGroup.can('duplicate', ['r2'])).toBe(false);
+ expect(lockedGroup.can('duplicate', ['r1', 'r2'])).toBe(false);
+ expect(await lockedGroup.run('duplicate', ['r2'])).toBe('skipped');
+ expect(lockedGroup.labels).toHaveLength(1);
+ expect(lockedGroup.errors).toEqual([]);
+ });
+
+ it('offers nothing for an empty selection or without an engine model', () => {
+ const h = setup(tree());
+ for (const command of ['delete', 'duplicate', 'group', 'ungroup'] as const) {
+ expect(h.can(command, [])).toBe(false);
+ expect(canRunLayerCommand(null, command, ['r1'])).toBe(false);
+ }
+ });
+
+ it('offers ungroup on a top-level leaf only when it has a group to leave', () => {
+ const h = setup(tree());
+ expect(h.can('ungroup', ['r1'])).toBe(false);
+ expect(h.can('ungroup', ['r2', 'r3'])).toBe(true);
+ expect(h.can('ungroup', ['r2', 'r4'])).toBe(false);
+ });
+
+ it('ends an open preview gesture only for a command that will run', async () => {
+ const h = setup(tree({ r3: true }));
+
+ h.run('delete', ['r3']);
+ h.run('group', ['r2', 'r3']);
+ h.run('ungroup', ['r3']);
+ await h.run('duplicate', ['ghost']);
+ expect(h.control.previewEnds).toBe(0);
+
+ expect(h.run('delete', ['r1'])).toBe('committed');
+ expect(h.control.previewEnds).toBe(1);
+ });
+});
+
+describe('undo labels', () => {
+ it('names delete, duplicate and group by how many nodes they act on, and a lone group as a group', async () => {
+ const h = setup(tree());
+
+ expect(await h.run('duplicate', ['r1'])).toBe('committed');
+ expect(await h.run('duplicate', ['r1', 'G'])).toBe('committed');
+ expect(h.run('group', ['r1', 'r4'])).toBe('committed');
+ expect(h.run('delete', ['G'])).toBe('committed');
+ expect(h.run('delete', ['r1', 'r4'])).toBe('committed');
+
+ expect(h.labels).toEqual([
+ 'Duplicate layer',
+ 'Duplicate 2 layers',
+ 'Group 2 layers',
+ 'Delete group',
+ 'Delete 2 layers',
+ ]);
+ expect(h.errors).toEqual([]);
+ });
+
+ it('counts a group selected with its own child once', async () => {
+ const h = setup(tree());
+
+ expect(await h.run('duplicate', ['G', 'r2'])).toBe('committed');
+ expect(h.run('group', ['r1', 'G', 'r2'])).toBe('committed');
+ expect(h.run('delete', ['G', 'r2'])).toBe('committed');
+
+ expect(h.labels).toEqual(['Duplicate group', 'Group 2 layers', 'Delete group']);
+ });
+
+ it('ungroups a group, and lifts leaves of one group above it instead, each named for what it did', () => {
+ const h = setup(tree());
+
+ expect(h.run('ungroup', ['r3', 'r2'])).toBe('committed');
+ expect(outline(h.document())).toEqual(['r1', 'r2', 'r3', 'G', 'r4']);
+
+ const regrouped = setup(tree());
+ expect(regrouped.run('ungroup', ['G'])).toBe('committed');
+ expect(outline(regrouped.document())).toEqual(['r1', 'r2', 'r3', 'r4']);
+
+ expect([...h.labels, ...regrouped.labels]).toEqual(['Remove from group', 'Ungroup']);
+ });
+});
+
+describe('group selection', () => {
+ it('selects the new group, and puts the previous selection back when the commit fails', () => {
+ const h = setup(tree());
+ publishLayerPanelSelection({ primaryId: 'r1', projectId: h.projectId, selectedIds: ['r1', 'r4'] });
+
+ expect(h.run('group', ['r1', 'r4'])).toBe('committed');
+ const groupId = h.panel().primaryId!;
+ expect(getDocumentIndex(h.document()).byId.get(groupId)?.node.type).toBe('group');
+ expect(h.panel()).toMatchObject({
+ expandedGroupIds: [groupId],
+ selectedIds: [groupId],
+ });
+
+ const failing = setup(tree());
+ publishLayerPanelSelection({ primaryId: 'r1', projectId: failing.projectId, selectedIds: ['r1', 'r4'] });
+ failing.control.commitResult = { recovered: 'reverted', status: 'postcondition-failed' };
+ expect(failing.run('group', ['r1', 'r4'])).toBe('failed');
+ expect(failing.panel()).toMatchObject({
+ expandedGroupIds: [],
+ primaryId: 'r1',
+ selectedIds: ['r1', 'r4'],
+ });
+ });
+});
+
+describe('failure feedback', () => {
+ it.each<LayerCommand>(['delete', 'group', 'ungroup'])(
+ '%s reports an eligible edit that does not land, once',
+ async (command) => {
+ const h = setup(tree());
+ h.control.commitResult = { recovered: 'unreverted', status: 'postcondition-failed' };
+
+ expect(await h.run(command, command === 'ungroup' ? ['G'] : ['r1', 'r4'])).toBe('failed');
+
+ expect(h.errors).toEqual([
+ ['Canvas edit failed', 'The edit could not be verified or reverted. Check the canvas before continuing.'],
+ ]);
+ }
+ );
+
+ it.each<[string, () => Promise<DuplicateLayersResult>, [string, string]]>([
+ [
+ 'refuses as stale',
+ () => Promise.resolve({ status: 'stale' }),
+ ['Layer action failed', 'The layer changed before this action finished, so nothing was changed. Try again.'],
+ ],
+ [
+ 'cannot read a layer',
+ () => Promise.resolve({ layerId: 'r1', layerName: 'Sky', status: 'unreadable' }),
+ [
+ 'Layer action failed',
+ '“Sky” could not be read (its image may have been deleted or damaged), so nothing was changed. Delete or replace that layer, then try again.',
+ ],
+ ],
+ [
+ 'rejects the transaction',
+ () => Promise.reject(new Error('rejected')),
+ ['Layer action failed', 'The layer could not be copied.'],
+ ],
+ ])('duplicate reports once when the engine %s', async (_name, result, error) => {
+ const h = setup(tree());
+ h.control.duplicateResult = result;
+
+ expect(await h.run('duplicate', ['r1'])).toBe('failed');
+ expect(h.errors).toEqual([error]);
+ });
+
+ it('stays quiet while another edit holds the canvas', async () => {
+ const h = setup(tree());
+ h.control.duplicateResult = () => Promise.resolve({ status: 'busy' });
+ expect(await h.run('duplicate', ['r1'])).toBe('skipped');
+ h.control.commitResult = { status: 'busy' };
+ expect(h.run('delete', ['r1'])).toBe('skipped');
+ expect(h.errors).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts
new file mode 100644
index 0000000000..aeed86b3f7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerCommands.ts
@@ -0,0 +1,324 @@
+import type {
+ CanvasCoreStoreCapability,
+ CanvasDocumentCapability,
+ CanvasDocumentContractV3,
+ CanvasDocumentModel,
+ CanvasEngineLayerCapability,
+ DocumentCommand,
+ StructuralCommitResult,
+} from '@workbench/canvas-engine/api';
+import type { TFunction } from 'i18next';
+
+import { getDocumentIndex, isGroupNode, outermostNodes } from '@workbench/canvas-engine/api';
+import { publishLayerPanelSelection, readLayerPanelState, setLayerGroupExpanded } from '@workbench/layerPanelState';
+import { useNotify } from '@workbench/useNotify';
+import { useCanvasDocumentRead } from '@workbench/widgets/canvas/engineStoreHooks';
+import { reportLayerOperation, reportStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { createLayerId, nextGroupName } from './layerOps';
+
+/**
+ * The structural commands every layer surface offers: the Canvas hotkeys, the panel footer, the row and group menus,
+ * and the tree's Delete key. Target rule, eligibility, undo label and feedback live here; a surface maps its trigger
+ * to one of these and keeps only its own concerns (placement, copy, focus).
+ */
+export type LayerCommand = 'delete' | 'duplicate' | 'group' | 'ungroup';
+
+/**
+ * `committed`: the edit landed. `skipped`: the model refused it or it would change nothing (the command was
+ * unavailable, as a disabled menu item is), or another edit holds the canvas; nothing is said. `failed`: an eligible
+ * edit did not land, and the reporter has been told why.
+ */
+export type LayerCommandOutcome = 'committed' | 'failed' | 'skipped';
+
+export interface LayerCommandEngine {
+ readonly document: Pick<CanvasDocumentCapability, 'model'>;
+ readonly layers: Pick<CanvasEngineLayerCapability, 'commitPrepared' | 'duplicateLayers' | 'endStructuralPreview'>;
+ readonly projectId: string;
+}
+
+export interface LayerCommandDeps {
+ readonly engine: LayerCommandEngine | null;
+ readonly reportError: (title: string, message: string) => void;
+ readonly t: TFunction;
+}
+
+/** The nodes a command on `subjectId` acts on: the whole selection when the subject is part of it, else itself. */
+export const layerCommandTargets = (selectedIds: readonly string[], subjectId: string): readonly string[] =>
+ selectedIds.includes(subjectId) ? selectedIds : [subjectId];
+
+/**
+ * The reparent that lifts `ids` out of their shared parent group to sit directly above it, in document order; null
+ * unless every id is a leaf of the same group.
+ */
+export const removeFromGroupCommand = (
+ document: CanvasDocumentContractV3,
+ ids: readonly string[]
+): Extract<DocumentCommand, { type: 'reparent' }> | null => {
+ const index = getDocumentIndex(document);
+ const entries = ids.flatMap((id) => index.byId.get(id) ?? []);
+ const groupId = entries[0]?.parentId ?? null;
+ if (
+ groupId === null ||
+ entries.length !== ids.length ||
+ entries.some((entry) => isGroupNode(entry.node) || entry.parentId !== groupId)
+ ) {
+ return null;
+ }
+ return {
+ beforeId: groupId,
+ ids: [...entries].sort((a, b) => a.order - b.order).map((entry) => entry.node.id),
+ parentId: index.byId.get(groupId)!.parentId,
+ type: 'reparent',
+ };
+};
+
+/** A group id no document holds, for asking the model whether a grouping would be accepted. */
+const PROBE_GROUP_ID = '\0group';
+
+/** The model decides a duplicate before it mints a copy's id, so asking it needs none. */
+const PROBE_CREATE_ID = (): string => '\0copy';
+
+/**
+ * Ungroup dissolves the groups among `ids`; with none among them, leaves of one group move out above it instead.
+ * Null when neither applies.
+ */
+const ungroupCommand = (model: CanvasDocumentModel, ids: readonly string[]): DocumentCommand | null => {
+ const groupIds = ids.filter((id) => {
+ const node = model.getNode(id);
+ return !!node && isGroupNode(node);
+ });
+ return groupIds.length > 0 ? { ids: groupIds, type: 'ungroup' } : removeFromGroupCommand(model.document, ids);
+};
+
+const accepts = (model: CanvasDocumentModel, command: DocumentCommand | null): boolean =>
+ !!command && model.refusalFor(command) === null;
+
+/** Whether the document model accepts `command` on `ids`: the rule every surface enables its control by. */
+export const canRunLayerCommand = (
+ model: CanvasDocumentModel | null,
+ command: LayerCommand,
+ ids: readonly string[]
+): boolean => {
+ if (!model || ids.length === 0) {
+ return false;
+ }
+ switch (command) {
+ case 'delete':
+ return accepts(model, { ids, type: 'remove' });
+ case 'duplicate':
+ return accepts(model, { createId: PROBE_CREATE_ID, ids, type: 'duplicate' });
+ case 'group':
+ return accepts(model, { groupId: PROBE_GROUP_ID, ids, name: '', type: 'group' });
+ case 'ungroup':
+ return accepts(model, ungroupCommand(model, ids));
+ }
+};
+
+/**
+ * How many nodes a command acts on, for its label: a node selected together with a group around it is part of that
+ * group's subtree, so a group and its child count as one.
+ */
+const targetCount = (model: CanvasDocumentModel, ids: readonly string[]): number =>
+ outermostNodes(getDocumentIndex(model.document), ids).length;
+
+const LABEL_KEYS = {
+ delete: { count: 'widgets.layers.actions.deleteCount', group: 'widgets.layers.actions.deleteGroup' },
+ duplicate: { count: 'widgets.layers.actions.duplicateCount', group: 'widgets.layers.actions.duplicateGroup' },
+} as const;
+
+/**
+ * The label a delete or duplicate of `ids` carries in menus and in history, so the two cannot drift: one group alone
+ * is named as a group, anything else by its outermost count.
+ */
+export const layerCommandLabel = (
+ document: CanvasDocumentContractV3,
+ command: 'delete' | 'duplicate',
+ ids: readonly string[]
+): { readonly count: number; readonly key: string } => {
+ const outer = outermostNodes(getDocumentIndex(document), ids);
+ const keys = LABEL_KEYS[command];
+ return outer.length === 1 && isGroupNode(outer[0]!.node)
+ ? { count: 1, key: keys.group }
+ : { count: outer.length, key: keys.count };
+};
+
+const translatedLabel = (
+ t: TFunction,
+ model: CanvasDocumentModel,
+ command: 'delete' | 'duplicate',
+ ids: readonly string[]
+): string => {
+ const { count, key } = layerCommandLabel(model.document, command, ids);
+ return t(key, { count });
+};
+
+/** Busy means another edit holds the canvas, which already shows; anything else that did not land is reported. */
+const settle = (deps: LayerCommandDeps, result: StructuralCommitResult): LayerCommandOutcome => {
+ if (result.status === 'committed') {
+ return 'committed';
+ }
+ if (result.status === 'busy') {
+ return 'skipped';
+ }
+ reportStructuralCommit(result, deps.reportError, deps.t);
+ return 'failed';
+};
+
+/**
+ * The engine and the committed document's model, once the model accepts `command` on `ids` as it stands. Only then
+ * does an open preview gesture end, so the edit and its inverse capture the committed document rather than previewed
+ * values; a refused command leaves the gesture alone. Null when the command is unavailable.
+ */
+const committedModel = (
+ engine: LayerCommandEngine | null,
+ command: LayerCommand,
+ ids: readonly string[]
+): { engine: LayerCommandEngine; model: CanvasDocumentModel } | null => {
+ if (!engine || !canRunLayerCommand(engine.document.model(), command, ids)) {
+ return null;
+ }
+ engine.layers.endStructuralPreview();
+ const model = engine.document.model();
+ return model ? { engine, model } : null;
+};
+
+/** Prepares the command `plan` names on the committed document and commits it as one undo step under its label. */
+const commitCommand = (
+ deps: LayerCommandDeps,
+ command: LayerCommand,
+ ids: readonly string[],
+ plan: (model: CanvasDocumentModel) => { command: DocumentCommand; label: string } | null
+): LayerCommandOutcome => {
+ const live = committedModel(deps.engine, command, ids);
+ const planned = live ? plan(live.model) : null;
+ const result = live && planned ? live.model.prepare(planned.command) : null;
+ return live && planned && result?.status === 'prepared'
+ ? settle(deps, live.engine.layers.commitPrepared(planned.label, result.edit))
+ : 'skipped';
+};
+
+/** Removes `ids` and everything inside them as one undo step. */
+export const deleteLayers = (deps: LayerCommandDeps, ids: readonly string[]): LayerCommandOutcome =>
+ commitCommand(deps, 'delete', ids, (model) => ({
+ command: { ids, type: 'remove' },
+ label: translatedLabel(deps.t, model, 'delete', ids),
+ }));
+
+/** Dissolves the groups among `ids`, or lifts leaves of one group out above it, as one undo step. */
+export const ungroupLayers = (deps: LayerCommandDeps, ids: readonly string[]): LayerCommandOutcome =>
+ commitCommand(deps, 'ungroup', ids, (model) => {
+ const command = ungroupCommand(model, ids);
+ if (!command) {
+ return null;
+ }
+ const labelKey =
+ command.type === 'reparent' ? 'widgets.layers.actions.removeFromGroup' : 'widgets.layers.actions.ungroup';
+ return { command, label: deps.t(labelKey) };
+ });
+
+/**
+ * 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 = (deps: LayerCommandDeps, ids: readonly string[]): LayerCommandOutcome => {
+ const live = committedModel(deps.engine, 'group', ids);
+ if (!live) {
+ return 'skipped';
+ }
+ const { engine, model } = live;
+ const { projectId } = engine;
+ 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 !== 'prepared') {
+ return 'skipped';
+ }
+ 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(
+ deps.t('widgets.layers.actions.groupCount', { count: targetCount(model, ids) }),
+ result.edit
+ );
+ if (outcome.status !== 'committed') {
+ publishLayerPanelSelection({
+ anchorId: previous.anchorId,
+ primaryId: previous.primaryId,
+ projectId,
+ selectedIds: previous.selectedIds,
+ });
+ setLayerGroupExpanded(projectId, previous.primaryId, [groupId], false);
+ }
+ return settle(deps, outcome);
+};
+
+/**
+ * Copies `ids` with their pixels as one undo step; the engine selects the copies in the panel as it publishes them.
+ * The model is asked first so a refused duplicate stays a silent no-op, as a disabled control would; the engine asks
+ * again when it commits.
+ */
+export const duplicateLayers = async (deps: LayerCommandDeps, ids: readonly string[]): Promise<LayerCommandOutcome> => {
+ const { engine, reportError, t } = deps;
+ const model = engine?.document.model() ?? null;
+ if (!engine || !model || !canRunLayerCommand(model, 'duplicate', ids)) {
+ return 'skipped';
+ }
+ try {
+ const result = await engine.layers.duplicateLayers(translatedLabel(t, model, 'duplicate', ids), ids);
+ switch (result.status) {
+ case 'duplicated':
+ return 'committed';
+ case 'busy':
+ return 'skipped';
+ case 'nothing':
+ break;
+ default:
+ reportLayerOperation(result.status === 'unreadable' ? result : result.status, reportError, t);
+ return 'failed';
+ }
+ } catch {
+ // The engine leaves the document unchanged on a rejected transaction.
+ }
+ reportError(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.copyFailed'));
+ return 'failed';
+};
+
+type LayerCommandReadEngine = CanvasCoreStoreCapability & {
+ readonly document: Pick<CanvasDocumentCapability, 'model'>;
+};
+
+const LAYER_COMMANDS: readonly LayerCommand[] = ['delete', 'duplicate', 'group', 'ungroup'];
+
+/**
+ * Which commands the model accepts on `ids`, read live: a lock, a removal or an undo from elsewhere updates it even
+ * when nothing the caller passes changed. One read, re-run only when the document changes (never on a pixel
+ * publish), answers with the accepted commands' names joined, a string that keeps its snapshot while unchanged.
+ */
+export const useLayerCommandAvailability = (
+ engine: LayerCommandReadEngine | null,
+ ids: readonly string[]
+): Readonly<Record<LayerCommand, boolean>> => {
+ const accepted = useCanvasDocumentRead(engine, () => {
+ const model = engine?.document.model() ?? null;
+ return LAYER_COMMANDS.filter((command) => canRunLayerCommand(model, command, ids)).join(' ');
+ });
+ return useMemo(() => {
+ const names = accepted.split(' ');
+ return {
+ delete: names.includes('delete'),
+ duplicate: names.includes('duplicate'),
+ group: names.includes('group'),
+ ungroup: names.includes('ungroup'),
+ };
+ }, [accepted]);
+};
+
+/** The commands' dependencies for a panel surface: its engine, the app's error notices and the active language. */
+export const useLayerCommandDeps = (engine: LayerCommandEngine | null): LayerCommandDeps => {
+ const notify = useNotify();
+ const { t } = useTranslation();
+ return useMemo(() => ({ engine, reportError: notify.error, t }), [engine, notify.error, t]);
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index e718f9a39c..e36612b52c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -82,6 +82,7 @@ const makeState = (
operationLocked: false,
canGroupSelection: true,
canDeleteSelection: true,
+ canDuplicateSelection: true,
mergeMasksEligibility: 'eligible',
canMergeSelection: true,
canRemoveFromGroup: true,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index aab1759b6f..332a36f9a3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -64,7 +64,7 @@ import {
} from 'lucide-react';
import { COLOR_LABEL_ITEMS } from './colorLabels';
-import { removeFromGroupCommand } from './layerGroupCommands';
+import { layerCommandLabel, layerCommandTargets, removeFromGroupCommand } from './layerCommands';
import { canAddRegionalReferenceImage, canConvertRasterControl, canMergeLayerDown } from './layerOps';
export type LayerContextActionId =
@@ -146,6 +146,8 @@ export interface LayerContextActionState {
canGroupSelection: boolean;
/** The model's answer for removing `actionTargets`, asked the same way. */
canDeleteSelection: boolean;
+ /** The model's answer for duplicating `actionTargets`, asked the same way. */
+ canDuplicateSelection: boolean;
/** Whether the whole multi-selection can merge into one raster, asked the same way. */
canMergeSelection: boolean;
/** Whether merge masks would take `actionTargets`, and if not, whether only their generation settings differ. */
@@ -313,11 +315,13 @@ const REGIONAL_ONLY = ['regional_guidance'] as const;
const alwaysVisible = (): boolean => true;
const isOperationFree = (context: LayerContextActionState): boolean => !context.operationLocked;
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. */
+/** The nodes a selection-wide action applies to, by the layer commands' rule. */
export const actionTargets = (context: Pick<LayerContextActionState, 'layer' | 'selectedIds'>): readonly string[] =>
- context.selectedIds.includes(context.layer.id) ? context.selectedIds : [context.layer.id];
+ layerCommandTargets(context.selectedIds, context.layer.id);
const targetCount = (context: LayerContextActionState): number => actionTargets(context).length;
+const commandLabel = (context: LayerContextActionState, command: 'delete' | 'duplicate') =>
+ layerCommandLabel(context.document, command, actionTargets(context));
const isMultiTarget = (context: LayerContextActionState): boolean => targetCount(context) > 1;
const targetNodes = (context: LayerContextActionState) => {
const index = getDocumentIndex(context.document);
@@ -558,14 +562,12 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
},
{
defaultLabel: 'Duplicate',
- getDefaultLabel: (context) => (isMultiTarget(context) ? `Duplicate ${targetCount(context)} layers` : 'Duplicate'),
- getLabelCount: targetCount,
- getLabelKey: (context) =>
- isMultiTarget(context) ? 'widgets.layers.actions.duplicateCount' : 'widgets.layers.actions.duplicate',
+ getLabelCount: (context) => commandLabel(context, 'duplicate').count,
+ getLabelKey: (context) => commandLabel(context, 'duplicate').key,
handler: ({ effects }) => effects.duplicate(),
icon: CopyIcon,
id: 'duplicate',
- isEnabled: isOperationFree,
+ isEnabled: (context) => isOperationFree(context) && context.canDuplicateSelection,
isVisible: alwaysVisible,
labelKey: 'widgets.layers.actions.duplicate',
order: 10,
@@ -1179,10 +1181,8 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
},
{
defaultLabel: 'Delete',
- getDefaultLabel: (context) => (isMultiTarget(context) ? `Delete ${targetCount(context)} layers` : 'Delete'),
- getLabelCount: targetCount,
- getLabelKey: (context) =>
- isMultiTarget(context) ? 'widgets.layers.actions.deleteCount' : 'widgets.layers.actions.delete',
+ getLabelCount: (context) => commandLabel(context, 'delete').count,
+ getLabelKey: (context) => commandLabel(context, 'delete').key,
handler: ({ effects }) => effects.delete(),
icon: Trash2Icon,
id: 'delete',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index 4b84cdf525..52a72ec4cc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -47,6 +47,7 @@ const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerCont
selectedIds: [layer.id],
canGroupSelection: true,
canDeleteSelection: true,
+ canDuplicateSelection: true,
mergeMasksEligibility: 'eligible',
canMergeSelection: true,
canRemoveFromGroup: true,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.test.ts
deleted file mode 100644
index 197aec6b46..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.test.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import type { CanvasDocumentContractV3, CanvasNodeContract, PreparedDocumentEdit } from '@workbench/canvas-engine/api';
-import type { Project } from '@workbench/projectContracts';
-import type { CanvasPreparedEngine } from '@workbench/widgets/canvas/useStructuralCommit';
-
-import { createDocumentModel, getDocumentIndex } from '@workbench/canvas-engine/api';
-import {
- groupContract as group,
- layerContract as layer,
- stacksFrom,
-} from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
-import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
-import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
-import { createInitialWorkbenchState } from '@workbench/workbenchState';
-import { describe, expect, it } from 'vitest';
-
-import { canRemoveFromGroup, removeFromGroup } from './layerGroupCommands';
-
-const projectWith = (nodes: CanvasNodeContract[]): Project =>
- applyCanvasProjectMutation(createInitialWorkbenchState().projects[0]!, {
- document: { ...createEmptyCanvasDocument(), selectedLayerId: null, stacks: stacksFrom(nodes) },
- type: 'replaceCanvasDocument',
- });
-
-/** Stacks top first, each node in preorder, indented by depth. */
-const outline = (document: CanvasDocumentContractV3): string[] =>
- getDocumentIndex(document).nodes.map((entry) => `${' '.repeat(entry.path.length)}${entry.node.id}`);
-
-/** A prepared-edit engine over a real document model whose commits apply through the real reducer. */
-const createEngine = (initial: Project) => {
- let project = initial;
- const edits: PreparedDocumentEdit[] = [];
- const engine: CanvasPreparedEngine = {
- document: { model: () => createDocumentModel(project.canvas.document, { editRevision: 0, projectId: project.id }) },
- layers: {
- commitPrepared: (_label, edit) => {
- edits.push(edit);
- project = applyCanvasProjectMutation(project, edit.forward);
- return { status: 'committed' };
- },
- endStructuralPreview: () => undefined,
- },
- };
- return {
- document: () => project.canvas.document,
- edits,
- engine,
- undo: () => {
- project = applyCanvasProjectMutation(project, edits.at(-1)!.inverse);
- },
- };
-};
-
-/** raster: r1, G[r2, H[r3, r4], r5], r6 */
-const tree = (overrides: { lockH?: boolean } = {}): CanvasNodeContract[] => [
- layer('r1'),
- group('G', [
- layer('r2'),
- group('H', [layer('r3'), layer('r4')], { isLocked: overrides.lockH ?? false }),
- layer('r5'),
- ]),
- layer('r6'),
-];
-
-describe('removeFromGroup', () => {
- it('moves a leaf directly above its group in the parent, and one undo puts it back', () => {
- const harness = createEngine(projectWith(tree()));
- const before = outline(harness.document());
-
- expect(removeFromGroup(harness.engine, ['r5'], 'Remove from group')).toEqual({ status: 'committed' });
-
- expect(outline(harness.document())).toEqual(['r1', 'r5', 'G', ' r2', ' H', ' r3', ' r4', 'r6']);
- expect(harness.edits).toHaveLength(1);
- harness.undo();
- expect(outline(harness.document())).toEqual(before);
- });
-
- it('lifts several leaves of a nested group above it in document order, whatever the selection order', () => {
- const harness = createEngine(projectWith(tree()));
-
- removeFromGroup(harness.engine, ['r4', 'r3'], 'Remove from group');
-
- expect(outline(harness.document())).toEqual(['r1', 'G', ' r2', ' r3', ' r4', ' H', ' r5', 'r6']);
- });
-
- it('refuses leaves inside a locked group and changes nothing', () => {
- const harness = createEngine(projectWith(tree({ lockH: true })));
- const before = outline(harness.document());
-
- expect(canRemoveFromGroup(harness.engine.document.model(), ['r3'])).toBe(false);
- expect(removeFromGroup(harness.engine, ['r3'], 'Remove from group')).toMatchObject({
- refusal: { status: 'locked' },
- status: 'refused',
- });
- expect(outline(harness.document())).toEqual(before);
- });
-
- it.each([
- ['a top-level leaf', ['r1']],
- ['leaves of different groups', ['r2', 'r3']],
- ['a group', ['H']],
- ['an absent id', ['r5', 'ghost']],
- ])('is unavailable for %s', (_name, ids) => {
- const harness = createEngine(projectWith(tree()));
-
- expect(canRemoveFromGroup(harness.engine.document.model(), ids)).toBe(false);
- expect(removeFromGroup(harness.engine, ids, 'Remove from group')).toEqual({ status: 'unchanged' });
- expect(harness.edits).toHaveLength(0);
- });
-
- it('is available for leaves of one unlocked group', () => {
- const harness = createEngine(projectWith(tree()));
-
- expect(canRemoveFromGroup(harness.engine.document.model(), ['r2', 'r5'])).toBe(true);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts
deleted file mode 100644
index 33a252ad11..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupCommands.ts
+++ /dev/null
@@ -1,124 +0,0 @@
-import type { CanvasDocumentContractV3, CanvasDocumentModel, DocumentCommand } 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';
-
-/** A group id no document holds, for asking the model whether a grouping would be accepted. */
-const ELIGIBILITY_GROUP_ID = '\0group';
-
-/** Whether the model would accept wrapping `ids` in one group; the same check the command runs. */
-export const canGroupSelection = (model: CanvasDocumentModel | null, ids: readonly string[]): boolean =>
- ids.length > 0 &&
- !!model &&
- model.refusalFor({ groupId: ELIGIBILITY_GROUP_ID, ids, name: '', type: 'group' }) === null;
-
-/** Whether the model would dissolve at least one group among `ids`. */
-export const canUngroupSelection = (model: CanvasDocumentModel | null, ids: readonly string[]): boolean => {
- const groupIds = ids.filter((id) => {
- const node = model?.getNode(id);
- return !!node && isGroupNode(node);
- });
- return groupIds.length > 0 && !!model && model.refusalFor({ ids: groupIds, type: 'ungroup' }) === null;
-};
-
-/**
- * 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 => {
- engine?.layers.endStructuralPreview();
- 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' });
- });
-
-/**
- * The reparent that lifts `ids` out of their shared parent group to sit directly above it, in document order; null
- * unless every id is a leaf of the same group.
- */
-export const removeFromGroupCommand = (
- document: CanvasDocumentContractV3,
- ids: readonly string[]
-): Extract<DocumentCommand, { type: 'reparent' }> | null => {
- const index = getDocumentIndex(document);
- const entries = ids.flatMap((id) => index.byId.get(id) ?? []);
- const groupId = entries[0]?.parentId ?? null;
- if (
- groupId === null ||
- entries.length !== ids.length ||
- entries.some((entry) => isGroupNode(entry.node) || entry.parentId !== groupId)
- ) {
- return null;
- }
- return {
- beforeId: groupId,
- ids: [...entries].sort((a, b) => a.order - b.order).map((entry) => entry.node.id),
- parentId: index.byId.get(groupId)!.parentId,
- type: 'reparent',
- };
-};
-
-/** Whether the model would accept lifting `ids` out of their group; the same check the command runs. */
-export const canRemoveFromGroup = (model: CanvasDocumentModel | null, ids: readonly string[]): boolean => {
- const command = model ? removeFromGroupCommand(model.document, ids) : null;
- return !!model && !!command && model.refusalFor(command) === null;
-};
-
-/** Moves leaves of one group directly above it as one edit; an ineligible selection is a quiet no-op. */
-export const removeFromGroup = (
- engine: CanvasPreparedEngine | null,
- ids: readonly string[],
- label: string
-): PreparedCommitOutcome =>
- commitPreparedEdit(engine, label, (model) => {
- const command = removeFromGroupCommand(model.document, ids);
- return command ? model.prepare(command) : { status: 'unchanged' };
- });
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts
deleted file mode 100644
index dbf5ce5a59..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useLayerSelectionCommands.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import type { CanvasEngineHandle } from '@workbench/canvas-operations/react';
-
-import { toaster } from '@platform/ui';
-import { publishLayerPanelSelection } from '@workbench/layerPanelState';
-import { reportLayerOperation, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
-import { useCallback, useMemo } from 'react';
-import { useTranslation } from 'react-i18next';
-
-import { groupLayers } from './layerGroupCommands';
-
-type SelectionEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;
-
-export interface LayerSelectionCommands {
- canDelete: boolean;
- canDuplicate: boolean;
- canGroup: boolean;
- deleteSelected: () => void;
- duplicateSelected: () => void;
- groupSelected: () => void;
-}
-
-/** Use model-authoritative eligibility for duplicate/group/delete on the current selection. */
-export const useLayerSelectionCommands = (
- engine: SelectionEngine | null,
- projectId: string,
- selectedIds: readonly string[],
- editingLocked: boolean
-): LayerSelectionCommands => {
- const commitPrepared = usePreparedCommit(engine);
- const { t } = useTranslation();
- const model = engine?.document.model() ?? null;
- const none = selectedIds.length === 0;
- const canGroup =
- !editingLocked &&
- !none &&
- !!model &&
- model.refusalFor({ groupId: '\0probe', ids: selectedIds, name: '', type: 'group' }) === null;
- const canDelete =
- !editingLocked && !none && !!model && model.refusalFor({ ids: selectedIds, type: 'remove' }) === null;
- const canDuplicate = !editingLocked && !none && !!engine;
-
- const duplicateSelected = useCallback(async (): Promise<void> => {
- try {
- const result = await engine?.layers.duplicateLayers(selectedIds);
- if (result?.status === 'duplicated') {
- publishLayerPanelSelection({
- primaryId: result.selectedLayerId,
- projectId,
- selectedIds: result.duplicateIds,
- });
- return;
- }
- if (result?.status === 'busy') {
- return;
- }
- if (result && result.status !== 'nothing') {
- reportLayerOperation(
- result.status === 'unreadable' ? result : result.status,
- (title, description) => toaster.create({ description, title, type: 'warning' }),
- t
- );
- return;
- }
- } catch {
- // 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' });
- }
- }, [engine, projectId, selectedIds, t]);
-
- const groupSelected = useCallback(
- () => groupLayers(engine, projectId, selectedIds, t('widgets.layers.actions.groupSelected')),
- [engine, projectId, selectedIds, t]
- );
-
- const deleteSelected = useCallback(() => {
- commitPrepared(t('widgets.layers.actions.deleteSelected'), (model) =>
- model.prepare({ ids: selectedIds, type: 'remove' })
- );
- }, [commitPrepared, selectedIds, t]);
-
- const runDuplicate = useCallback(() => {
- void duplicateSelected();
- }, [duplicateSelected]);
-
- return useMemo(
- () => ({
- canDelete,
- canDuplicate,
- canGroup,
- deleteSelected,
- duplicateSelected: runDuplicate,
- groupSelected,
- }),
- [canDelete, canDuplicate, canGroup, deleteSelected, groupSelected, runDuplicate]
- );
-};
diff --git a/invokeai/frontend/webv2/vite.config.mts b/invokeai/frontend/webv2/vite.config.mts
index 6489bbb2ff..0c2a70a82c 100644
--- a/invokeai/frontend/webv2/vite.config.mts
+++ b/invokeai/frontend/webv2/vite.config.mts
@@ -490,11 +490,11 @@ const CANVAS_LAYER_SHARED_MODULES = [
'/workbench/widgets/layers/LayerSaveToBoardSubmenu.tsx',
'/workbench/widgets/layers/RunLayerWorkflowDialog.tsx',
'/workbench/widgets/layers/colorLabels.ts',
+ '/workbench/widgets/layers/layerCommands.ts',
'/workbench/widgets/layers/layerActionSession.ts',
'/workbench/widgets/layers/layerContextActions.ts',
'/workbench/widgets/layers/layerContextMenuLayout.ts',
'/workbench/widgets/layers/layerExportActions.ts',
- '/workbench/widgets/layers/layerGroupCommands.ts',
'/workbench/widgets/layers/layerMenuState.ts',
'/workbench/widgets/layers/runLayerWorkflow.ts',
'/workbench/widgets/layers/useSelectedModelBase.ts',