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): anchor layer insertion to stack neighbours instead of flat indices

Josh Corbett97fd7a16f93f
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts
index ea299861e0..a352e4749f 100644
--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.test.ts
@@ -95,7 +95,7 @@ describe('Canvas edit classification', () => {
expect(
isHighConfidenceCanvasEdit(
mutation({
- add: { index: 0, layers: [{}] },
+ add: [{ anchor: {}, layers: [{}] }],
enabledUpdates: [],
selectedLayerId: 'new-layer',
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
index fb1073903e..b54aa239d8 100644
--- a/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
+++ b/invokeai/frontend/webv2/src/workbench/autoRoutePolicy.ts
@@ -155,7 +155,7 @@ export const isHighConfidenceCanvasEdit = (mutation: CanvasProjectMutation): boo
if (mutation.type === 'applyCanvasLayerStackMutation') {
return (
- (mutation.add?.layers.length ?? 0) > 0 ||
+ (mutation.add?.some((insertion) => insertion.layers.length > 0) ?? false) ||
(mutation.removeIds?.length ?? 0) > 0 ||
mutation.enabledUpdates.length > 0
);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 8f0edd041a..f429fa2736 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 { FlatLayerInsertionAnchor } from './document/insertionAnchors';
+import type { LayerStackKind } from './document/layerStacks';
import type { CanvasEditGate } from './editGate';
import type {
BboxToolOptions,
@@ -146,6 +148,10 @@ export interface CanvasDocumentCapability {
* captured value can be refused as stale once anything else lands.
*/
getEditRevision(): number;
+ /** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */
+ 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;
}
/** Immutable reducer canvas state captured at one engine document generation. */
@@ -415,7 +421,12 @@ export interface CanvasEngineLayerCapability extends CanvasLayerCapability {
cancelTransform(): void;
clearMask(layerId: string): boolean;
commitLayerConversion(label: string, expectedLiveLayer: CanvasLayerContract, after: CanvasLayerContract): boolean;
- commitLayerCopy(label: string, sourceLayerId: string, layer: CanvasLayerContract, index: number): boolean;
+ commitLayerCopy(
+ label: string,
+ sourceLayerId: string,
+ layer: CanvasLayerContract,
+ anchor: FlatLayerInsertionAnchor
+ ): boolean;
commitMaskImageResult(options: CommitMaskImageResultOptions): Promise<CommitMaskImageResult>;
commitOpenTextSession(): boolean;
commitRasterFilterResult(options: CommitRasterFilterOptions): Promise<CommitRasterFilterResult>;
@@ -530,6 +541,7 @@ export { isLayerPixelEditEligible } from './editing/controlPixelEdit';
export { type HideableLayer, isHideableLayer, isLayerHidden } from './document/sources';
export {
getStackOrder,
+ haveSameStackOrders,
LAYER_STACK_ORDER,
LAYER_STACKS_TOP_FIRST,
layerStackOf,
@@ -549,6 +561,14 @@ export {
isPixelBackedLayer,
} from './document/layerEligibility';
export { repairSelectedLayerId } from './document/selectionRepair';
+export {
+ captureInsertionAnchor,
+ captureRestoreAnchor,
+ insertLayersAtAnchor,
+ resolveInsertionIndex,
+ type FlatLayerInsertion,
+ type FlatLayerInsertionAnchor,
+} from './document/insertionAnchors';
export { isExportableRasterLayer } from './layerExportGuards';
export {
getLayerThumbnailFallbackRenderState,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
index 8bb0653f37..ce9c1df62a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/booleanMergeController.ts
@@ -1,5 +1,7 @@
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
@@ -29,6 +31,7 @@ export interface BooleanMergeControllerOptions<Permit> {
readonly exportBaked: (layerId: string) => Promise<ExportResult>;
readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
readonly createLayerId: () => string;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly dispatchPrepared: (
action: CanvasProjectMutation,
expectedReducer: () => boolean,
@@ -161,13 +164,14 @@ export class BooleanMergeController<Permit> {
];
const disabled = original.map(({ id }) => ({ id, isEnabled: false }));
const selectedLayerId = liveDocument.selectedLayerId;
+ const anchor = this.deps.captureInsertionAnchor('raster', upper.id);
const hasState = (doc: CanvasDocumentContractV2 | null, updates: typeof original): boolean =>
updates.every((update) => doc?.layers.find((layer) => layer.id === update.id)?.isEnabled === update.isEnabled);
const apply = (): void => {
const prepared = this.deps.preparePixels(resultId, resultRect, pixels);
this.deps.dispatchPrepared(
{
- add: { index: liveIndex, layers: [resultLayer] },
+ add: [{ anchor, layers: [resultLayer] }],
enabledUpdates: disabled,
selectedLayerId: resultId,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
index 05041f6017..b8a6099206 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/copyLayerController.ts
@@ -1,5 +1,7 @@
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
@@ -21,6 +23,7 @@ export interface CopyLayerControllerOptions<Permit> {
readonly exportBaked: (layerId: string) => Promise<ExportResult>;
readonly isGuardCurrent: (guard: LayerExportGuard) => boolean;
readonly createLayerId: () => string;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;
readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;
readonly dispatchPrepared: (
@@ -58,8 +61,7 @@ export class CopyLayerController<Permit> {
return null;
}
const liveDocument = this.deps.getDocument();
- const sourceIndex = liveDocument?.layers.findIndex((layer) => layer.id === layerId) ?? -1;
- if (!liveDocument || liveDocument.layers[sourceIndex] !== sourceLayer || sourceIndex < 0) {
+ if (!liveDocument || !liveDocument.layers.includes(sourceLayer)) {
return null;
}
const newId = this.deps.createLayerId();
@@ -75,11 +77,12 @@ export class CopyLayerController<Permit> {
type: 'raster',
};
const selectedLayerId = liveDocument.selectedLayerId;
+ const anchor = this.deps.captureInsertionAnchor('raster', layerId);
const apply = (): void => {
const prepared = this.deps.preparePixels(newId, baked.rect, baked.surface);
this.deps.dispatchPrepared(
{
- add: { index: sourceIndex, layers: [layer] },
+ add: [{ anchor, layers: [layer] }],
enabledUpdates: [],
selectedLayerId: newId,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
index e1d2bba192..6ff5e139c9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/editingController.test.ts
@@ -1,5 +1,6 @@
import type { SelectionState, SelectionStateDeps } from '@workbench/canvas-engine/selection/selectionState';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { describe, expect, it, vi } from 'vitest';
import { EditingController } from './editingController';
@@ -20,6 +21,7 @@ const createSelection = (): SelectionState => ({
const createTextOptions = () => ({
canEdit: () => true,
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
commitStructural: vi.fn(),
createLayerId: () => 'text-1',
getDocument: () => null,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
index 71d677e968..6e8cdaab60 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/extractMaskedAreaController.ts
@@ -1,6 +1,8 @@
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { CanvasDiagnostics } from '@workbench/canvas-engine/diagnostics';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { DerivedSurfaceCache } from '@workbench/canvas-engine/render/derivedSurfaceCache';
@@ -45,6 +47,7 @@ export interface ExtractMaskedAreaControllerOptions<Permit> {
readonly getAdjustedSurface: (layer: CanvasLayerContract, entry: LayerCacheEntry) => RasterSurface | null;
readonly getMaskPattern: (style: string, color: string) => RasterSurface | null;
readonly createLayerId: () => string;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;
readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;
readonly dispatchPrepared: (
@@ -195,11 +198,12 @@ export class ExtractMaskedAreaController<Permit> {
type: 'raster',
};
const selectedLayerId = liveDocument.selectedLayerId;
+ const anchor = this.deps.captureInsertionAnchor('raster', null);
const apply = (): void => {
const prepared = this.deps.preparePixels(resultId, rect, pixels);
this.deps.dispatchPrepared(
{
- add: { index: maskIndex, layers: [layer] },
+ add: [{ anchor, layers: [layer] }],
enabledUpdates: [],
selectedLayerId: resultId,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts
index 32165bcfb1..3882875cf7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/filterResultController.ts
@@ -150,10 +150,6 @@ export class FilterResultController {
});
return { layerId: liveLayer.id, status: 'committed' };
}
- const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);
- if (sourceIndex < 0) {
- return { status: 'missing' };
- }
const selectedLayerId = document.selectedLayerId;
const layerId = o.ctx.createLayerId();
let copy: CanvasLayerContract;
@@ -200,10 +196,11 @@ export class FilterResultController {
type: 'raster',
};
}
+ const anchor = o.ctx.captureInsertionAnchor(copy.type, liveLayer.id);
const apply = (): void => {
const prepared = o.ctx.preparePixels(layerId, rect, pixels);
o.ctx.dispatchPrepared(
- { index: sourceIndex, layer: copy, type: 'addCanvasLayer' },
+ { anchor, layer: copy, type: 'addCanvasLayer' },
() => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,
() => o.ctx.getDocument()?.layers.some((candidate) => candidate === copy) === true
);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts
index 23bc004c2c..7e6c95d015 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/generatedResultController.ts
@@ -154,10 +154,6 @@ export class GeneratedResultController {
});
return { layerId: liveLayer.id, status: 'committed' };
}
- const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);
- if (sourceIndex < 0) {
- return { status: 'missing' };
- }
const layerId = o.ctx.createLayerId();
const selectedLayerId = document.selectedLayerId;
const buildControlCopy = (): CanvasLayerContract => {
@@ -187,9 +183,10 @@ export class GeneratedResultController {
transform: identityTransform,
type: 'raster',
};
+ const anchor = o.ctx.captureInsertionAnchor(copy.type, liveLayer.id);
const publishCopy = (prepared: PreparedLayerCacheReplacement): void => {
o.ctx.dispatchPrepared(
- { index: sourceIndex, layer: copy, type: 'addCanvasLayer' },
+ { anchor, layer: copy, type: 'addCanvasLayer' },
() => o.ctx.getReducerDocument()?.layers.some((candidate) => candidate === copy) === true,
() => o.ctx.getDocument()?.layers.some((candidate) => candidate === copy) === true
);
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 98ba59e362..dde0d73362 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
@@ -1,5 +1,6 @@
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { describe, expect, it, vi } from 'vitest';
import { LayerController } from './layerController';
@@ -80,6 +81,7 @@ describe('LayerController', () => {
backend: {} as never,
capturePermit: () => null,
createLayerId: () => 'result',
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
dispatchPrepared: vi.fn(),
endBurst: vi.fn(),
exportBaked: vi.fn(),
@@ -97,6 +99,7 @@ describe('LayerController', () => {
backend: {} as never,
capturePermit: () => null,
createLayerId: () => 'result',
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
derived: {} as never,
diagnostics: {} as never,
dispatchPrepared: vi.fn(),
@@ -138,6 +141,7 @@ describe('LayerController', () => {
const copy = {
capturePermit: () => null,
createLayerId: () => 'copy',
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
dispatchPrepared: vi.fn(),
endBurst: vi.fn(),
exportBaked: vi.fn(),
@@ -154,6 +158,7 @@ describe('LayerController', () => {
backend: {} as never,
capturePermit: () => null,
createLayerId: () => 'new',
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
dispatchPrepared: vi.fn(),
endBurst: vi.fn(),
getDocument: () => null,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
index 38d7b5e802..27f4f4815b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/layerMutationController.ts
@@ -1,12 +1,17 @@
import type { DuplicateLayersResult } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { RasterMemoryReservationResult } from '@workbench/canvas-engine/controllers/rasterMemoryBudgetController';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
+import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';
+
export type CapturedLayerCache = { pixels: RasterSurface; rect: Rect } | null | 'not-ready';
export type DuplicateLayerRasterPlan =
@@ -29,6 +34,7 @@ export interface LayerMutationControllerOptions<Permit> {
readonly canEdit: () => boolean;
readonly capturePermit: () => Permit | null;
readonly captureCache: (layer: CanvasLayerContract, document: CanvasDocumentContractV2) => CapturedLayerCache;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly createLayerId: () => string;
readonly discardPersisted: (layerId: string) => void;
readonly dispatchPrepared: (
@@ -42,6 +48,7 @@ export interface LayerMutationControllerOptions<Permit> {
document: CanvasDocumentContractV2
) => DuplicateLayerRasterPlan;
readonly getDocument: () => CanvasDocumentContractV2 | null;
+ readonly getEditRevision: () => number;
readonly getReducerDocument: () => CanvasDocumentContractV2 | null;
readonly getSelectedLayerIds: (document: CanvasDocumentContractV2) => readonly string[];
readonly history: History;
@@ -188,32 +195,31 @@ export class LayerMutationController<Permit> {
return { status: 'stale' };
}
const duplicateBySource = new Map(sources.map((source, index) => [source.id, duplicates[index]!]));
- const orderedIds = document.layers.flatMap((layer) => {
- const duplicate = duplicateBySource.get(layer.id);
- return duplicate ? [duplicate.id, layer.id] : [layer.id];
- });
+ const insertions = sources.map((source, index) => ({
+ anchor: o.captureInsertionAnchor(source.type, source.id),
+ layers: [duplicates[index]!],
+ }));
+ const expectedLayers = insertions.reduce(
+ (layers, insertion) => insertLayersAtAnchor(layers, insertion.anchor, insertion.layers),
+ document.layers
+ );
const selectedLayerId =
(document.selectedLayerId ? duplicateBySource.get(document.selectedLayerId)?.id : null) ?? duplicates[0]!.id;
const previousSelectedLayerId = document.selectedLayerId;
const previousSelectedIds = [...o.getSelectedLayerIds(document)];
- const originalIds = document.layers.map((layer) => layer.id);
const duplicateIds = duplicates.map((layer) => layer.id);
const hasDuplicates = (candidate: CanvasDocumentContractV2 | null): boolean =>
- candidate?.selectedLayerId === selectedLayerId &&
- candidate.layers.length === orderedIds.length &&
- candidate.layers.every((layer, index) => layer.id === orderedIds[index]);
+ candidate?.selectedLayerId === selectedLayerId && haveSameStackOrders(candidate.layers, expectedLayers);
const hasOriginals = (candidate: CanvasDocumentContractV2 | null): boolean =>
candidate?.selectedLayerId === previousSelectedLayerId &&
- candidate.layers.length === originalIds.length &&
- candidate.layers.every((layer, index) => layer.id === originalIds[index]);
+ haveSameStackOrders(candidate.layers, document.layers);
const applyPrepared = (
prepared: readonly { duplicate: CanvasLayerContract; replacement: PreparedLayerCacheReplacement }[]
): void => {
o.dispatchPrepared(
{
- add: { index: 0, layers: duplicates },
+ add: insertions,
enabledUpdates: [],
- orderedIds,
selectedLayerId,
type: 'applyCanvasLayerStackMutation',
},
@@ -326,7 +332,7 @@ export class LayerMutationController<Permit> {
}
}
- copy(label: string, sourceLayerId: string, layer: CanvasLayerContract, index: number): boolean {
+ copy(label: string, sourceLayerId: string, layer: CanvasLayerContract, anchor: FlatLayerInsertionAnchor): boolean {
const o = this.options;
if (!o.canEdit() || o.isGestureActive()) {
return false;
@@ -334,7 +340,12 @@ export class LayerMutationController<Permit> {
o.endBurst();
const document = o.getDocument();
const source = document?.layers.find((candidate) => candidate.id === sourceLayerId);
- if (!document || !source || document.layers.some((candidate) => candidate.id === layer.id)) {
+ if (
+ !document ||
+ !source ||
+ anchor.capturedEditRevision !== o.getEditRevision() ||
+ document.layers.some((candidate) => candidate.id === layer.id)
+ ) {
return false;
}
const captured = o.captureCache(source, document);
@@ -346,7 +357,7 @@ export class LayerMutationController<Permit> {
const prepared = captured ? o.preparePixels(layer.id, captured.rect, captured.pixels) : null;
o.dispatchPrepared(
{
- add: { index, layers: [layer] },
+ add: [{ anchor, layers: [layer] }],
enabledUpdates: [],
selectedLayerId: layer.id,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts
index 33646562e2..5f28db862b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/maskResultController.ts
@@ -4,6 +4,8 @@ import type {
LayerExportGuard,
} from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
@@ -24,6 +26,7 @@ export type {
export interface MaskResultControllerOptions<Owner = symbol> {
readonly canEdit: (owner?: Owner) => boolean;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly createLayerId: () => string;
readonly dispatchPrepared: (
action: CanvasProjectMutation,
@@ -64,7 +67,6 @@ export class MaskResultController<Owner = symbol> {
if (liveLayer.type !== 'raster' && liveLayer.type !== 'control') {
return Promise.resolve({ status: 'unsupported' });
}
- const sourceIndex = document.layers.findIndex((candidate) => candidate.id === liveLayer.id);
if (o.isGestureActive()) {
return Promise.resolve({ status: 'busy' });
}
@@ -74,9 +76,6 @@ export class MaskResultController<Owner = symbol> {
if (options.signal?.aborted) {
return Promise.resolve({ status: 'aborted' });
}
- if (sourceIndex < 0) {
- return Promise.resolve({ status: 'missing' });
- }
const names = document.layers.map((layer) => layer.name);
const layerId = o.createLayerId();
const layer =
@@ -101,9 +100,10 @@ export class MaskResultController<Owner = symbol> {
rect: options.rect,
});
const selectedLayerId = document.selectedLayerId;
+ const anchor = o.captureInsertionAnchor(layer.type, liveLayer.id);
const apply = (): void =>
o.dispatchPrepared(
- { index: sourceIndex, layer, type: 'addCanvasLayer' },
+ { anchor, layer, type: 'addCanvasLayer' },
() => o.getReducerDocument()?.layers.some((candidate) => candidate === layer) === true,
() => o.getDocument()?.layers.some((candidate) => candidate === layer) === true
);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
index b81b8ca4ce..5bca34efbe 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mergeLayerController.ts
@@ -5,7 +5,9 @@ import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache
import type { RasterBackend, RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
+import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import { isMergeableRasterLayer } from '@workbench/canvas-engine/document/layerEligibility';
+import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';
import { mergeDownMatrix } from '@workbench/canvas-engine/document/mergeDown';
import { canMergeSelectedRasters, getMergeVisibleRasterLayers } from '@workbench/canvas-engine/document/mergeVisible';
import { isEmpty, roundOut, transformBounds, union } from '@workbench/canvas-engine/math/rect';
@@ -226,13 +228,14 @@ export class MergeLayerController {
type: 'raster',
};
const selectedLayerId = liveDocument.selectedLayerId;
+ const anchor = this.deps.ctx.captureInsertionAnchor('raster', null);
const hasResult = (doc: CanvasDocumentContractV2 | null): boolean =>
- doc?.selectedLayerId === resultId && doc.layers[0] === resultLayer;
+ doc?.selectedLayerId === resultId && doc.layers.includes(resultLayer);
const apply = (): void => {
const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);
this.deps.ctx.dispatchPrepared(
{
- add: { index: 0, layers: [resultLayer] },
+ add: [{ anchor, layers: [resultLayer] }],
enabledUpdates: [],
selectedLayerId: resultId,
type: 'applyCanvasLayerStackMutation',
@@ -385,27 +388,26 @@ export class MergeLayerController {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
};
- const originalIds = document.layers.map((layer) => layer.id);
const contributorIds = contributors.map((layer) => layer.id);
- const topIndex = document.layers.indexOf(contributors[0]!);
- const mergedIds = originalIds.filter((id) => !selectedIds.has(id));
- mergedIds.splice(topIndex, 0, resultId);
+ const anchor = this.deps.ctx.captureInsertionAnchor('raster', contributors[0]!.id);
+ const restoreInsertions = contributors.map((layer) => ({
+ anchor: this.deps.ctx.captureRestoreAnchor(layer.id)!,
+ layers: [layer],
+ }));
+ const mergedLayers = insertLayersAtAnchor(document.layers, anchor, [resultLayer]).filter(
+ (layer) => !selectedIds.has(layer.id)
+ );
const selectedLayerId = document.selectedLayerId;
const hasMerged = (candidate: CanvasDocumentContractV2 | null): boolean =>
- candidate?.selectedLayerId === resultId &&
- candidate.layers.length === mergedIds.length &&
- candidate.layers.every((layer, index) => layer.id === mergedIds[index]);
+ candidate?.selectedLayerId === resultId && haveSameStackOrders(candidate.layers, mergedLayers);
const hasOriginals = (candidate: CanvasDocumentContractV2 | null): boolean =>
- candidate?.selectedLayerId === selectedLayerId &&
- candidate.layers.length === originalIds.length &&
- candidate.layers.every((layer, index) => layer.id === originalIds[index]);
+ candidate?.selectedLayerId === selectedLayerId && haveSameStackOrders(candidate.layers, document.layers);
const applyPrepared = (): void => {
const prepared = this.deps.ctx.preparePixels(resultId, rect, pixels);
this.deps.ctx.dispatchPrepared(
{
- add: { index: topIndex, layers: [resultLayer] },
+ add: [{ anchor, layers: [resultLayer] }],
enabledUpdates: [],
- orderedIds: mergedIds,
removeIds: contributorIds,
selectedLayerId: resultId,
type: 'applyCanvasLayerStackMutation',
@@ -439,9 +441,8 @@ export class MergeLayerController {
}));
this.deps.ctx.dispatchPrepared(
{
- add: { index: topIndex, layers: contributors },
+ add: restoreInsertions,
enabledUpdates: [],
- orderedIds: originalIds,
removeIds: [resultId],
selectedLayerId,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts
index a573a86bb9..9426613de0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.test.ts
@@ -46,6 +46,7 @@ const createHarness = (overrides: Partial<CanvasMutationContextDeps> = {}) => {
createLayerId: () => 'layer-new',
dispatch: vi.fn(() => true),
editOwner,
+ projectId: 'p1',
editingLocked: lock,
endBurst: () => undefined,
getDocument: () => null,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
index 47cd1cc5a9..e27eb4a801 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/mutationContext.ts
@@ -1,12 +1,16 @@
import type { CanvasEditIntent, WorkbenchActionOrigin } from '@workbench/autoRoutePolicy';
import type { LayerExportGuard } from '@workbench/canvas-engine/capabilities';
-import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { Rect } from '@workbench/canvas-engine/types';
+import { captureInsertionAnchor, captureRestoreAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+
/**
* A claim on the current document-edit epoch. Captured before an async
* operation and re-checked ({@link CanvasMutationContext.isPermitCurrent})
@@ -31,6 +35,10 @@ export interface CanvasMutationContext {
getReducerDocument(): CanvasDocumentContractV2 | null;
/** Counts reducer document identities; a captured value is stale once any edit lands. */
getEditRevision(): number;
+ /** Where a new `stack` layer lands: above `aboveId` when it belongs to the stack, else the stack top. */
+ 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;
canEdit(owner?: symbol): boolean;
capturePermit(owner?: symbol): DocumentEditPermit | null;
isPermitCurrent(permit: DocumentEditPermit): boolean;
@@ -51,6 +59,7 @@ export interface CanvasMutationContext {
/** Engine-side wiring for {@link createCanvasMutationContext}. */
export interface CanvasMutationContextDeps {
+ readonly projectId: string;
readonly history: History;
readonly getDocument: () => CanvasDocumentContractV2 | null;
readonly getReducerDocument: () => CanvasDocumentContractV2 | null;
@@ -97,6 +106,11 @@ export const createCanvasMutationContext = (
}
};
const unsubscribeReducer = deps.subscribeReducer(syncEditRevision);
+ const getEditRevision = (): number => {
+ syncEditRevision();
+ return editRevision;
+ };
+ const currentLayers = (): readonly CanvasLayerContract[] => deps.getDocument()?.layers ?? [];
const canEdit = (owner?: symbol): boolean => owner === deps.editOwner || !deps.editingLocked.get();
const capturePermit = (owner?: symbol): DocumentEditPermit | null =>
canEdit(owner) ? { epoch: documentEditEpoch, owner } : null;
@@ -173,7 +187,16 @@ export const createCanvasMutationContext = (
return {
canEdit,
+ captureInsertionAnchor: (stack, aboveId) =>
+ captureInsertionAnchor(currentLayers(), {
+ aboveId,
+ editRevision: getEditRevision(),
+ projectId: deps.projectId,
+ stack,
+ }),
capturePermit,
+ captureRestoreAnchor: (layerId) =>
+ captureRestoreAnchor(currentLayers(), layerId, deps.projectId, getEditRevision()),
createLayerId: () => deps.createLayerId(),
dispatch: (action, origin) => deps.dispatch(action, origin),
dispatchPrepared,
@@ -183,10 +206,7 @@ export const createCanvasMutationContext = (
},
endBurst: () => deps.endBurst(),
getDocument: () => deps.getDocument(),
- getEditRevision: () => {
- syncEditRevision();
- return editRevision;
- },
+ getEditRevision,
getReducerDocument: () => deps.getReducerDocument(),
history: deps.history,
installPrepared: (prepared, persist) => deps.installPrepared(prepared, persist),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts
index bf7a05f57b..d6fcef68a9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.test.ts
@@ -7,6 +7,8 @@ import type { SelectionState } from '@workbench/canvas-engine/selection/selectio
import type { PlacedSurface, Rect } from '@workbench/canvas-engine/types';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createHistory } from '@workbench/canvas-engine/history/history';
import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
@@ -81,6 +83,7 @@ const createHarness = (options: HarnessOptions = {}) => {
const controller = new NewRasterLayerController({
backend,
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.layers ?? []),
capturePermit: () => (options.permit === undefined ? {} : options.permit),
createLayerId: () => `new-${(nextId += 1)}`,
dispatchPrepared: (action) => {
@@ -92,8 +95,8 @@ const createHarness = (options: HarnessOptions = {}) => {
if (action.removeIds) {
next = next.filter((layer) => !action.removeIds!.includes(layer.id));
}
- if (action.add) {
- next = [...next.slice(0, action.add.index), ...action.add.layers, ...next.slice(action.add.index)];
+ for (const insertion of action.add ?? []) {
+ next = insertLayersAtAnchor(next, insertion.anchor, insertion.layers);
}
document = { ...document, layers: next, selectedLayerId: action.selectedLayerId ?? null };
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts
index aeb72bdc21..5c333c9eb4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/newRasterLayerController.ts
@@ -1,4 +1,6 @@
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { LayerCacheStore, PreparedLayerCacheReplacement } from '@workbench/canvas-engine/render/layerCache';
@@ -24,6 +26,7 @@ export interface NewRasterLayerControllerOptions<Permit> {
readonly isGestureActive: () => boolean;
readonly endBurst: () => void;
readonly createLayerId: () => string;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly preparePixels: (layerId: string, rect: Rect, pixels: RasterSurface) => PreparedLayerCacheReplacement;
readonly installPrepared: (prepared: PreparedLayerCacheReplacement) => void;
readonly dispatchPrepared: (
@@ -87,16 +90,14 @@ export class NewRasterLayerController<Permit> {
type: 'raster',
};
- // Above the active layer: index 0 is top-most, so "above" is one index lower.
- const activeIndex = document.layers.findIndex((candidate) => candidate.id === document.selectedLayerId);
- const insertIndex = activeIndex >= 0 ? activeIndex : 0;
+ const anchor = this.deps.captureInsertionAnchor('raster', document.selectedLayerId);
const previousSelectedLayerId = document.selectedLayerId;
const apply = (): void => {
const prepared = this.deps.preparePixels(layerId, rect, pixels);
this.deps.dispatchPrepared(
{
- add: { index: insertIndex, layers: [layer] },
+ add: [{ anchor, layers: [layer] }],
enabledUpdates: [],
selectedLayerId: layerId,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts
index 8ff50431e4..f21d4a4b1f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.test.ts
@@ -1,6 +1,8 @@
import type { CanvasStagingCandidateContract, CanvasStateContractV2 } from '@workbench/canvas-engine/contracts';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createHistory } from '@workbench/canvas-engine/history/history';
import { describe, expect, it, vi } from 'vitest';
@@ -56,7 +58,10 @@ describe('StagedResultController', () => {
layers: mutation.removeIds
? reducerCanvas.document.layers.filter((layer) => !mutation.removeIds?.includes(layer.id))
: mutation.add
- ? [...mutation.add.layers, ...reducerCanvas.document.layers]
+ ? mutation.add.reduce(
+ (layers, insertion) => insertLayersAtAnchor(layers, insertion.anchor, insertion.layers),
+ reducerCanvas.document.layers
+ )
: reducerCanvas.document.layers,
selectedLayerId:
mutation.selectedLayerId === undefined
@@ -86,6 +91,7 @@ describe('StagedResultController', () => {
}
);
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => ({ epoch: 1 }),
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
@@ -124,6 +130,7 @@ describe('StagedResultController', () => {
const canvas = makeCanvas();
const history = createHistory();
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => ({ epoch: 1 }),
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
@@ -154,6 +161,7 @@ describe('StagedResultController', () => {
const dispatchPrepared = vi.fn();
const history = createHistory();
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => permit,
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
@@ -176,6 +184,7 @@ describe('StagedResultController', () => {
const canvas = makeCanvas();
const history = createHistory();
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => ({ epoch: 1 }),
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
@@ -204,6 +213,7 @@ describe('StagedResultController', () => {
history.undo();
expect(history.canRedo()).toBe(true);
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => ({ epoch: 1 }),
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
@@ -254,6 +264,7 @@ describe('StagedResultController', () => {
const dispatchPrepared = vi.fn();
const history = createHistory();
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => ({ epoch: 1 }),
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
@@ -277,6 +288,7 @@ describe('StagedResultController', () => {
const dispatchPrepared = vi.fn();
const history = createHistory();
const controller = new StagedResultController({
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
capturePermit: () => ({ epoch: 1 }),
createEventId: () => 'event-1',
createLayerId: () => 'layer-1',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts
index 16f77bcf79..eec3d35988 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/stagedResultController.ts
@@ -5,14 +5,19 @@ import type {
CanvasStagingCandidateContract,
CanvasStateContractV2,
} from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { History } from '@workbench/canvas-engine/history/history';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { ProjectEvent } from '@workbench/projectContracts';
+import { insertLayersAtAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';
import { getCanvasStagingCandidateFingerprint } from '@workbench/canvasStagingView';
export interface StagedResultControllerOptions<Permit, Owner = symbol> {
readonly capturePermit: (owner?: Owner) => Permit | null;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly createEventId: () => string;
readonly createLayerId: () => string;
readonly dispatchPrepared: (
@@ -104,17 +109,18 @@ export class StagedResultController<Permit, Owner = symbol> {
};
const previousSelectedLayerId = canvas.document.selectedLayerId;
const previousLayers = canvas.document.layers;
- const acceptedLayers = [layer, ...previousLayers];
+ const anchor = o.captureInsertionAnchor('raster', null);
+ const acceptedLayers = insertLayersAtAnchor(previousLayers, anchor, [layer]);
const previousStagingArea = canvas.stagingArea;
const acceptedSelectedLayerId = continueStaging ? previousSelectedLayerId : layer.id;
const hasPreviousLayerStack = (document: CanvasDocumentContractV2 | null): boolean =>
document?.selectedLayerId === previousSelectedLayerId &&
- document.layers.length === previousLayers.length &&
- document.layers.every((current, index) => current === previousLayers[index]);
+ !document.layers.some((current) => current.id === layer.id) &&
+ haveSameStackOrders(document.layers, previousLayers);
const hasAcceptedLayerStack = (document: CanvasDocumentContractV2 | null): boolean =>
document?.selectedLayerId === acceptedSelectedLayerId &&
- document.layers.length === acceptedLayers.length &&
- document.layers.every((current, index) => current === acceptedLayers[index]);
+ document.layers.includes(layer) &&
+ haveSameStackOrders(document.layers, acceptedLayers);
const isCommitted = (next: CanvasStateContractV2 | null): boolean =>
next?.document.selectedLayerId === acceptedSelectedLayerId &&
next.document.layers.some((current) => current === layer) &&
@@ -132,6 +138,7 @@ export class StagedResultController<Permit, Owner = symbol> {
o.endBurst();
o.dispatchPrepared(
{
+ anchor,
candidateFingerprint,
continueStaging,
event,
@@ -181,7 +188,7 @@ export class StagedResultController<Permit, Owner = symbol> {
}
};
const addAcceptedLayer: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }> = {
- add: { index: 0, layers: [layer] },
+ add: [{ anchor, layers: [layer] }],
enabledUpdates: [],
selectedLayerId: acceptedSelectedLayerId,
type: 'applyCanvasLayerStackMutation',
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 45a3dd70b9..087c94015f 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,7 @@ import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contract
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { Project } from '@workbench/projectContracts';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createHistory } from '@workbench/canvas-engine/history/history';
import { applyCanvasProjectMutation } from '@workbench/canvasProjectMutations';
import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
@@ -23,7 +24,11 @@ interface HarnessOptions {
const createHarness = (options: HarnessOptions & { now?: () => number } = {}) => {
const base = createInitialWorkbenchState().projects[0]!;
const layer = createEmptyPaintLayer('Layer', 'layer');
- let project: Project = applyCanvasProjectMutation(base, { index: 0, layer, type: 'addCanvasLayer' });
+ let project: Project = applyCanvasProjectMutation(base, {
+ anchor: stackTopAnchor(base.id),
+ layer,
+ type: 'addCanvasLayer',
+ });
let mirrorDocument = project.canvas.document;
const listeners = new Set<() => void>();
const dispatched: CanvasProjectMutation[] = [];
@@ -48,6 +53,7 @@ const createHarness = (options: HarnessOptions & { now?: () => number } = {}) =>
const ctx = createCanvasMutationContext({
commitEdit: vi.fn(),
createLayerId: () => 'new',
+ projectId: base.id,
dispatch,
editOwner: Symbol('owner'),
editingLocked: { get: () => options.locked ?? false, subscribe: () => () => undefined },
@@ -70,6 +76,7 @@ const createHarness = (options: HarnessOptions & { now?: () => number } = {}) =>
controller,
ctx,
dispatched,
+ projectId: base.id,
document: () => project.canvas.document,
history: ctx.history,
layer,
@@ -201,13 +208,34 @@ describe('StructuralLayerController', () => {
expect(report).toHaveBeenCalledWith('Structural edit could not be mirrored', 'Rename', expect.any(Error));
});
+ 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);
+ ctx.dispatch(rename('layer', 'Renamed'), 'system');
+ const added = createEmptyPaintLayer('Added', 'added');
+
+ expect(
+ controller.commit(
+ 'Add',
+ { anchor, layer: added, type: 'addCanvasLayer' },
+ { ids: ['added'], type: 'removeCanvasLayers' }
+ )
+ ).toEqual({
+ actualRevision: anchor.capturedEditRevision + 1,
+ expectedRevision: anchor.capturedEditRevision,
+ status: 'stale',
+ });
+ expect(document().layers.some((layer) => layer.id === 'added')).toBe(false);
+ expect(anchor.projectId).toBe(projectId);
+ });
+
it('moves a replay the reducer refuses as a reported no-op instead of wedging history', () => {
- const { controller, ctx, document, history, report } = createHarness();
+ const { controller, ctx, document, history, projectId, report } = createHarness();
const added = createEmptyPaintLayer('Added', 'added');
controller.commit(
'Add',
- { index: 0, layer: added, type: 'addCanvasLayer' },
+ { anchor: stackTopAnchor(projectId), layer: added, type: 'addCanvasLayer' },
{ ids: ['added'], type: 'removeCanvasLayers' }
);
ctx.dispatch({ ids: ['added'], type: 'removeCanvasLayers' }, 'system');
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 aa646e635c..303fcb867c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/structuralLayerController.ts
@@ -7,6 +7,18 @@ import { createDocumentPatchEntry } from '@workbench/canvas-engine/history/docum
import type { CanvasMutationContext } from './mutationContext';
+/** The edit revision a mutation's insertion was anchored at; a commit refuses an anchor captured earlier. */
+const anchorRevisionOf = (mutation: CanvasProjectMutation): number | undefined => {
+ switch (mutation.type) {
+ case 'addCanvasLayer':
+ return mutation.anchor.capturedEditRevision;
+ case 'applyCanvasLayerStackMutation':
+ return mutation.add?.[0]?.anchor.capturedEditRevision;
+ default:
+ return undefined;
+ }
+};
+
export type StructuralMutationContext = Pick<
CanvasMutationContext,
| 'canEdit'
@@ -75,7 +87,10 @@ export class StructuralLayerController {
inverse: CanvasProjectMutation,
options: StructuralCommitOptions = {}
): StructuralCommitResult {
- const refusal = this.refuse(options);
+ const refusal = this.refuse({
+ ...options,
+ expectedRevision: options.expectedRevision ?? anchorRevisionOf(forward) ?? anchorRevisionOf(inverse),
+ });
if (refusal) {
return refusal;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts
index 641b4249d1..d20c5526a2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.test.ts
@@ -2,6 +2,7 @@ import type { StructuralCommitResult } from '@workbench/canvas-engine/capabiliti
import type { CanvasDocumentContractV2 } from '@workbench/canvas-engine/contracts';
import type { TextEditSession } from '@workbench/canvas-engine/engineStores';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { DEFAULT_TEXT_OPTIONS } from '@workbench/canvas-engine/engineStores';
import { describe, expect, it, vi } from 'vitest';
@@ -15,6 +16,7 @@ const createHarness = (document: CanvasDocumentContractV2) => {
const invalidate = vi.fn();
const controller = new TextEditingController({
canEdit: () => true,
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p', () => document?.layers ?? []),
commitStructural,
createLayerId: () => 'text-new',
getDocument: () => document,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts
index 1b0c443466..cc4fea7f05 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/controllers/textEditingController.ts
@@ -1,5 +1,7 @@
import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { TextEditSession, TextSource, TextToolOptions } from '@workbench/canvas-engine/engineStores';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
import type { Vec2 } from '@workbench/canvas-engine/types';
@@ -16,6 +18,7 @@ export interface TextEditingControllerOptions {
readonly canEdit: () => boolean;
readonly isGestureActive: () => boolean;
readonly createLayerId: () => string;
+ readonly captureInsertionAnchor: (stack: LayerStackKind, aboveId: string | null) => FlatLayerInsertionAnchor;
readonly commitStructural: (
label: string,
forward: CanvasProjectMutation,
@@ -145,7 +148,11 @@ export class TextEditingController {
};
const added = this.deps.commitStructural(
'Add text',
- { index: 0, layer, type: 'addCanvasLayer' },
+ {
+ anchor: this.deps.captureInsertionAnchor('raster', this.deps.getDocument()?.selectedLayerId ?? null),
+ layer,
+ type: 'addCanvasLayer',
+ },
{ ids: [layerId], type: 'removeCanvasLayers' }
);
this.settle(added);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.ts
new file mode 100644
index 0000000000..15ee56ce9b
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.test.ts
@@ -0,0 +1,102 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+
+import { describe, expect, it } from 'vitest';
+
+import {
+ captureInsertionAnchor,
+ captureRestoreAnchor,
+ insertLayersAtAnchor,
+ resolveInsertionIndex,
+} from './insertionAnchors';
+
+const layer = (id: string, type: CanvasLayerContract['type'] = 'raster'): CanvasLayerContract =>
+ ({ id, type }) as CanvasLayerContract;
+
+const layers = [layer('i1', 'inpaint_mask'), layer('r1'), layer('c1', 'control'), layer('r2'), layer('r3')];
+const ids = (entries: readonly CanvasLayerContract[]): string[] => entries.map((entry) => entry.id);
+const capture = { editRevision: 7, projectId: 'p' };
+
+describe('captureInsertionAnchor', () => {
+ it('anchors above a compatible leaf and remembers the same-stack member above it', () => {
+ expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'r2', stack: 'raster' })).toEqual({
+ afterId: 'r1',
+ beforeId: 'r2',
+ capturedEditRevision: 7,
+ projectId: 'p',
+ stack: 'raster',
+ });
+ expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'r1', stack: 'raster' })).toMatchObject({
+ afterId: null,
+ beforeId: 'r1',
+ });
+ });
+
+ it('falls back to the stack top for an incompatible, absent, or omitted leaf', () => {
+ const top = { afterId: null, beforeId: 'r1', capturedEditRevision: 7, projectId: 'p', stack: 'raster' };
+
+ expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'c1', stack: 'raster' })).toEqual(top);
+ expect(captureInsertionAnchor(layers, { ...capture, aboveId: 'ghost', stack: 'raster' })).toEqual(top);
+ expect(captureInsertionAnchor(layers, { ...capture, stack: 'raster' })).toEqual(top);
+ expect(captureInsertionAnchor(layers, { ...capture, stack: 'regional_guidance' })).toMatchObject({
+ afterId: null,
+ beforeId: null,
+ });
+ });
+});
+
+describe('captureRestoreAnchor', () => {
+ it('captures the same-stack neighbours on both sides', () => {
+ expect(captureRestoreAnchor(layers, 'r2', 'p', 3)).toEqual({
+ afterId: 'r1',
+ beforeId: 'r3',
+ capturedEditRevision: 3,
+ projectId: 'p',
+ stack: 'raster',
+ });
+ expect(captureRestoreAnchor(layers, 'c1', 'p', 3)).toMatchObject({
+ afterId: null,
+ beforeId: null,
+ stack: 'control',
+ });
+ expect(captureRestoreAnchor(layers, 'ghost', 'p', 3)).toBeNull();
+ });
+});
+
+describe('resolveInsertionIndex', () => {
+ const anchor = captureInsertionAnchor(layers, { ...capture, aboveId: 'r2', stack: 'raster' });
+
+ it('lands before a surviving beforeId', () => {
+ expect(resolveInsertionIndex(layers, anchor)).toBe(3);
+ });
+
+ it('lands after a surviving afterId once beforeId is gone', () => {
+ const withoutR2 = layers.filter((entry) => entry.id !== 'r2');
+ expect(resolveInsertionIndex(withoutR2, anchor)).toBe(2);
+ });
+
+ it('lands at the stack top when neither survives, or at 0 for an empty stack', () => {
+ const onlyR3 = [layer('i1', 'inpaint_mask'), layer('c1', 'control'), layer('r3')];
+ expect(resolveInsertionIndex(onlyR3, anchor)).toBe(2);
+ expect(resolveInsertionIndex([layer('i1', 'inpaint_mask')], anchor)).toBe(0);
+ });
+
+ it('ignores ids that moved to another stack', () => {
+ const retyped = layers.map((entry) => (entry.id === 'r2' ? layer('r2', 'control') : entry));
+ expect(resolveInsertionIndex(retyped, anchor)).toBe(2);
+ });
+});
+
+describe('insertLayersAtAnchor', () => {
+ it('splices the inserted layers at the resolved index', () => {
+ const anchor = captureInsertionAnchor(layers, { ...capture, aboveId: 'r2', stack: 'raster' });
+ expect(ids(insertLayersAtAnchor(layers, anchor, [layer('n1'), layer('n2')]))).toEqual([
+ 'i1',
+ 'r1',
+ 'c1',
+ 'n1',
+ 'n2',
+ 'r2',
+ 'r3',
+ ]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.ts
new file mode 100644
index 0000000000..f21845adc5
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.testStub.ts
@@ -0,0 +1,20 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+
+import type { FlatLayerInsertionAnchor } from './insertionAnchors';
+import type { LayerStackKind } from './layerStacks';
+
+import { captureInsertionAnchor } from './insertionAnchors';
+
+export const stackTopAnchor = (projectId: string, stack: LayerStackKind = 'raster'): FlatLayerInsertionAnchor => ({
+ afterId: null,
+ beforeId: null,
+ capturedEditRevision: 0,
+ projectId,
+ stack,
+});
+
+/** Captures the way the engine does, against whatever `getLayers` returns at call time. */
+export const createTestInsertionAnchorCapture =
+ (projectId: string, getLayers: () => readonly CanvasLayerContract[] = () => []) =>
+ (stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor =>
+ captureInsertionAnchor(getLayers(), { aboveId, editRevision: 0, projectId, stack });
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts
new file mode 100644
index 0000000000..31cfd7935a
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/insertionAnchors.ts
@@ -0,0 +1,122 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+
+import type { LayerStackKind } from './layerStacks';
+
+/**
+ * Where a new layer lands in its stack, captured once against the document the caller saw.
+ * Resolution is exact: before a surviving `beforeId`, else after a surviving `afterId`, else at
+ * the top of `stack`. Ids that no longer belong to `stack` count as gone. The reducer refuses an
+ * anchor from another project; a structural commit refuses one captured at an older edit revision.
+ */
+export interface FlatLayerInsertionAnchor {
+ readonly projectId: string;
+ readonly stack: LayerStackKind;
+ readonly beforeId: string | null;
+ readonly afterId: string | null;
+ readonly capturedEditRevision: number;
+}
+
+export interface FlatLayerInsertion {
+ readonly anchor: FlatLayerInsertionAnchor;
+ readonly layers: readonly CanvasLayerContract[];
+}
+
+export interface InsertionAnchorCapture {
+ readonly projectId: string;
+ readonly stack: LayerStackKind;
+ readonly editRevision: number;
+ /** Land directly above this layer when it belongs to `stack`; otherwise at the stack top. */
+ readonly aboveId?: string | null;
+}
+
+const stackMemberIndex = (layers: readonly CanvasLayerContract[], stack: LayerStackKind, id: string | null): number =>
+ id === null ? -1 : layers.findIndex((layer) => layer.id === id && layer.type === stack);
+
+const nearestAbove = (
+ layers: readonly CanvasLayerContract[],
+ index: number,
+ stack: LayerStackKind
+): CanvasLayerContract | undefined => {
+ for (let position = index - 1; position >= 0; position -= 1) {
+ if (layers[position]!.type === stack) {
+ return layers[position];
+ }
+ }
+ return undefined;
+};
+
+const nearestBelow = (
+ layers: readonly CanvasLayerContract[],
+ index: number,
+ stack: LayerStackKind
+): CanvasLayerContract | undefined => layers.slice(index + 1).find((layer) => layer.type === stack);
+
+export const captureInsertionAnchor = (
+ layers: readonly CanvasLayerContract[],
+ capture: InsertionAnchorCapture
+): FlatLayerInsertionAnchor => {
+ const { editRevision, projectId, stack } = capture;
+ const leafIndex = stackMemberIndex(layers, stack, capture.aboveId ?? null);
+ if (leafIndex >= 0) {
+ return {
+ afterId: nearestAbove(layers, leafIndex, stack)?.id ?? null,
+ beforeId: layers[leafIndex]!.id,
+ capturedEditRevision: editRevision,
+ projectId,
+ stack,
+ };
+ }
+ return {
+ afterId: null,
+ beforeId: layers.find((layer) => layer.type === stack)?.id ?? null,
+ capturedEditRevision: editRevision,
+ projectId,
+ stack,
+ };
+};
+
+/** The anchor that puts `layerId` back between its current same-stack neighbours once removed. */
+export const captureRestoreAnchor = (
+ layers: readonly CanvasLayerContract[],
+ layerId: string,
+ projectId: string,
+ editRevision: number
+): FlatLayerInsertionAnchor | null => {
+ const index = layers.findIndex((layer) => layer.id === layerId);
+ if (index < 0) {
+ return null;
+ }
+ const stack = layers[index]!.type;
+ return {
+ afterId: nearestAbove(layers, index, stack)?.id ?? null,
+ beforeId: nearestBelow(layers, index, stack)?.id ?? null,
+ capturedEditRevision: editRevision,
+ projectId,
+ stack,
+ };
+};
+
+export const resolveInsertionIndex = (
+ layers: readonly CanvasLayerContract[],
+ anchor: FlatLayerInsertionAnchor
+): number => {
+ const before = stackMemberIndex(layers, anchor.stack, anchor.beforeId);
+ if (before >= 0) {
+ return before;
+ }
+ const after = stackMemberIndex(layers, anchor.stack, anchor.afterId);
+ if (after >= 0) {
+ return after + 1;
+ }
+ const top = layers.findIndex((layer) => layer.type === anchor.stack);
+ return top >= 0 ? top : 0;
+};
+
+export const insertLayersAtAnchor = <Layer extends CanvasLayerContract>(
+ layers: readonly Layer[],
+ anchor: FlatLayerInsertionAnchor,
+ inserted: readonly Layer[]
+): Layer[] => {
+ const index = resolveInsertionIndex(layers, anchor);
+ return [...layers.slice(0, index), ...inserted, ...layers.slice(index)];
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts
index 3f4d7b9acd..14fbb798a9 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.test.ts
@@ -4,6 +4,7 @@ import { describe, expect, it } from 'vitest';
import {
getStackOrder,
+ haveSameStackOrders,
LAYER_STACK_ORDER,
LAYER_STACKS_TOP_FIRST,
layerStackRank,
@@ -37,6 +38,19 @@ describe('layer stacks', () => {
expect(next?.[0]).toBe(layers[0]);
});
+ it('compares documents by their stack orders, not their flat interleaving', () => {
+ const interleaved = [
+ layer('r1', 'raster'),
+ layer('i1', 'inpaint_mask'),
+ layer('c1', 'control'),
+ layer('r2', 'raster'),
+ ];
+
+ expect(haveSameStackOrders(layers, interleaved)).toBe(true);
+ expect(haveSameStackOrders(layers, [...layers].reverse())).toBe(false);
+ expect(haveSameStackOrders(layers, layers.slice(1))).toBe(false);
+ });
+
it('accepts an unchanged order, a single-member stack, and an empty stack', () => {
expect(ids(reorderLayerStack(layers, { orderedIds: ['r1', 'r2'], stack: 'raster' }))).toEqual(ids(layers));
expect(ids(reorderLayerStack(layers, { orderedIds: ['c1'], stack: 'control' }))).toEqual(ids(layers));
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
index f5813d0e58..534f02b8d2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document/layerStacks.ts
@@ -59,6 +59,15 @@ export const reorderLayerStack = <Layer extends CanvasLayerContract>(
return next;
};
+/** Whether both documents hold the same members in the same order within every stack. */
+export const haveSameStackOrders = (a: readonly CanvasLayerContract[], b: readonly CanvasLayerContract[]): boolean =>
+ a.length === b.length &&
+ LAYER_STACK_ORDER.every((stack) => {
+ const left = getStackOrder(a, stack).orderedIds;
+ const right = getStackOrder(b, stack).orderedIds;
+ return left.length === right.length && left.every((id, index) => id === right[index]);
+ });
+
/** A z-move within a stack; index 0 is the front (top). */
export type LayerStackMoveKind = 'front' | 'forward' | 'backward' | 'back';
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index ee82822b9e..2c672e974a 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -30,6 +30,8 @@ import {
type EngineTestAction = WorkbenchAction | CanvasProjectMutation;
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
+import { haveSameStackOrders } from '@workbench/canvas-engine/document/layerStacks';
import { DEFAULT_CHECKER_COLORS } from '@workbench/canvas-engine/render/compositor';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import { canvasApplicationPort } from '@workbench/canvas-operations/applicationPort';
@@ -2245,10 +2247,10 @@ describe('createCanvasEngine', () => {
.map((call) => call[0] as EngineTestAction)
.find((action) => action.type === 'applyCanvasLayerStackMutation');
expect(mutation).toBeDefined();
- const added = mutation?.type === 'applyCanvasLayerStackMutation' ? mutation.add : undefined;
+ const added = mutation?.type === 'applyCanvasLayerStackMutation' ? mutation.add?.[0] : undefined;
const addedLayer = added?.layers[0];
if (added && addedLayer?.type === 'raster') {
- expect(added.index).toBe(1);
+ expect(added.anchor).toMatchObject({ beforeId: 'a', projectId, stack: 'raster' });
expect(addedLayer.id).toBe(newId);
expect(addedLayer.name).toBe('a copy');
expect(addedLayer.source).toEqual({ bitmap: null, offset: { x: 0, y: 0 }, type: 'paint' });
@@ -4202,7 +4204,7 @@ describe('commitStructural', () => {
expect(
engine.layers.commitStructural(
'Add',
- { index: 0, layer: added, type: 'addCanvasLayer' },
+ { anchor: stackTopAnchor(projectId), layer: added, type: 'addCanvasLayer' },
{ ids: ['added'], type: 'removeCanvasLayers' }
)
).toEqual({ status: 'committed' });
@@ -6370,9 +6372,14 @@ describe('structural raster publication failure atomicity', () => {
harness.bitmapStore.markLayerDirty.mockClear();
armStructuralFault(harness.faults, failure, { allocation: 1, draw: 1 });
- expect(() => harness.engine.layers.commitLayerCopy('Copy layer', source.id, copy, 0)).toThrow(
- structuralFaultMessage(failure)
- );
+ expect(() =>
+ harness.engine.layers.commitLayerCopy(
+ 'Copy layer',
+ source.id,
+ copy,
+ harness.engine.document.captureInsertionAnchor(copy.type, source.id)
+ )
+ ).toThrow(structuralFaultMessage(failure));
expectInitialFailureExact(harness, expectedDocument);
expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);
@@ -6562,7 +6569,14 @@ describe('structural raster publication failure atomicity', () => {
const harness = createFaultHarness(document);
const originalCache = await snapshotLayerCache(harness.engine, source.id);
const originalDocument = harness.engine.document.getDocument()!;
- expect(harness.engine.layers.commitLayerCopy('Copy layer', source.id, copy, 0)).toBe(true);
+ expect(
+ harness.engine.layers.commitLayerCopy(
+ 'Copy layer',
+ source.id,
+ copy,
+ harness.engine.document.captureInsertionAnchor(copy.type, source.id)
+ )
+ ).toBe(true);
const committedDocument = structuredClone(harness.engine.document.getDocument()!);
harness.engine.history.undo();
const restoredDocument = harness.engine.document.getDocument()!;
@@ -6737,7 +6751,11 @@ describe('structural raster publication failure atomicity', () => {
expect(harness.engine.stores.canUndo.get()).toBe(true);
expect(harness.engine.stores.canRedo.get()).toBe(false);
- harness.store.dispatch({ layer: sentinel, type: 'addCanvasLayer' });
+ harness.store.dispatch({
+ anchor: stackTopAnchor(harness.engine.projectId),
+ layer: sentinel,
+ type: 'addCanvasLayer',
+ });
expect(() => harness.engine.history.undo()).not.toThrow();
expect(harness.engine.document.getDocument()!.layers.some((layer) => layer.id === copiedId)).toBe(false);
expect(harness.engine.document.getDocument()!.selectedLayerId).toBe(sentinel.id);
@@ -6759,7 +6777,14 @@ describe('structural raster publication failure atomicity', () => {
);
(harness.store.dispatch as Mock).mockClear();
- expect(harness.engine.layers.commitLayerCopy('Copy layer', liveSource.id, copy, 0)).toBe(true);
+ expect(
+ harness.engine.layers.commitLayerCopy(
+ 'Copy layer',
+ liveSource.id,
+ copy,
+ harness.engine.document.captureInsertionAnchor(copy.type, liveSource.id)
+ )
+ ).toBe(true);
expect(harness.store.dispatch).toHaveBeenCalledWith(
expect.objectContaining({ type: 'applyCanvasLayerStackMutation' })
@@ -7156,8 +7181,12 @@ describe('mergeVisibleRasterLayers', () => {
expect(getPanelSelectedIds()).toEqual([merged.id]);
engine.history.undo();
- expect(engine.document.getDocument()!.layers).toEqual(before.layers);
- expect(engine.document.getDocument()!.selectedLayerId).toBe(before.selectedLayerId);
+ const restored = engine.document.getDocument()!;
+ expect(haveSameStackOrders(restored.layers, before.layers)).toBe(true);
+ expect(restored.layers.map((layer) => before.layers.find((candidate) => candidate.id === layer.id))).toEqual(
+ restored.layers
+ );
+ expect(restored.selectedLayerId).toBe(before.selectedLayerId);
expect(engine.exports.hasExportableLayerContent('upper')).toBe(true);
expect(engine.exports.hasExportableLayerContent('below')).toBe(true);
expect(getPanelSelectedIds()).toEqual(['upper', 'below']);
@@ -10416,7 +10445,7 @@ describe('commitGeneratedImageResult', () => {
engine.lifecycle.dispose();
});
- it('copies a generated result to an unlocked raster immediately above its source and restores selection on undo', async () => {
+ it('copies a generated result to a raster at the top of the raster stack and restores selection on undo', async () => {
const above = workflowRaster('above');
const source = workflowControl('source');
const selected = workflowRaster('selected');
@@ -10445,13 +10474,13 @@ describe('commitGeneratedImageResult', () => {
}
expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([
- above.id,
result.layerId,
+ above.id,
source.id,
selected.id,
]);
expect(engine.document.getDocument()!.layers[2]).toEqual(source);
- expect(engine.document.getDocument()!.layers[1]).toMatchObject({
+ expect(engine.document.getDocument()!.layers[0]).toMatchObject({
id: result.layerId,
isEnabled: true,
isLocked: false,
@@ -10466,7 +10495,7 @@ describe('commitGeneratedImageResult', () => {
expect(engine.document.getDocument()).toEqual(document);
expect(engine.stores.canUndo.get()).toBe(false);
engine.history.redo();
- expect(engine.document.getDocument()!.layers[1]?.id).toBe(result.layerId);
+ expect(engine.document.getDocument()!.layers[0]?.id).toBe(result.layerId);
expect(engine.document.getDocument()!.selectedLayerId).toBe(result.layerId);
expect(engine.stores.canRedo.get()).toBe(false);
engine.lifecycle.dispose();
@@ -11559,7 +11588,7 @@ describe('commitMaskImageResult', () => {
target: 'regional_guidance',
},
] as const)(
- 'adds a complete $target directly above the source with one exact history entry',
+ 'adds a complete $target at the top of its stack with one exact history entry',
async ({ expected, target }) => {
const document = docFor(target);
const { projectId, store } = createReducerBackedStore(document);
@@ -11591,8 +11620,8 @@ describe('commitMaskImageResult', () => {
const created = engine.document.getDocument()!.layers.find((layer) => layer.id === result.layerId)!;
expect(created).toEqual({ ...expected, id: result.layerId });
expect(engine.document.getDocument()!.layers.map((layer) => layer.id)).toEqual([
- document.layers[0]!.id,
result.layerId,
+ document.layers[0]!.id,
'source',
'below',
]);
@@ -13627,7 +13656,14 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',
};
const copy = { ...control, id: 'control-copy', name: 'Control copy' };
- expect(engine.layers.commitLayerCopy('Copy layer', raster.id, copy, 0)).toBe(true);
+ expect(
+ engine.layers.commitLayerCopy(
+ 'Copy layer',
+ raster.id,
+ copy,
+ engine.document.captureInsertionAnchor(copy.type, raster.id)
+ )
+ ).toBe(true);
expect((await engine.exports.exportLayerPixels(copy.id)).status).toBe('ok');
engine.history.undo();
expect(engine.document.getDocument()!.layers.some((layer) => layer.id === copy.id)).toBe(false);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index af256f70d9..534b67c25e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -96,6 +96,7 @@ import {
import { MaskResultController } from '@workbench/canvas-engine/controllers/maskResultController';
import {
createCanvasMutationContext,
+ type CanvasMutationContext,
type DocumentEditPermit,
} from '@workbench/canvas-engine/controllers/mutationContext';
import { PersistenceController } from '@workbench/canvas-engine/controllers/persistenceController';
@@ -855,6 +856,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
}
};
+ const captureInsertionAnchor: CanvasMutationContext['captureInsertionAnchor'] = (stack, aboveId) =>
+ mutationContext.captureInsertionAnchor(stack, aboveId);
const editingController = new EditingController({
floatingSelection: {
applyImagePatch,
@@ -907,6 +910,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
},
text: {
canEdit: () => canEditDocument(),
+ captureInsertionAnchor,
commitStructural: (label, forward, inverse) => commitToolStructural(label, forward, inverse),
createLayerId,
getDocument: () => mirror.getDocument(),
@@ -987,6 +991,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const toolContext: ToolContext = {
applyTransform: () => applyTransform(),
backend,
+ captureInsertionAnchor,
beginPixelEdit: (layerId) => beginPixelEdit(layerId),
beginTransformSession: (layerId) => beginTransformSession(layerId),
cancelTextEdit: () => cancelTextEdit(),
@@ -1156,6 +1161,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const mutationContext = createCanvasMutationContext({
commitEdit: (intent) => mutationPort.commitEdit(intent),
createLayerId,
+ projectId,
dispatch: (action, origin) => dispatchCanvasMutation(action, origin),
editOwner: documentEditOwner,
editingLocked: stores.documentEditingLocked,
@@ -2239,6 +2245,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const layerMutationController = new LayerMutationController({
canEdit: () => canEditDocument(),
+ captureInsertionAnchor,
capturePermit: () => captureDocumentEditPermit(),
captureCache: captureLayerCache,
createLayerId,
@@ -2247,6 +2254,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
endBurst: () => endNudgeBurst(),
getDuplicateRasterPlan,
getDocument: () => mirror.getDocument(),
+ getEditRevision: () => mutationContext.getEditRevision(),
getReducerDocument,
getSelectedLayerIds: resolveSelectedLayerIds,
hasPendingPixelWork: (layerId) => bitmapStore.hasPendingWork(layerId),
@@ -2281,6 +2289,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const maskResultController = new MaskResultController({
canEdit: (owner) => canEditDocument(owner),
+ captureInsertionAnchor,
createLayerId,
dispatchPrepared: dispatchPreparedMutation,
endBurst: () => endNudgeBurst(),
@@ -2316,6 +2325,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const commitGeneratedImageResult = generatedResultController.commit.bind(generatedResultController);
const stagedResultController = new StagedResultController({
+ captureInsertionAnchor,
capturePermit: (owner) => captureDocumentEditPermit(owner),
createEventId,
createLayerId,
@@ -2694,6 +2704,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
const layerController = new LayerController({
booleanMerge: {
backend,
+ captureInsertionAnchor,
capturePermit: () => captureDocumentEditPermit(),
createLayerId,
dispatchPrepared: dispatchPreparedMutation,
@@ -2728,6 +2739,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
preparePixels: prepareGeneratedPaintCache,
},
copy: {
+ captureInsertionAnchor,
capturePermit: () => captureDocumentEditPermit(),
createLayerId,
dispatchPrepared: dispatchPreparedMutation,
@@ -2744,6 +2756,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
},
extractMaskedArea: {
backend,
+ captureInsertionAnchor,
capturePermit: () => captureDocumentEditPermit(),
createLayerId,
derived: derivedSurfaceCache,
@@ -2769,6 +2782,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
commitGeneratedImageResult,
newRasterLayer: {
backend,
+ captureInsertionAnchor,
capturePermit: () => captureDocumentEditPermit(),
createLayerId,
dispatchPrepared: dispatchPreparedMutation,
@@ -2873,6 +2887,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
isLayerExportGuardCurrent,
};
const documentCapability: CanvasDocumentCapability = {
+ captureInsertionAnchor,
+ captureRestoreAnchor: (layerId) => mutationContext.captureRestoreAnchor(layerId),
captureSnapshot: captureDocumentSnapshot,
getDocument: () => mirror.getDocument(),
getEditRevision: () => mutationContext.getEditRevision(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
index 924cc12ab4..a12be2125b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
@@ -28,6 +28,7 @@ import type {
CanvasRegionalGuidanceLayerContract,
CanvasStagingAreaContractV2,
} from './contracts';
+import type { FlatLayerInsertion, FlatLayerInsertionAnchor } from './document/insertionAnchors';
import type { ReorderFlatStackCommand } from './document/layerStacks';
export type CanvasLayerBasePatch = Partial<
@@ -60,6 +61,7 @@ export type CanvasLayerConfigPatch =
export type CanvasProjectMutation =
| {
type: 'commitStagedImage';
+ anchor: FlatLayerInsertionAnchor;
candidateFingerprint: string;
continueStaging: boolean;
event: ProjectEvent;
@@ -81,14 +83,14 @@ export type CanvasProjectMutation =
| { type: 'toggleCanvasStagingVisibility' }
| { type: 'toggleCanvasStagingThumbnailsVisibility' }
| { type: 'clearCanvasStaging' }
- | { type: 'addCanvasLayer'; layer: CanvasLayerContract; index?: number }
+ | { type: 'addCanvasLayer'; layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor }
| {
type: 'applyCanvasLayerStackMutation';
- add?: { index: number; layers: readonly CanvasLayerContract[] };
+ /** Applied in order against the document before `removeIds`, so an anchor may name a removed layer. */
+ add?: readonly FlatLayerInsertion[];
removeIds?: readonly string[];
enabledUpdates: readonly { id: string; isEnabled: boolean }[];
lockedUpdates?: readonly { id: string; isLocked: boolean }[];
- orderedIds?: readonly string[];
/** Omit to preserve the current selection, repairing it if that layer is removed. */
selectedLayerId?: string | null;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts
index 0b7ec66320..5769a3faf5 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.test.ts
@@ -1,5 +1,6 @@
import type { StrokeCommittedEvent } from '@workbench/canvas-engine/tools/tool';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { createStrokeCommit, type CreateStrokeCommitDeps } from './strokeCommit';
@@ -79,7 +80,7 @@ describe('commitOrdinaryStroke', () => {
});
describe('a stroke that auto-created its layer', () => {
- const created = { index: 2, layer: { id: 'layer-1' } as never };
+ const created = { anchor: stackTopAnchor('p'), layer: { id: 'layer-1' } as never };
it('undoes by removing the layer, not just the pixels', () => {
createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));
@@ -88,12 +89,12 @@ describe('a stroke that auto-created its layer', () => {
expect(deps.dispatchCanvasMutation).toHaveBeenCalledWith({ ids: ['layer-1'], type: 'removeCanvasLayers' });
});
- it('redoes by re-adding the layer at its index, then writing the pixels back', () => {
+ it('redoes by re-adding the layer at its anchor, then writing the pixels back', () => {
createStrokeCommit(deps).commitOrdinaryStroke(strokeEvent({ createdLayer: created } as never));
const entry = deps.history.push.mock.calls[0]?.[0] as { redo(): void };
entry.redo();
expect(deps.dispatchCanvasMutation).toHaveBeenCalledWith({
- index: 2,
+ anchor: created.anchor,
layer: created.layer,
type: 'addCanvasLayer',
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts
index dde4e20a53..d243cbb553 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/strokeCommit.ts
@@ -1,4 +1,5 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { History, HistoryEntry } from '@workbench/canvas-engine/history/history';
import type { ImagePatchApply } from '@workbench/canvas-engine/history/imagePatch';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
@@ -37,7 +38,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =
const { applyImagePatch, dispatchCanvasMutation, history, layerCache } = deps;
const createComposedPaintEntry = (
- created: { layer: CanvasLayerContract; index: number },
+ created: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor },
event: StrokeCommittedEvent,
label: string
): HistoryEntry => {
@@ -48,7 +49,7 @@ export const createStrokeCommit = (deps: CreateStrokeCommitDeps): StrokeCommit =
bytes,
label,
redo: () => {
- dispatchCanvasMutation({ index: created.index, layer: created.layer, type: 'addCanvasLayer' });
+ dispatchCanvasMutation({ anchor: created.anchor, layer: created.layer, type: 'addCanvasLayer' });
// Re-create an EMPTY cache marked fresh so the async rasterize pass can't
// clobber the restored stroke; `applyImagePatch` grows it to the stroke's
// content bounds and writes the `after` pixels.
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts
index 97d93d9f63..a42155d02f 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/bboxTool.test.ts
@@ -4,6 +4,7 @@ import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { describe, expect, it, vi } from 'vitest';
@@ -70,6 +71,7 @@ const createHarness = (doc: CanvasDocumentContractV2): Harness => {
commits.push({ forward, inverse, label });
return { status: 'committed' as const };
},
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
createLayerId: () => 'x',
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts
index 2c0558a4e4..5213e112dc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts
@@ -4,6 +4,7 @@ import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
import type { PointerInput } from '@workbench/canvas-engine/types';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { createLayerCacheStore, type LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import { describe, expect, it, vi } from 'vitest';
@@ -97,6 +98,7 @@ const createHarness = (doc: CanvasDocumentContractV2 | null): Harness => {
const ctx: ToolContext = {
backend,
commitStructural: vi.fn(),
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
createLayerId: () => 'unused',
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts
index 8e99f05891..4c422411a6 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.test.ts
@@ -4,6 +4,7 @@ import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { describe, expect, it, vi } from 'vitest';
@@ -73,6 +74,7 @@ const createHarness = (doc: CanvasDocumentContractV2) => {
commits.push({ forward, inverse, label });
return { status: 'committed' as const };
},
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
createLayerId: () => `grad-${++idCounter}`,
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
index 67b73317ce..911215942b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/gradientTool.ts
@@ -167,7 +167,11 @@ export const createGradientTool = (): Tool => {
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: doc.bbox.x, y: doc.bbox.y },
type: 'raster',
};
- const forward: CanvasProjectMutation = { index: 0, layer, type: 'addCanvasLayer' };
+ const forward: CanvasProjectMutation = {
+ anchor: ctx.captureInsertionAnchor('raster', doc.selectedLayerId),
+ layer,
+ type: 'addCanvasLayer',
+ };
const inverse: CanvasProjectMutation = { ids: [layerId], type: 'removeCanvasLayers' };
ctx.commitStructural('Add gradient', forward, inverse);
clearPreview(ctx);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
index 45ca9b9107..b2e045aaff 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/moveTool.test.ts
@@ -5,6 +5,7 @@ import type { LayerTransform } from '@workbench/canvas-engine/transform/transfor
import type { PointerInput } from '@workbench/canvas-engine/types';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { createLayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
@@ -139,6 +140,7 @@ const createHarness = (doc: CanvasDocumentContractV2, options: HarnessOptions =
commits.push({ forward, inverse, label });
return { status: 'committed' as const };
},
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
createLayerId: () => 'x',
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
index e5ede8ed2b..95f7b9c77b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.test.ts
@@ -13,6 +13,7 @@ import type {
import type { PointerInput } from '@workbench/canvas-engine/types';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { isEmpty } from '@workbench/canvas-engine/math/rect';
import { createLayerCacheStore, type LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
@@ -144,6 +145,7 @@ const createHarness = (
const ctx: ToolContext = {
backend,
...(beginPixelEdit ? { beginPixelEdit } : {}),
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
commitStructural: vi.fn(),
createLayerId: () => {
const id = `new-layer-${(idCounter += 1)}`;
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
index 67339d9f79..5f5d2df242 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/paintTool.ts
@@ -15,6 +15,7 @@
*/
import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { PointerInput } from '@workbench/canvas-engine/types';
import { isLayerPaintable, isLayerTransparencyLocked } from '@workbench/canvas-engine/document/layerEligibility';
@@ -51,8 +52,8 @@ interface PaintTarget {
layerId: string;
commit(event: StrokeCommittedEvent): void;
cancel(): void;
- /** When the gesture auto-created its layer, the created contract + insert index (for history). */
- createdLayer?: { layer: CanvasLayerContract; index: number };
+ /** When the gesture auto-created its layer, the created contract + its anchor (for history). */
+ createdLayer?: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor };
/**
* Overrides the brush colour for this gesture (mask targets paint an opaque
* stencil — the stored RGB is irrelevant, the compositor colorizes by alpha).
@@ -178,8 +179,8 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget
transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },
type: 'raster',
};
- // Auto-create inserts at the top (index 0); the reducer selects it.
- ctx.dispatch({ layer, type: 'addCanvasLayer' });
+ const anchor = ctx.captureInsertionAnchor('raster', doc.selectedLayerId);
+ ctx.dispatch({ anchor, layer, type: 'addCanvasLayer' });
// A brand-new empty paint layer: create a zero-rect cache marked fresh so the
// async rasterize pass doesn't clobber the stroke mid-gesture. The first stroke
@@ -200,7 +201,7 @@ const resolveTarget = (ctx: ToolContext, tool: PaintToolSpec['id']): PaintTarget
ctx.dispatch({ id: previousSelectedLayerId, type: 'setCanvasSelectedLayer' });
},
commit: (event) => ctx.emitStrokeCommitted(event),
- createdLayer: { index: 0, layer },
+ createdLayer: { anchor, layer },
layerId,
};
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts
index f5dcd78744..d8154abd51 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.test.ts
@@ -4,6 +4,7 @@ import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
import type { Viewport } from '@workbench/canvas-engine/viewport';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { describe, expect, it, vi } from 'vitest';
@@ -50,6 +51,7 @@ const createHarness = (doc: CanvasDocumentContractV2) => {
commits.push({ forward, inverse, label });
return { status: 'committed' as const };
},
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
createLayerId: () => `shape-${++idCounter}`,
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: (action) => dispatched.push(action),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
index c2944fabd8..ecaab22b24 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/shapeTool.ts
@@ -150,7 +150,11 @@ export const createShapeTool = (): Tool => {
type: 'raster',
};
- const forward: CanvasProjectMutation = { index: 0, layer, type: 'addCanvasLayer' };
+ const forward: CanvasProjectMutation = {
+ anchor: ctx.captureInsertionAnchor('raster', doc.selectedLayerId),
+ layer,
+ type: 'addCanvasLayer',
+ };
const inverse: CanvasProjectMutation = { ids: [layerId], type: 'removeCanvasLayers' };
ctx.commitStructural('Add shape', forward, inverse);
clearPreview(ctx);
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
index 58b58f3a02..9682b94028 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/strokeSession.ts
@@ -38,6 +38,7 @@
*/
import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
import type { LayerCacheStore } from '@workbench/canvas-engine/render/layerCache';
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import type { PlacedSurface, PointerInput, Rect, Vec2 } from '@workbench/canvas-engine/types';
@@ -74,7 +75,7 @@ export interface StrokeSessionConfig {
composite: 'source-over' | 'destination-out' | 'source-atop';
tool: 'brush' | 'eraser';
/** Set only when this gesture auto-created its paint layer (for the composed history entry). */
- createdLayer?: { layer: CanvasLayerContract; index: number } | null;
+ createdLayer?: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor } | null;
/**
* The bounded selection mask to clip the stroke to (resolved once by the tool
* on pointer-down when a selection exists), as a placed surface in document
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index ebfe020b5b..cc88527df1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -15,6 +15,8 @@
import type { StructuralCommitResult } from '@workbench/canvas-engine/capabilities';
import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/document/insertionAnchors';
+import type { LayerStackKind } from '@workbench/canvas-engine/document/layerStacks';
import type { EngineStores } from '@workbench/canvas-engine/engineStores';
import type { CreatePath2D } from '@workbench/canvas-engine/freehand';
import type { CanvasProjectMutation } from '@workbench/canvas-engine/mutationContracts';
@@ -53,7 +55,7 @@ export interface StrokeCommittedEvent {
* now-empty auto-created layer (and a redo re-adds the layer + stroke).
* Absent for strokes painted into a pre-existing layer.
*/
- createdLayer?: { layer: CanvasLayerContract; index: number };
+ createdLayer?: { layer: CanvasLayerContract; anchor: FlatLayerInsertionAnchor };
}
export interface PixelEditPatch {
@@ -95,6 +97,8 @@ export interface ToolContext {
invalidate(payload: InvalidatePayload): void;
/** Reducer bridge. Painting tools use it for the single gesture-start `addCanvasLayer`. */
dispatch(action: CanvasProjectMutation): void;
+ /** Where a layer the tool creates lands: above `aboveId` when it belongs to `stack`, else the stack top. */
+ captureInsertionAnchor(stack: LayerStackKind, aboveId: string | null): FlatLayerInsertionAnchor;
/**
* Records a structural document edit on the engine-owned canvas history:
* dispatches `forward` now, and an undo dispatches `inverse` / a redo
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
index 084f896346..4cf886dadc 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/transformTool.test.ts
@@ -4,6 +4,7 @@ import type { Tool, ToolContext } from '@workbench/canvas-engine/tools/tool';
import type { LayerTransform } from '@workbench/canvas-engine/transform/transformMath';
import type { PointerInput, Vec2 } from '@workbench/canvas-engine/types';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEngineStores } from '@workbench/canvas-engine/engineStores';
import { applyToPoint } from '@workbench/canvas-engine/math/mat2d';
import {
@@ -158,6 +159,7 @@ const createHarness = (doc: CanvasDocumentContractV2, zoom = 1, float?: Floating
floatRef.current = null;
},
commitStructural: vi.fn(),
+ captureInsertionAnchor: createTestInsertionAnchorCapture('p'),
createLayerId: () => 'x',
createPath2D: (d) => ({ d }) as unknown as Path2D,
dispatch: vi.fn(),
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
index dd3e9ee906..a96748e4f4 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/createFromBbox.test.ts
@@ -6,6 +6,7 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createEmptyPaintLayer } from '@workbench/widgets/layers/layerOps';
import { createInitialWorkbenchState } from '@workbench/workbenchState';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -105,7 +106,7 @@ const createHarness = (
return { status: 'committed' as const };
});
const engine = {
- document: { getDocument },
+ document: { captureInsertionAnchor: createTestInsertionAnchorCapture(project.id), getDocument },
exports: { exportRasterComposite },
layers: {
canCommitStructural: vi.fn(() => options.canCommitStructural ?? true),
@@ -145,7 +146,7 @@ const getCommittedLayers = (harness: ReturnType<typeof createHarness>): readonly
if (forward?.type !== 'applyCanvasLayerStackMutation' || !forward.add) {
throw new Error('Expected add stack mutation');
}
- return forward.add.layers;
+ return forward.add.flatMap((insertion) => insertion.layers);
};
describe('createFromBbox', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
index eab95b160a..02b24c6e5d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/engineRegistry.test.ts
@@ -6,6 +6,7 @@ import type {
import { accountLifecycle } from '@platform/state/accountLifecycle';
import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import {
createCompositeDedupeCache,
@@ -347,6 +348,7 @@ describe('createEngineRegistry', () => {
type: 'replaceCanvasDocument',
});
project = applyCanvasProjectMutation(project, {
+ anchor: stackTopAnchor(project.id),
layer: {
blendMode: 'normal',
id: 'pending-layer',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
index 8351170946..4ae98692d7 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.test.ts
@@ -7,6 +7,7 @@ import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { accountLifecycle } from '@platform/state/accountLifecycle';
+import { createTestInsertionAnchorCapture } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import {
createControlLayer,
createEmptyPaintLayer,
@@ -145,14 +146,19 @@ const engine = (
projectId: string,
canCommitStructural: CanvasEngine['layers']['canCommitStructural'] = vi.fn(() => true),
commitStructural: CanvasEngine['layers']['commitStructural'] = vi.fn(() => ({ status: 'committed' as const }))
-): CanvasEngine => ({ layers: { canCommitStructural, commitStructural }, projectId }) as unknown as CanvasEngine;
+): CanvasEngine =>
+ ({
+ document: { captureInsertionAnchor: createTestInsertionAnchorCapture(projectId) },
+ layers: { canCommitStructural, commitStructural },
+ projectId,
+ }) as unknown as CanvasEngine;
const getForwardLayers = (action: WorkbenchAction | CanvasProjectMutation): readonly CanvasLayerContract[] => {
const mutation = action.type === 'applyCanvasProjectMutation' ? action.mutation : action;
if (mutation.type !== 'applyCanvasLayerStackMutation' || !mutation.add) {
throw new Error('Expected add stack mutation');
}
- return mutation.add.layers;
+ return mutation.add.flatMap((insertion) => insertion.layers);
};
const expectedLayer = (
@@ -250,7 +256,7 @@ describe('importGalleryImagesToCanvas', () => {
);
expect(result.layerIds).toEqual(layers.map((layer) => layer.id));
expect(forward).toMatchObject({
- add: { index: 0 },
+ add: [{ anchor: { afterId: null, beforeId: null, projectId: project.id, stack: layers[0]!.type } }],
enabledUpdates: [],
selectedLayerId: layers[1]!.id,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
index 3258db6b7e..e63dd3ec73 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/importGalleryImages.ts
@@ -1,6 +1,6 @@
import type { GalleryImage } from '@features/gallery';
import type { ModelConfig } from '@features/models';
-import type { CanvasLayerCapability } from '@workbench/canvas-engine/api';
+import type { CanvasDocumentCapability, CanvasLayerCapability, LayerStackKind } from '@workbench/canvas-engine/api';
import type { CanvasImageRef, CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
import type { Project } from '@workbench/projectContracts';
@@ -17,6 +17,7 @@ import {
captureAccountScope,
registerAccountOwnedResource,
} from '@platform/state/accountLifecycle';
+import { captureInsertionAnchor } from '@workbench/canvas-engine/api';
import { resolveDefaultControlModelForBase } from '@workbench/widgets/layers/controlModelOptions';
import {
createControlLayer,
@@ -224,7 +225,11 @@ const resizeImages = async (
};
};
-type GalleryImportEngine = { readonly projectId: string; readonly layers: CanvasLayerCapability };
+type GalleryImportEngine = {
+ readonly projectId: string;
+ readonly document: Pick<CanvasDocumentCapability, 'captureInsertionAnchor'>;
+ readonly layers: CanvasLayerCapability;
+};
export const importGalleryImagesToCanvas = async (options: {
applyCanvasMutation: (projectId: string, mutation: CanvasProjectMutation) => boolean | void;
@@ -281,8 +286,20 @@ export const importGalleryImagesToCanvas = async (options: {
const layers = buildLayers(layerImages, destination, project, models);
const previousSelectedLayerId = capturedDocument.selectedLayerId;
+ const anchorFor = (stack: LayerStackKind) =>
+ matchingProjectEngine
+ ? matchingProjectEngine.document.captureInsertionAnchor(stack, null)
+ : captureInsertionAnchor(capturedDocument.layers, {
+ aboveId: null,
+ editRevision: project.canvas.documentRevision,
+ projectId: project.id,
+ stack,
+ });
const forward: CanvasProjectMutation = {
- add: { index: 0, layers },
+ add: [...new Set(layers.map((layer) => layer.type))].map((stack) => ({
+ anchor: anchorFor(stack),
+ layers: layers.filter((layer) => layer.type === stack),
+ })),
enabledUpdates: [],
selectedLayerId: layers.at(-1)?.id ?? previousSelectedLayerId,
type: 'applyCanvasLayerStackMutation',
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
new file mode 100644
index 0000000000..9868078245
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/canvas-operations/layerRestoreHistory.test.ts
@@ -0,0 +1,95 @@
+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';
+import { createWorkbenchStore } from '@workbench/workbenchStore';
+import { describe, expect, it } from 'vitest';
+
+import { createCanvasEngine } from './createCanvasEngine';
+
+const raster = (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',
+});
+
+const setup = (layers: CanvasLayerContract[], selectedLayerId: string) => {
+ const store = createWorkbenchStore();
+ const projectId = store.getState().activeProjectId;
+ store.commands.canvas.apply(projectId, {
+ document: { ...createEmptyCanvasDocumentV2(), layers, selectedLayerId },
+ type: 'replaceCanvasDocument',
+ });
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ mutationPort: createCanvasProjectMutationPort(store, projectId),
+ projectId,
+ reportError: () => undefined,
+ });
+ const document = () => store.queries.getProject(projectId)!.canvas.document;
+ return { document, engine, original: document() };
+};
+
+describe('layer restore through history on an interleaved document', () => {
+ it('undoes a delete and then the duplicate that preceded it', async () => {
+ const { document, engine, original } = setup(
+ [raster('r0'), createInpaintMaskLayer('m1', 'm1'), raster('r1')],
+ 'r0'
+ );
+ const duplicated = await engine.layers.duplicateLayers(['r0']);
+ 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');
+ expect(document().layers.some((layer) => layer.id === 'r0')).toBe(false);
+
+ engine.history.undo();
+ expect(document().layers.find((layer) => layer.id === 'r0')).toEqual(r0);
+
+ expect(() => engine.history.undo()).not.toThrow();
+ expect(haveSameStackOrders(document().layers, original.layers)).toBe(true);
+ expect(document().selectedLayerId).toBe('r0');
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.lifecycle.dispose();
+ });
+
+ it('restores a multi-layer delete between the surviving neighbours before undoing the duplicate', async () => {
+ const { document, engine, original } = setup(
+ [raster('r0'), createInpaintMaskLayer('m1', 'm1'), raster('r1')],
+ 'r0'
+ );
+ const duplicated = await engine.layers.duplicateLayers(['r0']);
+ if (duplicated.status !== 'duplicated') {
+ throw new Error('expected a duplicate');
+ }
+ 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');
+ expect(document().layers.map((layer) => layer.id)).toEqual(['m1', 'r1']);
+
+ engine.history.undo();
+ expect(
+ document()
+ .layers.filter((layer) => layer.type === 'raster')
+ .map((layer) => layer.id)
+ ).toEqual([duplicateId, 'r0', 'r1']);
+
+ expect(() => engine.history.undo()).not.toThrow();
+ expect(haveSameStackOrders(document().layers, original.layers)).toBe(true);
+ expect(engine.stores.canUndo.get()).toBe(false);
+ engine.lifecycle.dispose();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts
index eac203c4eb..b13be47a24 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.test.ts
@@ -1,8 +1,9 @@
import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
+import { captureRestoreAnchor } from '@workbench/canvas-engine/api';
import { describe, expect, it } from 'vitest';
-import { deleteLayerActions, duplicateLayerActions, reorderLayerActions } from './canvasLayerOps';
+import { deleteLayerActions, deleteLayersActions, duplicateLayerActions, reorderLayerActions } from './canvasLayerOps';
const layer = (id: string): CanvasLayerContract => ({
blendMode: 'normal',
@@ -25,14 +26,68 @@ describe('duplicateLayerActions', () => {
});
});
+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 at the original index on undo', () => {
- const l = layer('a');
- expect(deleteLayerActions(l, 2)).toEqual({
- forward: { ids: ['a'], type: 'removeCanvasLayers' },
- inverse: { index: 2, layer: l, type: 'addCanvasLayer' },
+ 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', () => {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts
index cfd9b6bc26..63c81a15b0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasLayerOps.ts
@@ -4,13 +4,15 @@
* action pair for `engine.layers.commitStructural`, so the
* inverse-construction logic lives in exactly one place.
*
- * Index convention matches the contract and the layers panel: index 0 is the
- * top-most layer, so "up"/"forward" moves toward index 0.
- *
* Zero React, zero import-time side effects.
*/
-import type { CanvasLayerContract, ReorderFlatStackCommand } from '@workbench/canvas-engine/api';
+import type {
+ CanvasDocumentCapability,
+ CanvasLayerContract,
+ FlatLayerInsertion,
+ ReorderFlatStackCommand,
+} from '@workbench/canvas-engine/api';
import { getStackOrder } from '@workbench/canvas-engine/api';
@@ -31,11 +33,52 @@ export const duplicateLayerActions = (sourceId: string, newId: string): Structur
inverse: { ids: [newId], type: 'removeCanvasLayers' },
});
-/** Delete a layer (forward), re-adding it at its original index on undo (inverse). */
-export const deleteLayerActions = (layer: CanvasLayerContract, index: number): StructuralActions => ({
- forward: { ids: [layer.id], type: 'removeCanvasLayers' },
- inverse: { index, layer, type: 'addCanvasLayer' },
-});
+/** 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 = (
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
index ba60b05fd1..8d5f6ec826 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutationPort.test.ts
@@ -7,6 +7,7 @@ import type {
import type { RasterSurface } from '@workbench/canvas-engine/render/raster';
import { createBitmapStore } from '@workbench/canvas-engine/document/bitmapStore';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { createTestStubRasterBackend } from '@workbench/canvas-engine/render/raster.testStub';
import { describe, expect, it, vi } from 'vitest';
@@ -79,14 +80,22 @@ const setupProjects = (originLayer: CanvasLayerContract, otherLayer: CanvasLayer
document: createEmptyCanvasDocumentV2(),
type: 'replaceCanvasDocument',
});
- store.commands.canvas.apply(originProjectId, { layer: originLayer, type: 'addCanvasLayer' });
+ store.commands.canvas.apply(originProjectId, {
+ anchor: stackTopAnchor(originProjectId, originLayer.type),
+ layer: originLayer,
+ type: 'addCanvasLayer',
+ });
store.commands.projects.create();
const otherProjectId = store.getState().activeProjectId;
store.commands.canvas.apply(otherProjectId, {
document: createEmptyCanvasDocumentV2(),
type: 'replaceCanvasDocument',
});
- store.commands.canvas.apply(otherProjectId, { layer: otherLayer, type: 'addCanvasLayer' });
+ store.commands.canvas.apply(otherProjectId, {
+ anchor: stackTopAnchor(otherProjectId, otherLayer.type),
+ layer: otherLayer,
+ type: 'addCanvasLayer',
+ });
store.commands.projects.switchTo(originProjectId);
return { originProjectId, otherProjectId, store };
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
index d85f4086a9..f7be0520a0 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
@@ -8,7 +8,10 @@ import {
type CanvasProjectMutation,
type CanvasRasterLayerContractV2,
type CanvasStateContractV2,
+ type FlatLayerInsertion,
+ type FlatLayerInsertionAnchor,
type ReorderFlatStackCommand,
+ insertLayersAtAnchor,
isHideableLayer,
reorderLayerStack,
repairSelectedLayerId,
@@ -181,7 +184,11 @@ const setCanvasLayerPositions = (
return changed ? { ...document, layers } : document;
};
+const isInsertionValid = (projectId: string, insertion: FlatLayerInsertion): boolean =>
+ insertion.anchor.projectId === projectId && insertion.layers.every((layer) => layer.type === insertion.anchor.stack);
+
const applyLayerStackMutation = (
+ projectId: string,
document: CanvasDocumentContractV2,
mutation: Extract<CanvasProjectMutation, { type: 'applyCanvasLayerStackMutation' }>
): CanvasDocumentContractV2 => {
@@ -194,8 +201,11 @@ const applyLayerStackMutation = (
for (const id of removeIds) {
projectedIds.delete(id);
}
- if (mutation.add) {
- for (const layer of mutation.add.layers) {
+ for (const insertion of mutation.add ?? []) {
+ if (!isInsertionValid(projectId, insertion)) {
+ return document;
+ }
+ for (const layer of insertion.layers) {
if (currentIds.has(layer.id) || projectedIds.has(layer.id)) {
return document;
}
@@ -205,35 +215,24 @@ const applyLayerStackMutation = (
if (
mutation.enabledUpdates.some((update) => !projectedIds.has(update.id)) ||
(mutation.lockedUpdates?.some((update) => !projectedIds.has(update.id)) ?? false) ||
- (mutation.orderedIds !== undefined &&
- (mutation.orderedIds.length !== projectedIds.size ||
- new Set(mutation.orderedIds).size !== mutation.orderedIds.length ||
- mutation.orderedIds.some((id) => !projectedIds.has(id)))) ||
(mutation.selectedLayerId !== undefined &&
mutation.selectedLayerId !== null &&
!projectedIds.has(mutation.selectedLayerId))
) {
return document;
}
- let layers = document.layers;
+ let layers: CanvasLayers = document.layers;
let changed = false;
- if (mutation.add?.layers.length) {
- const index = Math.min(Math.max(0, Math.round(mutation.add.index)), layers.length);
- layers = [...layers.slice(0, index), ...mutation.add.layers, ...layers.slice(index)];
- changed = true;
+ for (const insertion of mutation.add ?? []) {
+ if (insertion.layers.length > 0) {
+ layers = insertLayersAtAnchor(layers, insertion.anchor, insertion.layers);
+ changed = true;
+ }
}
if (removeIds.size > 0) {
layers = layers.filter((layer) => !removeIds.has(layer.id));
changed = true;
}
- if (mutation.orderedIds) {
- const orderChanged = layers.some((layer, index) => layer.id !== mutation.orderedIds?.[index]);
- if (orderChanged) {
- const byId = new Map(layers.map((layer) => [layer.id, layer]));
- layers = mutation.orderedIds.map((id) => byId.get(id)!);
- changed = true;
- }
- }
const enabledById = new Map(mutation.enabledUpdates.map((update) => [update.id, update.isEnabled]));
const lockedById = new Map(mutation.lockedUpdates?.map((update) => [update.id, update.isLocked]) ?? []);
let baseChanged = false;
@@ -270,11 +269,21 @@ const applyLayerStackMutation = (
: document;
};
-const addLayer = (document: CanvasDocumentContractV2, layer: CanvasLayerContract, index = 0) => {
- const insertIndex = Math.min(Math.max(0, Math.round(index)), document.layers.length);
+const addLayer = (
+ projectId: string,
+ document: CanvasDocumentContractV2,
+ layer: CanvasLayerContract,
+ anchor: FlatLayerInsertionAnchor
+): CanvasDocumentContractV2 => {
+ if (
+ !isInsertionValid(projectId, { anchor, layers: [layer] }) ||
+ document.layers.some((candidate) => candidate.id === layer.id)
+ ) {
+ return document;
+ }
return {
...document,
- layers: [...document.layers.slice(0, insertIndex), layer, ...document.layers.slice(insertIndex)],
+ layers: insertLayersAtAnchor(document.layers, anchor, [layer]),
selectedLayerId: layer.id,
};
};
@@ -412,8 +421,11 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro
) {
return project;
}
- const { layer } = mutation;
- if (project.canvas.document.layers.some((candidate) => candidate.id === layer.id)) {
+ const { anchor, layer } = mutation;
+ if (
+ !isInsertionValid(project.id, { anchor, layers: [layer] }) ||
+ project.canvas.document.layers.some((candidate) => candidate.id === layer.id)
+ ) {
return project;
}
const selectedLayerId = mutation.continueStaging ? project.canvas.document.selectedLayerId : layer.id;
@@ -423,7 +435,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro
...project.canvas,
document: {
...project.canvas.document,
- layers: [layer, ...project.canvas.document.layers],
+ layers: insertLayersAtAnchor(project.canvas.document.layers, anchor, [layer]),
selectedLayerId,
},
stagingArea: mutation.continueStaging
@@ -440,7 +452,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro
: project.canvas.stagingArea.pendingImages.length === 0;
if (
project.canvas.document.selectedLayerId !== expectedSelectedLayerId ||
- project.canvas.document.layers[0] !== mutation.layer ||
+ !project.canvas.document.layers.includes(mutation.layer) ||
project.events[0] !== mutation.event ||
!stagingMatchesCommit
) {
@@ -452,7 +464,7 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro
...project.canvas,
document: {
...project.canvas.document,
- layers: project.canvas.document.layers.slice(1),
+ layers: project.canvas.document.layers.filter((layer) => layer !== mutation.layer),
selectedLayerId: mutation.selectedLayerId,
},
stagingArea: mutation.stagingArea,
@@ -561,9 +573,11 @@ export const applyCanvasProjectMutation = (project: Project, mutation: CanvasPro
case 'clearCanvasStaging':
return { ...project, canvas: { ...project.canvas, stagingArea: clearStagingArea(project.canvas.stagingArea) } };
case 'addCanvasLayer':
- return updateCanvasDocument(project, (document) => addLayer(document, mutation.layer, mutation.index));
+ return updateCanvasDocument(project, (document) =>
+ addLayer(project.id, document, mutation.layer, mutation.anchor)
+ );
case 'applyCanvasLayerStackMutation':
- return updateCanvasDocument(project, (document) => applyLayerStackMutation(document, mutation));
+ return updateCanvasDocument(project, (document) => applyLayerStackMutation(project.id, document, mutation));
case 'removeCanvasLayers':
return updateCanvasDocument(project, (document) => removeLayers(document, mutation.ids));
case 'duplicateCanvasLayer':
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 5c9f9a1148..ddefb72320 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 { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import { executeCanvasHotkeyCommand, type CanvasHotkeyContext } from './canvasHotkeyCommands';
@@ -48,6 +49,9 @@ const createEngine = (interaction: Partial<CanvasInteractionState> = {}) => {
};
const engine = {
projectId: 'project',
+ document: {
+ captureRestoreAnchor: () => stackTopAnchor('project'),
+ },
history: { redo: vi.fn(), undo: vi.fn() },
interaction: {
get: vi.fn((key: string) => state[key]),
@@ -283,7 +287,10 @@ describe('delete: pixels vs layer', () => {
expect(engine.layers.commitStructural).toHaveBeenCalledWith(
'widgets.canvas.commands.deleteLayer',
{ ids: ['a', 'c'], type: 'removeCanvasLayers' },
- expect.objectContaining({ orderedIds: ['a', 'b', 'c'], selectedLayerId: 'a' })
+ expect.objectContaining({
+ add: [expect.objectContaining({ layers: [layers[0]] }), expect.objectContaining({ layers: [layers[2]] })],
+ selectedLayerId: 'a',
+ })
);
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 3c33b81719..9bf158d90e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -4,11 +4,10 @@ import type {
LayerStackMoveKind,
StructuralCommitResult,
} from '@workbench/canvas-engine/api';
-import type { StructuralActions } from '@workbench/canvasLayerOps';
import type { CanvasProjectMutationDispatch } from '@workbench/useCanvasProjectMutationDispatch';
import { isHideableLayer, isLayerHidden, moveLayersWithinStacks } from '@workbench/canvas-engine/api';
-import { deleteLayerActions, reorderLayerActions } from '@workbench/canvasLayerOps';
+import { deleteLayersActions, reorderLayerActions } from '@workbench/canvasLayerOps';
import { canMergeLayerDown } from '@workbench/widgets/layers/layerOps';
import { publishLayerPanelSelection } from '@workbench/workbenchStore';
@@ -32,31 +31,6 @@ const REORDER_KINDS: Record<string, LayerStackMoveKind> = {
'canvas.layerToFront': 'front',
};
-const deleteSelectedLayerActions = (
- layers: CanvasDocumentContractV2['layers'],
- selectedIds: readonly string[],
- selectedLayerId: string
-): 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;
- }
- if (removed.length === 1) {
- return deleteLayerActions(removed[0]!, layers.indexOf(removed[0]!));
- }
- return {
- forward: { ids: removed.map((layer) => layer.id), type: 'removeCanvasLayers' },
- inverse: {
- add: { index: 0, layers: removed },
- enabledUpdates: [],
- orderedIds: layers.map((layer) => layer.id),
- selectedLayerId,
- type: 'applyCanvasLayerStackMutation',
- },
- };
-};
-
/**
* Everything the canvas hotkey dispatcher reads or drives. The widget supplies
* these from its render scope; keeping them as an explicit parameter is what
@@ -149,12 +123,12 @@ 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 = deleteSelectedLayerActions(layers, ctx.selectedLayerIds, selectedLayer.id);
- if (actions) {
- ctx.reportStructuralCommit(
- engine.layers.commitStructural(t('widgets.canvas.commands.deleteLayer'), actions.forward, actions.inverse)
- );
- }
+ 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' }
+ );
}
} else if (commandId === 'canvas.copySelection' || commandId === 'canvas.cutSelection') {
ctx.copySelection(commandId === 'canvas.cutSelection');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts
index 85e7a39c78..ee06220d85 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/executeCanvasImageDropImport.ts
@@ -11,7 +11,7 @@ import {
import { orderCanvasImageDropImages } from './canvasImageDnd';
-type CanvasImageDropEngine = Pick<CanvasEngineHandle, 'layers' | 'projectId'>;
+type CanvasImageDropEngine = Pick<CanvasEngineHandle, 'document' | 'layers' | 'projectId'>;
export const executeCanvasImageDropImport = async ({
destination,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index c2fb78d185..6929a0cfd0 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -21,7 +21,7 @@ import { deleteLayerActions, duplicateLayerActions, reorderLayerActions } from '
import { useNotify } from '@workbench/useNotify';
import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';
import { useCanvasDocumentEditingLocked, useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { publishLayerPanelSelection, readLayerPanelSelection } from '@workbench/workbenchStore';
import {
@@ -38,7 +38,7 @@ import { useTranslation } from 'react-i18next';
export type LayerContextMenuEngine = Pick<
CanvasEngineHandle,
- 'exports' | 'interaction' | 'layers' | 'projectId' | 'tools'
+ 'document' | 'exports' | 'interaction' | 'layers' | 'projectId' | 'tools'
>;
import type {
@@ -351,9 +351,13 @@ const LayerMenu = ({
}, [commitStructural, document.selectedLayerId, engine, layer.id, notify, projectId, t]);
const handleDelete = useCallback(() => {
- const { forward, inverse } = deleteLayerActions(layer, index);
- commitStructural(t('widgets.layers.actions.delete'), forward, inverse);
- }, [commitStructural, index, layer, t]);
+ 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]);
const handleMerge = useCallback(() => {
// Pixel work: engine-only, and not recorded on the undo history.
@@ -371,11 +375,18 @@ const LayerMenu = ({
if (!copied) {
throw new Error(t('widgets.layers.actions.copyFailed'));
}
- if (!engine?.layers.commitLayerCopy(label, layer.id, copied, index)) {
+ if (
+ !engine?.layers.commitLayerCopy(
+ label,
+ layer.id,
+ copied,
+ engine.document.captureInsertionAnchor(copied.type, layer.id)
+ )
+ ) {
throw new Error(t('widgets.layers.actions.copyFailed'));
}
},
- [engine, index, layer.id, t]
+ [engine, layer.id, t]
);
const convert = useCallback(
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
index 440e2fb07b..ff4e52f0c4 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerMultiSelectionActions.tsx
@@ -10,9 +10,10 @@ import {
type CanvasLayerContract,
type LayerStackMoveKind,
} from '@workbench/canvas-engine/api';
-import { reorderLayerActions } from '@workbench/canvasLayerOps';
+import { deleteLayersActions, reorderLayerActions } from '@workbench/canvasLayerOps';
+import { useNotify } from '@workbench/useNotify';
import { useCanvasRasterContentEpoch } from '@workbench/widgets/canvas/engineStoreHooks';
-import { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { publishLayerPanelSelection } from '@workbench/workbenchStore';
import {
ArrowDownIcon,
@@ -30,9 +31,7 @@ import {
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import { deleteLayersActions } from './layerMultiSelectionModel';
-
-type MultiSelectionEngine = Pick<CanvasEngineHandle, 'exports' | 'interaction' | 'layers'>;
+type MultiSelectionEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers'>;
const BULK_TOOLTIP_POSITIONING = { placement: 'top' } as const;
interface LayerMultiSelectionActionsProps {
@@ -54,6 +53,7 @@ export const LayerMultiSelectionActions = ({
}: LayerMultiSelectionActionsProps) => {
const commitStructural = useStructuralCommit(engine);
const { t } = useTranslation();
+ const notify = useNotify();
useCanvasRasterContentEpoch(engine);
const selected = useMemo(() => {
const ids = new Set(selectedIds);
@@ -160,11 +160,13 @@ export const LayerMultiSelectionActions = ({
}, [allLocked, commitStructural, selected, t]);
const deleteSelected = useCallback(() => {
- const actions = deleteLayersActions(layers, selectedIds, selectedLayerId);
- if (actions) {
- commitStructural(t('widgets.layers.actions.deleteSelected'), actions.forward, actions.inverse);
+ const actions = engine ? deleteLayersActions(layers, selectedIds, selectedLayerId, engine.document) : null;
+ if (!actions) {
+ reportStructuralCommit({ status: engine ? 'dispatch-rejected' : 'not-ready' }, notify.error, t);
+ return;
}
- }, [commitStructural, layers, selectedIds, selectedLayerId, t]);
+ commitStructural(t('widgets.layers.actions.deleteSelected'), actions.forward, actions.inverse);
+ }, [commitStructural, engine, layers, notify, selectedIds, selectedLayerId, t]);
return (
<HStack
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMultiSelectionModel.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMultiSelectionModel.test.ts
deleted file mode 100644
index b688d5a8f8..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMultiSelectionModel.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
-
-import { describe, expect, it } from 'vitest';
-
-import { deleteLayersActions } from './layerMultiSelectionModel';
-
-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('deleteLayersActions', () => {
- it('restores non-contiguous layers, order, and primary selection on undo', () => {
- const layers = [layer('a'), layer('b'), layer('c'), layer('d')];
- expect(deleteLayersActions(layers, ['a', 'c'], 'c')).toEqual({
- forward: { ids: ['a', 'c'], type: 'removeCanvasLayers' },
- inverse: {
- add: { index: 0, layers: [layers[0], layers[2]] },
- enabledUpdates: [],
- orderedIds: ['a', 'b', 'c', 'd'],
- selectedLayerId: 'c',
- type: 'applyCanvasLayerStackMutation',
- },
- });
- });
-
- it('ignores absent ids and returns null when none exist', () => {
- expect(deleteLayersActions([layer('a')], ['missing'], 'a')).toBeNull();
- });
-
- it('refuses to delete a selection containing a locked layer', () => {
- expect(deleteLayersActions([layer('a'), { ...layer('b'), isLocked: true }], ['a', 'b'], 'a')).toBeNull();
- });
-});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMultiSelectionModel.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMultiSelectionModel.ts
deleted file mode 100644
index f8dcaba640..0000000000
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerMultiSelectionModel.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import type { CanvasLayerContract } from '@workbench/canvas-engine/api';
-import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
-
-export interface MultiLayerStructuralActions {
- forward: CanvasProjectMutation;
- inverse: CanvasProjectMutation;
-}
-
-/** Builds one reversible edit for a non-contiguous, unlocked multi-layer delete. */
-export const deleteLayersActions = (
- layers: readonly CanvasLayerContract[],
- selectedIds: readonly string[],
- selectedLayerId: string | null
-): MultiLayerStructuralActions | 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;
- }
- return {
- forward: { ids: removed.map((layer) => layer.id), type: 'removeCanvasLayers' },
- inverse: {
- add: { index: 0, layers: removed },
- enabledUpdates: [],
- orderedIds: layers.map((layer) => layer.id),
- selectedLayerId,
- type: 'applyCanvasLayerStackMutation',
- },
- };
-};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
index 4a3e6d9818..86371e3e59 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/useAddLayer.ts
@@ -1,6 +1,9 @@
+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 { useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { reportStructuralCommit, useStructuralCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { nextLayerName } from '@workbench/workbenchState';
import { useCallback } from 'react';
@@ -24,14 +27,15 @@ import { useSelectedModelBase } from './useSelectedModelBase';
/**
* Returns a single `addLayer(id)` callback that creates a new layer of the given
- * kind at the top of the stack through the guarded structural commit (one undoable
- * history entry per add). Reused by the panel's add-layer menu AND each group
- * header's "New" button so both surfaces stay in lockstep.
+ * kind through the guarded structural commit (one undoable history entry per
+ * add). Reused by the panel's add-layer menu AND each group header's "New"
+ * button so both surfaces stay in lockstep.
*/
export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
const { t } = useTranslation();
const engine = useCanvasEngine();
const commitStructural = useStructuralCommit(engine);
+ const notify = useNotify();
const base = useSelectedModelBase();
const models = useModelsSelector((snapshot) => snapshot.models);
const layerNames = useActiveProjectSelector(
@@ -47,14 +51,28 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
if (!isAddLayerItemAvailable(id, base)) {
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' }
+ );
+ };
switch (id) {
case 'raster': {
const layer = createEmptyPaintLayer(nextLayerName(layerNames));
- commitStructural(
- t('widgets.layers.actions.addRasterLayer'),
- { index: 0, layer, type: 'addCanvasLayer' },
- { ids: [layer.id], type: 'removeCanvasLayers' }
- );
+ add(t('widgets.layers.actions.addRasterLayer'), layer);
return;
}
case 'control': {
@@ -64,29 +82,17 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
base,
resolveDefaultControlModelForBase(models, base)
);
- commitStructural(
- t('widgets.layers.actions.addControlLayer'),
- { index: 0, layer, type: 'addCanvasLayer' },
- { ids: [layer.id], type: 'removeCanvasLayers' }
- );
+ add(t('widgets.layers.actions.addControlLayer'), layer);
return;
}
case 'inpaint_mask': {
const layer = createInpaintMaskLayer(nextInpaintMaskName(layerNames));
- commitStructural(
- t('widgets.layers.actions.addInpaintMask'),
- { index: 0, layer, type: 'addCanvasLayer' },
- { ids: [layer.id], type: 'removeCanvasLayers' }
- );
+ add(t('widgets.layers.actions.addInpaintMask'), layer);
return;
}
case 'regional_guidance': {
const layer = createRegionalGuidanceLayer(nextRegionalGuidanceName(layerNames), regionalGuidanceCount);
- commitStructural(
- t('widgets.layers.actions.addRegionalGuidance'),
- { index: 0, layer, type: 'addCanvasLayer' },
- { ids: [layer.id], type: 'removeCanvasLayers' }
- );
+ add(t('widgets.layers.actions.addRegionalGuidance'), layer);
return;
}
case 'regional_reference_image': {
@@ -95,15 +101,11 @@ export const useAddLayer = (): ((id: AddLayerItemId) => void) => {
regionalGuidanceCount,
base
);
- commitStructural(
- t('widgets.layers.actions.addRegionalReferenceImage'),
- { index: 0, layer, type: 'addCanvasLayer' },
- { ids: [layer.id], type: 'removeCanvasLayers' }
- );
+ add(t('widgets.layers.actions.addRegionalReferenceImage'), layer);
return;
}
}
},
- [base, commitStructural, layerNames, models, regionalGuidanceCount, t]
+ [base, commitStructural, engine, layerNames, models, notify, regionalGuidanceCount, t]
);
};
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
index fa1c7844e6..d7d9531c70 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts
@@ -1,6 +1,7 @@
import type { GalleryImageItem, GalleryVideoItem, GeneratedImageContract } from '@features/gallery';
import type { GenerateWidgetValues, MainModelConfig } from '@features/generation/contracts';
import type { ModelConfig } from '@features/models';
+import type { FlatLayerInsertionAnchor } from '@workbench/canvas-engine/api';
import type {
CanvasControlLayerContract,
CanvasInpaintMaskLayerContract,
@@ -14,6 +15,7 @@ import type { Project, WorkbenchState } from '@workbench/projectContracts';
import { GALLERY_RECENT_IMAGE_LIMIT, legacyGeneratedImageToGalleryItem } from '@features/gallery/contracts';
import { MAX_PROMPT_HISTORY } from '@features/generation/settings';
import { createDefaultUpscaleWidgetValues } from '@features/upscale';
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { CanvasProjectMutation } from './canvasProjectMutations';
@@ -140,6 +142,7 @@ const commitSelectedStagedImage = (state: WorkbenchState, projectId = state.acti
};
return reduceWorkbench(state, {
mutation: {
+ anchor: stackTopAnchor(projectId),
candidateFingerprint: getCanvasStagingCandidateFingerprint(candidate),
continueStaging: false,
event: {
@@ -366,9 +369,10 @@ const withEmptyCanvas = (state: WorkbenchState): WorkbenchState =>
workbenchReducer(state, { document: createEmptyCanvasDocumentV2(), type: 'replaceCanvasDocument' });
const withCanvasLayers = (state: WorkbenchState, layers: Project['canvas']['document']['layers']): WorkbenchState =>
- [...layers]
- .reverse()
- .reduce((next, layer) => workbenchReducer(next, { layer, type: 'addCanvasLayer' }), withEmptyCanvas(state));
+ workbenchReducer(state, {
+ document: { ...createEmptyCanvasDocumentV2(), layers: [...layers], selectedLayerId: layers[0]?.id ?? null },
+ type: 'replaceCanvasDocument',
+ });
const getCanvas = (state: WorkbenchState) => getActiveProject(state).canvas;
@@ -4019,21 +4023,117 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
expect(document.selectedLayerId).toBe(mask?.id);
});
- it('adds a layer at the top and selects it, honoring an explicit insert index', () => {
+ it('adds a layer at its anchor and selects it', () => {
let state = withEmptyCanvas(createInitialWorkbenchState());
- state = workbenchReducer(state, { layer: createRasterLayer('a'), type: 'addCanvasLayer' });
- state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });
+ state = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId),
+ layer: createRasterLayer('a'),
+ type: 'addCanvasLayer',
+ });
+ state = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId),
+ layer: createRasterLayer('b'),
+ type: 'addCanvasLayer',
+ });
expect(getLayerIds(state)).toEqual(['b', 'a']);
expect(getCanvas(state).document.selectedLayerId).toBe('b');
- state = workbenchReducer(state, { index: 1, layer: createRasterLayer('c'), type: 'addCanvasLayer' });
+ state = workbenchReducer(state, {
+ anchor: { ...stackTopAnchor(state.activeProjectId), beforeId: 'a' },
+ layer: createRasterLayer('c'),
+ type: 'addCanvasLayer',
+ });
expect(getLayerIds(state)).toEqual(['b', 'c', 'a']);
+
+ const foreign = workbenchReducer(state, {
+ anchor: stackTopAnchor('other-project'),
+ layer: createRasterLayer('d'),
+ type: 'addCanvasLayer',
+ });
+ const wrongStack = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId, 'control'),
+ layer: createRasterLayer('d'),
+ type: 'addCanvasLayer',
+ });
+ expect(foreign).toBe(state);
+ expect(wrongStack).toBe(state);
expect(getCanvas(state).document.selectedLayerId).toBe('c');
});
+ it('commits a staged image at its anchor and rolls it back by identity', () => {
+ let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);
+ state = workbenchReducer(state, { id: 'b', type: 'setCanvasSelectedLayer' });
+ const candidate: Project['canvas']['stagingArea']['pendingImages'][number] = {
+ height: 64,
+ imageName: 'staged.png',
+ imageUrl: 'url',
+ placement: { height: 64, opacity: 1, width: 64, x: 0, y: 0 },
+ queuedAt: 'now',
+ sourceQueueItemId: 'queue-1',
+ thumbnailUrl: 'thumb',
+ width: 64,
+ };
+ const stagingArea: Project['canvas']['stagingArea'] = {
+ ...getCanvas(state).stagingArea,
+ isVisible: true,
+ pendingImageIds: ['queue-1'],
+ pendingImages: [candidate],
+ selectedImageIndex: 0,
+ sourceQueueItemId: 'queue-1',
+ };
+ state = {
+ ...state,
+ projects: state.projects.map((project) =>
+ project.id === state.activeProjectId ? { ...project, canvas: { ...project.canvas, stagingArea } } : project
+ ),
+ };
+ const projectId = state.activeProjectId;
+ const layer: CanvasRasterLayerContractV2 = { ...createRasterLayer('accepted', 'staged.png'), name: 'Accepted' };
+ const event = {
+ createdAt: '2026-07-16T00:00:00.000Z',
+ id: 'event-accepted',
+ summary: 'Accepted staged.png into a new raster layer',
+ type: 'canvas-layer-accepted' as const,
+ };
+ const commit = (anchor: FlatLayerInsertionAnchor) =>
+ workbenchReducer(state, {
+ anchor,
+ candidateFingerprint: getCanvasStagingCandidateFingerprint(candidate),
+ continueStaging: false,
+ event,
+ layer,
+ selectedImageIndex: 0,
+ type: 'commitStagedImage',
+ });
+
+ expect(commit(stackTopAnchor('other-project'))).toBe(state);
+ expect(commit(stackTopAnchor(projectId, 'control'))).toBe(state);
+
+ const committed = commit({ ...stackTopAnchor(projectId), afterId: 'a' });
+ expect(getLayerIds(committed)).toEqual(['a', 'accepted', 'b']);
+ expect(getCanvas(committed).document.selectedLayerId).toBe('accepted');
+ expect(getCanvas(committed).stagingArea.pendingImages).toEqual([]);
+
+ const rollback = (rolledBackLayer: CanvasRasterLayerContractV2) =>
+ workbenchReducer(committed, {
+ continueStaging: false,
+ event,
+ layer: rolledBackLayer,
+ selectedLayerId: 'b',
+ stagingArea,
+ type: 'rollbackStagedImageCommit',
+ });
+
+ expect(rollback({ ...layer })).toBe(committed);
+ const rolledBack = rollback(layer);
+ expect(getLayerIds(rolledBack)).toEqual(['a', 'b']);
+ expect(getCanvas(rolledBack).document.selectedLayerId).toBe('b');
+ expect(getCanvas(rolledBack).stagingArea).toBe(stagingArea);
+ });
+
it('removes layers and repairs selection to the nearest remaining layer (below, then above)', () => {
let state = withCanvasLayers(createInitialWorkbenchState(), [
createRasterLayer('a'),
@@ -4208,10 +4308,14 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
it('atomically restores deleted layers into their original non-contiguous order', () => {
const layers = [createRasterLayer('a'), createRasterLayer('b'), createRasterLayer('c')];
- const removed = workbenchReducer(withCanvasLayers(createInitialWorkbenchState(), [layers[1]!]), {
- add: { index: 0, layers: [layers[0]!, layers[2]!] },
+ const initial = withCanvasLayers(createInitialWorkbenchState(), [layers[1]!]);
+ const projectId = initial.activeProjectId;
+ const removed = workbenchReducer(initial, {
+ add: [
+ { anchor: { ...stackTopAnchor(projectId), beforeId: 'b' }, layers: [layers[0]!] },
+ { anchor: { ...stackTopAnchor(projectId), afterId: 'b' }, layers: [layers[2]!] },
+ ],
enabledUpdates: [],
- orderedIds: ['a', 'b', 'c'],
selectedLayerId: 'c',
type: 'applyCanvasLayerStackMutation',
});
@@ -4228,9 +4332,8 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
type: 'setCanvasSelectedLayer',
});
const merged = workbenchReducer(initial, {
- add: { index: 0, layers: [result] },
+ add: [{ anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: 'a' }, layers: [result] }],
enabledUpdates: [],
- orderedIds: ['result', 'b'],
removeIds: ['a', 'c'],
selectedLayerId: 'result',
type: 'applyCanvasLayerStackMutation',
@@ -4240,9 +4343,11 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
expect(getCanvas(merged).document.selectedLayerId).toBe('result');
const restored = workbenchReducer(merged, {
- add: { index: 0, layers: [layers[0]!, layers[2]!] },
+ add: [
+ { anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: 'b' }, layers: [layers[0]!] },
+ { anchor: { ...stackTopAnchor(initial.activeProjectId), afterId: 'b' }, layers: [layers[2]!] },
+ ],
enabledUpdates: [],
- orderedIds: ['a', 'b', 'c'],
removeIds: ['result'],
selectedLayerId: 'c',
type: 'applyCanvasLayerStackMutation',
@@ -4297,7 +4402,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
const unrelatedBefore = getCanvas(initial).document.layers[0];
const applied = workbenchReducer(initial, {
- add: { index: 1, layers: [result] },
+ add: [{ anchor: { ...stackTopAnchor(initial.activeProjectId), beforeId: upper.id }, layers: [result] }],
enabledUpdates: [
{ id: upper.id, isEnabled: false },
{ id: below.id, isEnabled: false },
@@ -4342,7 +4447,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
const initial = withCanvasLayers(createInitialWorkbenchState(), [existing]);
const next = workbenchReducer(initial, {
- add: { index: 0, layers: [layerA, layerB] },
+ add: [{ anchor: stackTopAnchor(initial.activeProjectId), layers: [layerA, layerB] }],
enabledUpdates: [],
selectedLayerId: layerB.id,
type: 'applyCanvasLayerStackMutation',
@@ -4362,7 +4467,7 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
const layerB = createRasterLayer('b');
const next = workbenchReducer(state, {
- add: { index: 0, layers: [layerA, layerB] },
+ add: [{ anchor: stackTopAnchor(firstProjectId), layers: [layerA, layerB] }],
enabledUpdates: [],
projectId: firstProjectId,
selectedLayerId: layerB.id,
@@ -4381,11 +4486,23 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
);
const invalidActions = [
{
- add: { index: 0, layers: [createRasterLayer('a')] },
+ add: [{ anchor: stackTopAnchor(initial.activeProjectId), layers: [createRasterLayer('a')] }],
enabledUpdates: [{ id: 'b', isEnabled: false }],
selectedLayerId: 'b',
type: 'applyCanvasLayerStackMutation',
},
+ {
+ add: [{ anchor: stackTopAnchor('other-project'), layers: [createRasterLayer('c')] }],
+ enabledUpdates: [{ id: 'b', isEnabled: false }],
+ selectedLayerId: 'c',
+ type: 'applyCanvasLayerStackMutation',
+ },
+ {
+ add: [{ anchor: stackTopAnchor(initial.activeProjectId, 'control'), layers: [createRasterLayer('c')] }],
+ enabledUpdates: [{ id: 'b', isEnabled: false }],
+ selectedLayerId: 'c',
+ type: 'applyCanvasLayerStackMutation',
+ },
{
enabledUpdates: [{ id: 'a', isEnabled: false }],
removeIds: ['missing'],
@@ -4409,14 +4526,16 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
type: 'applyCanvasLayerStackMutation',
},
{
- add: { index: 0, layers: [createRasterLayer('a')] },
+ add: [{ anchor: stackTopAnchor(initial.activeProjectId), layers: [createRasterLayer('a')] }],
enabledUpdates: [],
removeIds: ['a'],
selectedLayerId: 'b',
type: 'applyCanvasLayerStackMutation',
},
{
- add: { index: 0, layers: [createRasterLayer('c'), createRasterLayer('c')] },
+ add: [
+ { anchor: stackTopAnchor(initial.activeProjectId), layers: [createRasterLayer('c'), createRasterLayer('c')] },
+ ],
enabledUpdates: [{ id: 'b', isEnabled: false }],
selectedLayerId: 'c',
type: 'applyCanvasLayerStackMutation',
@@ -4977,7 +5096,11 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
expect(getCanvas(state).snapshots[0]?.document.layers.map((layer) => layer.id)).toEqual(['a']);
// Mutate the live document, then restore the snapshot back over it.
- state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });
+ state = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId),
+ layer: createRasterLayer('b'),
+ type: 'addCanvasLayer',
+ });
expect(getLayerIds(state)).toEqual(['b', 'a']);
state = workbenchReducer(state, { snapshotId: 'snap-1', type: 'restoreCanvasSnapshot' });
@@ -4993,7 +5116,11 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
// Ordinary incremental edits never bump the revision.
state = workbenchReducer(state, { id: 'a', patch: { opacity: 0.3 }, type: 'updateCanvasLayer' });
- state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });
+ state = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId),
+ layer: createRasterLayer('b'),
+ type: 'addCanvasLayer',
+ });
state = workbenchReducer(state, { bbox: { height: 32, width: 32, x: 0, y: 0 }, type: 'setCanvasBbox' });
state = workbenchReducer(state, { height: 256, type: 'resizeCanvasDocument', width: 256 });
expect(getCanvas(state).documentRevision).toBe(initialRevision);
@@ -5018,7 +5145,11 @@ describe('workbenchReducer canvas v2 layer reducers', () => {
let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a')]);
state = workbenchReducer(state, { id: 'a', patch: { opacity: 0.3 }, type: 'updateCanvasLayer' });
- state = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });
+ state = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId),
+ layer: createRasterLayer('b'),
+ type: 'addCanvasLayer',
+ });
state = workbenchReducer(state, { ids: ['a'], type: 'removeCanvasLayers' });
expect(getActiveProject(state).undoRedo.past).toEqual([]);
@@ -5657,7 +5788,11 @@ describe('auto invocation route switching', () => {
expect(getRoute(selected)).toMatchObject({ destination: 'gallery', sourceId: 'workflow' });
- const edited = workbenchReducer(state, { layer: createRasterLayer('b'), type: 'addCanvasLayer' });
+ const edited = workbenchReducer(state, {
+ anchor: stackTopAnchor(state.activeProjectId),
+ layer: createRasterLayer('b'),
+ type: 'addCanvasLayer',
+ });
expect(getRoute(edited)).toMatchObject({ destination: 'canvas', sourceId: 'canvas' });
});
@@ -5667,7 +5802,7 @@ describe('auto invocation route switching', () => {
state = workbenchReducer(state, { sourceId: 'workflow', type: 'setInvocationSource' });
state = workbenchReducer(state, {
- add: { index: 1, layers: [createRasterLayer('b')] },
+ add: [{ anchor: { ...stackTopAnchor(state.activeProjectId), afterId: 'a' }, layers: [createRasterLayer('b')] }],
enabledUpdates: [],
selectedLayerId: 'b',
type: 'applyCanvasLayerStackMutation',
@@ -5751,6 +5886,7 @@ describe('auto invocation route switching', () => {
});
sourceLockedState = workbenchReducer(sourceLockedState, { type: 'toggleSourceLock' });
sourceLockedState = workbenchReducer(sourceLockedState, {
+ anchor: stackTopAnchor(sourceLockedState.activeProjectId),
layer: createRasterLayer('a'),
type: 'addCanvasLayer',
});
diff --git a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
index bbc755b9a4..a6ba0a304e 100644
--- a/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/workbenchStore.test.ts
@@ -1,3 +1,4 @@
+import { stackTopAnchor } from '@workbench/canvas-engine/document/insertionAnchors.testStub';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { CanvasLayerContract } from './canvas-engine/contracts';
@@ -73,8 +74,16 @@ describe('createWorkbenchStore', () => {
it('resets transient layer multi-selection across project switches even without a Layers panel', () => {
const store = createWorkbenchStore();
const firstProjectId = store.getSnapshot().activeProject.id;
- store.commands.canvas.apply(firstProjectId, { layer: paintLayer('a'), type: 'addCanvasLayer' });
- store.commands.canvas.apply(firstProjectId, { layer: paintLayer('b'), type: 'addCanvasLayer' });
+ store.commands.canvas.apply(firstProjectId, {
+ anchor: stackTopAnchor(firstProjectId),
+ layer: paintLayer('a'),
+ type: 'addCanvasLayer',
+ });
+ store.commands.canvas.apply(firstProjectId, {
+ anchor: stackTopAnchor(firstProjectId),
+ layer: paintLayer('b'),
+ type: 'addCanvasLayer',
+ });
publishLayerPanelSelection({ primaryId: 'b', projectId: firstProjectId, selectedIds: ['a', 'b'] });
const secondProject = store.commands.projects.create();
@@ -88,7 +97,11 @@ describe('createWorkbenchStore', () => {
const store = createWorkbenchStore();
const projectId = store.getSnapshot().activeProject.id;
for (const id of ['a', 'b', 'c']) {
- store.commands.canvas.apply(projectId, { layer: paintLayer(id), type: 'addCanvasLayer' });
+ store.commands.canvas.apply(projectId, {
+ anchor: stackTopAnchor(projectId),
+ layer: paintLayer(id),
+ type: 'addCanvasLayer',
+ });
}
// Model a panel-originated multi-selection: it publishes before dispatching
// its new primary, so the store preserves the selected set.