Skip to content

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

feat(canvas): commit prepared flat edits through one transaction seam

Josh Corbett99c18cfb8ba7
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index ffc65a4327..563c441044 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2293,6 +2293,11 @@
"failed": "Canvas edit failed",
"gestureActive": "Finish the current canvas gesture, then try again.",
"notReady": "The canvas is not ready to record this edit.",
+ "refusedInvalidTarget": "That layer cannot be the target of this edit.",
+ "refusedLocked": "A locked layer is in the way. Unlock it first.",
+ "refusedMissing": "A layer this edit needs is no longer in the canvas.",
+ "refusedUnsupported": "This edit is not available here.",
+ "refusedWrongType": "This edit does not apply to this kind of layer.",
"rejected": "The canvas did not accept this edit. Nothing changed.",
"reverted": "The edit could not be verified and was reverted.",
"stale": "The canvas changed before this edit landed. Try again.",
diff --git a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
index 331f96884d..cfef6555f8 100644
--- a/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
+++ b/invokeai/frontend/webv2/src/architecture/workbenchOwnershipManifest.json
@@ -90,7 +90,6 @@
"canvasDimsSync.ts": "workbench",
"canvasInvocationPreparation.ts": "workbench",
"canvasLayerContent.ts": "workbench",
- "canvasLayerOps.ts": "workbench",
"canvasLoadContracts.ts": "workbench",
"canvasMigration.ts": "workbench",
"canvasProjectMutationPort.ts": "workbench",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index d6415974f1..9825272cef 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -9,6 +9,8 @@ import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { NewRasterLayerResult } from './controllers/newRasterLayerController';
+import type { FlatEditOrigin, PreparedFlatEdit } from './document-model/flatDocumentCommands';
+import type { FlatCanvasDocumentModel } from './document-model/flatDocumentModel';
import type { CanvasCommandRefusal } from './document/commandRefusal';
import type { FlatLayerInsertionAnchor } from './document/insertionAnchors';
import type { LayerStackKind } from './document/layerStacks';
@@ -150,6 +152,8 @@ export interface CanvasDocumentCapability {
captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;
/** The anchor that restores `layerId` between its current same-stack neighbours; null when absent. */
captureRestoreAnchor(layerId: string): FlatLayerInsertionAnchor | null;
+ /** The pure model over the current document; the same instance until the document changes. */
+ model(): FlatCanvasDocumentModel | null;
}
/** Immutable reducer canvas state captured at one engine document generation. */
@@ -313,9 +317,15 @@ export interface CanvasLayerCapability {
inverse: CanvasProjectMutation,
options?: StructuralCommitOptions
): StructuralCommitResult;
+ /** Runs a prepared flat edit through the transaction: refusals, dispatch, verification and history. */
+ commitPrepared(label: string, edit: PreparedFlatEdit, options?: PreparedCommitOptions): StructuralCommitResult;
invertMask(layerId: string): boolean;
}
+export interface PreparedCommitOptions {
+ readonly origin?: FlatEditOrigin;
+}
+
export interface CommitStagedImageOptions {
candidate: CanvasStagingCandidateContract;
/** Save a disabled layer without clearing or otherwise disturbing staging. */
@@ -597,6 +607,22 @@ export {
isPixelBackedLayer,
} from './document/layerEligibility';
export { repairSelectedLayerId } from './document/selectionRepair';
+export {
+ type FlatDocumentCommand,
+ type FlatDocumentRefusal,
+ type FlatEditOrigin,
+ type MergeDownEligibility,
+ type PreparedFlatEdit,
+ type PrepareFlatEditResult,
+} from './document-model/flatDocumentCommands';
+export { createFlatDocumentModel, type FlatCanvasDocumentModel } from './document-model/flatDocumentModel';
+export { checkFlatEditPostconditions, type FlatEditPostcondition } from './document-model/postconditions';
+export {
+ planScreenComposition,
+ type CanvasScreenViewState,
+ type ScreenCompositionPlan,
+} from './document-model/screenComposition';
+export { type SemanticLeafV2 } from './document-model/semanticLeaf';
export {
captureInsertionAnchor,
captureRestoreAnchor,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
index 942387cfb7..16cbc3463e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.test.ts
@@ -42,6 +42,7 @@ describe('LayerController', () => {
ctx: {
canEdit: () => true,
capturePermit: () => ({ epoch: 0 }),
+ projectId: 'p',
dispatch: vi.fn(() => true),
dispatchPrepared: vi.fn(),
getDocument: () => null,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts
index d124f7a209..c1521d4ee1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerController.ts
@@ -15,7 +15,12 @@ import { ThumbnailController, type ThumbnailControllerOptions } from './thumbnai
export type LayerControllerDeps = Omit<
CanvasLayerCapability,
- 'applyStructuralPreview' | 'canCommitStructural' | 'commitStagedImage' | 'commitStructural' | 'invertMask'
+ | 'applyStructuralPreview'
+ | 'canCommitStructural'
+ | 'commitPrepared'
+ | 'commitStagedImage'
+ | 'commitStructural'
+ | 'invertMask'
> &
Omit<CanvasPreviewCapability, 'drawLayerThumbnail' | 'requestLayerThumbnail'> & {
mask: MaskLayerControllerOptions;
@@ -62,6 +67,8 @@ export class LayerController {
canCommitStructural: () => this.structural.canCommit(),
commitGeneratedImageResult: (options) =>
this.disposed ? Promise.resolve({ status: 'aborted' }) : deps.commitGeneratedImageResult(options),
+ commitPrepared: (label, edit, options) =>
+ this.disposed ? { status: 'not-ready' } : this.structural.commitPrepared(label, edit, options),
commitStructural: (label, forward, inverse, options) =>
this.disposed ? { status: 'not-ready' } : this.structural.commit(label, forward, inverse, options),
invertMask: (layerId) => (this.disposed ? false : this.mask.invert(layerId)),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts
index 087c94015f..a54f538fb3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.test.ts
@@ -2,6 +2,10 @@ import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contract
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { Project } from '@workbench/projectContracts';
+import {
+ createFlatDocumentModel,
+ type FlatCanvasDocumentModel,
+} from '@workbench/canvas-engine/document-model/flatDocumentModel';
import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createHistory } from '@workbench/canvas-engine/history/history';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
@@ -208,6 +212,58 @@ describe('StructuralLayerController', () => {
expect(report).toHaveBeenCalledWith('Structural edit could not be mirrored', 'Rename', expect.any(Error));
});
+ describe('commitPrepared', () => {
+ const prepareRename = (model: FlatCanvasDocumentModel, name: string) => {
+ const result = model.prepare({ id: 'layer', patch: { name }, type: 'patch' });
+ if (result.status !== 'prepared') {
+ throw new Error(`expected a prepared edit, got ${result.status}`);
+ }
+ return result.edit;
+ };
+
+ it('applies a prepared edit, verifies its postconditions and records one entry', () => {
+ const { controller, ctx, document, history, projectId } = createHarness();
+ const model = createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });
+
+ expect(controller.commitPrepared('Rename', prepareRename(model, 'Renamed'))).toEqual({ status: 'committed' });
+ expect(layerName(document())).toBe('Renamed');
+ expect(history.canUndo()).toBe(true);
+ history.undo();
+ expect(layerName(document())).toBe('Layer');
+ });
+
+ it('refuses an edit prepared against an older revision or another project', () => {
+ const { controller, ctx, document, history, projectId } = createHarness();
+ const stale = prepareRename(
+ createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId }),
+ 'A'
+ );
+ ctx.dispatch(rename('layer', 'Elsewhere'), 'system');
+
+ expect(controller.commitPrepared('Rename', stale)).toMatchObject({ status: 'stale' });
+ const foreign = prepareRename(
+ createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId: 'other' }),
+ 'B'
+ );
+ expect(controller.commitPrepared('Rename', foreign)).toEqual({ status: 'dispatch-rejected' });
+ expect(layerName(document())).toBe('Elsewhere');
+ expect(history.canUndo()).toBe(false);
+ });
+
+ it('skips history for an edit whose policy is none', () => {
+ const { controller, ctx, document, history, projectId } = createHarness();
+ const model = createFlatDocumentModel(document(), { editRevision: ctx.getEditRevision(), projectId });
+ const result = model.prepare({ id: null, type: 'select' });
+ if (result.status !== 'prepared') {
+ throw new Error('expected a prepared selection change');
+ }
+
+ expect(controller.commitPrepared('Select', result.edit)).toEqual({ status: 'committed' });
+ expect(document().selectedLayerId).toBeNull();
+ expect(history.canUndo()).toBe(false);
+ });
+ });
+
it('refuses an insertion anchored at an older edit revision as stale', () => {
const { controller, ctx, document, projectId } = createHarness();
const anchor = ctx.captureInsertionAnchor('raster', document().selectedLayerId);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
index 303fcb867c..85247ab670 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
@@ -1,7 +1,14 @@
-import type { StructuralCommitOptions, StructuralCommitResult } from '@workbench/canvas-engine/capabilities';
+import type { WorkbenchActionOrigin } from '@workbench/autoRoutePolicy';
+import type {
+ PreparedCommitOptions,
+ StructuralCommitOptions,
+ StructuralCommitResult,
+} from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+import type { FlatEditOrigin, PreparedFlatEdit } from '@workbench/canvas-engine/document-model/flatDocumentCommands';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import { checkFlatEditPostconditions } from '@workbench/canvas-engine/document-model/postconditions';
import { isLayerEditable } from '@workbench/canvas-engine/document/layerEligibility';
import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/documentPatch';
@@ -19,6 +26,9 @@ const anchorRevisionOf = (mutation: CanvasProjectMutation): number | undefined =
}
};
+const toWorkbenchOrigin = (origin: FlatEditOrigin | undefined): WorkbenchActionOrigin | undefined =>
+ origin === undefined ? undefined : origin === 'system' ? 'system' : 'user';
+
export type StructuralMutationContext = Pick<
CanvasMutationContext,
| 'canEdit'
@@ -30,6 +40,7 @@ export type StructuralMutationContext = Pick<
| 'getReducerDocument'
| 'history'
| 'isGestureActive'
+ | 'projectId'
>;
export type StructuralFailureReport =
@@ -102,6 +113,29 @@ export class StructuralLayerController {
return applied;
}
+ /** A prepared flat edit: refused as `stale` unless its revision and project still match, verified by its postconditions. */
+ commitPrepared(label: string, edit: PreparedFlatEdit, options: PreparedCommitOptions = {}): StructuralCommitResult {
+ const refusal = this.refuse({ expectedRevision: edit.expectedRevision });
+ if (refusal) {
+ return refusal;
+ }
+ if (edit.projectId !== this.deps.ctx.projectId) {
+ return { status: 'dispatch-rejected' };
+ }
+ this.endBurst();
+ const applied = this.apply(
+ label,
+ edit.forward,
+ edit.inverse,
+ (document) => checkFlatEditPostconditions(document, edit.postconditions),
+ toWorkbenchOrigin(options.origin)
+ );
+ if (applied.status === 'committed' && edit.history === 'record') {
+ this.deps.ctx.history.push(this.entry(label, edit.forward, edit.inverse));
+ }
+ return applied;
+ }
+
preview(action: CanvasProjectMutation): boolean {
if (!this.canCommit()) {
return false;
@@ -187,7 +221,8 @@ export class StructuralLayerController {
label: string,
forward: CanvasProjectMutation,
inverse: CanvasProjectMutation,
- verify: (document: CanvasDocumentContractV2) => boolean = () => true
+ verify: (document: CanvasDocumentContractV2) => boolean = () => true,
+ origin?: WorkbenchActionOrigin
): StructuralCommitResult {
const { ctx } = this.deps;
const before = ctx.getReducerDocument();
@@ -197,7 +232,7 @@ export class StructuralLayerController {
return document !== null && document !== before && verify(document);
};
try {
- ctx.dispatchPrepared(forward, isApplied, isMirrored);
+ ctx.dispatchPrepared(forward, isApplied, isMirrored, origin);
return { status: 'committed' };
} catch (error) {
const after = ctx.getReducerDocument();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
index ce2cafda64..7a957f9ef5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentCommands.ts
@@ -1,10 +1,14 @@
-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { CanvasLayerContract, CanvasLayerSourceContract } from '@workbench/canvas-engine/contracts';
import type {
LayerStackKind,
LayerStackMoveKind,
ReorderFlatStackCommand,
} from '@workbench/canvas-engine/document/layerStacks';
-import type { CanvasLayerBasePatch, CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type {
+ CanvasLayerBasePatch,
+ CanvasLayerConfigPatch,
+ CanvasProjectMutation,
+} from '@workbench/canvas-engine/mutationContracts';
import type { FlatEditPostcondition } from './postconditions';
@@ -21,9 +25,27 @@ export type FlatDocumentCommand =
| { readonly type: 'duplicate'; readonly sourceId: string; readonly newId: string }
| { readonly type: 'move'; readonly ids: readonly string[]; readonly kind: LayerStackMoveKind }
| { readonly type: 'reorder'; readonly stacks: readonly ReorderFlatStackCommand[] }
- | { readonly type: 'patch'; readonly id: string; readonly patch: CanvasLayerBasePatch }
+ | {
+ readonly type: 'patch';
+ readonly id: string;
+ readonly patch: CanvasLayerBasePatch;
+ /** The values before a previewed gesture; the inverse restores these instead of the current ones. */
+ readonly before?: CanvasLayerBasePatch;
+ }
+ | {
+ readonly type: 'patch-config';
+ readonly id: string;
+ readonly config: CanvasLayerConfigPatch;
+ readonly before?: CanvasLayerConfigPatch;
+ }
+ | { readonly type: 'patch-source'; readonly id: string; readonly source: CanvasLayerSourceContract }
+ | { readonly type: 'set-enabled'; readonly updates: readonly { id: string; isEnabled: boolean }[] }
+ | { readonly type: 'set-hidden'; readonly updates: readonly { id: string; isHidden: boolean }[] }
+ | { readonly type: 'set-locked'; readonly updates: readonly { id: string; isLocked: boolean }[] }
| { readonly type: 'select'; readonly id: string | null };
+export type FlatEditOrigin = 'human' | 'operation' | 'system' | 'ai';
+
export type FlatDocumentRefusal =
| { readonly status: 'missing'; readonly ids: readonly string[] }
| { readonly status: 'locked'; readonly ids: readonly string[] }
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
index 226c6de82a..87a0166e5a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.test.ts
@@ -1,6 +1,7 @@
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { Project } from '@workbench/projectContracts';
+import { isHideableLayer } from '@workbench/canvas-engine/document/layerEligibility';
import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';
import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
@@ -80,6 +81,9 @@ const modelOf = (project: Project) => createFlatDocumentModel(project.canvas.doc
const ids = (document: CanvasDocumentContractV2): string[] => document.layers.map((entry) => entry.id);
const byId = (left: CanvasLayerContract, right: CanvasLayerContract): number => left.id.localeCompare(right.id);
+/** The reducer writes an explicit `isHidden: false` on undo where the original layer had no key. */
+const withExplicitHidden = (layer: CanvasLayerContract): CanvasLayerContract =>
+ isHideableLayer(layer) ? { ...layer, isHidden: layer.isHidden === true } : layer;
const roundTrip = (project: Project, command: FlatDocumentCommand): { after: Project; edit: PreparedFlatEdit } => {
const result = modelOf(project).prepare(command);
@@ -93,7 +97,9 @@ const roundTrip = (project: Project, command: FlatDocumentCommand): { after: Pro
const restored = applyCanvasProjectMutation(after, result.edit.inverse).canvas.document;
const original = project.canvas.document;
expect(haveSameStackOrders(restored.layers, original.layers)).toBe(true);
- expect([...restored.layers].sort(byId)).toEqual([...original.layers].sort(byId));
+ expect([...restored.layers].sort(byId).map(withExplicitHidden)).toEqual(
+ [...original.layers].sort(byId).map(withExplicitHidden)
+ );
expect({ ...restored, layers: [] }).toEqual({ ...original, layers: [] });
return { after, edit: result.edit };
};
@@ -306,6 +312,136 @@ describe('createFlatDocumentModel', () => {
});
});
+ it('takes a pre-gesture baseline so a previewed patch still records a real inverse', () => {
+ const previewed = applyCanvasProjectMutation(projectWith(interleaved(), 'r1'), {
+ id: 'r1',
+ patch: { opacity: 0.4 },
+ type: 'updateCanvasLayer',
+ });
+ const model = modelOf(previewed);
+ expect(model.prepare({ id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toEqual({ status: 'unchanged' });
+
+ const result = model.prepare({ before: { opacity: 1 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' });
+ expect(result).toMatchObject({
+ edit: { inverse: { id: 'r1', patch: { opacity: 1 }, type: 'updateCanvasLayer' } },
+ status: 'prepared',
+ });
+ expect(model.prepare({ before: { opacity: 0.4 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })).toEqual({
+ status: 'unchanged',
+ });
+ expect(
+ model.prepare({ before: { name: 'r1', opacity: 1 }, id: 'r1', patch: { opacity: 0.4 }, type: 'patch' })
+ ).toEqual({ operation: 'patch baseline names other fields', status: 'unsupported' });
+ expect(
+ modelOf(projectWith(interleaved(), 'r1')).prepare({
+ before: { opacity: 1 },
+ id: 'r1',
+ patch: { opacity: 0.4 },
+ type: 'patch',
+ }).status
+ ).toBe('prepared');
+
+ const fillBefore = { color: '#e07575', style: 'diagonal' as const };
+ const fillNext = { color: '#00ff00', style: 'diagonal' as const };
+ const previewedFill = applyCanvasProjectMutation(projectWith(interleaved(), 'i1'), {
+ config: { layerType: 'inpaint_mask', mask: { fill: fillNext } },
+ id: 'i1',
+ type: 'updateCanvasLayerConfig',
+ });
+ const fill = modelOf(previewedFill).prepare({
+ before: { layerType: 'inpaint_mask', mask: { fill: fillBefore } },
+ config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },
+ id: 'i1',
+ type: 'patch-config',
+ });
+ expect(fill).toMatchObject({
+ edit: { inverse: { config: { layerType: 'inpaint_mask', mask: { fill: fillBefore } }, id: 'i1' } },
+ status: 'prepared',
+ });
+ expect(
+ modelOf(previewedFill).prepare({
+ before: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },
+ config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },
+ id: 'i1',
+ type: 'patch-config',
+ })
+ ).toEqual({ status: 'unchanged' });
+ expect(
+ modelOf(previewedFill).prepare({
+ config: { layerType: 'inpaint_mask', mask: { fill: { ...fillNext } } },
+ id: 'i1',
+ type: 'patch-config',
+ })
+ ).toEqual({ status: 'unchanged' });
+ });
+
+ it('round-trips config, source and flag commands through the reducer', () => {
+ const project = projectWith(interleaved(), 'r1');
+ const control = roundTrip(project, {
+ config: { adapter: { weight: 0.5 }, layerType: 'control', withTransparencyEffect: true },
+ id: 'c1',
+ type: 'patch-config',
+ });
+ expect(control.after.canvas.document.layers[2]).toMatchObject({
+ adapter: { weight: 0.5 },
+ withTransparencyEffect: true,
+ });
+ expect(control.edit.inverse).toEqual({
+ config: { adapter: { weight: 1 }, layerType: 'control', withTransparencyEffect: false },
+ id: 'c1',
+ type: 'updateCanvasLayerConfig',
+ });
+
+ const source = { bitmap: null, offset: { x: 3, y: 4 }, type: 'paint' as const };
+ const patched = roundTrip(project, { id: 'r2', source, type: 'patch-source' });
+ expect((patched.after.canvas.document.layers[3] as { source: unknown }).source).toBe(source);
+
+ const enabled = roundTrip(project, {
+ type: 'set-enabled',
+ updates: [
+ { id: 'r1', isEnabled: false },
+ { id: 'c1', isEnabled: true },
+ ],
+ });
+ expect(enabled.edit).toMatchObject({ touchedIds: ['r1'], touchedStacks: ['raster'] });
+
+ const hidden = roundTrip(project, { type: 'set-hidden', updates: [{ id: 'c1', isHidden: true }] });
+ expect(hidden.after.canvas.document.layers[2]).toMatchObject({ isHidden: true });
+
+ const locked = roundTrip(project, { type: 'set-locked', updates: [{ id: 'g1', isLocked: true }] });
+ expect(locked.after.canvas.document.layers[4]).toMatchObject({ isLocked: true });
+ });
+
+ it.each<[string, FlatDocumentCommand, PrepareFlatEditResult]>([
+ [
+ 'hiding a raster layer',
+ { type: 'set-hidden', updates: [{ id: 'r1', isHidden: true }] },
+ { actual: 'raster', expected: ['control', 'inpaint_mask', 'regional_guidance'], status: 'wrong-type' },
+ ],
+ [
+ 'a config patch for another layer type',
+ { config: { layerType: 'control', withTransparencyEffect: true }, id: 'r1', type: 'patch-config' },
+ { actual: 'raster', expected: ['control'], status: 'wrong-type' },
+ ],
+ [
+ 'a source patch on a mask',
+ { id: 'i1', source: { bitmap: null, type: 'paint' }, type: 'patch-source' },
+ { actual: 'inpaint_mask', expected: ['raster', 'control'], status: 'wrong-type' },
+ ],
+ [
+ 'an empty flag update',
+ { type: 'set-locked', updates: [] },
+ { operation: 'set-locked nothing', status: 'unsupported' },
+ ],
+ [
+ 'flags that already hold',
+ { type: 'set-enabled', updates: [{ id: 'r1', isEnabled: true }] },
+ { status: 'unchanged' },
+ ],
+ ])('answers %s', (_label, command, result) => {
+ expect(modelOf(projectWith(interleaved(), 'r1')).prepare(command)).toEqual(result);
+ });
+
it('selects without recording history and reports the current selection as unchanged', () => {
const project = projectWith(interleaved(), 'r1');
const { edit } = roundTrip(project, { id: 'c1', type: 'select' });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
index 9156c23481..0274809d77 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/flatDocumentModel.ts
@@ -1,14 +1,23 @@
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { FlatLayerInsertion } from '@workbench/canvas-engine/document/insertionAnchors';
import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
-import type { CanvasLayerBasePatch, CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
+import type {
+ CanvasLayerBasePatch,
+ CanvasLayerConfigPatch,
+ CanvasProjectMutation,
+} from '@workbench/canvas-engine/mutationContracts';
import {
captureInsertionAnchor,
captureRestoreAnchor,
insertLayersAtAnchor,
} from '@workbench/canvas-engine/document/insertionAnchors';
-import { isLayerContributing, isPixelBackedLayer } from '@workbench/canvas-engine/document/layerEligibility';
+import {
+ isHideableLayer,
+ isLayerContributing,
+ isLayerHidden,
+ isPixelBackedLayer,
+} from '@workbench/canvas-engine/document/layerEligibility';
import {
getStackOrder,
LAYER_STACKS_TOP_FIRST,
@@ -28,7 +37,7 @@ import type {
import type { FlatEditPostcondition } from './postconditions';
import type { SemanticLeafV2 } from './semanticLeaf';
-import { isPatchApplied } from './postconditions';
+import { isConfigApplied, isPatchApplied, sameValue } from './postconditions';
import { compileSemanticLeaf } from './semanticLeaf';
export interface FlatDocumentModelContext {
@@ -99,13 +108,13 @@ const indexOf = (document: CanvasDocumentContractV2): DocumentIndex => {
const compileLeaves = (
document: CanvasDocumentContractV2,
index: DocumentIndex,
- previous: FlatCanvasDocumentModel | null
+ previousDocument: CanvasDocumentContractV2 | null
): readonly SemanticLeafV2[] => {
if (index.leaves) {
return index.leaves;
}
- const reusable = previous ? indexOf(previous.document).leaves : null;
- if (reusable && previous?.document.layers === document.layers) {
+ const reusable = previousDocument ? indexOf(previousDocument).leaves : null;
+ if (reusable && previousDocument?.layers === document.layers) {
index.leaves = reusable;
return reusable;
}
@@ -126,6 +135,23 @@ const compileLeaves = (
const unique = <T>(values: readonly T[]): T[] => [...new Set(values)];
+/** Whether two patches name the same fields, including the same transform axes and nested config fields. */
+const sameKeys = (left: Record<string, unknown>, right: Record<string, unknown>): boolean => {
+ const leftKeys = Object.keys(left).sort();
+ const rightKeys = Object.keys(right).sort();
+ return (
+ leftKeys.length === rightKeys.length &&
+ leftKeys.every((key, position) => key === rightKeys[position]) &&
+ leftKeys.every((key) => {
+ const a = left[key];
+ const b = right[key];
+ return typeof a === 'object' && a !== null && !Array.isArray(a) && typeof b === 'object' && b !== null
+ ? sameKeys(a as Record<string, unknown>, b as Record<string, unknown>)
+ : true;
+ })
+ );
+};
+
const stacksTopFirst = (stacks: readonly LayerStackKind[]): LayerStackKind[] =>
LAYER_STACKS_TOP_FIRST.filter((stack) => stacks.includes(stack));
@@ -160,6 +186,7 @@ export const createFlatDocumentModel = (
): FlatCanvasDocumentModel => {
const index = indexOf(document);
const { layers, selectedLayerId } = document;
+ const previousDocument = previous?.document ?? null;
const lookup = (ids: readonly string[]): { entries: LayerIndexEntry[] } | FlatDocumentRefusal => {
const absent = ids.filter((id) => !index.byId.has(id));
@@ -361,12 +388,16 @@ export const createFlatDocumentModel = (
if (Object.keys(command.patch).length === 0) {
return { operation: 'patch nothing', status: 'unsupported' };
}
- if (isPatchApplied(entry.layer, command.patch)) {
+ if (command.before && !sameKeys(command.before, command.patch)) {
+ return { operation: 'patch baseline names other fields', status: 'unsupported' };
+ }
+ const inverse = command.before ?? patchInverse(entry.layer, command.patch);
+ if (command.before ? sameValue(command.before, command.patch) : isPatchApplied(entry.layer, command.patch)) {
return { status: 'unchanged' };
}
return prepared(
{ id: command.id, patch: command.patch, type: 'updateCanvasLayer' },
- { id: command.id, patch: patchInverse(entry.layer, command.patch), type: 'updateCanvasLayer' },
+ { id: command.id, patch: inverse, type: 'updateCanvasLayer' },
{
history: 'record',
postconditions: [{ id: command.id, kind: 'patched', patch: command.patch }],
@@ -377,6 +408,193 @@ export const createFlatDocumentModel = (
);
};
+ const configInverse = (layer: CanvasLayerContract, config: CanvasLayerConfigPatch): CanvasLayerConfigPatch => {
+ const current = layer as unknown as Record<string, unknown>;
+ const inverse: Record<string, unknown> = { layerType: config.layerType };
+ for (const [key, value] of Object.entries(config)) {
+ if (key === 'layerType') {
+ continue;
+ }
+ const before = current[key];
+ inverse[key] =
+ (key === 'adapter' || key === 'mask') &&
+ typeof value === 'object' &&
+ value !== null &&
+ typeof before === 'object'
+ ? Object.fromEntries(Object.keys(value).map((field) => [field, (before as Record<string, unknown>)[field]]))
+ : before;
+ }
+ return inverse as CanvasLayerConfigPatch;
+ };
+
+ const preparePatchConfig = (
+ command: Extract<FlatDocumentCommand, { type: 'patch-config' }>
+ ): PrepareFlatEditResult => {
+ const entry = index.byId.get(command.id);
+ if (!entry) {
+ return missing([command.id]);
+ }
+ if (entry.layer.type !== command.config.layerType) {
+ return { actual: entry.layer.type, expected: [command.config.layerType], status: 'wrong-type' };
+ }
+ if (Object.keys(command.config).length <= 1) {
+ return { operation: 'patch nothing', status: 'unsupported' };
+ }
+ if (command.before && !sameKeys(command.before, command.config)) {
+ return { operation: 'config baseline names other fields', status: 'unsupported' };
+ }
+ if (command.before ? sameValue(command.before, command.config) : isConfigApplied(entry.layer, command.config)) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { config: command.config, id: command.id, type: 'updateCanvasLayerConfig' },
+ {
+ config: command.before ?? configInverse(entry.layer, command.config),
+ id: command.id,
+ type: 'updateCanvasLayerConfig',
+ },
+ {
+ history: 'record',
+ postconditions: [{ config: command.config, id: command.id, kind: 'config' }],
+ selectionAfter: selectedLayerId,
+ touchedIds: [command.id],
+ touchedStacks: [entry.stack],
+ }
+ );
+ };
+
+ const preparePatchSource = (
+ command: Extract<FlatDocumentCommand, { type: 'patch-source' }>
+ ): PrepareFlatEditResult => {
+ const entry = index.byId.get(command.id);
+ if (!entry) {
+ return missing([command.id]);
+ }
+ if (entry.layer.type !== 'raster' && entry.layer.type !== 'control') {
+ return { actual: entry.layer.type, expected: ['raster', 'control'], status: 'wrong-type' };
+ }
+ if (entry.layer.source === command.source) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { id: command.id, source: command.source, type: 'updateCanvasLayerSource' },
+ { id: command.id, source: entry.layer.source, type: 'updateCanvasLayerSource' },
+ {
+ history: 'record',
+ postconditions: [{ id: command.id, kind: 'source', source: command.source }],
+ selectionAfter: selectedLayerId,
+ touchedIds: [command.id],
+ touchedStacks: [entry.stack],
+ }
+ );
+ };
+
+ const prepareFlags = (
+ command: Extract<FlatDocumentCommand, { type: 'set-enabled' | 'set-hidden' | 'set-locked' }>
+ ): PrepareFlatEditResult => {
+ const ids = unique(command.updates.map((update) => update.id));
+ if (ids.length === 0) {
+ return { operation: `${command.type} nothing`, status: 'unsupported' };
+ }
+ const found = lookup(ids);
+ if ('status' in found) {
+ return found;
+ }
+ if (command.type === 'set-hidden') {
+ const notHideable = found.entries.find((entry) => !isHideableLayer(entry.layer));
+ if (notHideable) {
+ return {
+ actual: notHideable.layer.type,
+ expected: ['control', 'inpaint_mask', 'regional_guidance'],
+ status: 'wrong-type',
+ };
+ }
+ }
+ const detail = (updated: readonly { id: string }[]) => ({
+ history: 'record' as const,
+ selectionAfter: selectedLayerId,
+ touchedIds: updated.map((update) => update.id),
+ touchedStacks: stacksTopFirst(updated.map((update) => index.byId.get(update.id)!.stack)),
+ });
+ switch (command.type) {
+ case 'set-enabled': {
+ const updates = command.updates.filter(
+ (update) => index.byId.get(update.id)!.layer.isEnabled !== update.isEnabled
+ );
+ if (updates.length === 0) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { type: 'setCanvasLayersEnabled', updates },
+ {
+ type: 'setCanvasLayersEnabled',
+ updates: updates.map((update) => ({
+ id: update.id,
+ isEnabled: index.byId.get(update.id)!.layer.isEnabled,
+ })),
+ },
+ {
+ ...detail(updates),
+ postconditions: updates.map((update) => ({
+ id: update.id,
+ kind: 'patched',
+ patch: { isEnabled: update.isEnabled },
+ })),
+ }
+ );
+ }
+ case 'set-hidden': {
+ const updates = command.updates.filter(
+ (update) => isLayerHidden(index.byId.get(update.id)!.layer) !== update.isHidden
+ );
+ if (updates.length === 0) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { type: 'setCanvasLayersHidden', updates },
+ {
+ type: 'setCanvasLayersHidden',
+ updates: updates.map((update) => ({
+ id: update.id,
+ isHidden: isLayerHidden(index.byId.get(update.id)!.layer),
+ })),
+ },
+ {
+ ...detail(updates),
+ postconditions: updates.map((update) => ({ id: update.id, isHidden: update.isHidden, kind: 'hidden' })),
+ }
+ );
+ }
+ case 'set-locked': {
+ const updates = command.updates.filter(
+ (update) => index.byId.get(update.id)!.layer.isLocked !== update.isLocked
+ );
+ if (updates.length === 0) {
+ return { status: 'unchanged' };
+ }
+ return prepared(
+ { enabledUpdates: [], lockedUpdates: updates, type: 'applyCanvasLayerStackMutation' },
+ {
+ enabledUpdates: [],
+ lockedUpdates: updates.map((update) => ({
+ id: update.id,
+ isLocked: index.byId.get(update.id)!.layer.isLocked,
+ })),
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ ...detail(updates),
+ postconditions: updates.map((update) => ({
+ id: update.id,
+ kind: 'patched',
+ patch: { isLocked: update.isLocked },
+ })),
+ }
+ );
+ }
+ }
+ };
+
const prepareSelect = (command: Extract<FlatDocumentCommand, { type: 'select' }>): PrepareFlatEditResult => {
if (command.id !== null && !index.byId.has(command.id)) {
return missing([command.id]);
@@ -424,7 +642,7 @@ export const createFlatDocumentModel = (
}
return { lowerId: lower.id, status: 'eligible', upperId };
},
- compileLeaves: () => compileLeaves(document, index, previous),
+ compileLeaves: () => compileLeaves(document, index, previousDocument),
document,
getLayer: (id) => index.byId.get(id)?.layer ?? null,
getStack: (kind) => index.stacks[kind],
@@ -442,6 +660,14 @@ export const createFlatDocumentModel = (
return prepareReorder(command.stacks);
case 'patch':
return preparePatch(command);
+ case 'patch-config':
+ return preparePatchConfig(command);
+ case 'patch-source':
+ return preparePatchSource(command);
+ case 'set-enabled':
+ case 'set-hidden':
+ case 'set-locked':
+ return prepareFlags(command);
case 'select':
return prepareSelect(command);
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
index 5d75ca5af2..b8f431d55e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/postconditions.ts
@@ -1,7 +1,12 @@
-import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type {
+ CanvasDocumentContractV2,
+ CanvasLayerContract,
+ CanvasLayerSourceContract,
+} from '@workbench/canvas-engine/contracts';
import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
-import type { CanvasLayerBasePatch } from '@workbench/canvas-engine/mutationContracts';
+import type { CanvasLayerBasePatch, CanvasLayerConfigPatch } from '@workbench/canvas-engine/mutationContracts';
+import { isLayerHidden } from '@workbench/canvas-engine/document/layerEligibility';
import { getStackOrder } from '@workbench/canvas-engine/document/layerStacks';
/** What a document must show after a prepared edit landed; evaluated against the reducer document. */
@@ -10,9 +15,34 @@ export type FlatEditPostcondition =
| { readonly kind: 'absent'; readonly ids: readonly string[] }
| { readonly kind: 'stack-order'; readonly stack: LayerStackKind; readonly orderedIds: readonly string[] }
| { readonly kind: 'selection'; readonly id: string | null }
- | { readonly kind: 'patched'; readonly id: string; readonly patch: CanvasLayerBasePatch };
+ | { readonly kind: 'patched'; readonly id: string; readonly patch: CanvasLayerBasePatch }
+ | { readonly kind: 'config'; readonly id: string; readonly config: CanvasLayerConfigPatch }
+ | { readonly kind: 'source'; readonly id: string; readonly source: CanvasLayerSourceContract }
+ | { readonly kind: 'hidden'; readonly id: string; readonly isHidden: boolean };
-/** Whether every field named by `patch` already holds its patched value on `layer`. */
+const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null;
+
+/** Structural equality over the plain data a layer contract holds. */
+export const sameValue = (left: unknown, right: unknown): boolean => {
+ if (Object.is(left, right)) {
+ return true;
+ }
+ if (Array.isArray(left) || Array.isArray(right)) {
+ return (
+ Array.isArray(left) &&
+ Array.isArray(right) &&
+ left.length === right.length &&
+ left.every((item, index) => sameValue(item, right[index]))
+ );
+ }
+ if (!isRecord(left) || !isRecord(right)) {
+ return false;
+ }
+ const keys = Object.keys(left);
+ return keys.length === Object.keys(right).length && keys.every((key) => sameValue(left[key], right[key]));
+};
+
+/** Whether every field named by `patch` already holds its value on `layer`. */
export const isPatchApplied = (layer: CanvasLayerContract, patch: CanvasLayerBasePatch): boolean =>
(Object.keys(patch) as (keyof CanvasLayerBasePatch)[]).every((key) =>
key === 'transform'
@@ -22,6 +52,23 @@ export const isPatchApplied = (layer: CanvasLayerContract, patch: CanvasLayerBas
: layer[key] === patch[key]
);
+/** Whether every field named by `config` already holds its value; nested partials compare field by field. */
+export const isConfigApplied = (layer: CanvasLayerContract, config: CanvasLayerConfigPatch): boolean => {
+ if (layer.type !== config.layerType) {
+ return false;
+ }
+ const target = layer as unknown as Record<string, unknown>;
+ return Object.entries(config).every(([key, value]) => {
+ if (key === 'layerType') {
+ return true;
+ }
+ const current = target[key];
+ return isRecord(value) && isRecord(current) && (key === 'adapter' || key === 'mask')
+ ? Object.entries(value).every(([field, expected]) => sameValue(current[field], expected))
+ : sameValue(current, value);
+ });
+};
+
export const checkFlatEditPostconditions = (
document: CanvasDocumentContractV2,
postconditions: readonly FlatEditPostcondition[]
@@ -45,5 +92,17 @@ export const checkFlatEditPostconditions = (
const layer = document.layers.find((candidate) => candidate.id === postcondition.id);
return layer !== undefined && isPatchApplied(layer, postcondition.patch);
}
+ case 'config': {
+ const layer = document.layers.find((candidate) => candidate.id === postcondition.id);
+ return layer !== undefined && isConfigApplied(layer, postcondition.config);
+ }
+ case 'source': {
+ const layer = document.layers.find((candidate) => candidate.id === postcondition.id);
+ return layer !== undefined && 'source' in layer && layer.source === postcondition.source;
+ }
+ case 'hidden': {
+ const layer = document.layers.find((candidate) => candidate.id === postcondition.id);
+ return layer !== undefined && isLayerHidden(layer) === postcondition.isHidden;
+ }
}
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 7532b4330a..3d874f92ee 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -109,6 +109,10 @@ import { RenderController } from '@workbench/canvas-engine/controllers/renderCon
import { StagedResultController } from '@workbench/canvas-engine/controllers/stagedResultController';
import { StructuralLayerController } from '@workbench/canvas-engine/controllers/structuralLayerController';
import { createCanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
+import {
+ createFlatDocumentModel,
+ type FlatCanvasDocumentModel,
+} from '@workbench/canvas-engine/document-model/flatDocumentModel';
import {
createEngineStores,
type EngineStores,
@@ -2865,12 +2869,28 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
hasExportableLayerContent,
isLayerExportGuardCurrent,
};
+ let documentModel: FlatCanvasDocumentModel | null = null;
+ const currentDocumentModel = (): FlatCanvasDocumentModel | null => {
+ const document = mutationPort.getCanvasState()?.document ?? null;
+ if (!document) {
+ return null;
+ }
+ if (documentModel?.document !== document) {
+ documentModel = createFlatDocumentModel(
+ document,
+ { editRevision: mutationContext.getEditRevision(), projectId },
+ documentModel
+ );
+ }
+ return documentModel;
+ };
const documentCapability: CanvasDocumentCapability = {
captureInsertionAnchor,
captureRestoreAnchor: (layerId) => mutationContext.captureRestoreAnchor(layerId),
captureSnapshot: captureDocumentSnapshot,
getDocument: () => mirror.getDocument(),
getEditRevision: () => mutationContext.getEditRevision(),
+ model: currentDocumentModel,
};
const selectionCapability: CanvasEngineSelectionCapability = {
deselect,
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 9868078245..1b32350cba 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
@@ -2,7 +2,6 @@ import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import { haveSameStackOrders } from '@workbench/canvas-engine/api';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
-import { deleteLayerActions, deleteLayersActions } from '@workbench/canvasLayerOps';
import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';
import { createCanvasProjectMutationPort } from '@workbench/canvasProjectMutationPort';
import { createInpaintMaskLayer } from '@workbench/widgets/layers/layerOps';
@@ -51,8 +50,11 @@ describe('layer restore through history on an interleaved document', () => {
expect(duplicated.status).toBe('duplicated');
const r0 = document().layers.find((layer) => layer.id === 'r0')!;
- const actions = deleteLayerActions(r0, engine.document)!;
- expect(engine.layers.commitStructural('Delete', actions.forward, actions.inverse).status).toBe('committed');
+ const remove = engine.document.model()!.prepare({ ids: ['r0'], type: 'remove' });
+ if (remove.status !== 'prepared') {
+ throw new Error('expected a prepared removal');
+ }
+ expect(engine.layers.commitPrepared('Delete', remove.edit).status).toBe('committed');
expect(document().layers.some((layer) => layer.id === 'r0')).toBe(false);
engine.history.undo();
@@ -76,8 +78,11 @@ describe('layer restore through history on an interleaved document', () => {
}
const duplicateId = duplicated.duplicateIds[0]!;
- const actions = deleteLayersActions(document().layers, [duplicateId, 'r0'], 'r0', engine.document)!;
- expect(engine.layers.commitStructural('Delete', actions.forward, actions.inverse).status).toBe('committed');
+ const remove = engine.document.model()!.prepare({ ids: [duplicateId, 'r0'], type: 'remove' });
+ if (remove.status !== 'prepared') {
+ throw new Error('expected a prepared removal');
+ }
+ expect(engine.layers.commitPrepared('Delete', remove.edit).status).toBe('committed');
expect(document().layers.map((layer) => layer.id)).toEqual(['m1', 'r1']);
engine.history.undo();
diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts
deleted file mode 100644
index b13be47a24..0000000000
--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
-
-import { captureRestoreAnchor } from '@workbench/canvas-engine/api';
-import { describe, expect, it } from 'vitest';
-
-import { deleteLayerActions, deleteLayersActions, duplicateLayerActions, reorderLayerActions } from './canvasLayerOps';
-
-const layer = (id: string): CanvasLayerContract => ({
- blendMode: 'normal',
- id,
- isEnabled: true,
- isLocked: false,
- name: id,
- opacity: 1,
- source: { bitmap: null, type: 'paint' },
- transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
- type: 'raster',
-});
-
-describe('duplicateLayerActions', () => {
- it('duplicates forward and removes the duplicate on undo', () => {
- expect(duplicateLayerActions('a', 'a-copy')).toEqual({
- forward: { newId: 'a-copy', sourceId: 'a', type: 'duplicateCanvasLayer' },
- inverse: { ids: ['a-copy'], type: 'removeCanvasLayers' },
- });
- });
-});
-
-let current: CanvasLayerContract[] = [];
-const anchors = {
- captureRestoreAnchor: (layerId: string) => captureRestoreAnchor(current, layerId, 'p', 0),
-};
-const restoreAnchor = (beforeId: string | null, afterId: string | null) => ({
- afterId,
- beforeId,
- capturedEditRevision: 0,
- projectId: 'p',
- stack: 'raster',
-});
-
-describe('deleteLayerActions', () => {
- it('removes forward and re-adds between the same-stack neighbours on undo', () => {
- current = [layer('a'), layer('b'), layer('c')];
- expect(deleteLayerActions(current[1]!, anchors)).toEqual({
- forward: { ids: ['b'], type: 'removeCanvasLayers' },
- inverse: {
- anchor: { afterId: 'a', beforeId: 'c', capturedEditRevision: 0, projectId: 'p', stack: 'raster' },
- layer: current[1],
- type: 'addCanvasLayer',
- },
- });
- });
-
- it('returns null for a layer that is not in the document', () => {
- current = [layer('a')];
- expect(deleteLayerActions(layer('ghost'), anchors)).toBeNull();
- });
-});
-
-describe('deleteLayersActions', () => {
- it('restores non-contiguous layers between their neighbours, top first, and the primary selection', () => {
- current = [layer('a'), layer('b'), layer('c'), layer('d')];
- expect(deleteLayersActions(current, ['c', 'a'], 'c', anchors)).toEqual({
- forward: { ids: ['a', 'c'], type: 'removeCanvasLayers' },
- inverse: {
- add: [
- { anchor: restoreAnchor('b', null), layers: [current[0]] },
- { anchor: restoreAnchor('d', 'b'), layers: [current[2]] },
- ],
- enabledUpdates: [],
- selectedLayerId: 'c',
- type: 'applyCanvasLayerStackMutation',
- },
- });
- });
-
- it('ignores absent ids and returns null when none exist', () => {
- current = [layer('a')];
- expect(deleteLayersActions(current, ['missing'], 'a', anchors)).toBeNull();
- });
-
- it('refuses to delete a selection containing a locked layer', () => {
- current = [layer('a'), { ...layer('b'), isLocked: true }];
- expect(deleteLayersActions(current, ['a', 'b'], 'a', anchors)).toBeNull();
- });
-
- it('refuses when a selected layer is missing from the engine document', () => {
- current = [layer('a')];
- expect(deleteLayersActions([layer('a'), layer('b')], ['a', 'b'], 'a', anchors)).toBeNull();
- });
-});
-
-describe('reorderLayerActions', () => {
- it("applies the stack commands forward and restores each stack's current order on undo", () => {
- const layers = [layer('a'), layer('b'), layer('c')];
- const command = { orderedIds: ['b', 'a', 'c'], stack: 'raster' as const };
-
- const stacks = [command];
- const actions = reorderLayerActions(layers, stacks);
-
- expect(actions).toEqual({
- forward: { stacks: [command], type: 'reorderCanvasLayerStacks' },
- inverse: { stacks: [{ orderedIds: ['a', 'b', 'c'], stack: 'raster' }], type: 'reorderCanvasLayerStacks' },
- });
- expect((actions.forward as { stacks: unknown }).stacks).not.toBe(stacks);
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts
deleted file mode 100644
index 63c81a15b0..0000000000
--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-/**
- * Pure builders for the structural document edits shared by the layers panel and
- * the canvas widget's layer hotkeys: each returns the forward + inverse reducer
- * action pair for `engine.layers.commitStructural`, so the
- * inverse-construction logic lives in exactly one place.
- *
- * Zero React, zero import-time side effects.
- */
-
-import type {
- CanvasDocumentCapability,
- CanvasLayerContract,
- FlatLayerInsertion,
- ReorderFlatStackCommand,
-} from '@workbench/canvas-engine/api';
-
-import { getStackOrder } from '@workbench/canvas-engine/api';
-
-import type { CanvasProjectMutation } from './canvasProjectMutations';
-
-/** A forward/inverse reducer-action pair for one reversible structural edit. */
-export interface StructuralActions {
- forward: CanvasProjectMutation;
- inverse: CanvasProjectMutation;
-}
-
-/** Mints a fresh layer id (matches the engine's / layers panel's id shape). */
-export const createLayerId = (): string => `layer-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
-
-/** Duplicate a layer (forward), removing the duplicate on undo (inverse). */
-export const duplicateLayerActions = (sourceId: string, newId: string): StructuralActions => ({
- forward: { newId, sourceId, type: 'duplicateCanvasLayer' },
- inverse: { ids: [newId], type: 'removeCanvasLayers' },
-});
-
-/** The engine surface that captures where deleted layers go back on undo. */
-export type InsertionAnchorSource = Pick<CanvasDocumentCapability, 'captureRestoreAnchor'>;
-
-/** Delete a layer (forward), re-adding it between its current same-stack neighbours on undo (inverse). */
-export const deleteLayerActions = (
- layer: CanvasLayerContract,
- anchors: InsertionAnchorSource
-): StructuralActions | null => {
- const anchor = anchors.captureRestoreAnchor(layer.id);
- return anchor
- ? {
- forward: { ids: [layer.id], type: 'removeCanvasLayers' },
- inverse: { anchor, layer, type: 'addCanvasLayer' },
- }
- : null;
-};
-
-/**
- * Delete every selected unlocked layer (forward), restoring each between its neighbours on undo
- * (inverse), top first so every anchor resolves. Null when nothing is selected, a selected layer is
- * locked, or a selected layer is missing from the engine document.
- */
-export const deleteLayersActions = (
- layers: readonly CanvasLayerContract[],
- selectedIds: readonly string[],
- selectedLayerId: string | null,
- anchors: InsertionAnchorSource
-): StructuralActions | null => {
- const selected = new Set(selectedIds);
- const removed = layers.filter((layer) => selected.has(layer.id));
- if (removed.length === 0 || removed.some((layer) => layer.isLocked)) {
- return null;
- }
- const add: FlatLayerInsertion[] = [];
- for (const layer of removed) {
- const anchor = anchors.captureRestoreAnchor(layer.id);
- if (!anchor) {
- return null;
- }
- add.push({ anchor, layers: [layer] });
- }
- return {
- forward: { ids: removed.map((layer) => layer.id), type: 'removeCanvasLayers' },
- inverse: { add, enabledUpdates: [], selectedLayerId, type: 'applyCanvasLayerStackMutation' },
- };
-};
-
-/** Apply the stack reorders (forward), restoring each stack's current order on undo (inverse). */
-export const reorderLayerActions = (
- layers: readonly CanvasLayerContract[],
- stacks: readonly ReorderFlatStackCommand[]
-): StructuralActions => ({
- forward: { stacks: [...stacks], type: 'reorderCanvasLayerStacks' },
- inverse: { stacks: stacks.map((command) => getStackOrder(layers, command.stack)), type: 'reorderCanvasLayerStacks' },
-});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index f6aa487847..ae6100708e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -58,7 +58,7 @@ import { ToolStrip } from './ToolStrip';
import { useCanvasEngine } from './useCanvasEngine';
import { useCanvasGallerySave } from './useCanvasGallerySave';
import { useCreateFromBbox } from './useCreateFromBbox';
-import { reportStructuralCommit } from './useStructuralCommit';
+import { reportPreparedCommit, reportStructuralCommit } from './useStructuralCommit';
/**
* The canvas widget shell. The engine owns pixels and interaction and renders
@@ -381,6 +381,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
notifyLayerDuplicateFailed: () =>
notifications.add({ kind: 'error', title: t('widgets.layers.actions.copyFailed') }),
pasteFromClipboard,
+ reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),
reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),
selectedLayerIds,
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 ddefb72320..23e630840e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -6,6 +6,7 @@ import type {
} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createFlatDocumentModel } from '@workbench/canvas-engine/api';
import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
@@ -51,6 +52,7 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {
projectId: 'project',
document: {
captureRestoreAnchor: () => stackTopAnchor('project'),
+ model: vi.fn(),
},
history: { redo: vi.fn(), undo: vi.fn() },
interaction: {
@@ -61,6 +63,7 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {
},
layers: {
clearMask: vi.fn(),
+ commitPrepared: vi.fn(() => ({ status: 'committed' as const })),
commitStructural: vi.fn(),
duplicateLayers: vi.fn(() =>
Promise.resolve<
@@ -93,6 +96,7 @@ let pasteFromClipboard: Mock<() => void>;
const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyContext => ({
copySelection,
dispatch,
+ reportPreparedCommit: () => undefined,
reportStructuralCommit: () => undefined,
document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a'),
engine: createEngine(),
@@ -108,6 +112,9 @@ const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyCo
const run = (commandId: string, overrides: Partial<CanvasHotkeyContext> = {}) => {
const ctx = contextOf(overrides);
+ (ctx.engine!.document.model as Mock).mockImplementation(() =>
+ createFlatDocumentModel(ctx.document, { editRevision: 0, projectId: 'project' })
+ );
executeCanvasHotkeyCommand(commandId, ctx);
return ctx.engine as ReturnType<typeof createEngine>;
};
@@ -139,7 +146,7 @@ describe('staging precedence', () => {
it('delete discards the selected staged candidate before touching layers', () => {
const engine = run('canvas.deleteSelected', { hasSelectedStagedCandidate: true });
expect(dispatch).toHaveBeenCalledWith({ type: 'discardSelectedStagedImage' });
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
expect(engine.selection.eraseSelection).not.toHaveBeenCalled();
});
@@ -168,7 +175,7 @@ describe('interaction lock', () => {
])('blocks %s', (commandId) => {
const engine = run(commandId, { isInteractionLocked: true });
expect(engine.tools.setTool).not.toHaveBeenCalled();
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
expect(engine.layers.nudgeSelectedLayer).not.toHaveBeenCalled();
expect(engine.history.undo).not.toHaveBeenCalled();
expect(engine.selection.selectAll).not.toHaveBeenCalled();
@@ -209,22 +216,21 @@ describe('layer reorder', () => {
document: documentOf([rasterLayer('a'), rasterLayer('b'), rasterLayer('c')], 'b'),
selectedLayerIds: ['b'],
});
- expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
'widgets.canvas.commands.reorderLayer',
- expect.anything(),
- expect.anything()
+ expect.objectContaining({ forward: expect.objectContaining({ type: 'reorderCanvasLayerStacks' }) })
);
}
);
it('is a no-op at the edge of the stack', () => {
const engine = run('canvas.layerToFront', { document: documentOf([rasterLayer('a'), rasterLayer('b')], 'a') });
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
it('is a no-op with no selected layer', () => {
const engine = run('canvas.layerBackward', { document: documentOf([rasterLayer('a')], null) });
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
it('is a no-op without an engine', () => {
@@ -243,22 +249,17 @@ describe('layer reorder', () => {
selectedLayerIds: ['c2', 'r2'],
});
- expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
'widgets.canvas.commands.reorderLayer',
- {
- stacks: [
- { orderedIds: ['c2', 'c1'], stack: 'control' },
- { orderedIds: ['r2', 'r1'], stack: 'raster' },
- ],
- type: 'reorderCanvasLayerStacks',
- },
- {
- stacks: [
- { orderedIds: ['c1', 'c2'], stack: 'control' },
- { orderedIds: ['r1', 'r2'], stack: 'raster' },
- ],
- type: 'reorderCanvasLayerStacks',
- }
+ expect.objectContaining({
+ forward: {
+ stacks: [
+ { orderedIds: ['c2', 'c1'], stack: 'control' },
+ { orderedIds: ['r2', 'r1'], stack: 'raster' },
+ ],
+ type: 'reorderCanvasLayerStacks',
+ },
+ })
);
});
});
@@ -267,16 +268,15 @@ 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.commitStructural).not.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.commitStructural).toHaveBeenCalledWith(
+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
'widgets.canvas.commands.deleteLayer',
- expect.anything(),
- expect.anything()
+ expect.objectContaining({ forward: { ids: ['a'], type: 'removeCanvasLayers' } })
);
});
@@ -284,12 +284,14 @@ describe('delete: pixels vs layer', () => {
const layers = [rasterLayer('a'), rasterLayer('b'), rasterLayer('c')];
const engine = run('canvas.deleteSelected', { document: documentOf(layers, 'a'), selectedLayerIds: ['a', 'c'] });
- expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
'widgets.canvas.commands.deleteLayer',
- { ids: ['a', 'c'], type: 'removeCanvasLayers' },
expect.objectContaining({
- add: [expect.objectContaining({ layers: [layers[0]] }), expect.objectContaining({ layers: [layers[2]] })],
- selectedLayerId: 'a',
+ forward: { ids: ['a', 'c'], type: 'removeCanvasLayers' },
+ inverse: expect.objectContaining({
+ add: [expect.objectContaining({ layers: [layers[0]] }), expect.objectContaining({ layers: [layers[2]] })],
+ selectedLayerId: 'a',
+ }),
})
);
});
@@ -300,13 +302,13 @@ describe('delete: pixels vs layer', () => {
selectedLayerIds: ['a', 'b'],
});
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
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.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
});
@@ -314,7 +316,7 @@ describe('duplicate: lift vs whole layer', () => {
it('lifts the pixel selection into a new layer when one exists', () => {
const engine = run('canvas.duplicateLayer', { engine: createEngine({ hasSelection: true }) });
expect(engine.selection.liftSelectionToLayer).toHaveBeenCalled();
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
it('duplicates the whole layer with no pixel selection', () => {
@@ -459,26 +461,30 @@ describe('mergeDown', () => {
describe('toggleNonRasterLayers', () => {
it('does nothing when there are no hideable layers', () => {
const engine = run('canvas.toggleNonRasterLayers');
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
it('hides all hideable layers when all are visible, and restores prior state on undo', () => {
const mask = rasterLayer('m', { type: 'inpaint_mask' } as Partial<CanvasLayerContract>);
const engine = run('canvas.toggleNonRasterLayers', { document: documentOf([rasterLayer('a'), mask], 'a') });
- expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
'widgets.canvas.commands.toggleNonRasterLayers',
- { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] },
- { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: false }] }
+ expect.objectContaining({
+ forward: { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] },
+ inverse: { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: false }] },
+ })
);
});
it('reveals hideable layers when any is already hidden', () => {
const mask = rasterLayer('m', { isHidden: true, type: 'inpaint_mask' } as Partial<CanvasLayerContract>);
const engine = run('canvas.toggleNonRasterLayers', { document: documentOf([rasterLayer('a'), mask], 'a') });
- expect(engine.layers.commitStructural).toHaveBeenCalledWith(
+ expect(engine.layers.commitPrepared).toHaveBeenCalledWith(
'widgets.canvas.commands.toggleNonRasterLayers',
- { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: false }] },
- { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] }
+ expect.objectContaining({
+ forward: { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: false }] },
+ inverse: { type: 'setCanvasLayersHidden', updates: [{ id: 'm', isHidden: true }] },
+ })
);
});
});
@@ -488,7 +494,7 @@ describe('robustness', () => {
const engine = run('canvas.nonexistent');
expect(dispatch).not.toHaveBeenCalled();
expect(engine.tools.setTool).not.toHaveBeenCalled();
- expect(engine.layers.commitStructural).not.toHaveBeenCalled();
+ expect(engine.layers.commitPrepared).not.toHaveBeenCalled();
});
it('never throws without an engine', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index a12412d945..16fd1b0b4c 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -6,9 +6,9 @@ import type {
} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
-import { isHideableLayer, isLayerHidden, moveLayersWithinStacks } from '@workbench/canvas-engine/api';
-import { deleteLayersActions, reorderLayerActions } from '@workbench/canvasLayerOps';
+import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';
import { publishLayerPanelSelection } from '@workbench/layerPanelState';
+import { commitPreparedEdit, type PreparedCommitOutcome } from '@workbench/widgets/canvas/useStructuralCommit';
import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
/** Command id → document-space nudge delta (shift variants are ×10). */
@@ -50,6 +50,7 @@ export interface CanvasHotkeyContext {
readonly pasteFromClipboard: () => void;
readonly notifyLayerDuplicateFailed: () => void;
readonly reportStructuralCommit: (result: StructuralCommitResult) => void;
+ readonly reportPreparedCommit: (outcome: PreparedCommitOutcome) => void;
readonly t: (key: string) => string;
}
@@ -100,19 +101,16 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
return;
}
- // Layer z-reorder: same forward/inverse construction as the layers panel.
+ // Layer z-reorder: the same prepared move the layers panel commits.
const reorderKind = REORDER_KINDS[commandId];
if (reorderKind) {
if (!engine || selectedIndex < 0) {
return;
}
- const stacks = moveLayersWithinStacks(layers, ctx.selectedLayerIds, reorderKind);
- if (stacks.length === 0) {
- return;
- }
- const { forward, inverse } = reorderLayerActions(layers, stacks);
- ctx.reportStructuralCommit(
- engine.layers.commitStructural(t('widgets.canvas.commands.reorderLayer'), forward, inverse)
+ ctx.reportPreparedCommit(
+ commitPreparedEdit(engine, t('widgets.canvas.commands.reorderLayer'), (model) =>
+ model.prepare({ ids: ctx.selectedLayerIds, kind: reorderKind, type: 'move' })
+ )
);
return;
}
@@ -123,11 +121,10 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
if (engine?.interaction.get('hasSelection')) {
engine.selection.eraseSelection();
} else if (engine && selectedLayer && selectedIndex >= 0 && !selectedLayer.isLocked) {
- const actions = deleteLayersActions(layers, ctx.selectedLayerIds, selectedLayer.id, engine.document);
- ctx.reportStructuralCommit(
- actions
- ? engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), actions.forward, actions.inverse)
- : { status: 'dispatch-rejected' }
+ ctx.reportPreparedCommit(
+ commitPreparedEdit(engine, t('widgets.canvas.commands.deleteLayer'), (model) =>
+ model.prepare({ ids: ctx.selectedLayerIds, type: 'remove' })
+ )
);
}
} else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {
@@ -140,17 +137,12 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
const hideable = layers.filter(isHideableLayer);
if (engine && hideable.length > 0) {
const nextHidden = hideable.every((layer) => !isLayerHidden(layer));
- ctx.reportStructuralCommit(
- engine.layers.commitStructural(
- t('widgets.canvas.commands.toggleNonRasterLayers'),
- {
- type: 'setCanvasLayersHidden',
+ ctx.reportPreparedCommit(
+ commitPreparedEdit(engine, t('widgets.canvas.commands.toggleNonRasterLayers'), (model) =>
+ model.prepare({
+ type: 'set-hidden',
updates: hideable.map((layer) => ({ id: layer.id, isHidden: nextHidden })),
- },
- {
- type: 'setCanvasLayersHidden',
- updates: hideable.map((layer) => ({ id: layer.id, isHidden: isLayerHidden(layer) })),
- }
+ })
)
);
}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx
index 9b83a437a2..fb0530c9d7 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx
@@ -5,7 +5,7 @@ import { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/reac
import { ColorPicker, Select } from '@platform/ui';
import { useGradientOptions } from '@workbench/widgets/canvas/engineStoreHooks';
import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -32,7 +32,7 @@ const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;
*/
export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const options = useGradientOptions(engine);
const sampleColor = useColorSampler(engine);
@@ -74,14 +74,12 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
if (selected && commit) {
const before = selected.source;
const after: GradientSource = { ...before, angle: next.angle, kind: next.kind, stops: next.stops };
- commitStructural(
- t('widgets.canvas.toolOptions.gradientEdit'),
- { id: selected.id, source: after, type: 'updateCanvasLayerSource' },
- { id: selected.id, source: before, type: 'updateCanvasLayerSource' }
+ commitPrepared(t('widgets.canvas.toolOptions.gradientEdit'), (model) =>
+ model.prepare({ id: selected.id, source: after, type: 'patch-source' })
);
}
},
- [commitStructural, engine, selected, t]
+ [commitPrepared, engine, selected, t]
);
const setStopColor = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx
index 12fa183c84..33f1f6b8f3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/MoveOptions.tsx
@@ -1,7 +1,7 @@
import type { NumberInput as ChakraNumberInput } from '@chakra-ui/react';
import { HStack, NumberInput, Text } from '@chakra-ui/react';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
@@ -22,7 +22,7 @@ interface SelectedTransform {
*/
export const MoveOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const selected = useActiveProjectSelector(
(project): SelectedTransform | null => {
const { document } = project.canvas;
@@ -39,15 +39,15 @@ export const MoveOptions = ({ engine }: ToolOptionsComponentProps) => {
if (!selected || next === selected[axis]) {
return;
}
- const forwardTransform = axis === 'x' ? { x: next } : { y: next };
- const inverseTransform = axis === 'x' ? { x: selected.x } : { y: selected.y };
- commitStructural(
- t('widgets.canvas.toolOptions.movePosition'),
- { id: selected.id, patch: { transform: forwardTransform }, type: 'updateCanvasLayer' },
- { id: selected.id, patch: { transform: inverseTransform }, type: 'updateCanvasLayer' }
+ commitPrepared(t('widgets.canvas.toolOptions.movePosition'), (model) =>
+ model.prepare({
+ id: selected.id,
+ patch: { transform: axis === 'x' ? { x: next } : { y: next } },
+ type: 'patch',
+ })
);
},
- [commitStructural, selected, t]
+ [commitPrepared, selected, t]
);
const onXChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
index 2225aa0ead..cc23a3fe21 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
@@ -6,7 +6,7 @@ import { ColorPicker, Select, ToggleIconButton } from '@platform/ui';
import { MAX_SHAPE_STROKE_WIDTH } from '@workbench/canvas-engine/api';
import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';
import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { PaintBucketIcon, SquareIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -37,7 +37,7 @@ const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;
*/
export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const options = useShapeOptions(engine);
const sampleColor = useColorSampler(engine);
@@ -85,14 +85,12 @@ export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {
if (selected && commit) {
const before = selected.source;
const after: ShapeSource = { ...before, ...patch };
- commitStructural(
- t('widgets.canvas.toolOptions.shapeEdit'),
- { id: selected.id, source: after, type: 'updateCanvasLayerSource' },
- { id: selected.id, source: before, type: 'updateCanvasLayerSource' }
+ commitPrepared(t('widgets.canvas.toolOptions.shapeEdit'), (model) =>
+ model.prepare({ id: selected.id, source: after, type: 'patch-source' })
);
}
},
- [commitStructural, engine, fill, kind, selected, stroke, strokeWidth, t]
+ [commitPrepared, engine, fill, kind, selected, stroke, strokeWidth, t]
);
const onKindChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx
index b60061433f..7a59c20782 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx
@@ -11,7 +11,7 @@ import {
} from '@workbench/canvas-engine/api';
import { useTextEditSession, useTextOptions } from '@workbench/widgets/canvas/engineStoreHooks';
import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -88,7 +88,7 @@ const AlignButton = ({
*/
export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const options = useTextOptions(engine);
const sampleColor = useColorSampler(engine);
const session = useTextEditSession(engine);
@@ -145,14 +145,12 @@ export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {
if (selected && commit) {
const before = selected.source;
const after: TextSource = { ...before, ...patch };
- commitStructural(
- t('widgets.canvas.toolOptions.textEdit'),
- { id: selected.id, source: after, type: 'updateCanvasLayerSource' },
- { id: selected.id, source: before, type: 'updateCanvasLayerSource' }
+ commitPrepared(t('widgets.canvas.toolOptions.textEdit'), (model) =>
+ model.prepare({ id: selected.id, source: after, type: 'patch-source' })
);
}
},
- [align, color, commitStructural, engine, fontFamily, fontSize, fontWeight, lineHeight, selected, session, t]
+ [align, color, commitPrepared, engine, fontFamily, fontSize, fontWeight, lineHeight, selected, session, t]
);
const onFamilyChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts
index ad682c10c2..efc87c13bc 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.test.ts
@@ -3,9 +3,17 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';
import type { TFunction } from 'i18next';
+import { createFlatDocumentModel } from '@workbench/canvas-engine/api';
+import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';
+import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
import { describe, expect, it, vi } from 'vitest';
-import { commitStructuralEdit, reportStructuralCommit } from './useStructuralCommit';
+import {
+ commitPreparedEdit,
+ commitStructuralEdit,
+ reportPreparedCommit,
+ reportStructuralCommit,
+} from './useStructuralCommit';
const forward: CanvasProjectMutation = { ids: ['a'], type: 'removeCanvasLayers' };
const inverse: CanvasProjectMutation = { id: 'a', type: 'setCanvasSelectedLayer' };
@@ -50,3 +58,65 @@ describe('reportStructuralCommit', () => {
expect(report).toHaveBeenCalledWith('widgets.canvas.structural.failed', message);
});
});
+
+describe('commitPreparedEdit', () => {
+ const layer = createEmptyPaintLayer('Layer', 'a');
+ const document = { ...createEmptyCanvasDocumentV2(), layers: [layer], selectedLayerId: 'a' };
+ const model = createFlatDocumentModel(document, { editRevision: 3, projectId: 'p' });
+
+ it('commits a prepared edit through the engine transaction', () => {
+ const commitPrepared = vi.fn(() => ({ status: 'committed' as const }));
+ const engine = { document: { model: () => model }, layers: { commitPrepared } };
+
+ expect(
+ commitPreparedEdit(engine, 'Rename', (m) => m.prepare({ id: 'a', patch: { name: 'B' }, type: 'patch' }))
+ ).toEqual({
+ status: 'committed',
+ });
+ expect(commitPrepared).toHaveBeenCalledWith(
+ 'Rename',
+ expect.objectContaining({ expectedRevision: 3, projectId: 'p' })
+ );
+ });
+
+ it('never dispatches a refusal or an unchanged command', () => {
+ const commitPrepared = vi.fn(() => ({ status: 'committed' as const }));
+ const engine = { document: { model: () => model }, layers: { commitPrepared } };
+
+ expect(commitPreparedEdit(engine, 'Delete', (m) => m.prepare({ ids: ['ghost'], type: 'remove' }))).toEqual({
+ refusal: { ids: ['ghost'], status: 'missing' },
+ status: 'refused',
+ });
+ expect(commitPreparedEdit(engine, 'Select', (m) => m.prepare({ id: 'a', type: 'select' }))).toEqual({
+ status: 'unchanged',
+ });
+ expect(commitPrepared).not.toHaveBeenCalled();
+ });
+
+ it('refuses as not-ready without an engine or a document', () => {
+ expect(commitPreparedEdit(null, 'Rename', () => ({ status: 'unchanged' }))).toEqual({ status: 'not-ready' });
+ const engine = { document: { model: () => null }, layers: { commitPrepared: vi.fn() } };
+ expect(commitPreparedEdit(engine, 'Rename', () => ({ status: 'unchanged' }))).toEqual({ status: 'not-ready' });
+ });
+});
+
+describe('reportPreparedCommit', () => {
+ const t = ((key: string) => key) as TFunction;
+
+ it('stays silent for unchanged and reports refusals with their own message', () => {
+ const reportError = vi.fn();
+ reportPreparedCommit({ status: 'unchanged' }, reportError, t);
+ expect(reportError).not.toHaveBeenCalled();
+ reportPreparedCommit({ refusal: { ids: ['a'], status: 'locked' }, status: 'refused' }, reportError, t);
+ expect(reportError).toHaveBeenLastCalledWith(
+ 'widgets.canvas.structural.failed',
+ 'widgets.canvas.structural.refusedLocked'
+ );
+ });
+
+ it('forwards transaction outcomes to the structural reporter', () => {
+ const reportError = vi.fn();
+ reportPreparedCommit({ status: 'stale', actualRevision: 2, expectedRevision: 1 }, reportError, t);
+ expect(reportError).toHaveBeenCalledWith('widgets.canvas.structural.failed', 'widgets.canvas.structural.stale');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
index da0dd59ead..81eb2600a5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useStructuralCommit.ts
@@ -1,4 +1,12 @@
-import type { CanvasStructuralEngine, StructuralCommitResult } from '@workbench/canvas-engine/api';
+import type {
+ CanvasDocumentCapability,
+ CanvasLayerCapability,
+ CanvasStructuralEngine,
+ FlatCanvasDocumentModel,
+ FlatDocumentRefusal,
+ PrepareFlatEditResult,
+ StructuralCommitResult,
+} from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { TFunction } from 'i18next';
@@ -76,3 +84,79 @@ export const useStructuralCommit = (engine: CanvasStructuralEngine | null): Stru
[engine, notify, t]
);
};
+
+/** The engine surface a prepared edit needs: the document model and the transaction. */
+export interface CanvasPreparedEngine {
+ readonly document: Pick<CanvasDocumentCapability, 'model'>;
+ readonly layers: Pick<CanvasLayerCapability, 'commitPrepared'>;
+}
+
+export type PreparedCommitOutcome =
+ | StructuralCommitResult
+ | { status: 'refused'; refusal: FlatDocumentRefusal }
+ | { status: 'unchanged' };
+
+/** Prepares an edit against the engine's current model and commits it; refusals and no-ops never dispatch. */
+export const commitPreparedEdit = (
+ engine: CanvasPreparedEngine | null,
+ label: string,
+ prepare: (model: FlatCanvasDocumentModel) => PrepareFlatEditResult
+): PreparedCommitOutcome => {
+ const model = engine?.document.model() ?? null;
+ if (!engine || !model) {
+ return { status: 'not-ready' };
+ }
+ const result = prepare(model);
+ switch (result.status) {
+ case 'prepared':
+ return engine.layers.commitPrepared(label, result.edit);
+ case 'unchanged':
+ return result;
+ default:
+ return { refusal: result, status: 'refused' };
+ }
+};
+
+const REFUSAL_KEYS: Record<FlatDocumentRefusal['status'], string> = {
+ 'invalid-target': 'widgets.canvas.structural.refusedInvalidTarget',
+ locked: 'widgets.canvas.structural.refusedLocked',
+ missing: 'widgets.canvas.structural.refusedMissing',
+ unsupported: 'widgets.canvas.structural.refusedUnsupported',
+ 'wrong-type': 'widgets.canvas.structural.refusedWrongType',
+};
+
+export const reportPreparedCommit = (
+ outcome: PreparedCommitOutcome,
+ reportError: (title: string, message: string) => void,
+ t: TFunction
+): void => {
+ if (outcome.status === 'unchanged') {
+ return;
+ }
+ if (outcome.status === 'refused') {
+ reportError(t('widgets.canvas.structural.failed'), t(REFUSAL_KEYS[outcome.refusal.status]));
+ return;
+ }
+ reportStructuralCommit(outcome, reportError, t);
+};
+
+export type PreparedCommit = (
+ label: string,
+ prepare: (model: FlatCanvasDocumentModel) => PrepareFlatEditResult
+) => PreparedCommitOutcome;
+
+/** A widget-side prepared commit that reports every refusal the user needs to hear about. */
+export const usePreparedCommit = (engine: CanvasPreparedEngine | null): PreparedCommit => {
+ const notify = useNotify();
+ const { t } = useTranslation();
+
+ return useCallback(
+ (label, prepare) => {
+ const outcome = commitPreparedEdit(engine, label, prepare);
+
+ reportPreparedCommit(outcome, notify.error, t);
+ return outcome;
+ },
+ [engine, notify, t]
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 74d667eafc..b164195029 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -17,12 +17,11 @@ import { useModelsSelector } from '@features/models';
import { IconButton, MenuContent, RenameDialog, Tooltip } from '@platform/ui';
import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/api';
import { getCanvasOperations } from '@workbench/canvas-operations/api';
-import { deleteLayerActions, duplicateLayerActions, reorderLayerActions } from '@workbench/canvasLayerOps';
import { publishLayerPanelSelection, readLayerPanelState } from '@workbench/layerPanelState';
import { useNotify } from '@workbench/useNotify';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';
-import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import {
ArrowRightLeftIcon,
@@ -67,7 +66,6 @@ import {
getLayerContextMenuRenderEntries,
} from './layerContextMenuLayout';
import { copyBlobToClipboard, saveLayerToAssets } from './layerExportActions';
-import { reorderWithinGroupByKind } from './layerGroups';
import { resolveMenuTargetForRender } from './layerMenuState';
import {
convertRasterToControl,
@@ -155,7 +153,6 @@ interface LayerMenuProps {
engine: LayerContextMenuEngine | null;
index: number;
layer: CanvasLayerContract;
- layers: readonly CanvasLayerContract[];
/** Where the menu opens: the panel anchors to its trigger; the canvas uses a
* virtual rect at the cursor. */
positioning: MenuPositioning;
@@ -196,7 +193,6 @@ const LayerMenu = ({
engine,
index,
layer,
- layers,
positioning,
withTrigger,
open,
@@ -208,7 +204,7 @@ const LayerMenu = ({
beforeDangerItems,
showGroupLabels,
}: LayerMenuProps) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
const projectId = useActiveProjectId();
const { widgets } = useWorkbenchCommands();
@@ -245,37 +241,24 @@ const LayerMenu = ({
);
const patchBase = useCallback(
- (label: string, forward: Partial<CanvasLayerContract>, inverse: Partial<CanvasLayerContract>) => {
- commitStructural(
- label,
- { id: layer.id, patch: forward, type: 'updateCanvasLayer' },
- { id: layer.id, patch: inverse, type: 'updateCanvasLayer' }
- );
+ (label: string, forward: Partial<CanvasLayerContract>) => {
+ commitPrepared(label, (model) => model.prepare({ id: layer.id, patch: forward, type: 'patch' }));
},
- [commitStructural, layer.id]
+ [commitPrepared, layer.id]
);
const patchConfig = useCallback(
- (label: string, forward: LayerConfigPatch, inverse: LayerConfigPatch) => {
- commitStructural(
- label,
- { config: forward, id: layer.id, type: 'updateCanvasLayerConfig' },
- { config: inverse, id: layer.id, type: 'updateCanvasLayerConfig' }
- );
+ (label: string, forward: LayerConfigPatch) => {
+ commitPrepared(label, (model) => model.prepare({ config: forward, id: layer.id, type: 'patch-config' }));
},
- [commitStructural, layer.id]
+ [commitPrepared, layer.id]
);
const reorder = useCallback(
(kind: LayerStackMoveKind, label: string) => {
- const next = reorderWithinGroupByKind(layers, layer.id, kind);
- if (!next) {
- return;
- }
- const { forward, inverse } = reorderLayerActions(layers, [next]);
- commitStructural(label, forward, inverse);
+ commitPrepared(label, (model) => model.prepare({ ids: [layer.id], kind, type: 'move' }));
},
- [commitStructural, layer.id, layers]
+ [commitPrepared, layer.id]
);
const actionState = useMemo<LayerContextActionState>(
@@ -346,18 +329,14 @@ const LayerMenu = ({
notify.error(t('widgets.layers.actions.actionFailed'), t('widgets.layers.actions.copyFailed'));
return;
}
- const { forward, inverse } = duplicateLayerActions(layer.id, createLayerId());
- commitStructural(t('widgets.layers.actions.duplicate'), forward, inverse);
- }, [commitStructural, document.selectedLayerId, engine, layer.id, notify, projectId, t]);
+ commitPrepared(t('widgets.layers.actions.duplicate'), (model) =>
+ model.prepare({ newId: createLayerId(), sourceId: layer.id, type: 'duplicate' })
+ );
+ }, [commitPrepared, document.selectedLayerId, engine, layer.id, notify, projectId, t]);
const handleDelete = useCallback(() => {
- const actions = engine ? deleteLayerActions(layer, engine.document) : null;
- if (!actions) {
- reportStructuralCommit({ status: engine ? 'dispatch-rejected' : 'not-ready' }, notify.error, t);
- return;
- }
- commitStructural(t('widgets.layers.actions.delete'), actions.forward, actions.inverse);
- }, [commitStructural, engine, layer, notify, t]);
+ commitPrepared(t('widgets.layers.actions.delete'), (model) => model.prepare({ ids: [layer.id], type: 'remove' }));
+ }, [commitPrepared, layer.id, t]);
const handleMerge = useCallback(() => {
// Pixel work: engine-only, and not recorded on the undo history.
@@ -414,15 +393,11 @@ const LayerMenu = ({
);
const handleToggleVisibility = useCallback(() => {
- patchBase(
- t('widgets.layers.actions.toggleVisibility'),
- { isEnabled: !layer.isEnabled },
- { isEnabled: layer.isEnabled }
- );
+ patchBase(t('widgets.layers.actions.toggleVisibility'), { isEnabled: !layer.isEnabled });
}, [layer.isEnabled, patchBase, t]);
const handleToggleLock = useCallback(() => {
- patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked }, { isLocked: layer.isLocked });
+ patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked });
}, [layer.isLocked, patchBase, t]);
const openRename = useCallback(() => setDialogKind('rename'), [setDialogKind]);
@@ -454,9 +429,9 @@ const LayerMenu = ({
);
const submitRename = useCallback(
(name: string) => {
- patchBase(t('widgets.layers.actions.rename'), { name }, { name: layer.name });
+ patchBase(t('widgets.layers.actions.rename'), { name });
},
- [layer.name, patchBase, t]
+ [patchBase, t]
);
const handleTransform = useCallback(() => {
@@ -469,7 +444,7 @@ const LayerMenu = ({
if (!transform) {
throw makeStatusError('empty');
}
- patchBase(getActionLabel('fit-to-bbox'), { transform }, { transform: layer.transform });
+ patchBase(getActionLabel('fit-to-bbox'), { transform });
}, [bbox, documentRect, getActionLabel, layer, makeStatusError, patchBase]);
const handleSaveToAssets = useCallback(async () => {
@@ -621,26 +596,19 @@ const LayerMenu = ({
const handleLayerConfigAction = useCallback(
(id: LayerConfigPatchKind) => {
if (id === 'control-transparency-effect' && layer.type === 'control') {
- const { forward, inverse } = getControlTransparencyEffectPatch(layer);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getControlTransparencyEffectPatch(layer));
} else if (id === 'regional-positive-prompt' && layer.type === 'regional_guidance') {
- const { forward, inverse } = getRegionalGuidancePositivePromptPatch(layer);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getRegionalGuidancePositivePromptPatch(layer));
} else if (id === 'regional-negative-prompt' && layer.type === 'regional_guidance') {
- const { forward, inverse } = getRegionalGuidanceNegativePromptPatch(layer);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getRegionalGuidanceNegativePromptPatch(layer));
} else if (id === 'regional-reference-image' && layer.type === 'regional_guidance') {
- const { forward, inverse } = getRegionalGuidanceReferenceImagePatch(layer, base);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getRegionalGuidanceReferenceImagePatch(layer, base));
} else if (id === 'regional-auto-negative' && layer.type === 'regional_guidance') {
- const { forward, inverse } = getRegionalGuidanceAutoNegativePatch(layer);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getRegionalGuidanceAutoNegativePatch(layer));
} else if (id === 'inpaint-noise' && layer.type === 'inpaint_mask') {
- const { forward, inverse } = getInpaintNoisePatch(layer);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getInpaintNoisePatch(layer));
} else if (id === 'inpaint-denoise-limit' && layer.type === 'inpaint_mask') {
- const { forward, inverse } = getInpaintDenoiseLimitPatch(layer);
- patchConfig(getActionLabel(id), forward, inverse);
+ patchConfig(getActionLabel(id), getInpaintDenoiseLimitPatch(layer));
}
},
[base, getActionLabel, layer, patchConfig]
@@ -896,7 +864,6 @@ export const CanvasLayerContextMenu = ({
engine={engine}
index={index}
layer={layer}
- layers={layers}
lazyMount
// The menu itself is visible only while the live target is set; once a
// sibling dialog closes it (target → null), the subtree stays mounted.
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
index d42cc6a43b..8c1715f8a0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerGroupSection.tsx
@@ -12,9 +12,8 @@ import { restrictToParentElement, restrictToVerticalAxis } from '@dnd-kit/modifi
import { SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { IconButton, toaster, Tooltip } from '@platform/ui';
import { canMergeVisibleRasters } from '@workbench/canvas-engine/api';
-import { reorderLayerActions } from '@workbench/canvasLayerOps';
import { useCanvasDocumentEditingLocked } from '@workbench/widgets/canvas/engineStoreHooks';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectName } from '@workbench/WorkbenchContext';
import { ChevronDownIcon, EyeIcon, EyeOffIcon, FileDownIcon, LayersIcon, PlusIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -73,7 +72,7 @@ export const LayerGroupSection = ({
selectedIds,
selectedLayerId,
}: LayerGroupSectionProps) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
const editingLocked = useCanvasDocumentEditingLocked(engine);
@@ -103,10 +102,11 @@ export const LayerGroupSection = ({
if (!next) {
return;
}
- const { forward, inverse } = reorderLayerActions(layers, [next]);
- commitStructural(t('widgets.layers.actions.reorder'), forward, inverse);
+ commitPrepared(t('widgets.layers.actions.reorder'), (model) =>
+ model.prepare({ stacks: [next], type: 'reorder' })
+ );
},
- [commitStructural, editingLocked, layers, selectedIds, t]
+ [commitPrepared, editingLocked, layers, selectedIds, t]
);
const handleToggleCollapse = useCallback(() => onToggleCollapse(groupKey), [groupKey, onToggleCollapse]);
@@ -212,7 +212,7 @@ const GroupActions = ({
groupLayers: readonly CanvasLayerContract[];
layers: readonly CanvasLayerContract[];
}) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
const addLayer = useAddLayer();
const projectName = useActiveProjectName();
@@ -233,24 +233,20 @@ const GroupActions = ({
// not change the generated image. The raster group has no display axis, so
// it keeps toggling enablement.
if (groupVisibilityAxis(groupKey) === 'hidden') {
- const { forward, inverse } = planGroupHiddenToggle(groupLayers);
- if (forward.length === 0) {
+ const { updates } = planGroupHiddenToggle(groupLayers);
+ if (updates.length === 0) {
return;
}
- commitStructural(
- t('widgets.layers.groupActions.toggleHidden'),
- { type: 'setCanvasLayersHidden', updates: forward },
- { type: 'setCanvasLayersHidden', updates: inverse }
+ commitPrepared(t('widgets.layers.groupActions.toggleHidden'), (model) =>
+ model.prepare({ type: 'set-hidden', updates })
);
return;
}
- const { forward, inverse } = planGroupVisibilityToggle(groupLayers);
- commitStructural(
- t('widgets.layers.groupActions.toggleVisibility'),
- { type: 'setCanvasLayersEnabled', updates: forward },
- { type: 'setCanvasLayersEnabled', updates: inverse }
+ const { updates } = planGroupVisibilityToggle(groupLayers);
+ commitPrepared(t('widgets.layers.groupActions.toggleVisibility'), (model) =>
+ model.prepare({ type: 'set-enabled', updates })
);
- }, [commitStructural, groupKey, groupLayers, t]);
+ }, [commitPrepared, groupKey, groupLayers, t]);
const handleMergeVisible = useCallback(() => {
if (!engine) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx
index 318be4ea0c..fdaaa8a275 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.browser.test.tsx
@@ -1,4 +1,5 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { PreparedFlatEdit } from '@workbench/canvas-engine/api';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { ChakraProvider } from '@chakra-ui/react';
@@ -13,6 +14,8 @@ import {
} from '@dnd-kit/core';
import { arrayMove, SortableContext, verticalListSortingStrategy } from '@dnd-kit/sortable';
import { system } from '@theme/system';
+import { createFlatDocumentModel } from '@workbench/canvas-engine/api';
+import { createEmptyCanvasDocumentV2 } from '@workbench/canvasMigration';
import { createLayerPanelState, selectLayerInPanel } from '@workbench/layerPanelState';
import { createInstance } from 'i18next';
import { act, useCallback, useMemo, useState } from 'react';
@@ -106,7 +109,18 @@ const Harness = () => {
const engine = useMemo(
() =>
({
+ document: {
+ model: () =>
+ createFlatDocumentModel(
+ { ...createEmptyCanvasDocumentV2(), layers, selectedLayerId: selection.primaryId },
+ { editRevision: 0, projectId: 'test-project' }
+ ),
+ },
layers: {
+ commitPrepared: (_label: string, edit: PreparedFlatEdit) => {
+ dispatch(edit.forward);
+ return { status: 'committed' as const };
+ },
commitStructural: (_label: string, mutation: CanvasProjectMutation) => {
dispatch(mutation);
return { status: 'committed' as const };
@@ -118,7 +132,7 @@ const Harness = () => {
},
projectId: 'test-project',
}) as unknown as LayerListItemEngine,
- [dispatch]
+ [dispatch, layers, selection.primaryId]
);
const handleDragEnd = useCallback((event: DragEndEvent) => {
if (!event.over || event.active.id === event.over.id) {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
index 4156e977a5..8207ffc5a1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerListItem.tsx
@@ -10,7 +10,7 @@ import { CSS } from '@dnd-kit/utilities';
import { IconButton, Row, ToggleDot } from '@platform/ui';
import { MiddleTruncate } from '@platform/ui/MiddleTruncate';
import { isHideableLayer, isLayerHidden } from '@workbench/canvas-engine/api';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { EyeIcon, EyeOffIcon, LockIcon, LockOpenIcon } from 'lucide-react';
import { useCallback, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
@@ -110,7 +110,7 @@ export const LayerListItem = ({
layers,
onSelect,
}: LayerListItemProps) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
const interaction = getLayerListItemInteractionState(editingLocked);
const { attributes, isDragging, listeners, setActivatorNodeRef, setNodeRef, transform, transition } = useSortable({
@@ -148,40 +148,34 @@ export const LayerListItem = ({
}, [isSelected, layer.id, onSelect]);
const patchBase = useCallback(
- (label: string, forward: Partial<CanvasLayerContract>, inverse: Partial<CanvasLayerContract>) => {
- commitStructural(
- label,
- { id: layer.id, patch: forward, type: 'updateCanvasLayer' },
- { id: layer.id, patch: inverse, type: 'updateCanvasLayer' }
- );
+ (label: string, forward: Partial<CanvasLayerContract>) => {
+ commitPrepared(label, (model) => model.prepare({ id: layer.id, patch: forward, type: 'patch' }));
},
- [commitStructural, layer.id]
+ [commitPrepared, layer.id]
);
const handleToggleVisible = useCallback(
(checked: boolean) => {
- patchBase(t('widgets.layers.actions.toggleVisibility'), { isEnabled: checked }, { isEnabled: layer.isEnabled });
+ patchBase(t('widgets.layers.actions.toggleVisibility'), { isEnabled: checked });
},
- [layer.isEnabled, patchBase, t]
+ [patchBase, t]
);
const handleToggleHidden = useCallback(
(event: { stopPropagation: () => void }) => {
event.stopPropagation();
const isHidden = !isLayerHidden(layer);
- commitStructural(
- t('widgets.layers.actions.toggleHidden'),
- { type: 'setCanvasLayersHidden', updates: [{ id: layer.id, isHidden }] },
- { type: 'setCanvasLayersHidden', updates: [{ id: layer.id, isHidden: !isHidden }] }
+ commitPrepared(t('widgets.layers.actions.toggleHidden'), (model) =>
+ model.prepare({ type: 'set-hidden', updates: [{ id: layer.id, isHidden }] })
);
},
- [commitStructural, layer, t]
+ [commitPrepared, layer, t]
);
const handleToggleLock = useCallback(
(event: { stopPropagation: () => void }) => {
event.stopPropagation();
- patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked }, { isLocked: layer.isLocked });
+ patchBase(t('widgets.layers.actions.toggleLock'), { isLocked: !layer.isLocked });
},
[layer.isLocked, patchBase, t]
);
@@ -195,7 +189,7 @@ export const LayerListItem = ({
setIsEditing(false);
const name = draftName.trim();
if (name && name !== layer.name) {
- patchBase(t('widgets.layers.actions.rename'), { name }, { name: layer.name });
+ patchBase(t('widgets.layers.actions.rename'), { name });
}
}, [draftName, layer.name, patchBase, t]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
index 6e847f7da6..21cf2a9524 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
@@ -6,15 +6,12 @@ import { IconButton } from '@platform/ui/Button';
import { Tooltip } from '@platform/ui/Tooltip';
import {
canMergeSelectedRasters,
- moveLayersWithinStacks,
type CanvasLayerContract,
type LayerStackMoveKind,
} from '@workbench/canvas-engine/api';
-import { deleteLayersActions, reorderLayerActions } from '@workbench/canvasLayerOps';
import { publishLayerPanelSelection } from '@workbench/layerPanelState';
-import { useNotify } from '@workbench/useNotify';
import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';
-import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import {
ArrowDownIcon,
ArrowUpIcon,
@@ -40,7 +37,6 @@ interface LayerMultiSelectionActionsProps {
layers: readonly CanvasLayerContract[];
projectId: string;
selectedIds: readonly string[];
- selectedLayerId: string | null;
}
export const LayerMultiSelectionActions = ({
@@ -49,11 +45,9 @@ export const LayerMultiSelectionActions = ({
layers,
projectId,
selectedIds,
- selectedLayerId,
}: LayerMultiSelectionActionsProps) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
- const notify = useNotify();
useCanvasRasterContentEpoch(engine);
const selected = useMemo(() => {
const ids = new Set(selectedIds);
@@ -106,14 +100,9 @@ export const LayerMultiSelectionActions = ({
const reorder = useCallback(
(kind: LayerStackMoveKind, label: string) => {
- const next = moveLayersWithinStacks(layers, selectedIds, kind);
- if (next.length === 0) {
- return;
- }
- const { forward, inverse } = reorderLayerActions(layers, next);
- commitStructural(label, forward, inverse);
+ commitPrepared(label, (model) => model.prepare({ ids: selectedIds, kind, type: 'move' }));
},
- [commitStructural, layers, selectedIds]
+ [commitPrepared, selectedIds]
);
const moveToFront = useCallback(
@@ -132,41 +121,25 @@ export const LayerMultiSelectionActions = ({
const toggleEnabled = useCallback(() => {
const isEnabled = !allEnabled;
- commitStructural(
+ commitPrepared(
t(isEnabled ? 'widgets.layers.actions.enableSelected' : 'widgets.layers.actions.disableSelected'),
- { type: 'setCanvasLayersEnabled', updates: selected.map((layer) => ({ id: layer.id, isEnabled })) },
- {
- type: 'setCanvasLayersEnabled',
- updates: selected.map((layer) => ({ id: layer.id, isEnabled: layer.isEnabled })),
- }
+ (model) => model.prepare({ type: 'set-enabled', updates: selected.map((layer) => ({ id: layer.id, isEnabled })) })
);
- }, [allEnabled, commitStructural, selected, t]);
+ }, [allEnabled, commitPrepared, selected, t]);
const toggleLocked = useCallback(() => {
const isLocked = !allLocked;
- commitStructural(
+ commitPrepared(
t(isLocked ? 'widgets.layers.actions.lockSelected' : 'widgets.layers.actions.unlockSelected'),
- {
- enabledUpdates: [],
- lockedUpdates: selected.map((layer) => ({ id: layer.id, isLocked })),
- type: 'applyCanvasLayerStackMutation',
- },
- {
- enabledUpdates: [],
- lockedUpdates: selected.map((layer) => ({ id: layer.id, isLocked: layer.isLocked })),
- type: 'applyCanvasLayerStackMutation',
- }
+ (model) => model.prepare({ type: 'set-locked', updates: selected.map((layer) => ({ id: layer.id, isLocked })) })
);
- }, [allLocked, commitStructural, selected, t]);
+ }, [allLocked, commitPrepared, selected, t]);
const deleteSelected = useCallback(() => {
- const actions = engine ? deleteLayersActions(layers, selectedIds, selectedLayerId, engine.document) : null;
- if (!actions) {
- reportStructuralCommit({ status: engine ? 'dispatch-rejected' : 'not-ready' }, notify.error, t);
- return;
- }
- commitStructural(t('widgets.layers.actions.deleteSelected'), actions.forward, actions.inverse);
- }, [commitStructural, engine, layers, notify, selectedIds, selectedLayerId, t]);
+ commitPrepared(t('widgets.layers.actions.deleteSelected'), (model) =>
+ model.prepare({ ids: selectedIds, type: 'remove' })
+ );
+ }, [commitPrepared, selectedIds, t]);
return (
<HStack
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx
index 6a5b45c012..cbf2659456 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersPanelHeader.tsx
@@ -18,7 +18,7 @@ import {
readCanvasDenoisingStrength,
} from '@workbench/widgets/canvas/invoke/canvasStrength';
import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { getProjectWidgetValues } from '@workbench/widgetState';
import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useCallback, useMemo, useRef } from 'react';
@@ -27,7 +27,7 @@ import { useTranslation } from 'react-i18next';
import { DenoisingStrengthWave } from './DenoisingStrengthWave';
import { applyStructuralPreview, CANVAS_BLEND_MODES } from './layerOps';
-type LayersPanelHeaderEngine = Pick<CanvasEngineHandle, 'interaction' | 'layers'>;
+type LayersPanelHeaderEngine = Pick<CanvasEngineHandle, 'document' | 'interaction' | 'layers'>;
const STRENGTH_DEBOUNCE_MS = 250;
const SELECT_POSITIONING = { placement: 'bottom-start', sameWidth: true } as const;
@@ -101,7 +101,7 @@ const BlendModeControl = ({
engine: LayersPanelHeaderEngine | null;
layer: CanvasLayerContract | null;
}) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
const disabled = isLayerEditingDisabled(layer, editingLocked);
const blendMode = layer?.blendMode ?? 'normal';
@@ -120,13 +120,11 @@ const BlendModeControl = ({
if (!layer || !mode || mode === layer.blendMode) {
return;
}
- commitStructural(
- t('widgets.layers.actions.blendMode'),
- { id: layer.id, patch: { blendMode: mode }, type: 'updateCanvasLayer' },
- { id: layer.id, patch: { blendMode: layer.blendMode }, type: 'updateCanvasLayer' }
+ commitPrepared(t('widgets.layers.actions.blendMode'), (model) =>
+ model.prepare({ id: layer.id, patch: { blendMode: mode }, type: 'patch' })
);
},
- [commitStructural, layer, t]
+ [commitPrepared, layer, t]
);
return (
@@ -156,7 +154,7 @@ const OpacityRow = ({
engine: LayersPanelHeaderEngine | null;
layer: CanvasLayerContract | null;
}) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
// The uncommitted opacity edit: captured once per gesture. `before` is the
// pre-gesture value (the undo target); `latest` tracks the live value because
@@ -175,12 +173,15 @@ const OpacityRow = ({
if (!pending || pending.before === pending.latest) {
return;
}
- commitStructural(
- t('widgets.layers.actions.opacity'),
- { id: pending.id, patch: { opacity: pending.latest }, type: 'updateCanvasLayer' },
- { id: pending.id, patch: { opacity: pending.before }, type: 'updateCanvasLayer' }
+ commitPrepared(t('widgets.layers.actions.opacity'), (model) =>
+ model.prepare({
+ before: { opacity: pending.before },
+ id: pending.id,
+ patch: { opacity: pending.latest },
+ type: 'patch',
+ })
);
- }, [commitStructural, t]);
+ }, [commitPrepared, t]);
const handleOpacityChange = useCallback(
({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {
@@ -275,28 +276,22 @@ const MaskFillSwatch = ({
engine: LayersPanelHeaderEngine | null;
layer: MaskLayer;
}) => {
- const commitStructural = useStructuralCommit(engine);
+ const commitPrepared = usePreparedCommit(engine);
const { t } = useTranslation();
const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);
const fill = layer.mask.fill;
const patchFill = useCallback(
(next: CanvasMaskFillContract, before: CanvasMaskFillContract) => {
- const config =
- layer.type === 'inpaint_mask'
- ? ({ layerType: 'inpaint_mask', mask: { fill: next } } as const)
- : ({ layerType: 'regional_guidance', mask: { fill: next } } as const);
- const inverseConfig =
+ const configFor = (value: CanvasMaskFillContract) =>
layer.type === 'inpaint_mask'
- ? ({ layerType: 'inpaint_mask', mask: { fill: before } } as const)
- : ({ layerType: 'regional_guidance', mask: { fill: before } } as const);
- commitStructural(
- t('widgets.layers.maskFill.fill'),
- { config, id: layer.id, type: 'updateCanvasLayerConfig' },
- { config: inverseConfig, id: layer.id, type: 'updateCanvasLayerConfig' }
+ ? ({ layerType: 'inpaint_mask', mask: { fill: value } } as const)
+ : ({ layerType: 'regional_guidance', mask: { fill: value } } as const);
+ commitPrepared(t('widgets.layers.maskFill.fill'), (model) =>
+ model.prepare({ before: configFor(before), config: configFor(next), id: layer.id, type: 'patch-config' })
);
},
- [commitStructural, layer.id, layer.type, t]
+ [commitPrepared, layer.id, layer.type, t]
);
const handleColorChange = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index 03345f588b..d91d044073 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -80,7 +80,6 @@ export const LayersWidgetView = () => {
layers={layers}
projectId={projectId}
selectedIds={selectedIds}
- selectedLayerId={selectedLayerId}
/>
) : null}
{groups.length === 0 ? (
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts
index cf15f1fa50..45bbaf76c3 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.test.ts
@@ -97,31 +97,23 @@ describe('isGroupAllVisible', () => {
describe('planGroupVisibilityToggle', () => {
it('hides all when every layer is visible', () => {
const layers = [inpaint('a', true), inpaint('b', true)];
- const { forward, inverse, nextVisible } = planGroupVisibilityToggle(layers);
+ const { updates, nextVisible } = planGroupVisibilityToggle(layers);
expect(nextVisible).toBe(false);
- expect(forward).toEqual([
+ expect(updates).toEqual([
{ id: 'a', isEnabled: false },
{ id: 'b', isEnabled: false },
]);
// Inverse restores each layer's prior visibility verbatim (single undo entry).
- expect(inverse).toEqual([
- { id: 'a', isEnabled: true },
- { id: 'b', isEnabled: true },
- ]);
});
- it('shows all when any layer is hidden, preserving the mixed prior state in the inverse', () => {
+ it('shows all when any layer is hidden, toggling every layer to the shared target', () => {
const layers = [inpaint('a', true), inpaint('b', false)];
- const { forward, inverse, nextVisible } = planGroupVisibilityToggle(layers);
+ const { updates, nextVisible } = planGroupVisibilityToggle(layers);
expect(nextVisible).toBe(true);
- expect(forward).toEqual([
+ expect(updates).toEqual([
{ id: 'a', isEnabled: true },
{ id: 'b', isEnabled: true },
]);
- expect(inverse).toEqual([
- { id: 'a', isEnabled: true },
- { id: 'b', isEnabled: false },
- ]);
});
});
@@ -147,7 +139,7 @@ describe('planGroupHiddenToggle', () => {
it('hides every layer when all are currently shown', () => {
const plan = planGroupHiddenToggle([control('a'), control('b')]);
expect(plan.nextVisible).toBe(false);
- expect(plan.forward).toEqual([
+ expect(plan.updates).toEqual([
{ id: 'a', isHidden: true },
{ id: 'b', isHidden: true },
]);
@@ -156,20 +148,12 @@ describe('planGroupHiddenToggle', () => {
it('shows every layer when any is currently hidden', () => {
const plan = planGroupHiddenToggle([control('a', true), control('b')]);
expect(plan.nextVisible).toBe(true);
- expect(plan.forward).toEqual([
+ expect(plan.updates).toEqual([
{ id: 'a', isHidden: false },
{ id: 'b', isHidden: false },
]);
});
- it('restores each layer prior state verbatim, so undo is one entry', () => {
- const plan = planGroupHiddenToggle([control('a', true), control('b')]);
- expect(plan.inverse).toEqual([
- { id: 'a', isHidden: true },
- { id: 'b', isHidden: false },
- ]);
- });
-
it('never touches enablement — hiding must not change the generated image', () => {
const plan = planGroupHiddenToggle([control('a')]);
expect(JSON.stringify(plan)).not.toContain('isEnabled');
@@ -188,7 +172,7 @@ describe('planGroupHiddenToggle', () => {
type: 'raster',
};
const plan = planGroupHiddenToggle([raster, control('a')]);
- expect(plan.forward.map((update) => update.id)).toEqual(['a']);
+ expect(plan.updates.map((update) => update.id)).toEqual(['a']);
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts
index a0448ee6c0..6e8c7cd9b6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroupActions.ts
@@ -60,32 +60,23 @@ export const isGroupAllVisible = (
/**
* Plans a group show/hide-all toggle as ONE reversible bulk action: if every
* layer is currently visible, hide them all; otherwise show them all (legacy
- * `CanvasEntityType` toggle semantics). `forward` sets the shared target;
- * `inverse` restores each layer's prior state verbatim, so undo is a single
- * history entry.
+ * `CanvasEntityType` toggle semantics); the prepared edit restores each
+ * layer's prior state on undo.
*/
export const planGroupVisibilityToggle = (
groupLayers: readonly CanvasLayerContract[]
-): { forward: LayerVisibilityUpdate[]; inverse: LayerVisibilityUpdate[]; nextVisible: boolean } => {
+): { updates: LayerVisibilityUpdate[]; nextVisible: boolean } => {
const nextVisible = !isGroupAllVisible(groupLayers);
- return {
- forward: groupLayers.map((layer) => ({ id: layer.id, isEnabled: nextVisible })),
- inverse: groupLayers.map((layer) => ({ id: layer.id, isEnabled: layer.isEnabled })),
- nextVisible,
- };
+ return { nextVisible, updates: groupLayers.map((layer) => ({ id: layer.id, isEnabled: nextVisible })) };
};
/** The display-axis counterpart of {@link planGroupVisibilityToggle}. */
export const planGroupHiddenToggle = (
groupLayers: readonly CanvasLayerContract[]
-): { forward: LayerHiddenUpdate[]; inverse: LayerHiddenUpdate[]; nextVisible: boolean } => {
+): { updates: LayerHiddenUpdate[]; nextVisible: boolean } => {
const hideable = groupLayers.filter(isHideableLayer);
const nextVisible = !isGroupAllVisible(hideable, 'hidden');
- return {
- forward: hideable.map((layer) => ({ id: layer.id, isHidden: !nextVisible })),
- inverse: hideable.map((layer) => ({ id: layer.id, isHidden: isLayerHidden(layer) })),
- nextVisible,
- };
+ return { nextVisible, updates: hideable.map((layer) => ({ id: layer.id, isHidden: !nextVisible })) };
};
// Merge-visible contributor selection lives in the engine's document layer
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts
index 8272df7afc..ee10042d05 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.test.ts
@@ -7,13 +7,7 @@ import type {
import { describe, expect, it } from 'vitest';
-import {
- getGroupPosition,
- groupLayers,
- reorderSelectionWithinGroup,
- reorderWithinGroup,
- reorderWithinGroupByKind,
-} from './layerGroups';
+import { getGroupPosition, groupLayers, reorderSelectionWithinGroup, reorderWithinGroup } from './layerGroups';
import { createEmptyPaintLayer } from './layerOps';
const raster = (id: string): CanvasLayerContract => createEmptyPaintLayer(id, id);
@@ -152,51 +146,3 @@ describe('reorderSelectionWithinGroup', () => {
expect(reorderSelectionWithinGroup(layers, 'r1', 'r3', ['r1', 'r3'])).toBeNull();
});
});
-
-describe('reorderWithinGroupByKind', () => {
- const layers = [inpaint('i1'), raster('r1'), regional('g1'), raster('r2'), raster('r3')];
-
- it('moves to front (top of the group)', () => {
- expect(reorderWithinGroupByKind(layers, 'r3', 'front')).toEqual({
- orderedIds: ['r3', 'r1', 'r2'],
- stack: 'raster',
- });
- });
-
- it('moves to back (bottom of the group)', () => {
- expect(reorderWithinGroupByKind(layers, 'r1', 'back')).toEqual({ orderedIds: ['r2', 'r3', 'r1'], stack: 'raster' });
- });
-
- it('moves forward one within the group', () => {
- expect(reorderWithinGroupByKind(layers, 'r2', 'forward')).toEqual({
- orderedIds: ['r2', 'r1', 'r3'],
- stack: 'raster',
- });
- });
-
- it('moves backward one within the group', () => {
- expect(reorderWithinGroupByKind(layers, 'r1', 'backward')).toEqual({
- orderedIds: ['r2', 'r1', 'r3'],
- stack: 'raster',
- });
- });
-
- it('is a no-op at the group front boundary (forward)', () => {
- expect(reorderWithinGroupByKind(layers, 'r1', 'forward')).toBeNull();
- expect(reorderWithinGroupByKind(layers, 'r1', 'front')).toBeNull();
- });
-
- it('is a no-op at the group back boundary (backward)', () => {
- expect(reorderWithinGroupByKind(layers, 'r3', 'backward')).toBeNull();
- expect(reorderWithinGroupByKind(layers, 'r3', 'back')).toBeNull();
- });
-
- it('is a no-op for a lone group member', () => {
- expect(reorderWithinGroupByKind(layers, 'i1', 'front')).toBeNull();
- expect(reorderWithinGroupByKind(layers, 'i1', 'back')).toBeNull();
- });
-
- it('returns null for an absent id', () => {
- expect(reorderWithinGroupByKind(layers, 'ghost', 'front')).toBeNull();
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts
index 85ca966586..bd509f5bc6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerGroups.ts
@@ -1,16 +1,6 @@
-import type {
- CanvasLayerContract,
- LayerStackKind,
- LayerStackMoveKind,
- ReorderFlatStackCommand,
-} from '@workbench/canvas-engine/api';
+import type { CanvasLayerContract, LayerStackKind, ReorderFlatStackCommand } from '@workbench/canvas-engine/api';
-import {
- getStackOrder,
- LAYER_STACKS_TOP_FIRST,
- layerStackOf,
- moveLayersWithinStacks,
-} from '@workbench/canvas-engine/api';
+import { getStackOrder, LAYER_STACKS_TOP_FIRST, layerStackOf } from '@workbench/canvas-engine/api';
import { moveItem } from './layersDnd';
@@ -129,10 +119,3 @@ export const reorderSelectionWithinGroup = (
return [...remaining.slice(0, insertAt), ...moving, ...remaining.slice(insertAt)];
});
};
-
-/** Moves `layerId` within its own stack; null when it is absent or already at the boundary. */
-export const reorderWithinGroupByKind = (
- layers: readonly CanvasLayerContract[],
- layerId: string,
- kind: LayerStackMoveKind
-): ReorderFlatStackCommand | null => moveLayersWithinStacks(layers, [layerId], kind)[0] ?? null;
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
index f34093bc6c..5ab0b8cd56 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts
@@ -441,41 +441,29 @@ describe('menu patch helpers', () => {
it('builds control transparency effect patches', () => {
const layer = createControlLayer('control', 'c1');
- expect(getControlTransparencyEffectPatch(layer)).toEqual({
- forward: { layerType: 'control', withTransparencyEffect: false },
- inverse: { layerType: 'control', withTransparencyEffect: true },
- });
+ expect(getControlTransparencyEffectPatch(layer)).toEqual({ layerType: 'control', withTransparencyEffect: false });
});
it('builds regional prompt and reference image patches', () => {
const layer = createRegionalGuidanceLayer('region', 0, 'r1');
expect(getRegionalGuidancePositivePromptPatch(layer)).toEqual({
- forward: { layerType: 'regional_guidance', positivePrompt: '' },
- inverse: { layerType: 'regional_guidance', positivePrompt: null },
+ layerType: 'regional_guidance',
+ positivePrompt: '',
});
expect(getRegionalGuidanceNegativePromptPatch(layer)).toEqual({
- forward: { layerType: 'regional_guidance', negativePrompt: '' },
- inverse: { layerType: 'regional_guidance', negativePrompt: null },
- });
- expect(getRegionalGuidanceAutoNegativePatch(layer)).toEqual({
- forward: { autoNegative: true, layerType: 'regional_guidance' },
- inverse: { autoNegative: false, layerType: 'regional_guidance' },
+ layerType: 'regional_guidance',
+ negativePrompt: '',
});
- expect(getRegionalGuidanceReferenceImagePatch(layer, 'sdxl').forward.referenceImages).toHaveLength(1);
+ expect(getRegionalGuidanceAutoNegativePatch(layer)).toEqual({ autoNegative: true, layerType: 'regional_guidance' });
+ expect(getRegionalGuidanceReferenceImagePatch(layer, 'sdxl').referenceImages).toHaveLength(1);
});
it('builds inpaint modifier patches', () => {
const layer = createInpaintMaskLayer('mask', 'm1');
- expect(getInpaintNoisePatch(layer)).toEqual({
- forward: { layerType: 'inpaint_mask', noiseLevel: 0.25 },
- inverse: { layerType: 'inpaint_mask', noiseLevel: undefined },
- });
- expect(getInpaintDenoiseLimitPatch(layer)).toEqual({
- forward: { denoiseLimit: 0.8, layerType: 'inpaint_mask' },
- inverse: { denoiseLimit: undefined, layerType: 'inpaint_mask' },
- });
+ expect(getInpaintNoisePatch(layer)).toEqual({ layerType: 'inpaint_mask', noiseLevel: 0.25 });
+ expect(getInpaintDenoiseLimitPatch(layer)).toEqual({ denoiseLimit: 0.8, layerType: 'inpaint_mask' });
});
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
index e49baddcf9..b6aa8d2616 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts
@@ -38,8 +38,6 @@ type RegionalGuidanceConfigPatch = {
referenceImages?: CanvasRegionalGuidanceLayerContract['referenceImages'];
};
type InpaintMaskConfigPatch = { layerType: 'inpaint_mask'; noiseLevel?: number; denoiseLimit?: number };
-type PatchPair<T> = { forward: T; inverse: T };
-
/**
* Re-exported so existing imports of `isMergeableRasterLayer` from this module
* keep working; the canonical definition lives in the engine's `document/sources`
@@ -369,55 +367,39 @@ export const fitLayerTransformToBbox = (
};
};
-export const getControlTransparencyEffectPatch = (
- layer: CanvasControlLayerContract
-): PatchPair<ControlConfigPatch> => ({
- forward: { layerType: 'control', withTransparencyEffect: !layer.withTransparencyEffect },
- inverse: { layerType: 'control', withTransparencyEffect: layer.withTransparencyEffect },
+export const getControlTransparencyEffectPatch = (layer: CanvasControlLayerContract): ControlConfigPatch => ({
+ layerType: 'control',
+ withTransparencyEffect: !layer.withTransparencyEffect,
});
export const getRegionalGuidancePositivePromptPatch = (
layer: CanvasRegionalGuidanceLayerContract
-): PatchPair<RegionalGuidanceConfigPatch> => ({
- forward: { layerType: 'regional_guidance', positivePrompt: layer.positivePrompt ?? '' },
- inverse: { layerType: 'regional_guidance', positivePrompt: layer.positivePrompt },
-});
+): RegionalGuidanceConfigPatch => ({ layerType: 'regional_guidance', positivePrompt: layer.positivePrompt ?? '' });
export const getRegionalGuidanceNegativePromptPatch = (
layer: CanvasRegionalGuidanceLayerContract
-): PatchPair<RegionalGuidanceConfigPatch> => ({
- forward: { layerType: 'regional_guidance', negativePrompt: layer.negativePrompt ?? '' },
- inverse: { layerType: 'regional_guidance', negativePrompt: layer.negativePrompt },
-});
+): RegionalGuidanceConfigPatch => ({ layerType: 'regional_guidance', negativePrompt: layer.negativePrompt ?? '' });
export const getRegionalGuidanceAutoNegativePatch = (
layer: CanvasRegionalGuidanceLayerContract
-): PatchPair<RegionalGuidanceConfigPatch> => ({
- forward: { autoNegative: !layer.autoNegative, layerType: 'regional_guidance' },
- inverse: { autoNegative: layer.autoNegative, layerType: 'regional_guidance' },
-});
+): RegionalGuidanceConfigPatch => ({ autoNegative: !layer.autoNegative, layerType: 'regional_guidance' });
export const getRegionalGuidanceReferenceImagePatch = (
layer: CanvasRegionalGuidanceLayerContract,
base: string | null
-): PatchPair<RegionalGuidanceConfigPatch> => ({
- forward: {
- layerType: 'regional_guidance',
- referenceImages: [...layer.referenceImages, createRegionalReferenceImage(base)],
- },
- inverse: { layerType: 'regional_guidance', referenceImages: layer.referenceImages },
+): RegionalGuidanceConfigPatch => ({
+ layerType: 'regional_guidance',
+ referenceImages: [...layer.referenceImages, createRegionalReferenceImage(base)],
});
-export const getInpaintNoisePatch = (layer: CanvasInpaintMaskLayerContract): PatchPair<InpaintMaskConfigPatch> => ({
- forward: { layerType: 'inpaint_mask', noiseLevel: layer.noiseLevel === undefined ? 0.25 : undefined },
- inverse: { layerType: 'inpaint_mask', noiseLevel: layer.noiseLevel },
+export const getInpaintNoisePatch = (layer: CanvasInpaintMaskLayerContract): InpaintMaskConfigPatch => ({
+ layerType: 'inpaint_mask',
+ noiseLevel: layer.noiseLevel === undefined ? 0.25 : undefined,
});
-export const getInpaintDenoiseLimitPatch = (
- layer: CanvasInpaintMaskLayerContract
-): PatchPair<InpaintMaskConfigPatch> => ({
- forward: { denoiseLimit: layer.denoiseLimit === undefined ? 0.8 : undefined, layerType: 'inpaint_mask' },
- inverse: { denoiseLimit: layer.denoiseLimit, layerType: 'inpaint_mask' },
+export const getInpaintDenoiseLimitPatch = (layer: CanvasInpaintMaskLayerContract): InpaintMaskConfigPatch => ({
+ denoiseLimit: layer.denoiseLimit === undefined ? 0.8 : undefined,
+ layerType: 'inpaint_mask',
});
/**
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
index 86371e3e59..cbb9466a12 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
@@ -1,9 +1,8 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
import { useModelsSelector } from '@features/models';
-import { useNotify } from '@workbench/useNotify';
import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';
-import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { nextLayerName } from '@workbench/workbenchState';
import { useCallback } from 'react';
@@ -34,8 +33,7 @@ import { useSelectedModelBase } from './useSelectedModelBase';
export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
const { t } = useTranslation();
const engine = useCanvasEngine();
- const commitStructural = useStructuralCommit(engine);
- const notify = useNotify();
+ const commitPrepared = usePreparedCommit(engine);
const base = useSelectedModelBase();
const models = useModelsSelector((snapshot) => snapshot.models);
const layerNames = useActiveProjectSelector(
@@ -52,21 +50,8 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
return;
}
const add = (label: string, layer: CanvasLayerContract): void => {
- if (!engine) {
- reportStructuralCommit({ status: 'not-ready' }, notify.error, t);
- return;
- }
- commitStructural(
- label,
- {
- anchor: engine.document.captureInsertionAnchor(
- layer.type,
- engine.document.getDocument()?.selectedLayerId ?? null
- ),
- layer,
- type: 'addCanvasLayer',
- },
- { ids: [layer.id], type: 'removeCanvasLayers' }
+ commitPrepared(label, (model) =>
+ model.prepare({ aboveId: model.document.selectedLayerId, layers: [layer], type: 'insert' })
);
};
switch (id) {
@@ -106,6 +91,6 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
}
}
},
- [base, commitStructural, engine, layerNames, models, notify, regionalGuidanceCount, t]
+ [base, commitPrepared, layerNames, models, regionalGuidanceCount, t]
);
};