Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
refactor(canvas): complete layer action registry
joshistoast47afab0f71c9
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.jsonindex e5649e1d23..e75b406761 100644--- a/invokeai/frontend/webv2/public/locales/en.json+++ b/invokeai/frontend/webv2/public/locales/en.json@@ -1120,11 +1120,21 @@"layers": {"actions": {"addControlLayer": "Control layer",+ "addDenoiseLimit": "Add denoise limit",+ "addImageNoise": "Add image noise","addInpaintMask": "Inpaint mask",+ "addNegativePrompt": "Add negative prompt",+ "addPositivePrompt": "Add positive prompt","addRasterLayer": "Raster layer",+ "addReferenceImage": "Add reference image","addRegionalGuidance": "Regional guidance","addRegionalReferenceImage": "Regional reference image",+ "actionFailed": "Layer action failed",+ "adjustments": "Adjustments","blendMode": "Blend mode",+ "busy": "The canvas is busy. Try again when the current action finishes.",+ "copyFailed": "The layer could not be copied.",+ "copyLayerToClipboard": "Copy layer to clipboard","copyToControl": "Copy to control layer","copyToInpaintMask": "Copy to inpaint mask","copyToRasterLayer": "Copy to raster layer",@@ -1133,27 +1143,44 @@"convertToInpaintMask": "Convert to inpaint mask","convertToRaster": "Convert to raster layer","convertToRegionalGuidance": "Convert to regional guidance",+ "cropFailed": "The layer could not be cropped.",+ "cropLayerToBbox": "Crop layer to bbox","cutaway": "Cutaway with layer below","cutout": "Cutout with layer below","delete": "Delete layer",+ "disableAutoNegative": "Disable auto-negative",+ "disableTransparencyEffect": "Disable transparency effect",+ "disabled": "Enable the layer before using this action.","duplicate": "Duplicate layer",+ "empty": "This layer has no content.",+ "enableAutoNegative": "Enable auto-negative",+ "enableTransparencyEffect": "Enable transparency effect","exclude": "Exclude layer below","extractMaskedArea": "Extract masked area",+ "fitToBbox": "Fit to bbox","hide": "Hide layer","intersect": "Intersect with layer below","lock": "Lock layer",+ "locked": "Unlock the layer before using this action.","mergeDown": "Merge down",+ "missing": "The layer no longer exists.","moveBackward": "Move backward","moveForward": "Move forward","moveToBack": "Move to back","moveToFront": "Move to front",+ "notReady": "The layer content is still loading. Try again shortly.","opacity": "Opacity","rasterize": "Rasterize layer","rename": "Rename layer","reorder": "Reorder layer",+ "saveLayerToAssets": "Save layer to assets","show": "Show layer",+ "toggleAutoNegative": "Toggle auto-negative","toggleLock": "Toggle lock",+ "toggleTransparencyEffect": "Toggle transparency effect","toggleVisibility": "Toggle visibility",+ "transform": "Transform",+ "unsupported": "This action is not supported for this layer.","unlock": "Unlock layer"},"control": {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.tsindex 2acaab2f96..7ecc1a7e9e 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts@@ -3668,6 +3668,209 @@ describe('document mirror wiring: prop vs source change (paint-pixel survival)',});});+describe('hasExportableLayerContent', () => {+ const sourceLayer = (id: string, source: CanvasLayerSourceContract, isEnabled = true): CanvasLayerContract => ({+ blendMode: 'normal',+ id,+ isEnabled,+ isLocked: false,+ name: id,+ opacity: 1,+ source,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'raster',+ });++ const createContentEngine = (layers: CanvasLayerContract[]) => {+ const { store } = createFakeStore({ ...makeDoc(), layers });+ return createCanvasEngine({+ backend: createTestStubRasterBackend(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ };++ const createLiveUnpersistedLayer = async (layer: CanvasLayerContract) => {+ const raf = createControllableRaf();+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);+ vi.stubGlobal('Path2D', class FakePath2D {});++ const { setDocument, store } = createReactiveStore({+ ...makeDoc(),+ layers: [layer],+ selectedLayerId: layer.id,+ });+ const engine = createCanvasEngine({+ backend: createTestStubRasterBackend(),+ bitmapStore: createSpyBitmapStore(),+ imageResolver: () => Promise.resolve(new Blob()),+ projectId: 'p1',+ store,+ });+ const overlay = createInputCanvas();+ engine.attach(createInputCanvas().element, overlay.element);++ // Settle the initial empty paint/mask rasterization before drawing. A stroke+ // then grows that current cache without updating the persisted contract.+ raf.flush();+ await flushMicrotasks();+ raf.flush();+ engine.setTool('brush');+ overlay.fire('pointerdown', pointerAt(20, 20));+ overlay.fire('pointermove', pointerAt(40, 40));+ overlay.fire('pointerup', pointerAt(40, 40, { buttons: 0 }));++ return { engine, setDocument };+ };++ it('returns true for image, persisted paint, and every supported parametric source', () => {+ const sources: { id: string; source: CanvasLayerSourceContract }[] = [+ {+ id: 'image',+ source: { image: { height: 12, imageName: 'image', width: 14 }, type: 'image' },+ },+ {+ id: 'persisted-paint',+ source: {+ bitmap: { height: 15, imageName: 'paint', width: 16 },+ offset: { x: -3, y: 4 },+ type: 'paint',+ },+ },+ {+ id: 'rect',+ source: { fill: '#000', height: 18, kind: 'rect', stroke: null, strokeWidth: 0, type: 'shape', width: 20 },+ },+ {+ id: 'ellipse',+ source: {+ fill: '#000',+ height: 18,+ kind: 'ellipse',+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 20,+ },+ },+ {+ id: 'gradient',+ source: {+ angle: 45,+ height: 22,+ kind: 'linear',+ stops: [{ color: '#000', offset: 0 }],+ type: 'gradient',+ width: 24,+ },+ },+ {+ id: 'text',+ source: {+ align: 'left',+ color: '#000',+ content: 'Export me',+ fontFamily: 'Inter',+ fontSize: 20,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ },+ ];+ // Disabled layers remain exportable because Save/Clipboard may explicitly+ // export hidden content.+ const engine = createContentEngine(sources.map(({ id, source }) => sourceLayer(id, source, false)));++ for (const { id } of sources) {+ expect(engine.hasExportableLayerContent(id), id).toBe(true);+ }+ engine.dispose();+ });++ it('returns false for empty paint, unsupported polygon, and missing ids', () => {+ const polygon: CanvasLayerSourceContract = {+ fill: '#000',+ height: 20,+ kind: 'polygon',+ points: [+ { x: 0, y: 0 },+ { x: 20, y: 0 },+ { x: 10, y: 20 },+ ],+ stroke: null,+ strokeWidth: 0,+ type: 'shape',+ width: 20,+ };+ const engine = createContentEngine([+ sourceLayer('empty-paint', { bitmap: null, type: 'paint' }),+ sourceLayer('polygon', polygon),+ ]);++ expect(engine.hasExportableLayerContent('empty-paint')).toBe(false);+ expect(engine.hasExportableLayerContent('polygon')).toBe(false);+ expect(engine.hasExportableLayerContent('missing')).toBe(false);+ engine.dispose();+ });++ it('returns true for a persisted disabled mask and false for an empty mask', () => {+ const persistedMask: CanvasInpaintMaskLayerContract = {+ ...maskLayer('persisted-mask'),+ isEnabled: false,+ mask: {+ ...maskLayer('persisted-mask').mask,+ bitmap: { height: 17, imageName: 'persisted-mask', width: 19 },+ offset: { x: 2, y: 3 },+ },+ };+ const engine = createContentEngine([persistedMask, maskLayer('empty-mask')]);++ expect(engine.hasExportableLayerContent('persisted-mask')).toBe(true);+ expect(engine.hasExportableLayerContent('empty-mask')).toBe(false);+ engine.dispose();+ });++ it('returns true for current live unpersisted paint pixels', async () => {+ const { engine } = await createLiveUnpersistedLayer(sourceLayer('live-paint', { bitmap: null, type: 'paint' }));++ expect(engine.hasExportableLayerContent('live-paint')).toBe(true);+ engine.dispose();+ });++ it('returns false for a stale non-empty live cache with no persisted pixels', async () => {+ const { engine, setDocument } = await createLiveUnpersistedLayer(+ sourceLayer('stale-paint', { bitmap: null, type: 'paint' })+ );+ expect(engine.hasExportableLayerContent('stale-paint')).toBe(true);++ const doc = engine.getDocument()!;+ const layer = doc.layers[0];+ if (!layer || layer.type !== 'raster') {+ throw new Error('expected raster paint layer');+ }+ // A genuine source-reference change invalidates the still-non-empty live+ // cache synchronously. Do not run the scheduled frame that would rebuild it.+ setDocument({+ ...doc,+ layers: [{ ...layer, source: { bitmap: null, type: 'paint' } }],+ });+ const { target } = createThumbnailTarget();+ expect(engine.drawLayerThumbnail('stale-paint', target, 96)).toBe(true);+ expect(engine.hasExportableLayerContent('stale-paint')).toBe(false);+ engine.dispose();+ });++ it('returns true for current live unpersisted mask pixels', async () => {+ const { engine } = await createLiveUnpersistedLayer(maskLayer('live-mask'));++ expect(engine.hasExportableLayerContent('live-mask')).toBe(true);+ engine.dispose();+ });+});+// ---- I4: structural edits are no-ops during an active pointer gesture -----describe('gesture guard: nudge / commitStructural mid-stroke', () => {diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.tsindex 645cb692b6..7682a364f2 100644--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts@@ -310,6 +310,12 @@ export interface CanvasEngine {* the download name (extension appended if absent).*/exportRasterLayersToPsd(fileName: string): Promise<PsdExportResult>;+ /**+ * True when a layer has pixels that Save/Clipboard can export. Hidden layers+ * are eligible; unsupported polygon sources, missing layers, and empty or+ * stale unpersisted paint/mask caches are not.+ */+ hasExportableLayerContent(layerId: string): boolean;/*** Ensures one layer's pixels are rasterized in the shared layer cache and returns* the cache surface plus its layer-local content rect. Read-only: no dispatches,@@ -1092,6 +1098,29 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {return true;};+ const hasExportableLayerContent = (layerId: string): boolean => {+ const doc = mirror.getDocument();+ const layer = doc?.layers.find((candidate) => candidate.id === layerId);+ if (!doc || !layer) {+ return false;+ }+ const source = renderableSourceOf(layer);+ if (!source || !isSupportedExportSource(source)) {+ return false;+ }+ if (!isEmpty(getSourceContentRect(layer, doc))) {+ return true;+ }+ // Only paint-backed layers (including masks through renderableSourceOf) can+ // have real pixels beyond their persisted source rect. The live cache must+ // describe the current source revision and must not be mid-rasterization.+ if (source.type !== 'paint') {+ return false;+ }+ const entry = layerCache.get(layerId);+ return !!entry && !entry.stale && !inFlight.has(layerId) && !isEmpty(entry.rect);+ };+const rasterizeLayerPixels = async (layerId: string,options: ExportLayerPixelsOptions = {}@@ -3690,6 +3719,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngine => {}),getDocument: () => mirror.getDocument(),handleEscapePriority,+ hasExportableLayerContent,invertMask,invertSelection,mergeLayerDown,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsxindex eeb9aae234..3db4099860 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx@@ -22,7 +22,7 @@ import { useCallback, useEffect, useEffectEvent, useState } from 'react';import { useTranslation } from 'react-i18next';import { gridSizeForModelBase } from './bboxGrid';-import { isCanvasStagingActive } from './canvasInteractionLock';+import { isCanvasInteractionLocked } from './canvasInteractionLock';import {CANVAS_SETTINGS,CANVAS_SHOW_PROGRESS_KEY,@@ -157,7 +157,6 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {const selectedPlaceholder = selectedSlot?.kind === 'placeholder' ? selectedSlot : null;const hasStagingSlots = stagingSlots.length > 0;const hasMultipleStagingSlots = stagingSlots.length > 1;-const isCanvasGenerationInFlight = queueItems.some((item) =>item.snapshot.destination === 'canvas' &&@@ -168,10 +167,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {// fresh canvas (F2). `documentRevision` bumps only on those swaps.item.snapshot.canvas.documentRevision === canvas.documentRevision);- const isInteractionLocked = isCanvasStagingActive({- hasStagedCandidates: hasStagingSlots,- isCanvasGenerationInFlight,- });+ const isInteractionLocked = isCanvasInteractionLocked(canvas, queueItems);useEffect(() => {engine?.setInteractionLocked(isInteractionLocked);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.tsindex 4c9040e7a6..5d71cd1a59 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.test.ts@@ -1,8 +1,85 @@+import type { CanvasStagingCandidateContract, QueueItem, QueueItemStatus } from '@workbench/types';++import { createEmptyCanvasStateV2 } from '@workbench/canvasMigration';import { describe, expect, it } from 'vitest';-import { isCanvasStagingActive, isCanvasToolEnabled } from './canvasInteractionLock';+import { isCanvasInteractionLocked, isCanvasStagingActive, isCanvasToolEnabled } from './canvasInteractionLock';++const createStagedCandidate = (): CanvasStagingCandidateContract => ({+ height: 512,+ imageName: 'staged.png',+ imageUrl: '/api/v1/images/i/staged.png/full',+ placement: { height: 512, opacity: 1, width: 512, x: 0, y: 0 },+ queuedAt: '2026-06-09T00:00:00.000Z',+ sourceQueueItemId: 'queue-staged',+ thumbnailUrl: '/api/v1/images/i/staged.png/thumbnail',+ width: 512,+});++const createCanvas = ({ revision = 1, staged = false }: { revision?: number; staged?: boolean } = {}) => {+ const canvas = createEmptyCanvasStateV2(512, 512);+ const pendingImages = staged ? [createStagedCandidate()] : [];++ return {+ ...canvas,+ documentRevision: revision,+ stagingArea: {+ ...canvas.stagingArea,+ isVisible: staged,+ pendingImageIds: pendingImages.map((image) => image.imageName),+ pendingImages,+ },+ };+};++const createQueueItem = ({ revision = 1, status }: { revision?: number; status: QueueItemStatus }): QueueItem =>+ ({+ backendItemIds: [1],+ completedBackendItemIds: [1],+ id: `queue-${status}`,+ snapshot: {+ canvas: { documentRevision: revision },+ destination: 'canvas',+ submittedAt: '2026-06-09T00:00:00.000Z',+ },+ status,+ }) as QueueItem;describe('canvas interaction lock', () => {+ it('does not lock an empty canvas', () => {+ expect(isCanvasInteractionLocked(createCanvas(), [])).toBe(false);+ });++ it('locks while a staged candidate exists', () => {+ expect(isCanvasInteractionLocked(createCanvas({ staged: true }), [])).toBe(true);+ });++ it('locks for a pending queue item on the current document revision without staging slots', () => {+ expect(+ isCanvasInteractionLocked(createCanvas({ revision: 2 }), [createQueueItem({ revision: 2, status: 'pending' })])+ ).toBe(true);+ });++ it('locks for a running queue item on the current document revision without staging slots', () => {+ expect(+ isCanvasInteractionLocked(createCanvas({ revision: 2 }), [createQueueItem({ revision: 2, status: 'running' })])+ ).toBe(true);+ });++ it('does not lock for terminal queue items', () => {+ const canvas = createCanvas({ revision: 2 });++ for (const status of ['completed', 'failed', 'cancelled'] as const) {+ expect(isCanvasInteractionLocked(canvas, [createQueueItem({ revision: 2, status })])).toBe(false);+ }+ });++ it('does not lock for an active queue item from a stale document revision', () => {+ expect(+ isCanvasInteractionLocked(createCanvas({ revision: 2 }), [createQueueItem({ revision: 1, status: 'running' })])+ ).toBe(false);+ });+it('treats pending staged candidates and in-flight canvas generation as active staging', () => {expect(isCanvasStagingActive({ hasStagedCandidates: true, isCanvasGenerationInFlight: false })).toBe(true);expect(isCanvasStagingActive({ hasStagedCandidates: false, isCanvasGenerationInFlight: true })).toBe(true);diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.tsindex 971b6544bb..1753c9d95d 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasInteractionLock.ts@@ -1,4 +1,16 @@import type { ToolId } from '@workbench/canvas-engine/types';+import type { CanvasStateContractV2, QueueItem } from '@workbench/types';++import { getCanvasStagingSlots } from '@workbench/canvasStagingView';++export const isCanvasInteractionLocked = (canvas: CanvasStateContractV2, queueItems: readonly QueueItem[]): boolean =>+ getCanvasStagingSlots(canvas, queueItems).length > 0 ||+ queueItems.some(+ (item) =>+ item.snapshot.destination === 'canvas' &&+ item.snapshot.canvas.documentRevision === canvas.documentRevision &&+ (item.status === 'pending' || item.status === 'running')+ );export const isCanvasStagingActive = ({hasStagedCandidates,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 8067086fd5..fa9c13bea1 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -1,47 +1,46 @@-import type { CanvasEngine } from '@workbench/canvas-engine/engine';+import type { BooleanRasterOperation, CanvasEngine } from '@workbench/canvas-engine/engine';import type { GenerateReferenceImage } from '@workbench/generation/types';-import type { CanvasLayerContract, CanvasMaskContract } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasMaskContract } from '@workbench/types';import type { WorkbenchAction } from '@workbench/workbenchState';import type { LucideIcon } from 'lucide-react';import type { ComponentProps, Dispatch } from 'react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';+import { getSourceContentRect, renderableSourceOf } from '@workbench/canvas-engine/document/sources';import { deleteLayerActions, duplicateLayerActions } from '@workbench/canvasLayerOps';import { IconButton, MenuContent, RenameDialog } from '@workbench/components/ui';import { uploadGalleryImage } from '@workbench/gallery/api';import { useModelsSelector } from '@workbench/models/modelsStore';+import { useNotify } from '@workbench/useNotify';+import { isCanvasInteractionLocked } from '@workbench/widgets/canvas/canvasInteractionLock';+import { useLayerThumbnailVersion } from '@workbench/widgets/canvas/engineStoreHooks';import { getProjectWidgetValues } from '@workbench/widgetState';import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import {- ArrowDownIcon,- ArrowDownToLineIcon,ArrowRightLeftIcon,- ArrowUpIcon,- ArrowUpToLineIcon,ArrowUpDownIcon,ChevronRightIcon,CopyIcon,- CropIcon,- EyeIcon,- EyeOffIcon,- ImageIcon,- LockIcon,- LockOpenIcon,MergeIcon,MoreVerticalIcon,- PencilIcon,PlusIcon,- SaveIcon,- SlidersHorizontalIcon,- Trash2Icon,} from 'lucide-react';import { useCallback, useMemo, useState } from 'react';import { useTranslation } from 'react-i18next';import type { LayerContextMenuItem, LayerContextMenuSection, LayerContextSubmenuId } from './layerContextMenuLayout';import type { LayerMoveKind } from './layerGroups';+import type { LayerPropertiesSection } from './layerPropertiesRequestStore';-import { getLayerContextActions, type LayerContextAction, type LayerContextActionId } from './layerContextActions';+import {+ getLayerContextActions,+ type LayerConfigPatchKind,+ type LayerContextAction,+ type LayerContextActionEffects,+ type LayerContextActionId,+ type LayerContextActionState,+ type LayerType,+} from './layerContextActions';import { getLayerContextMenuLayout } from './layerContextMenuLayout';import { copyBlobToClipboard } from './layerExportActions';import { reorderWithinGroupByKind } from './layerGroups';@@ -89,6 +88,28 @@ type LayerConfigPatch =const PANEL_POSITIONING: MenuPositioning = { placement: 'bottom-end' };+const toErrorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error));++type LayerActionErrorStatus = 'busy' | 'disabled' | 'empty' | 'locked' | 'missing' | 'not-ready' | 'unsupported';++const LAYER_ACTION_ERROR_KEYS: Record<LayerActionErrorStatus, string> = {+ busy: 'widgets.layers.actions.busy',+ disabled: 'widgets.layers.actions.disabled',+ empty: 'widgets.layers.actions.empty',+ locked: 'widgets.layers.actions.locked',+ missing: 'widgets.layers.actions.missing',+ 'not-ready': 'widgets.layers.actions.notReady',+ unsupported: 'widgets.layers.actions.unsupported',+};++const hasPureExportableLayerContent = (layer: CanvasLayerContract, document: CanvasDocumentContractV2): boolean => {+ if (!renderableSourceOf(layer)) {+ return false;+ }+ const contentRect = getSourceContentRect(layer, document);+ return contentRect.width > 0 && contentRect.height > 0;+};+/** The main model's base, read from the generate widget values (drives regional ref-image support). */const useSelectedModelBase = (): string | null => {const modelKey = useActiveProjectSelector((project) => {@@ -157,11 +178,22 @@ const LayerMenu = ({onRenamingChange,}: LayerMenuProps) => {const { t } = useTranslation();+ const notify = useNotify();const base = useSelectedModelBase();- const { bbox, documentRect } = useActiveProjectSelector((project) => ({- bbox: project.canvas.document.bbox,- documentRect: { height: project.canvas.document.height, width: project.canvas.document.width, x: 0, y: 0 },- }));+ const canvas = useActiveProjectSelector((project) => project.canvas);+ const queueItems = useActiveProjectSelector((project) => project.queue.items);+ const { document } = canvas;+ const { bbox } = document;+ const documentRect = useMemo(+ () => ({ height: document.height, width: document.width, x: 0, y: 0 }),+ [document.height, document.width]+ );+ const interactionLocked = isCanvasInteractionLocked(canvas, queueItems);+ // Re-render when live, not-yet-persisted paint/mask pixels change.+ useLayerThumbnailVersion(engine, layer.id);+ const hasSupportedContent = engine+ ? engine.hasExportableLayerContent(layer.id)+ : hasPureExportableLayerContent(layer, document);const [internalRenaming, setInternalRenaming] = useState(false);// Controlled (canvas) vs. uncontrolled (panel): the canvas parent owns the flag// so the rename dialog outlives the menu closing. The panel keeps it internally.@@ -217,16 +249,32 @@ const LayerMenu = ({[dispatch, engine, layer.id, layers]);- const handleMoveToFront = useCallback(() => reorder('front', t('widgets.layers.actions.moveToFront')), [reorder, t]);- const handleMoveForward = useCallback(- () => reorder('forward', t('widgets.layers.actions.moveForward')),- [reorder, t]+ const actionState = useMemo<LayerContextActionState>(+ () => ({+ document,+ hasEngine: engine !== null,+ hasSupportedContent,+ index,+ interactionLocked,+ layer,+ }),+ [document, engine, hasSupportedContent, index, interactionLocked, layer]+ );+ const actions = useMemo(() => getLayerContextActions(actionState), [actionState]);+ const menuLayout = useMemo(() => getLayerContextMenuLayout(actions), [actions]);++ const getActionLabel = useCallback(+ (id: LayerContextActionId) => {+ const action = actions.find((entry) => entry.id === id);+ return action ? t(action.labelKey, { defaultValue: action.defaultLabel }) : id;+ },+ [actions, t]);- const handleMoveBackward = useCallback(- () => reorder('backward', t('widgets.layers.actions.moveBackward')),- [reorder, t]++ const makeStatusError = useCallback(+ (status: LayerActionErrorStatus): Error => new Error(t(LAYER_ACTION_ERROR_KEYS[status])),+ [t]);- const handleMoveToBack = useCallback(() => reorder('back', t('widgets.layers.actions.moveToBack')), [reorder, t]);const handleDuplicate = useCallback(() => {const { forward, inverse } = duplicateLayerActions(layer.id, createLayerId());@@ -252,10 +300,12 @@ const LayerMenu = ({const addCopy = useCallback((copied: CanvasLayerContract | null, label: string) => {if (!copied) {- return;+ throw new Error(t('widgets.layers.actions.copyFailed'));}if (engine) {- engine.commitLayerCopy(label, layer.id, copied, index);+ if (!engine.commitLayerCopy(label, layer.id, copied, index)) {+ throw new Error(t('widgets.layers.actions.copyFailed'));+ }return;}applyStructural(@@ -266,7 +316,7 @@ const LayerMenu = ({{ ids: [copied.id], type: 'removeCanvasLayers' });},- [dispatch, engine, index, layer.id]+ [dispatch, engine, index, layer.id, t]);const convert = useCallback(@@ -282,7 +332,7 @@ const LayerMenu = ({? convertRasterControlLayer(layer, 'raster'): null;if (!converted) {- return;+ throw makeStatusError('unsupported');}// Convert in place, preserving the pixel source + id. The inverse restores// the layer verbatim (adapter/filter config and all).@@ -299,24 +349,7 @@ const LayerMenu = ({);}},- [dispatch, engine, layer]- );-- const handleConvertToControl = useCallback(- () => convert('control', t('widgets.layers.actions.convertToControl')),- [convert, t]- );- const handleConvertToRaster = useCallback(- () => convert('raster', t('widgets.layers.actions.convertToRaster')),- [convert, t]- );- const handleConvertToInpaintMask = useCallback(- () => convert('inpaint_mask', t('widgets.layers.actions.convertToInpaintMask')),- [convert, t]- );- const handleConvertToRegionalGuidance = useCallback(- () => convert('regional_guidance', t('widgets.layers.actions.convertToRegionalGuidance')),- [convert, t]+ [dispatch, engine, layer, makeStatusError]);const handleToggleVisibility = useCallback(() => {@@ -340,20 +373,6 @@ const LayerMenu = ({[layer.name, patchBase, t]);- const actions = useMemo(- () => getLayerContextActions({ hasEngine: !!engine, index, layer, layers }),- [engine, index, layer, layers]- );- const menuLayout = useMemo(() => getLayerContextMenuLayout(actions), [actions]);-- const getActionLabel = useCallback(- (id: LayerContextActionId) => {- const action = actions.find((entry) => entry.id === id);- return action ? t(action.labelKey, { defaultValue: action.defaultLabel }) : id;- },- [actions, t]- );-const handleTransform = useCallback(() => {dispatch({ id: layer.id, type: 'setCanvasSelectedLayer' });engine?.setTool('transform');@@ -362,55 +381,86 @@ const LayerMenu = ({const handleFitToBbox = useCallback(() => {const transform = fitLayerTransformToBbox(layer, bbox, documentRect);if (!transform) {- return;+ throw makeStatusError('empty');}patchBase(getActionLabel('fit-to-bbox'), { transform }, { transform: layer.transform });- }, [bbox, documentRect, getActionLabel, layer, patchBase]);+ }, [bbox, documentRect, getActionLabel, layer, makeStatusError, patchBase]);const handleSaveToAssets = useCallback(async () => {- const result = await engine?.exportBakedLayerBlob(layer.id, { includeDisabled: true });- if (!result || result.status !== 'ok') {- return;+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = await engine.exportBakedLayerBlob(layer.id, { includeDisabled: true });+ if (result.status !== 'ok') {+ throw makeStatusError(result.status);}const file = new File([result.blob], `layer-${layer.id}.png`, { type: result.blob.type || 'image/png' });await uploadGalleryImage(file, 'none');- }, [engine, layer.id]);+ }, [engine, layer.id, makeStatusError]);const handleCopyToClipboard = useCallback(async () => {- const result = await engine?.exportBakedLayerBlob(layer.id, { includeDisabled: true });- if (!result || result.status !== 'ok') {- return;+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = await engine.exportBakedLayerBlob(layer.id, { includeDisabled: true });+ if (result.status !== 'ok') {+ throw makeStatusError(result.status);}await copyBlobToClipboard(result.blob);- }, [engine, layer.id]);+ }, [engine, layer.id, makeStatusError]);- const handleCropToBbox = useCallback(() => {- void engine?.cropLayerToBbox(layer.id);- }, [engine, layer.id]);+ const handleCropToBbox = useCallback(async () => {+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ if (!(await engine.cropLayerToBbox(layer.id))) {+ throw new Error(t('widgets.layers.actions.cropFailed'));+ }+ }, [engine, layer.id, makeStatusError, t]);- const handleExtractMaskedArea = useCallback(() => {- void engine?.extractMaskedArea(layer.id);- }, [engine, layer.id]);+ const handleExtractMaskedArea = useCallback(async () => {+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = await engine.extractMaskedArea(layer.id);+ if (result.status !== 'extracted') {+ throw makeStatusError(result.status);+ }+ }, [engine, layer.id, makeStatusError]);- const handleFilter = useCallback(() => {- dispatch({ region: 'right', type: 'openRegionWidget', widgetId: 'layers' });- requestLayerProperties(layer.id, 'filter');- }, [dispatch, layer.id]);+ const handleOpenProperties = useCallback(+ (section: LayerPropertiesSection) => {+ dispatch({ region: 'right', type: 'openRegionWidget', widgetId: 'layers' });+ requestLayerProperties(layer.id, section);+ },+ [dispatch, layer.id]+ );const handleBooleanRaster = useCallback(- (operation: 'intersect' | 'cutout' | 'cutaway' | 'exclude') => {- void engine?.booleanMergeRasterLayers(layer.id, operation);+ async (operation: BooleanRasterOperation) => {+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ const result = await engine.booleanMergeRasterLayers(layer.id, operation);+ if (result !== 'merged') {+ throw makeStatusError(result);+ }},- [engine, layer.id]+ [engine, layer.id, makeStatusError]);- const handleCopyToRaster = useCallback(() => {+ const handleCopyToRaster = useCallback(async () => {if (layer.type === 'control') {addCopy(copyControlToRaster(layer, createLayerId()), getActionLabel('copy-to-raster'));return;}- void engine?.copyLayerToRaster(layer.id);- }, [addCopy, engine, getActionLabel, layer]);+ if (!engine) {+ throw makeStatusError('not-ready');+ }+ if ((await engine.copyLayerToRaster(layer.id)) === null) {+ throw new Error(t('widgets.layers.actions.copyFailed'));+ }+ }, [addCopy, engine, getActionLabel, layer, makeStatusError, t]);const handleCopyToControl = useCallback(() => {if (layer.type === 'raster') {@@ -444,8 +494,24 @@ const LayerMenu = ({addCopy(copied, getActionLabel('copy-to-regional-guidance'));}, [addCopy, getActionLabel, layer]);+ const handleCopyTo = useCallback(+ (target: LayerType): void | Promise<void> => {+ switch (target) {+ case 'raster':+ return handleCopyToRaster();+ case 'control':+ return handleCopyToControl();+ case 'inpaint_mask':+ return handleCopyToInpaintMask();+ case 'regional_guidance':+ return handleCopyToRegionalGuidance();+ }+ },+ [handleCopyToControl, handleCopyToInpaintMask, handleCopyToRaster, handleCopyToRegionalGuidance]+ );+const handleLayerConfigAction = useCallback(- (id: LayerContextActionId) => {+ (id: LayerConfigPatchKind) => {if (id === 'control-transparency-effect' && layer.type === 'control') {const { forward, inverse } = getControlTransparencyEffectPatch(layer);patchConfig(getActionLabel(id), forward, inverse);@@ -472,130 +538,73 @@ const LayerMenu = ({[base, getActionLabel, layer, patchConfig]);- const handleAction = useCallback(- (id: LayerContextActionId) => {- switch (id) {- case 'move-to-front':- handleMoveToFront();- break;- case 'move-forward':- handleMoveForward();- break;- case 'move-backward':- handleMoveBackward();- break;- case 'move-to-back':- handleMoveToBack();- break;- case 'duplicate':- handleDuplicate();- break;- case 'rename':- openRename();- break;- case 'transform':- handleTransform();- break;- case 'fit-to-bbox':- handleFitToBbox();- break;- case 'save-to-assets':- void handleSaveToAssets();- break;- case 'copy-to-clipboard':- void handleCopyToClipboard();- break;- case 'crop-to-bbox':- handleCropToBbox();- break;- case 'extract-masked-area':- handleExtractMaskedArea();- break;- case 'filter':- handleFilter();- break;- case 'intersect':- case 'cutout':- case 'cutaway':- case 'exclude':- handleBooleanRaster(id);- break;- case 'copy-to-raster':- handleCopyToRaster();- break;- case 'copy-to-control':- handleCopyToControl();- break;- case 'copy-to-inpaint-mask':- handleCopyToInpaintMask();- break;- case 'copy-to-regional-guidance':- handleCopyToRegionalGuidance();- break;- case 'rasterize':- handleRasterize();- break;- case 'convert-to-control':- handleConvertToControl();- break;- case 'convert-to-raster':- handleConvertToRaster();- break;- case 'convert-to-inpaint-mask':- handleConvertToInpaintMask();- break;- case 'convert-to-regional-guidance':- handleConvertToRegionalGuidance();- break;- case 'merge-down':- handleMerge();- break;- case 'toggle-visibility':- handleToggleVisibility();- break;- case 'toggle-lock':- handleToggleLock();- break;- case 'delete':- handleDelete();- break;- default:- handleLayerConfigAction(id);- break;- }- },+ const effects = useMemo<LayerContextActionEffects>(+ () => ({+ booleanMerge: handleBooleanRaster,+ convertTo: (target) => {+ const actionId: LayerContextActionId =+ target === 'control'+ ? 'convert-to-control'+ : target === 'raster'+ ? 'convert-to-raster'+ : target === 'inpaint_mask'+ ? 'convert-to-inpaint-mask'+ : 'convert-to-regional-guidance';+ convert(target, getActionLabel(actionId));+ },+ copyTo: handleCopyTo,+ copyToClipboard: handleCopyToClipboard,+ cropToBbox: handleCropToBbox,+ delete: handleDelete,+ duplicate: handleDuplicate,+ extractMaskedArea: handleExtractMaskedArea,+ fitToBbox: handleFitToBbox,+ mergeDown: handleMerge,+ openProperties: handleOpenProperties,+ openRename,+ patchConfig: handleLayerConfigAction,+ rasterize: handleRasterize,+ reorder: (kind, actionId) => reorder(kind, getActionLabel(actionId)),+ saveToAssets: handleSaveToAssets,+ toggleLock: handleToggleLock,+ toggleVisibility: handleToggleVisibility,+ transform: handleTransform,+ }),[- handleConvertToControl,- handleConvertToInpaintMask,- handleConvertToRegionalGuidance,- handleConvertToRaster,+ convert,+ getActionLabel,handleBooleanRaster,- handleCopyToControl,+ handleCopyTo,handleCopyToClipboard,- handleCopyToInpaintMask,- handleCopyToRaster,- handleCopyToRegionalGuidance,handleCropToBbox,handleDelete,handleDuplicate,handleExtractMaskedArea,handleFitToBbox,- handleFilter,handleLayerConfigAction,handleMerge,- handleMoveBackward,- handleMoveForward,- handleMoveToBack,- handleMoveToFront,+ handleOpenProperties,handleRasterize,+ handleSaveToAssets,handleToggleLock,handleToggleVisibility,handleTransform,- handleSaveToAssets,openRename,+ reorder,]);+ const runAction = useCallback(+ (action: LayerContextAction) => {+ void Promise.resolve()+ .then(() => action.handler({ ...actionState, effects }))+ .catch((error: unknown) => {+ notify.error(t('widgets.layers.actions.actionFailed'), toErrorMessage(error));+ });+ },+ [actionState, effects, notify, t]+ );+return (<><Menu.Root@@ -622,7 +631,7 @@ const LayerMenu = ({<Menu.Positioner><MenuContent minW="14rem" py="1">{menuLayout.map((section) => (- <LayerMenuSection key={section.id} handleAction={handleAction} section={section} t={t} />+ <LayerMenuSection key={section.id} runAction={runAction} section={section} t={t} />))}</MenuContent></Menu.Positioner>@@ -747,46 +756,6 @@ export const CanvasLayerContextMenu = ({);};-const LAYER_ACTION_ICONS: Record<LayerContextActionId, LucideIcon> = {- 'control-transparency-effect': SlidersHorizontalIcon,- 'copy-to-clipboard': CopyIcon,- 'copy-to-control': CopyIcon,- 'copy-to-inpaint-mask': CopyIcon,- 'copy-to-raster': CopyIcon,- 'copy-to-regional-guidance': CopyIcon,- 'crop-to-bbox': CropIcon,- 'convert-to-control': SlidersHorizontalIcon,- 'convert-to-inpaint-mask': ImageIcon,- 'convert-to-raster': ImageIcon,- 'convert-to-regional-guidance': ImageIcon,- cutaway: MergeIcon,- cutout: MergeIcon,- delete: Trash2Icon,- duplicate: CopyIcon,- exclude: MergeIcon,- 'extract-masked-area': CropIcon,- 'fit-to-bbox': ImageIcon,- filter: SlidersHorizontalIcon,- 'inpaint-denoise-limit': SlidersHorizontalIcon,- 'inpaint-noise': SlidersHorizontalIcon,- intersect: MergeIcon,- 'merge-down': MergeIcon,- 'move-backward': ArrowDownIcon,- 'move-forward': ArrowUpIcon,- 'move-to-back': ArrowDownToLineIcon,- 'move-to-front': ArrowUpToLineIcon,- rasterize: ImageIcon,- 'regional-auto-negative': SlidersHorizontalIcon,- 'regional-negative-prompt': PencilIcon,- 'regional-positive-prompt': PencilIcon,- 'regional-reference-image': ImageIcon,- rename: PencilIcon,- 'save-to-assets': SaveIcon,- 'toggle-lock': LockIcon,- 'toggle-visibility': EyeIcon,- transform: SlidersHorizontalIcon,-};-const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();const SUBMENU_META: Record<LayerContextSubmenuId, { defaultLabel: string; icon: LucideIcon; labelKey: string }> = {@@ -805,11 +774,11 @@ const SUBMENU_META: Record<LayerContextSubmenuId, { defaultLabel: string; icon:const SUBMENU_POSITIONING = { placement: 'right-start' } as const;const LayerMenuSection = ({- handleAction,+ runAction,section,t,}: {- handleAction: (id: LayerContextActionId) => void;+ runAction: (action: LayerContextAction) => void;section: LayerContextMenuSection;t: (key: string, options: { defaultValue: string }) => string;}) => {@@ -817,8 +786,8 @@ const LayerMenuSection = ({<LayerMenuLayoutItemkey={item.kind === 'action' ? item.action.id : item.id}compact={section.presentation === 'row'}- handleAction={handleAction}item={item}+ runAction={runAction}t={t}/>));@@ -837,35 +806,35 @@ const LayerMenuSection = ({const LayerMenuLayoutItem = ({compact,- handleAction,item,+ runAction,t,}: {compact: boolean;- handleAction: (id: LayerContextActionId) => void;item: LayerContextMenuItem;+ runAction: (action: LayerContextAction) => void;t: (key: string, options: { defaultValue: string }) => string;}) => {if (item.kind === 'action') {return compact ? (- <LayerMenuIconActionItem action={item.action} handleAction={handleAction} t={t} />+ <LayerMenuIconActionItem action={item.action} runAction={runAction} t={t} />) : (- <LayerMenuActionItem action={item.action} handleAction={handleAction} t={t} />+ <LayerMenuActionItem action={item.action} runAction={runAction} t={t} />);}- return <LayerMenuSubmenu compact={compact} handleAction={handleAction} item={item} t={t} />;+ return <LayerMenuSubmenu compact={compact} item={item} runAction={runAction} t={t} />;};const LayerMenuSubmenu = ({compact,- handleAction,item,+ runAction,t,}: {compact: boolean;- handleAction: (id: LayerContextActionId) => void;item: Extract<LayerContextMenuItem, { kind: 'submenu' }>;+ runAction: (action: LayerContextAction) => void;t: (key: string, options: { defaultValue: string }) => string;}) => {const meta = SUBMENU_META[item.id];@@ -894,7 +863,7 @@ const LayerMenuSubmenu = ({<Menu.Positioner><MenuContent minW="13rem" py="1">{item.actions.map((action) => (- <LayerMenuActionItem key={action.id} action={action} handleAction={handleAction} t={t} />+ <LayerMenuActionItem key={action.id} action={action} runAction={runAction} t={t} />))}</MenuContent></Menu.Positioner>@@ -905,19 +874,19 @@ const LayerMenuSubmenu = ({const LayerMenuIconActionItem = ({action,- handleAction,+ runAction,t,}: {action: LayerContextAction;- handleAction: (id: LayerContextActionId) => void;+ runAction: (action: LayerContextAction) => void;t: (key: string, options: { defaultValue: string }) => string;}) => {- const onSelect = useCallback(() => handleAction(action.id), [action.id, handleAction]);+ const onSelect = useCallback(() => runAction(action), [action, runAction]);return (<LayerMenuIconItemdisabled={action.isDisabled}- icon={LAYER_ACTION_ICONS[action.id]}+ icon={action.icon}label={t(action.labelKey, { defaultValue: action.defaultLabel })}value={action.id}onSelect={onSelect}@@ -927,20 +896,20 @@ const LayerMenuIconActionItem = ({const LayerMenuActionItem = ({action,- handleAction,+ runAction,t,}: {action: LayerContextAction;- handleAction: (id: LayerContextActionId) => void;+ runAction: (action: LayerContextAction) => void;t: (key: string, options: { defaultValue: string }) => string;}) => {- const onSelect = useCallback(() => handleAction(action.id), [action.id, handleAction]);+ const onSelect = useCallback(() => runAction(action), [action, runAction]);return (<LayerMenuItemcolor={action.tone === 'danger' ? 'fg.error' : undefined}disabled={action.isDisabled}- icon={getLayerActionIcon(action)}+ icon={action.icon}label={t(action.labelKey, { defaultValue: action.defaultLabel })}value={action.id}onSelect={onSelect}@@ -948,16 +917,6 @@ const LayerMenuActionItem = ({);};-const getLayerActionIcon = (action: LayerContextAction): LucideIcon => {- if (action.id === 'toggle-visibility') {- return action.defaultLabel === 'Hide' ? EyeOffIcon : EyeIcon;- }- if (action.id === 'toggle-lock') {- return action.defaultLabel === 'Unlock' ? LockOpenIcon : LockIcon;- }- return LAYER_ACTION_ICONS[action.id];-};-const LayerMenuItem = ({color,disabled,diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.tsindex 4bdf42d9a7..b36ee2cea3 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -1,8 +1,17 @@-import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';-import { getLayerContextActions } from './layerContextActions';+import {+ getLayerContextActionDefinition,+ getLayerContextActions,+ LAYER_CONTEXT_ACTION_DEFINITIONS,+ type LayerContextAction,+ type LayerContextActionEffects,+ type LayerContextActionId,+ type LayerContextActionRuntimeContext,+ type LayerContextActionState,+} from './layerContextActions';import {createControlLayer,createEmptyPaintLayer,@@ -10,23 +19,386 @@ import {createRegionalGuidanceLayer,} from './layerOps';-const paintLayer = (id: string, patch: Partial<CanvasRasterLayerContractV2> = {}): CanvasLayerContract => ({+const englishCatalogModules = import.meta.glob('../../../../public/locales/en.json', {+ eager: true,+ import: 'default',+});+const en = Object.values(englishCatalogModules)[0] as unknown;++const paintLayer = (id: string, patch: Partial<CanvasRasterLayerContractV2> = {}): CanvasRasterLayerContractV2 => ({...createEmptyPaintLayer(id, id),+ source: { bitmap: { height: 10, imageName: `${id}.png`, width: 10 }, type: 'paint' },...patch,});-const idsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer], hasEngine = true) =>- getLayerContextActions({ hasEngine, index: layers.indexOf(layer), layer, layers }).map((action) => action.id);+const rasterLayer = paintLayer('raster');+const nonEmptyControlLayer = {+ ...createControlLayer('Control', 'control'),+ source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' as const },+};++const makeLayer = (type: CanvasLayerContract['type']): CanvasLayerContract => {+ switch (type) {+ case 'raster':+ return paintLayer('raster');+ case 'control':+ return nonEmptyControlLayer;+ case 'inpaint_mask':+ return createInpaintMaskLayer('Mask', 'mask');+ case 'regional_guidance':+ return createRegionalGuidanceLayer('Region', 0, 'region');+ }+};++const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ height: 512,+ layers,+ selectedLayerId: layers[0]?.id ?? null,+ version: 2,+ width: 512,+});++const makeState = (+ layer: CanvasLayerContract,+ overrides: Partial<LayerContextActionState> = {}+): LayerContextActionState => {+ const document = overrides.document ?? makeDocument([layer]);+ return {+ document,+ hasEngine: true,+ hasSupportedContent: true,+ index: document.layers.findIndex((entry) => entry.id === layer.id),+ interactionLocked: false,+ layer,+ ...overrides,+ };+};++const makeEffects = (): LayerContextActionEffects => ({+ booleanMerge: vi.fn(() => Promise.resolve()),+ copyTo: vi.fn(),+ copyToClipboard: vi.fn(() => Promise.resolve()),+ cropToBbox: vi.fn(() => Promise.resolve()),+ delete: vi.fn(),+ duplicate: vi.fn(),+ extractMaskedArea: vi.fn(() => Promise.resolve()),+ fitToBbox: vi.fn(),+ mergeDown: vi.fn(),+ openProperties: vi.fn(),+ openRename: vi.fn(),+ patchConfig: vi.fn(),+ rasterize: vi.fn(),+ reorder: vi.fn(),+ saveToAssets: vi.fn(() => Promise.resolve()),+ toggleLock: vi.fn(),+ toggleVisibility: vi.fn(),+ transform: vi.fn(),+ convertTo: vi.fn(),+});++const makeRuntimeContext = (+ layer: CanvasLayerContract,+ overrides: Partial<LayerContextActionRuntimeContext> = {}+): LayerContextActionRuntimeContext => ({+ ...makeState(layer, overrides),+ effects: makeEffects(),+ ...overrides,+});++const byId = (actions: readonly LayerContextAction[], id: LayerContextActionId): LayerContextAction => {+ const action = actions.find((entry) => entry.id === id);+ expect(action, `Expected action ${id}`).toBeDefined();+ return action!;+};++const idsFor = (+ layer: CanvasLayerContract,+ layers: readonly CanvasLayerContract[] = [layer],+ overrides: Partial<LayerContextActionState> = {}+): LayerContextActionId[] =>+ getLayerContextActions(makeState(layer, { document: makeDocument([...layers]), ...overrides })).map(+ (action) => action.id+ );++const getEnglishTranslation = (key: string): unknown =>+ key.split('.').reduce<unknown>((value, segment) => {+ if (!value || typeof value !== 'object') {+ return undefined;+ }+ return (value as Record<string, unknown>)[segment];+ }, en);++describe('layer context action registry', () => {+ it('defines every action as complete executable data', () => {+ for (const definition of LAYER_CONTEXT_ACTION_DEFINITIONS) {+ expect(definition.icon).toBeDefined();+ expect(definition.section).toMatch(/^(quick|primary|operations|output|state|danger)$/);+ expect(definition.order).toEqual(expect.any(Number));+ expect(definition.supportedLayerTypes.length).toBeGreaterThan(0);+ expect(definition.isVisible).toEqual(expect.any(Function));+ expect(definition.isEnabled).toEqual(expect.any(Function));+ expect(definition.handler).toEqual(expect.any(Function));+ }+ });++ it('has one definition per action id', () => {+ const ids = LAYER_CONTEXT_ACTION_DEFINITIONS.map((definition) => definition.id);+ expect(new Set(ids).size).toBe(ids.length);+ });++ it('has English translations for registry labels and action errors', () => {+ const keys = [+ ...LAYER_CONTEXT_ACTION_DEFINITIONS.map((definition) => definition.labelKey),+ 'widgets.layers.actions.enableTransparencyEffect',+ 'widgets.layers.actions.disableTransparencyEffect',+ 'widgets.layers.actions.enableAutoNegative',+ 'widgets.layers.actions.disableAutoNegative',+ 'widgets.layers.actions.actionFailed',+ 'widgets.layers.actions.missing',+ 'widgets.layers.actions.unsupported',+ 'widgets.layers.actions.busy',+ 'widgets.layers.actions.locked',+ 'widgets.layers.actions.notReady',+ 'widgets.layers.actions.empty',+ 'widgets.layers.actions.disabled',+ 'widgets.layers.actions.copyFailed',+ 'widgets.layers.actions.cropFailed',+ ];++ for (const key of keys) {+ expect(getEnglishTranslation(key), key).toEqual(expect.any(String));+ }+ });++ it('throws for an unknown action definition', () => {+ expect(() => getLayerContextActionDefinition('unknown' as LayerContextActionId)).toThrow(+ 'Unknown layer context action: unknown'+ );+ });++ it('dispatches a registry handler through injected effects', () => {+ const transform = vi.fn();+ const context = makeRuntimeContext(rasterLayer, { effects: { ...makeEffects(), transform } });+ getLayerContextActionDefinition('transform').handler(context);+ expect(transform).toHaveBeenCalledOnce();+ });++ it('dispatches parameterized registry handlers through injected effects', () => {+ const effects = makeEffects();+ const context = makeRuntimeContext(rasterLayer, { effects });++ getLayerContextActionDefinition('move-to-front').handler(context);+ getLayerContextActionDefinition('adjustments').handler(context);+ getLayerContextActionDefinition('intersect').handler(context);+ getLayerContextActionDefinition('copy-to-control').handler(context);+ getLayerContextActionDefinition('convert-to-control').handler(context);+ getLayerContextActionDefinition('regional-auto-negative').handler(context);++ expect(effects.reorder).toHaveBeenCalledWith('front', 'move-to-front');+ expect(effects.openProperties).toHaveBeenCalledWith('adjustments');+ expect(effects.booleanMerge).toHaveBeenCalledWith('intersect');+ expect(effects.copyTo).toHaveBeenCalledWith('control');+ expect(effects.convertTo).toHaveBeenCalledWith('control');+ expect(effects.patchConfig).toHaveBeenCalledWith('regional-auto-negative');+ });+});describe('getLayerContextActions', () => {+ it.each([+ ['raster', 'adjustments', true],+ ['control', 'adjustments', false],+ ['inpaint_mask', 'extract-masked-area', true],+ ['control', 'extract-masked-area', false],+ ] as const)('resolves %s visibility for %s', (type, actionId, expected) => {+ const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === actionId);+ expect(Boolean(action)).toBe(expected);+ });++ it.each([+ ['raster', true],+ ['control', true],+ ['inpaint_mask', false],+ ['regional_guidance', false],+ ] as const)('exposes transform only for engine-supported %s layers', (type, expected) => {+ const action = getLayerContextActions(makeState(makeLayer(type))).find((item) => item.id === 'transform');+ expect(Boolean(action)).toBe(expected);+ });++ it('disables transform for a hidden layer', () => {+ const hidden = { ...rasterLayer, isEnabled: false };+ expect(byId(getLayerContextActions(makeState(hidden)), 'transform').isDisabled).toBe(true);+ });++ it('disables mutating pixel actions while interaction is locked', () => {+ const rasterActions = getLayerContextActions(makeState(rasterLayer, { interactionLocked: true }));+ const controlActions = getLayerContextActions(makeState(nonEmptyControlLayer, { interactionLocked: true }));+ expect(byId(rasterActions, 'crop-to-bbox').isDisabled).toBe(true);+ expect(byId(rasterActions, 'transform').isDisabled).toBe(true);+ expect(byId(controlActions, 'filter').isDisabled).toBe(true);+ expect(byId(rasterActions, 'copy-to-clipboard').isDisabled).toBe(true);+ });++ it('disables every layer action while canvas interaction is locked', () => {+ const above = paintLayer('interaction-above');+ const raster = paintLayer('interaction-raster');+ const below = paintLayer('interaction-below');+ const rasterDocument = makeDocument([above, raster, below]);+ const text = paintLayer('interaction-text', {+ source: {+ align: 'left',+ color: '#fff',+ content: 'locked',+ fontFamily: 'Inter',+ fontSize: 32,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });+ const inpaint = createInpaintMaskLayer('Interaction mask', 'interaction-mask');+ const regional = createRegionalGuidanceLayer('Interaction region', 0, 'interaction-region');+ const contexts = [+ makeState(raster, { document: rasterDocument, interactionLocked: true }),+ makeState(nonEmptyControlLayer, { interactionLocked: true }),+ makeState(inpaint, { interactionLocked: true }),+ makeState(regional, { interactionLocked: true }),+ makeState(text, { interactionLocked: true }),+ ];+ const actions = contexts.flatMap((context) => getLayerContextActions(context));+ const actionsById = new Map(actions.map((action) => [action.id, action]));+ const actionIds: readonly LayerContextActionId[] = [+ 'move-to-front',+ 'move-forward',+ 'move-backward',+ 'move-to-back',+ 'duplicate',+ 'rename',+ 'transform',+ 'fit-to-bbox',+ 'adjustments',+ 'save-to-assets',+ 'copy-to-clipboard',+ 'crop-to-bbox',+ 'extract-masked-area',+ 'filter',+ 'intersect',+ 'cutout',+ 'cutaway',+ 'exclude',+ 'copy-to-raster',+ 'copy-to-control',+ 'copy-to-inpaint-mask',+ 'copy-to-regional-guidance',+ 'rasterize',+ 'convert-to-control',+ 'convert-to-raster',+ 'convert-to-inpaint-mask',+ 'convert-to-regional-guidance',+ 'control-transparency-effect',+ 'regional-positive-prompt',+ 'regional-negative-prompt',+ 'regional-reference-image',+ 'regional-auto-negative',+ 'inpaint-noise',+ 'inpaint-denoise-limit',+ 'merge-down',+ 'toggle-visibility',+ 'toggle-lock',+ 'delete',+ ];++ expect(actionIds).toHaveLength(LAYER_CONTEXT_ACTION_DEFINITIONS.length);+ expect(actionIds.filter((id) => !actionsById.has(id))).toEqual([]);+ expect([...new Set(actions.filter((action) => !action.isDisabled).map((action) => action.id))]).toEqual([]);+ });++ it('still allows non-destructive copy and export from a locked layer when interaction is free', () => {+ const actions = getLayerContextActions(makeState({ ...rasterLayer, isLocked: true }));+ expect(byId(actions, 'copy-to-clipboard').isDisabled).toBe(false);+ expect(byId(actions, 'save-to-assets').isDisabled).toBe(false);+ });++ it('disables locked-layer mutations but keeps toggle lock enabled', () => {+ const lockedRaster = { ...rasterLayer, isLocked: true };+ const below = paintLayer('below-locked-raster');+ const actions = getLayerContextActions(makeState(lockedRaster, { document: makeDocument([lockedRaster, below]) }));++ for (const id of [+ 'fit-to-bbox',+ 'adjustments',+ 'crop-to-bbox',+ 'convert-to-control',+ 'intersect',+ 'merge-down',+ 'delete',+ ] as const) {+ expect(byId(actions, id).isDisabled, id).toBe(true);+ }+ expect(byId(actions, 'toggle-lock').isDisabled).toBe(false);++ const lockedControl = { ...nonEmptyControlLayer, isLocked: true };+ const controlActions = getLayerContextActions(makeState(lockedControl));+ expect(byId(controlActions, 'filter').isDisabled).toBe(true);+ expect(byId(controlActions, 'control-transparency-effect').isDisabled).toBe(true);+ expect(byId(controlActions, 'convert-to-raster').isDisabled).toBe(true);++ const lockedText = paintLayer('locked-text', {+ isLocked: true,+ source: {+ align: 'left',+ color: '#fff',+ content: 'locked',+ fontFamily: 'Inter',+ fontSize: 32,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });+ expect(byId(getLayerContextActions(makeState(lockedText)), 'rasterize').isDisabled).toBe(true);+ });++ it('keeps boolean operations visible but disabled when an adjacent raster is locked', () => {+ const upper = { ...paintLayer('locked-upper'), isLocked: true };+ const below = paintLayer('below-locked-upper');+ const actions = getLayerContextActions(makeState(upper, { document: makeDocument([upper, below]) }));++ for (const id of ['intersect', 'cutout', 'cutaway', 'exclude'] as const) {+ expect(byId(actions, id).isDisabled, id).toBe(true);+ }+ });++ it('requires an engine and supported content for pixel actions', () => {+ const noEngine = getLayerContextActions(makeState(rasterLayer, { hasEngine: false }));+ const empty = getLayerContextActions(makeState(rasterLayer, { hasSupportedContent: false }));++ for (const id of ['transform', 'save-to-assets', 'copy-to-clipboard', 'crop-to-bbox'] as const) {+ expect(byId(noEngine, id).isDisabled, id).toBe(true);+ }+ for (const id of ['save-to-assets', 'copy-to-clipboard', 'crop-to-bbox'] as const) {+ expect(byId(empty, id).isDisabled, id).toBe(true);+ }+ });++ it('does not offer fit for cache-only content whose bounds are not yet persisted', () => {+ const cacheOnly = createEmptyPaintLayer('Cache only', 'cache-only');+ const actions = getLayerContextActions(makeState(cacheOnly, { hasSupportedContent: true }));++ expect(byId(actions, 'save-to-assets').isDisabled).toBe(false);+ expect(byId(actions, 'fit-to-bbox').isDisabled).toBe(true);+ });+it('keeps common actions available for a raster layer', () => {- expect(idsFor(paintLayer('raster'))).toEqual(+ expect(idsFor(rasterLayer)).toEqual(expect.arrayContaining(['move-to-front','duplicate','rename','transform','fit-to-bbox',+ 'adjustments','save-to-assets','copy-to-clipboard','crop-to-bbox',@@ -36,6 +408,27 @@ describe('getLayerContextActions', () => {);});+ it('resolves movement boundaries within the layer type group', () => {+ const first = paintLayer('first');+ const middle = paintLayer('middle');+ const last = paintLayer('last');+ const document = makeDocument([first, middle, last]);++ const firstActions = getLayerContextActions(makeState(first, { document }));+ expect(byId(firstActions, 'move-to-front').isDisabled).toBe(true);+ expect(byId(firstActions, 'move-forward').isDisabled).toBe(true);+ expect(byId(firstActions, 'move-backward').isDisabled).toBe(false);+ expect(byId(firstActions, 'move-to-back').isDisabled).toBe(false);++ const middleActions = getLayerContextActions(makeState(middle, { document }));+ expect(byId(middleActions, 'move-forward').isDisabled).toBe(false);+ expect(byId(middleActions, 'move-backward').isDisabled).toBe(false);++ const lastActions = getLayerContextActions(makeState(last, { document }));+ expect(byId(lastActions, 'move-forward').isDisabled).toBe(false);+ expect(byId(lastActions, 'move-backward').isDisabled).toBe(true);+ });+it('exposes only pixel-backed raster to control conversion', () => {const paint = paintLayer('paint');const text = paintLayer('text', {@@ -65,10 +458,10 @@ describe('getLayerContextActions', () => {expect(idsFor(text)).not.toContain('copy-to-inpaint-mask');});- it('exposes control-only transparency and raster conversion actions', () => {- const layer = createControlLayer('Control', 'control');+ it('exposes control-only transparency, filter, and raster conversion actions', () => {+ const empty = createControlLayer('Control', 'control-empty');- expect(idsFor(layer)).toEqual(+ expect(idsFor(empty, [empty], { hasSupportedContent: false })).toEqual(expect.arrayContaining(['control-transparency-effect','convert-to-raster',@@ -77,21 +470,17 @@ describe('getLayerContextActions', () => {'copy-to-regional-guidance',]));- expect(idsFor(layer)).not.toContain('filter');-- const withContent = {- ...layer,- source: { image: { height: 10, imageName: 'control-image', width: 10 }, type: 'image' as const },- };- expect(idsFor(withContent)).toContain('filter');+ expect(idsFor(empty, [empty], { hasSupportedContent: false })).not.toContain('filter');+ expect(idsFor(empty, [empty], { hasSupportedContent: true })).toContain('filter');+ expect(idsFor(nonEmptyControlLayer)).toContain('filter');});it('does not expose copy-to-raster for raster layers', () => {- expect(idsFor(paintLayer('raster'))).not.toContain('copy-to-raster');+ expect(idsFor(rasterLayer)).not.toContain('copy-to-raster');});it('exposes regional guidance add actions only for missing prompts', () => {- const layer = { ...createRegionalGuidanceLayer('Region', 0, 'region'), positivePrompt: 'already' };+ const layer = { ...createRegionalGuidanceLayer('Region', 0, 'region-prompts'), positivePrompt: 'already' };expect(idsFor(layer)).toContain('regional-negative-prompt');expect(idsFor(layer)).toContain('regional-reference-image');@@ -100,7 +489,7 @@ describe('getLayerContextActions', () => {});it('exposes inpaint modifier add actions only for missing modifiers', () => {- const layer = { ...createInpaintMaskLayer('Mask', 'mask'), noiseLevel: 0.25 };+ const layer = { ...createInpaintMaskLayer('Mask', 'mask-modifiers'), noiseLevel: 0.25 };expect(idsFor(layer)).toContain('inpaint-denoise-limit');expect(idsFor(layer)).toContain('copy-to-regional-guidance');@@ -108,44 +497,14 @@ describe('getLayerContextActions', () => {expect(idsFor(layer)).not.toContain('inpaint-noise');});- it('exposes masked extraction only for inpaint masks and disables it without an engine', () => {- const mask = createInpaintMaskLayer('Mask', 'mask');- const withoutEngine = getLayerContextActions({ hasEngine: false, index: 0, layer: mask, layers: [mask] });-- expect(withoutEngine.find((action) => action.id === 'extract-masked-area')?.isDisabled).toBe(true);- expect(idsFor(paintLayer('raster'))).not.toContain('extract-masked-area');- });-- it('copies regional guidance to an inpaint mask without offering unsupported conversions', () => {- const layer = createRegionalGuidanceLayer('Region', 0, 'region');+ it('copies regional guidance to an inpaint mask without unsupported conversions', () => {+ const layer = createRegionalGuidanceLayer('Region', 0, 'region-copy');expect(idsFor(layer)).toContain('copy-to-inpaint-mask');expect(idsFor(layer)).not.toContain('convert-to-inpaint-mask');expect(idsFor(layer)).not.toContain('copy-to-control');});- it('disables transform and merge-down without an engine', () => {- const layer = paintLayer('raster');- const actions = getLayerContextActions({ hasEngine: false, index: 0, layer, layers: [layer] });-- expect(actions.find((action) => action.id === 'transform')?.isDisabled).toBe(true);- expect(actions.find((action) => action.id === 'save-to-assets')?.isDisabled).toBe(true);- expect(actions.find((action) => action.id === 'copy-to-clipboard')?.isDisabled).toBe(true);- expect(actions.find((action) => action.id === 'crop-to-bbox')?.isDisabled).toBe(true);- expect(actions.find((action) => action.id === 'merge-down')?.isDisabled).toBe(true);-- const control = createControlLayer('Control', 'control');- const controlActions = getLayerContextActions({ hasEngine: false, index: 0, layer: control, layers: [control] });- expect(controlActions.find((action) => action.id === 'copy-to-raster')?.isDisabled).toBe(true);- });-- it('disables crop-to-bbox for locked layers', () => {- const layer = paintLayer('raster', { isLocked: true });- const actions = getLayerContextActions({ hasEngine: true, index: 0, layer, layers: [layer] });-- expect(actions.find((action) => action.id === 'crop-to-bbox')?.isDisabled).toBe(true);- });-it('exposes boolean raster actions only for an adjacent mergeable raster pair', () => {const upper = paintLayer('upper');const below = paintLayer('below');@@ -153,7 +512,7 @@ describe('getLayerContextActions', () => {expect(idsFor(upper, [upper, below])).toEqual(expect.arrayContaining(operations));expect(idsFor(below, [upper, below])).toEqual(expect.not.arrayContaining(operations));- expect(idsFor(upper, [upper, createInpaintMaskLayer('Mask', 'mask')])).toEqual(+ expect(idsFor(upper, [upper, createInpaintMaskLayer('Mask', 'mask-below')])).toEqual(expect.not.arrayContaining(operations));});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsindex e7a495f43f..31be9a5e74 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -1,4 +1,29 @@-import type { CanvasLayerContract } from '@workbench/types';+import type { BooleanRasterOperation } from '@workbench/canvas-engine/engine';+import type { CanvasDocumentContractV2, CanvasLayerContract } from '@workbench/types';+import type { LucideIcon } from 'lucide-react';++import { getSourceContentRect } from '@workbench/canvas-engine/document/sources';+import {+ ArrowDownIcon,+ ArrowDownToLineIcon,+ ArrowUpIcon,+ ArrowUpToLineIcon,+ CopyIcon,+ CropIcon,+ EyeIcon,+ EyeOffIcon,+ ImageIcon,+ LockIcon,+ LockOpenIcon,+ MergeIcon,+ PencilIcon,+ SaveIcon,+ SlidersHorizontalIcon,+ Trash2Icon,+} from 'lucide-react';++import type { LayerMoveKind } from './layerGroups';+import type { LayerPropertiesSection } from './layerPropertiesRequestStore';import { getGroupPosition } from './layerGroups';import { canConvertRasterControl, canMergeLayerDown } from './layerOps';@@ -12,6 +37,7 @@ export type LayerContextActionId =| 'rename'| 'transform'| 'fit-to-bbox'+ | 'adjustments'| 'save-to-assets'| 'copy-to-clipboard'| 'crop-to-bbox'@@ -42,29 +68,104 @@ export type LayerContextActionId =| 'toggle-lock'| 'delete';-export type LayerContextActionGroup = 'icons' | 'edit' | 'convert' | 'layerConfig' | 'state' | 'danger';+export type LayerType = CanvasLayerContract['type'];+export type LayerContextMenuSectionId = 'quick' | 'primary' | 'operations' | 'output' | 'state' | 'danger';+export type LayerContextSubmenuId = 'arrange' | 'add-modifiers' | 'add-regional' | 'boolean' | 'copy-to' | 'convert-to';-export interface LayerContextActionContext {+export interface LayerContextActionState {+ document: CanvasDocumentContractV2;hasEngine: boolean;+ hasSupportedContent: boolean;index: number;+ interactionLocked: boolean;layer: CanvasLayerContract;- layers: readonly CanvasLayerContract[];}-export interface LayerContextAction {+export interface LayerContextActionEffects {+ reorder(kind: LayerMoveKind, actionId: LayerContextActionId): void;+ duplicate(): void;+ openRename(): void;+ transform(): void;+ fitToBbox(): void;+ openProperties(section: LayerPropertiesSection): void;+ saveToAssets(): Promise<void>;+ copyToClipboard(): Promise<void>;+ cropToBbox(): Promise<void>;+ extractMaskedArea(): Promise<void>;+ booleanMerge(operation: BooleanRasterOperation): Promise<void>;+ copyTo(target: LayerType): void | Promise<void>;+ rasterize(): void;+ convertTo(target: LayerType): void;+ patchConfig(kind: LayerConfigPatchKind): void;+ mergeDown(): void;+ toggleVisibility(): void;+ toggleLock(): void;+ delete(): void;+}++export interface LayerContextActionRuntimeContext extends LayerContextActionState {+ effects: LayerContextActionEffects;+}++export interface LayerContextActionDefinition {+ id: LayerContextActionId;+ labelKey: string;defaultLabel: string;- group: LayerContextActionGroup;+ icon: LucideIcon;+ getIcon?(context: LayerContextActionState): LucideIcon;+ section: LayerContextMenuSectionId;+ submenu?: LayerContextSubmenuId;+ order: number;+ supportedLayerTypes: readonly LayerType[];+ tone?: 'danger';+ isVisible(context: LayerContextActionState): boolean;+ isEnabled(context: LayerContextActionState): boolean;+ handler(context: LayerContextActionRuntimeContext): void | Promise<void>;+ getDefaultLabel?(context: LayerContextActionState): string;+ getLabelKey?(context: LayerContextActionState): string;+}++export interface LayerContextAction {id: LayerContextActionId;- isDisabled: boolean;labelKey: string;+ defaultLabel: string;+ icon: LucideIcon;+ section: LayerContextMenuSectionId;+ submenu?: LayerContextSubmenuId;+ order: number;tone?: 'danger';+ isDisabled: boolean;+ handler(context: LayerContextActionRuntimeContext): void | Promise<void>;}-type LayerContextActionDefinition = Omit<LayerContextAction, 'isDisabled'> & {- getDefaultLabel?: (ctx: LayerContextActionContext) => string;- getLabelKey?: (ctx: LayerContextActionContext) => string;- isDisabled?: (ctx: LayerContextActionContext) => boolean;- isVisible?: (ctx: LayerContextActionContext) => boolean;+export type LayerConfigPatchKind =+ | 'control-transparency-effect'+ | 'regional-positive-prompt'+ | 'regional-negative-prompt'+ | 'regional-reference-image'+ | 'regional-auto-negative'+ | 'inpaint-noise'+ | 'inpaint-denoise-limit';++const ALL_LAYER_TYPES = ['raster', 'control', 'inpaint_mask', 'regional_guidance'] as const;+const RASTER_ONLY = ['raster'] as const;+const CONTROL_ONLY = ['control'] as const;+const INPAINT_ONLY = ['inpaint_mask'] as const;+const REGIONAL_ONLY = ['regional_guidance'] as const;++const alwaysVisible = (): boolean => true;+const isInteractionFree = (context: LayerContextActionState): boolean => !context.interactionLocked;+const isLayerMutable = (context: LayerContextActionState): boolean =>+ isInteractionFree(context) && !context.layer.isLocked;+const hasReadablePixels = (context: LayerContextActionState): boolean =>+ context.hasEngine && context.hasSupportedContent && !context.interactionLocked;+const hasMutablePixels = (context: LayerContextActionState): boolean =>+ isLayerMutable(context) && hasReadablePixels(context);+const hasTransformablePixels = (context: LayerContextActionState): boolean =>+ context.layer.isEnabled && hasMutablePixels(context);+const hasDocumentContent = (context: LayerContextActionState): boolean => {+ const contentRect = getSourceContentRect(context.layer, context.document);+ return contentRect.width > 0 && contentRect.height > 0;};const isParametricRasterizable = (layer: CanvasLayerContract): boolean =>@@ -77,289 +178,562 @@ const isPixelBacked = (layer: CanvasLayerContract): boolean =>(layer.type === 'raster' || layer.type === 'control') &&(layer.source.type === 'image' || layer.source.type === 'paint');-const hasFilterableControlContent = (layer: CanvasLayerContract): boolean =>- layer.type === 'control' &&- (layer.source.type === 'image' || (layer.source.type === 'paint' && layer.source.bitmap !== null));+const hasFilterableControlContent = (context: LayerContextActionState): boolean =>+ context.hasSupportedContent &&+ context.layer.type === 'control' &&+ (context.layer.source.type === 'image' || context.layer.source.type === 'paint');-const groupPosition = (ctx: LayerContextActionContext) => getGroupPosition(ctx.layers, ctx.layer.id);+const groupPosition = (context: LayerContextActionState) => getGroupPosition(context.document.layers, context.layer.id);-const canMoveForward = (ctx: LayerContextActionContext): boolean => {- const position = groupPosition(ctx);- return !!position && position.index > 0;+const canMoveForward = (context: LayerContextActionState): boolean => {+ const position = groupPosition(context);+ return isInteractionFree(context) && !!position && position.index > 0;};-const canMoveBackward = (ctx: LayerContextActionContext): boolean => {- const position = groupPosition(ctx);- return !!position && position.index < position.count - 1;+const canMoveBackward = (context: LayerContextActionState): boolean => {+ const position = groupPosition(context);+ return isInteractionFree(context) && !!position && position.index < position.count - 1;};+const hasMergeableLayerBelow = (context: LayerContextActionState): boolean =>+ canMergeLayerDown(context.document.layers, context.index, true);++const isBooleanRasterLayer = (layer: CanvasLayerContract | undefined): boolean =>+ !!layer &&+ layer.isEnabled &&+ layer.type === 'raster' &&+ (layer.source.type === 'paint' || layer.source.type === 'image');++const hasBooleanRasterPair = (context: LayerContextActionState): boolean =>+ isBooleanRasterLayer(context.document.layers[context.index]) &&+ isBooleanRasterLayer(context.document.layers[context.index + 1]);+export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinition[] = [{defaultLabel: 'Move to front',- group: 'icons',+ handler: ({ effects }) => effects.reorder('front', 'move-to-front'),+ icon: ArrowUpToLineIcon,id: 'move-to-front',- isDisabled: (ctx) => !canMoveForward(ctx),+ isEnabled: canMoveForward,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.moveToFront',+ order: 0,+ section: 'quick',+ submenu: 'arrange',+ supportedLayerTypes: ALL_LAYER_TYPES,},{defaultLabel: 'Move forward',- group: 'icons',+ handler: ({ effects }) => effects.reorder('forward', 'move-forward'),+ icon: ArrowUpIcon,id: 'move-forward',- isDisabled: (ctx) => !canMoveForward(ctx),+ isEnabled: canMoveForward,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.moveForward',+ order: 1,+ section: 'quick',+ submenu: 'arrange',+ supportedLayerTypes: ALL_LAYER_TYPES,},{defaultLabel: 'Move backward',- group: 'icons',+ handler: ({ effects }) => effects.reorder('backward', 'move-backward'),+ icon: ArrowDownIcon,id: 'move-backward',- isDisabled: (ctx) => !canMoveBackward(ctx),+ isEnabled: canMoveBackward,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.moveBackward',+ order: 2,+ section: 'quick',+ submenu: 'arrange',+ supportedLayerTypes: ALL_LAYER_TYPES,},{defaultLabel: 'Move to back',- group: 'icons',+ handler: ({ effects }) => effects.reorder('back', 'move-to-back'),+ icon: ArrowDownToLineIcon,id: 'move-to-back',- isDisabled: (ctx) => !canMoveBackward(ctx),+ isEnabled: canMoveBackward,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.moveToBack',+ order: 3,+ section: 'quick',+ submenu: 'arrange',+ supportedLayerTypes: ALL_LAYER_TYPES,+ },+ {+ defaultLabel: 'Duplicate',+ handler: ({ effects }) => effects.duplicate(),+ icon: CopyIcon,+ id: 'duplicate',+ isEnabled: isInteractionFree,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.duplicate',+ order: 10,+ section: 'quick',+ supportedLayerTypes: ALL_LAYER_TYPES,+ },+ {+ defaultLabel: 'Add image noise',+ handler: ({ effects }) => effects.patchConfig('inpaint-noise'),+ icon: SlidersHorizontalIcon,+ id: 'inpaint-noise',+ isEnabled: isLayerMutable,+ isVisible: (context) => context.layer.type === 'inpaint_mask' && context.layer.noiseLevel === undefined,+ labelKey: 'widgets.layers.actions.addImageNoise',+ order: 0,+ section: 'primary',+ submenu: 'add-modifiers',+ supportedLayerTypes: INPAINT_ONLY,+ },+ {+ defaultLabel: 'Add denoise limit',+ handler: ({ effects }) => effects.patchConfig('inpaint-denoise-limit'),+ icon: SlidersHorizontalIcon,+ id: 'inpaint-denoise-limit',+ isEnabled: isLayerMutable,+ isVisible: (context) => context.layer.type === 'inpaint_mask' && context.layer.denoiseLimit === undefined,+ labelKey: 'widgets.layers.actions.addDenoiseLimit',+ order: 1,+ section: 'primary',+ submenu: 'add-modifiers',+ supportedLayerTypes: INPAINT_ONLY,+ },+ {+ defaultLabel: 'Add positive prompt',+ handler: ({ effects }) => effects.patchConfig('regional-positive-prompt'),+ icon: PencilIcon,+ id: 'regional-positive-prompt',+ isEnabled: isLayerMutable,+ isVisible: (context) => context.layer.type === 'regional_guidance' && context.layer.positivePrompt === null,+ labelKey: 'widgets.layers.actions.addPositivePrompt',+ order: 0,+ section: 'primary',+ submenu: 'add-regional',+ supportedLayerTypes: REGIONAL_ONLY,+ },+ {+ defaultLabel: 'Add negative prompt',+ handler: ({ effects }) => effects.patchConfig('regional-negative-prompt'),+ icon: PencilIcon,+ id: 'regional-negative-prompt',+ isEnabled: isLayerMutable,+ isVisible: (context) => context.layer.type === 'regional_guidance' && context.layer.negativePrompt === null,+ labelKey: 'widgets.layers.actions.addNegativePrompt',+ order: 1,+ section: 'primary',+ submenu: 'add-regional',+ supportedLayerTypes: REGIONAL_ONLY,+ },+ {+ defaultLabel: 'Add reference image',+ handler: ({ effects }) => effects.patchConfig('regional-reference-image'),+ icon: ImageIcon,+ id: 'regional-reference-image',+ isEnabled: isLayerMutable,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.addReferenceImage',+ order: 2,+ section: 'primary',+ submenu: 'add-regional',+ supportedLayerTypes: REGIONAL_ONLY,},- { defaultLabel: 'Duplicate', group: 'icons', id: 'duplicate', labelKey: 'widgets.layers.actions.duplicate' },- { defaultLabel: 'Rename', group: 'edit', id: 'rename', labelKey: 'widgets.layers.actions.rename' },{defaultLabel: 'Transform',- group: 'edit',+ handler: ({ effects }) => effects.transform(),+ icon: SlidersHorizontalIcon,id: 'transform',- isDisabled: (ctx) => !ctx.hasEngine,+ isEnabled: hasTransformablePixels,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.transform',+ order: 10,+ section: 'primary',+ supportedLayerTypes: ['raster', 'control'],+ },+ {+ defaultLabel: 'Rename',+ handler: ({ effects }) => effects.openRename(),+ icon: PencilIcon,+ id: 'rename',+ isEnabled: isInteractionFree,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.rename',+ order: 20,+ section: 'primary',+ supportedLayerTypes: ALL_LAYER_TYPES,+ },+ {+ defaultLabel: 'Fit to bbox',+ handler: ({ effects }) => effects.fitToBbox(),+ icon: ImageIcon,+ id: 'fit-to-bbox',+ isEnabled: (context) => hasDocumentContent(context) && isLayerMutable(context),+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.fitToBbox',+ order: 30,+ section: 'primary',+ supportedLayerTypes: ALL_LAYER_TYPES,+ },+ {+ defaultLabel: 'Adjustments',+ handler: ({ effects }) => effects.openProperties('adjustments'),+ icon: SlidersHorizontalIcon,+ id: 'adjustments',+ isEnabled: hasMutablePixels,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.adjustments',+ order: 31,+ section: 'primary',+ supportedLayerTypes: RASTER_ONLY,},- { defaultLabel: 'Fit to bbox', group: 'edit', id: 'fit-to-bbox', labelKey: 'widgets.layers.actions.fitToBbox' },{- defaultLabel: 'Save layer to assets',- group: 'edit',- id: 'save-to-assets',- isDisabled: (ctx) => !ctx.hasEngine,- labelKey: 'widgets.layers.actions.saveLayerToAssets',+ defaultLabel: 'Filter',+ handler: ({ effects }) => effects.openProperties('filter'),+ icon: SlidersHorizontalIcon,+ id: 'filter',+ isEnabled: hasMutablePixels,+ isVisible: hasFilterableControlContent,+ labelKey: 'widgets.layers.control.filter',+ order: 40,+ section: 'primary',+ supportedLayerTypes: CONTROL_ONLY,},{- defaultLabel: 'Copy layer to clipboard',- group: 'edit',- id: 'copy-to-clipboard',- isDisabled: (ctx) => !ctx.hasEngine,- labelKey: 'widgets.layers.actions.copyLayerToClipboard',+ defaultLabel: 'Toggle transparency effect',+ getDefaultLabel: (context) =>+ context.layer.type === 'control' && context.layer.withTransparencyEffect+ ? 'Disable transparency effect'+ : 'Enable transparency effect',+ getLabelKey: (context) =>+ context.layer.type === 'control' && context.layer.withTransparencyEffect+ ? 'widgets.layers.actions.disableTransparencyEffect'+ : 'widgets.layers.actions.enableTransparencyEffect',+ handler: ({ effects }) => effects.patchConfig('control-transparency-effect'),+ icon: SlidersHorizontalIcon,+ id: 'control-transparency-effect',+ isEnabled: isLayerMutable,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.toggleTransparencyEffect',+ order: 50,+ section: 'primary',+ supportedLayerTypes: CONTROL_ONLY,},{- defaultLabel: 'Crop layer to bbox',- group: 'edit',- id: 'crop-to-bbox',- isDisabled: (ctx) => !ctx.hasEngine || ctx.layer.isLocked,- labelKey: 'widgets.layers.actions.cropLayerToBbox',+ defaultLabel: 'Toggle auto-negative',+ getDefaultLabel: (context) =>+ context.layer.type === 'regional_guidance' && context.layer.autoNegative+ ? 'Disable auto-negative'+ : 'Enable auto-negative',+ getLabelKey: (context) =>+ context.layer.type === 'regional_guidance' && context.layer.autoNegative+ ? 'widgets.layers.actions.disableAutoNegative'+ : 'widgets.layers.actions.enableAutoNegative',+ handler: ({ effects }) => effects.patchConfig('regional-auto-negative'),+ icon: SlidersHorizontalIcon,+ id: 'regional-auto-negative',+ isEnabled: isLayerMutable,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.toggleAutoNegative',+ order: 50,+ section: 'primary',+ supportedLayerTypes: REGIONAL_ONLY,},{defaultLabel: 'Extract masked area',- group: 'edit',+ handler: ({ effects }) => effects.extractMaskedArea(),+ icon: CropIcon,id: 'extract-masked-area',- isDisabled: (ctx) => !ctx.hasEngine,- isVisible: (ctx) => ctx.layer.type === 'inpaint_mask',+ isEnabled: hasMutablePixels,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.extractMaskedArea',+ order: 60,+ section: 'primary',+ supportedLayerTypes: INPAINT_ONLY,},{- defaultLabel: 'Filter',- group: 'edit',- id: 'filter',- isVisible: (ctx) => hasFilterableControlContent(ctx.layer),- labelKey: 'widgets.layers.control.filter',+ defaultLabel: 'Merge down',+ handler: ({ effects }) => effects.mergeDown(),+ icon: MergeIcon,+ id: 'merge-down',+ isEnabled: (context) => hasMutablePixels(context) && hasMergeableLayerBelow(context),+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.mergeDown',+ order: 0,+ section: 'operations',+ supportedLayerTypes: ALL_LAYER_TYPES,},{defaultLabel: 'Intersect with layer below',- group: 'edit',+ handler: ({ effects }) => effects.booleanMerge('intersect'),+ icon: MergeIcon,id: 'intersect',- isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ isEnabled: (context) => hasMutablePixels(context) && hasMergeableLayerBelow(context),+ isVisible: hasBooleanRasterPair,labelKey: 'widgets.layers.actions.intersect',+ order: 10,+ section: 'operations',+ submenu: 'boolean',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Cutout with layer below',- group: 'edit',+ handler: ({ effects }) => effects.booleanMerge('cutout'),+ icon: MergeIcon,id: 'cutout',- isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ isEnabled: (context) => hasMutablePixels(context) && hasMergeableLayerBelow(context),+ isVisible: hasBooleanRasterPair,labelKey: 'widgets.layers.actions.cutout',+ order: 11,+ section: 'operations',+ submenu: 'boolean',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Cutaway with layer below',- group: 'edit',+ handler: ({ effects }) => effects.booleanMerge('cutaway'),+ icon: MergeIcon,id: 'cutaway',- isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ isEnabled: (context) => hasMutablePixels(context) && hasMergeableLayerBelow(context),+ isVisible: hasBooleanRasterPair,labelKey: 'widgets.layers.actions.cutaway',+ order: 12,+ section: 'operations',+ submenu: 'boolean',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Exclude layer below',- group: 'edit',+ handler: ({ effects }) => effects.booleanMerge('exclude'),+ icon: MergeIcon,id: 'exclude',- isVisible: (ctx) => canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ isEnabled: (context) => hasMutablePixels(context) && hasMergeableLayerBelow(context),+ isVisible: hasBooleanRasterPair,labelKey: 'widgets.layers.actions.exclude',+ order: 13,+ section: 'operations',+ submenu: 'boolean',+ supportedLayerTypes: RASTER_ONLY,+ },+ {+ defaultLabel: 'Copy layer to clipboard',+ handler: ({ effects }) => effects.copyToClipboard(),+ icon: CopyIcon,+ id: 'copy-to-clipboard',+ isEnabled: hasReadablePixels,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.copyLayerToClipboard',+ order: 20,+ section: 'operations',+ submenu: 'copy-to',+ supportedLayerTypes: ALL_LAYER_TYPES,},{defaultLabel: 'Copy to raster layer',- group: 'convert',+ handler: ({ effects }) => effects.copyTo('raster'),+ icon: CopyIcon,id: 'copy-to-raster',- isDisabled: (ctx) => !ctx.hasEngine,- isVisible: (ctx) => ctx.layer.type !== 'raster',+ isEnabled: hasReadablePixels,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.copyToRasterLayer',+ order: 21,+ section: 'operations',+ submenu: 'copy-to',+ supportedLayerTypes: ['control', 'inpaint_mask', 'regional_guidance'],},{defaultLabel: 'Copy to control layer',- group: 'convert',+ handler: ({ effects }) => effects.copyTo('control'),+ icon: CopyIcon,id: 'copy-to-control',- isDisabled: (ctx) => !ctx.hasEngine,- isVisible: (ctx) => ctx.layer.type === 'raster' && isPixelBacked(ctx.layer),+ isEnabled: hasReadablePixels,+ isVisible: (context) => isPixelBacked(context.layer),labelKey: 'widgets.layers.actions.copyToControl',+ order: 22,+ section: 'operations',+ submenu: 'copy-to',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Copy to inpaint mask',- group: 'convert',+ handler: ({ effects }) => effects.copyTo('inpaint_mask'),+ icon: CopyIcon,id: 'copy-to-inpaint-mask',- isDisabled: (ctx) => !ctx.hasEngine,- isVisible: (ctx) => isPixelBacked(ctx.layer) || ctx.layer.type === 'regional_guidance',+ isEnabled: hasReadablePixels,+ isVisible: (context) => isPixelBacked(context.layer) || context.layer.type === 'regional_guidance',labelKey: 'widgets.layers.actions.copyToInpaintMask',+ order: 23,+ section: 'operations',+ submenu: 'copy-to',+ supportedLayerTypes: ['raster', 'control', 'regional_guidance'],},{defaultLabel: 'Copy to regional guidance',- group: 'convert',+ handler: ({ effects }) => effects.copyTo('regional_guidance'),+ icon: CopyIcon,id: 'copy-to-regional-guidance',- isDisabled: (ctx) => !ctx.hasEngine,- isVisible: (ctx) => isPixelBacked(ctx.layer) || ctx.layer.type === 'inpaint_mask',+ isEnabled: hasReadablePixels,+ isVisible: (context) => isPixelBacked(context.layer) || context.layer.type === 'inpaint_mask',labelKey: 'widgets.layers.actions.copyToRegionalGuidance',+ order: 24,+ section: 'operations',+ submenu: 'copy-to',+ supportedLayerTypes: ['raster', 'control', 'inpaint_mask'],},{defaultLabel: 'Rasterize',- group: 'convert',+ handler: ({ effects }) => effects.rasterize(),+ icon: ImageIcon,id: 'rasterize',- isVisible: (ctx) => ctx.hasEngine && isParametricRasterizable(ctx.layer),+ isEnabled: hasMutablePixels,+ isVisible: (context) => isParametricRasterizable(context.layer),labelKey: 'widgets.layers.actions.rasterize',+ order: 30,+ section: 'operations',+ submenu: 'convert-to',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Convert to Control Layer',- group: 'convert',+ handler: ({ effects }) => effects.convertTo('control'),+ icon: SlidersHorizontalIcon,id: 'convert-to-control',- isVisible: (ctx) => ctx.layer.type === 'raster' && canConvertRasterControl(ctx.layer),+ isEnabled: isLayerMutable,+ isVisible: (context) => canConvertRasterControl(context.layer),labelKey: 'widgets.layers.actions.convertToControl',+ order: 31,+ section: 'operations',+ submenu: 'convert-to',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Convert to Raster Layer',- group: 'convert',+ handler: ({ effects }) => effects.convertTo('raster'),+ icon: ImageIcon,id: 'convert-to-raster',- isVisible: (ctx) => ctx.layer.type === 'control',+ isEnabled: isLayerMutable,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.convertToRaster',+ order: 32,+ section: 'operations',+ submenu: 'convert-to',+ supportedLayerTypes: CONTROL_ONLY,},{defaultLabel: 'Convert to inpaint mask',- group: 'convert',+ handler: ({ effects }) => effects.convertTo('inpaint_mask'),+ icon: ImageIcon,id: 'convert-to-inpaint-mask',- isVisible: (ctx) => ctx.layer.type === 'raster' && isPixelBacked(ctx.layer),+ isEnabled: isLayerMutable,+ isVisible: (context) => isPixelBacked(context.layer),labelKey: 'widgets.layers.actions.convertToInpaintMask',+ order: 33,+ section: 'operations',+ submenu: 'convert-to',+ supportedLayerTypes: RASTER_ONLY,},{defaultLabel: 'Convert to regional guidance',- group: 'convert',+ handler: ({ effects }) => effects.convertTo('regional_guidance'),+ icon: ImageIcon,id: 'convert-to-regional-guidance',- isVisible: (ctx) => ctx.layer.type === 'raster' && isPixelBacked(ctx.layer),+ isEnabled: isLayerMutable,+ isVisible: (context) => isPixelBacked(context.layer),labelKey: 'widgets.layers.actions.convertToRegionalGuidance',+ order: 34,+ section: 'operations',+ submenu: 'convert-to',+ supportedLayerTypes: RASTER_ONLY,},{- getDefaultLabel: (ctx) =>- ctx.layer.type === 'control' && ctx.layer.withTransparencyEffect- ? 'Disable transparency effect'- : 'Enable transparency effect',- getLabelKey: (ctx) =>- ctx.layer.type === 'control' && ctx.layer.withTransparencyEffect- ? 'widgets.layers.actions.disableTransparencyEffect'- : 'widgets.layers.actions.enableTransparencyEffect',- defaultLabel: 'Toggle transparency effect',- group: 'layerConfig',- id: 'control-transparency-effect',- isVisible: (ctx) => ctx.layer.type === 'control',- labelKey: 'widgets.layers.actions.toggleTransparencyEffect',- },- {- defaultLabel: 'Add positive prompt',- group: 'layerConfig',- id: 'regional-positive-prompt',- isVisible: (ctx) => ctx.layer.type === 'regional_guidance' && ctx.layer.positivePrompt === null,- labelKey: 'widgets.layers.actions.addPositivePrompt',- },- {- defaultLabel: 'Add negative prompt',- group: 'layerConfig',- id: 'regional-negative-prompt',- isVisible: (ctx) => ctx.layer.type === 'regional_guidance' && ctx.layer.negativePrompt === null,- labelKey: 'widgets.layers.actions.addNegativePrompt',- },- {- defaultLabel: 'Add reference image',- group: 'layerConfig',- id: 'regional-reference-image',- isVisible: (ctx) => ctx.layer.type === 'regional_guidance',- labelKey: 'widgets.layers.actions.addReferenceImage',- },- {- getDefaultLabel: (ctx) =>- ctx.layer.type === 'regional_guidance' && ctx.layer.autoNegative- ? 'Disable auto-negative'- : 'Enable auto-negative',- getLabelKey: (ctx) =>- ctx.layer.type === 'regional_guidance' && ctx.layer.autoNegative- ? 'widgets.layers.actions.disableAutoNegative'- : 'widgets.layers.actions.enableAutoNegative',- defaultLabel: 'Toggle auto-negative',- group: 'layerConfig',- id: 'regional-auto-negative',- isVisible: (ctx) => ctx.layer.type === 'regional_guidance',- labelKey: 'widgets.layers.actions.toggleAutoNegative',- },- {- defaultLabel: 'Add image noise',- group: 'layerConfig',- id: 'inpaint-noise',- isVisible: (ctx) => ctx.layer.type === 'inpaint_mask' && ctx.layer.noiseLevel === undefined,- labelKey: 'widgets.layers.actions.addImageNoise',- },- {- defaultLabel: 'Add denoise limit',- group: 'layerConfig',- id: 'inpaint-denoise-limit',- isVisible: (ctx) => ctx.layer.type === 'inpaint_mask' && ctx.layer.denoiseLimit === undefined,- labelKey: 'widgets.layers.actions.addDenoiseLimit',+ defaultLabel: 'Crop layer to bbox',+ handler: ({ effects }) => effects.cropToBbox(),+ icon: CropIcon,+ id: 'crop-to-bbox',+ isEnabled: hasMutablePixels,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.cropLayerToBbox',+ order: 0,+ section: 'output',+ supportedLayerTypes: ALL_LAYER_TYPES,},{- defaultLabel: 'Merge down',- group: 'state',- id: 'merge-down',- isDisabled: (ctx) => !canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),- labelKey: 'widgets.layers.actions.mergeDown',+ defaultLabel: 'Save layer to assets',+ handler: ({ effects }) => effects.saveToAssets(),+ icon: SaveIcon,+ id: 'save-to-assets',+ isEnabled: hasReadablePixels,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.saveLayerToAssets',+ order: 10,+ section: 'output',+ supportedLayerTypes: ALL_LAYER_TYPES,},{- getDefaultLabel: (ctx) => (ctx.layer.isEnabled ? 'Hide' : 'Show'),- getLabelKey: (ctx) => (ctx.layer.isEnabled ? 'widgets.layers.actions.hide' : 'widgets.layers.actions.show'),defaultLabel: 'Toggle visibility',- group: 'state',+ getDefaultLabel: (context) => (context.layer.isEnabled ? 'Hide' : 'Show'),+ getIcon: (context) => (context.layer.isEnabled ? EyeOffIcon : EyeIcon),+ getLabelKey: (context) => (context.layer.isEnabled ? 'widgets.layers.actions.hide' : 'widgets.layers.actions.show'),+ handler: ({ effects }) => effects.toggleVisibility(),+ icon: EyeIcon,id: 'toggle-visibility',+ isEnabled: isInteractionFree,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.toggleVisibility',+ order: 0,+ section: 'state',+ supportedLayerTypes: ALL_LAYER_TYPES,},{- getDefaultLabel: (ctx) => (ctx.layer.isLocked ? 'Unlock' : 'Lock'),- getLabelKey: (ctx) => (ctx.layer.isLocked ? 'widgets.layers.actions.unlock' : 'widgets.layers.actions.lock'),defaultLabel: 'Toggle lock',- group: 'state',+ getDefaultLabel: (context) => (context.layer.isLocked ? 'Unlock' : 'Lock'),+ getIcon: (context) => (context.layer.isLocked ? LockOpenIcon : LockIcon),+ getLabelKey: (context) =>+ context.layer.isLocked ? 'widgets.layers.actions.unlock' : 'widgets.layers.actions.lock',+ handler: ({ effects }) => effects.toggleLock(),+ icon: LockIcon,id: 'toggle-lock',+ isEnabled: isInteractionFree,+ isVisible: alwaysVisible,labelKey: 'widgets.layers.actions.toggleLock',+ order: 10,+ section: 'state',+ supportedLayerTypes: ALL_LAYER_TYPES,+ },+ {+ defaultLabel: 'Delete',+ handler: ({ effects }) => effects.delete(),+ icon: Trash2Icon,+ id: 'delete',+ isEnabled: isLayerMutable,+ isVisible: alwaysVisible,+ labelKey: 'widgets.layers.actions.delete',+ order: 0,+ section: 'danger',+ supportedLayerTypes: ALL_LAYER_TYPES,+ tone: 'danger',},- { defaultLabel: 'Delete', group: 'danger', id: 'delete', labelKey: 'widgets.layers.actions.delete', tone: 'danger' },];-export const getLayerContextActions = (ctx: LayerContextActionContext): LayerContextAction[] =>- LAYER_CONTEXT_ACTION_DEFINITIONS.filter((definition) => definition.isVisible?.(ctx) ?? true).map((definition) => ({- defaultLabel: definition.getDefaultLabel?.(ctx) ?? definition.defaultLabel,- group: definition.group,+export const getLayerContextActionDefinition = (id: LayerContextActionId): LayerContextActionDefinition => {+ const definition = LAYER_CONTEXT_ACTION_DEFINITIONS.find((candidate) => candidate.id === id);+ if (!definition) {+ throw new Error(`Unknown layer context action: ${id}`);+ }+ return definition;+};++export const getLayerContextActions = (context: LayerContextActionState): LayerContextAction[] =>+ LAYER_CONTEXT_ACTION_DEFINITIONS.filter(+ (definition) => definition.supportedLayerTypes.includes(context.layer.type) && definition.isVisible(context)+ ).map((definition) => ({+ defaultLabel: definition.getDefaultLabel?.(context) ?? definition.defaultLabel,+ handler: definition.handler,+ icon: definition.getIcon?.(context) ?? definition.icon,id: definition.id,- isDisabled: definition.isDisabled?.(ctx) ?? false,- labelKey: definition.getLabelKey?.(ctx) ?? definition.labelKey,+ isDisabled: !definition.isEnabled(context),+ labelKey: definition.getLabelKey?.(context) ?? definition.labelKey,+ order: definition.order,+ section: definition.section,+ submenu: definition.submenu,tone: definition.tone,}));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.tsindex 0c37e0573b..40add2cc6b 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts@@ -1,9 +1,9 @@-import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';+import type { CanvasDocumentContractV2, CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';import { describe, expect, it } from 'vitest';import { getLayerContextActions } from './layerContextActions';-import { getLayerContextMenuLayout } from './layerContextMenuLayout';+import { getLayerContextMenuLayout, type LayerContextMenuSection } from './layerContextMenuLayout';import {createControlLayer,createEmptyPaintLayer,@@ -13,16 +13,35 @@ import {const paintLayer = (id: string, patch: Partial<CanvasRasterLayerContractV2> = {}): CanvasLayerContract => ({...createEmptyPaintLayer(id, id),+ source: { bitmap: { height: 10, imageName: `${id}.png`, width: 10 }, type: 'paint' },...patch,});-const layoutFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) => {- const actions = getLayerContextActions({ hasEngine: true, index: layers.indexOf(layer), layer, layers });- return getLayerContextMenuLayout(actions);-};+const makeDocument = (layers: CanvasLayerContract[]): CanvasDocumentContractV2 => ({+ background: 'transparent',+ bbox: { height: 512, width: 512, x: 0, y: 0 },+ height: 512,+ layers,+ selectedLayerId: layers[0]?.id ?? null,+ version: 2,+ width: 512,+});-const summarize = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) =>- layoutFor(layer, layers).map((section) => ({+const actionsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) =>+ getLayerContextActions({+ document: makeDocument([...layers]),+ hasEngine: true,+ hasSupportedContent: true,+ index: layers.indexOf(layer),+ interactionLocked: false,+ layer,+ });++const layoutFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) =>+ getLayerContextMenuLayout(actionsFor(layer, layers));++const summarizeLayout = (layout: readonly LayerContextMenuSection[]) =>+ layout.map((section) => ({id: section.id,items: section.items.map((item) =>item.kind === 'action' ? item.action.id : `${item.id}(${item.actions.map((action) => action.id).join(',')})`@@ -30,6 +49,9 @@ const summarize = (layer: CanvasLayerContract, layers: readonly CanvasLayerContrpresentation: section.presentation,}));+const summarize = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer]) =>+ summarizeLayout(layoutFor(layer, layers));+describe('getLayerContextMenuLayout', () => {it('organizes raster actions like the legacy menu and keeps delete last', () => {const upper = paintLayer('upper');@@ -41,7 +63,7 @@ describe('getLayerContextMenuLayout', () => {items: ['arrange(move-to-front,move-forward,move-backward,move-to-back)', 'duplicate'],presentation: 'row',},- { id: 'primary', items: ['transform', 'rename', 'fit-to-bbox'], presentation: 'list' },+ { id: 'primary', items: ['transform', 'rename', 'fit-to-bbox', 'adjustments'], presentation: 'list' },{id: 'operations',items: [@@ -64,20 +86,13 @@ describe('getLayerContextMenuLayout', () => {expect(summarize(inpaint)[1]).toEqual({id: 'primary',- items: [- 'add-modifiers(inpaint-noise,inpaint-denoise-limit)',- 'transform',- 'rename',- 'fit-to-bbox',- 'extract-masked-area',- ],+ items: ['add-modifiers(inpaint-noise,inpaint-denoise-limit)', 'rename', 'fit-to-bbox', 'extract-masked-area'],presentation: 'list',});expect(summarize(regional)[1]).toEqual({id: 'primary',items: ['add-regional(regional-positive-prompt,regional-negative-prompt,regional-reference-image)',- 'transform','rename','fit-to-bbox','regional-auto-negative',@@ -107,4 +122,15 @@ describe('getLayerContextMenuLayout', () => {presentation: 'list',});});++ it('derives the same hierarchy when the input registry order is shuffled', () => {+ const upper = paintLayer('upper-shuffled');+ const below = paintLayer('below-shuffled');+ const actions = actionsFor(upper, [upper, below]);+ const reversed = [...actions].reverse();++ expect(summarizeLayout(getLayerContextMenuLayout(reversed))).toEqual(+ summarizeLayout(getLayerContextMenuLayout(actions))+ );+ });});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.tsindex 15d4367e0a..986e937547 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.ts@@ -1,111 +1,70 @@-import type { LayerContextAction, LayerContextActionId } from './layerContextActions';+import type { LayerContextAction, LayerContextMenuSectionId, LayerContextSubmenuId } from './layerContextActions';-export type LayerContextSubmenuId = 'arrange' | 'add-modifiers' | 'add-regional' | 'boolean' | 'copy-to' | 'convert-to';+export type { LayerContextSubmenuId } from './layerContextActions';export type LayerContextMenuItem =| { action: LayerContextAction; kind: 'action' }| { actions: readonly LayerContextAction[]; id: LayerContextSubmenuId; kind: 'submenu' };export interface LayerContextMenuSection {- id: 'quick' | 'primary' | 'operations' | 'output' | 'state' | 'danger';+ id: LayerContextMenuSectionId;items: readonly LayerContextMenuItem[];presentation: 'row' | 'list';}-const ARRANGE_IDS: readonly LayerContextActionId[] = ['move-to-front', 'move-forward', 'move-backward', 'move-to-back'];-const MODIFIER_IDS: readonly LayerContextActionId[] = ['inpaint-noise', 'inpaint-denoise-limit'];-const REGIONAL_ADD_IDS: readonly LayerContextActionId[] = [- 'regional-positive-prompt',- 'regional-negative-prompt',- 'regional-reference-image',-];-const PRIMARY_IDS: readonly LayerContextActionId[] = [- 'transform',- 'rename',- 'fit-to-bbox',- 'filter',- 'control-transparency-effect',- 'regional-auto-negative',- 'extract-masked-area',-];-const BOOLEAN_IDS: readonly LayerContextActionId[] = ['intersect', 'cutout', 'cutaway', 'exclude'];-const COPY_IDS: readonly LayerContextActionId[] = [- 'copy-to-clipboard',- 'copy-to-raster',- 'copy-to-control',- 'copy-to-inpaint-mask',- 'copy-to-regional-guidance',-];-const CONVERT_IDS: readonly LayerContextActionId[] = [- 'rasterize',- 'convert-to-control',- 'convert-to-raster',- 'convert-to-inpaint-mask',- 'convert-to-regional-guidance',+const SECTION_LAYOUT: readonly {+ id: LayerContextMenuSectionId;+ order: number;+ presentation: 'row' | 'list';+}[] = [+ { id: 'quick', order: 0, presentation: 'row' },+ { id: 'primary', order: 1, presentation: 'list' },+ { id: 'operations', order: 2, presentation: 'list' },+ { id: 'output', order: 3, presentation: 'list' },+ { id: 'state', order: 4, presentation: 'list' },+ { id: 'danger', order: 5, presentation: 'list' },];-const orderedActions = (- byId: ReadonlyMap<LayerContextActionId, LayerContextAction>,- ids: readonly LayerContextActionId[]-): LayerContextAction[] => ids.flatMap((id) => (byId.has(id) ? [byId.get(id)!] : []));+const sortActions = (actions: readonly LayerContextAction[]): LayerContextAction[] =>+ [...actions].sort((a, b) => a.order - b.order || a.id.localeCompare(b.id));-const actionItem = (- byId: ReadonlyMap<LayerContextActionId, LayerContextAction>,- id: LayerContextActionId-): LayerContextMenuItem[] => {- const action = byId.get(id);- return action ? [{ action, kind: 'action' }] : [];-};+interface OrderedMenuItem {+ id: string;+ item: LayerContextMenuItem;+ order: number;+}-const submenuItem = (- byId: ReadonlyMap<LayerContextActionId, LayerContextAction>,- id: LayerContextSubmenuId,- actionIds: readonly LayerContextActionId[]-): LayerContextMenuItem[] => {- const actions = orderedActions(byId, actionIds);- return actions.length > 0 ? [{ actions, id, kind: 'submenu' }] : [];-};+const buildSectionItems = (actions: readonly LayerContextAction[]): LayerContextMenuItem[] => {+ const ordered: OrderedMenuItem[] = [];+ const submenus = new Map<LayerContextSubmenuId, LayerContextAction[]>();-/** Builds the legacy-style layer-menu hierarchy without coupling it to Chakra rendering. */-export const getLayerContextMenuLayout = (actions: readonly LayerContextAction[]): LayerContextMenuSection[] => {- const byId = new Map(actions.map((action) => [action.id, action]));- const sections: LayerContextMenuSection[] = [- {- id: 'quick',- items: [...submenuItem(byId, 'arrange', ARRANGE_IDS), ...actionItem(byId, 'duplicate')],- presentation: 'row',- },- {- id: 'primary',- items: [- ...submenuItem(byId, 'add-modifiers', MODIFIER_IDS),- ...submenuItem(byId, 'add-regional', REGIONAL_ADD_IDS),- ...orderedActions(byId, PRIMARY_IDS).map((action) => ({ action, kind: 'action' }) as const),- ],- presentation: 'list',- },- {- id: 'operations',- items: [- ...actionItem(byId, 'merge-down'),- ...submenuItem(byId, 'boolean', BOOLEAN_IDS),- ...submenuItem(byId, 'copy-to', COPY_IDS),- ...submenuItem(byId, 'convert-to', CONVERT_IDS),- ],- presentation: 'list',- },- {- id: 'output',- items: [...actionItem(byId, 'crop-to-bbox'), ...actionItem(byId, 'save-to-assets')],- presentation: 'list',- },- {- id: 'state',- items: [...actionItem(byId, 'toggle-visibility'), ...actionItem(byId, 'toggle-lock')],- presentation: 'list',- },- { id: 'danger', items: actionItem(byId, 'delete'), presentation: 'list' },- ];+ for (const action of actions) {+ if (!action.submenu) {+ ordered.push({ id: action.id, item: { action, kind: 'action' }, order: action.order });+ continue;+ }+ const submenuActions = submenus.get(action.submenu) ?? [];+ submenuActions.push(action);+ submenus.set(action.submenu, submenuActions);+ }- return sections.filter((section) => section.items.length > 0);+ for (const [id, submenuActions] of submenus) {+ const sorted = sortActions(submenuActions);+ ordered.push({+ id,+ item: { actions: sorted, id, kind: 'submenu' },+ order: sorted[0]?.order ?? Number.POSITIVE_INFINITY,+ });+ }++ return ordered.sort((a, b) => a.order - b.order || a.id.localeCompare(b.id)).map(({ item }) => item);};++/** Builds the layer-menu hierarchy exclusively from executable registry metadata. */+export const getLayerContextMenuLayout = (actions: readonly LayerContextAction[]): LayerContextMenuSection[] =>+ [...SECTION_LAYOUT]+ .sort((a, b) => a.order - b.order)+ .flatMap((section): LayerContextMenuSection[] => {+ const items = buildSectionItems(actions.filter((action) => action.section === section.id));+ return items.length > 0 ? [{ id: section.id, items, presentation: section.presentation }] : [];+ });diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex c7218cd7ae..b5552075b2 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -289,6 +289,60 @@ describe('fitLayerTransformToBbox', () => {it('returns null for empty content', () => {expect(fitLayerTransformToBbox(createEmptyPaintLayer('empty'), { height: 512, width: 512, x: 0, y: 0 })).toBeNull();});++ it('contains and centers landscape content without stretching', () => {+ const layer = paintLayer('landscape', {+ source: {+ bitmap: { height: 100, imageName: 'landscape', width: 200 },+ offset: { x: 10, y: 20 },+ type: 'paint',+ },+ });++ expect(fitLayerTransformToBbox(layer, { height: 100, width: 100, x: 0, y: 0 })).toEqual({+ rotation: 0,+ scaleX: 0.5,+ scaleY: 0.5,+ x: -5,+ y: 15,+ });+ });++ it('contains and centers portrait content without stretching', () => {+ const layer = paintLayer('portrait', {+ source: {+ bitmap: { height: 200, imageName: 'portrait', width: 100 },+ offset: { x: 10, y: 20 },+ type: 'paint',+ },+ });++ expect(fitLayerTransformToBbox(layer, { height: 100, width: 100, x: 0, y: 0 })).toEqual({+ rotation: 0,+ scaleX: 0.5,+ scaleY: 0.5,+ x: 20,+ y: -10,+ });+ });++ it('accounts for non-zero local content origins and bbox placement', () => {+ const layer = paintLayer('offset', {+ source: {+ bitmap: { height: 50, imageName: 'offset', width: 50 },+ offset: { x: -20, y: 30 },+ type: 'paint',+ },+ });++ expect(fitLayerTransformToBbox(layer, { height: 100, width: 200, x: 50, y: 100 })).toEqual({+ rotation: 0,+ scaleX: 2,+ scaleY: 2,+ x: 140,+ y: 40,+ });+ });});describe('menu patch helpers', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 9646941dc2..a7ae0548b5 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -318,14 +318,13 @@ export const fitLayerTransformToBbox = (if (contentRect.width <= 0 || contentRect.height <= 0) {return null;}- const scaleX = bbox.width / contentRect.width;- const scaleY = bbox.height / contentRect.height;+ const scale = Math.min(bbox.width / contentRect.width, bbox.height / contentRect.height);return {rotation: 0,- scaleX,- scaleY,- x: bbox.x - contentRect.x * scaleX,- y: bbox.y - contentRect.y * scaleY,+ scaleX: scale,+ scaleY: scale,+ x: bbox.x + (bbox.width - contentRect.width * scale) / 2 - contentRect.x * scale,+ y: bbox.y + (bbox.height - contentRect.height * scale) / 2 - contentRect.y * scale,};};diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.tsindex 843825d128..824069031e 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.test.ts@@ -14,10 +14,18 @@ describe('layerPropertiesRequestStore', () => {clearLayerPropertiesRequest();});- it('publishes the requested layer and section', () => {- requestLayerProperties('control-1', 'filter');+ it.each(['filter', 'adjustments'] as const)('publishes and token-safely clears a %s request', (section) => {+ requestLayerProperties('layer-1', section);+ const first = getLayerPropertiesRequest();+ requestLayerProperties('layer-2', section);+ const second = getLayerPropertiesRequest();- expect(getLayerPropertiesRequest()).toMatchObject({ layerId: 'control-1', section: 'filter' });+ expect(first).toMatchObject({ layerId: 'layer-1', section });+ expect(second).toMatchObject({ layerId: 'layer-2', section });+ clearLayerPropertiesRequest(first?.token);+ expect(getLayerPropertiesRequest()).toEqual(second);+ clearLayerPropertiesRequest(second?.token);+ expect(getLayerPropertiesRequest()).toBeNull();});it('publishes a fresh token for repeated requests and notifies subscribers', () => {diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.tsindex bf758e2d73..83d8e31871 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerPropertiesRequestStore.ts@@ -2,7 +2,7 @@ import type { CanvasLayerContract } from '@workbench/types';import { createExternalStore } from '@workbench/externalStore';-export type LayerPropertiesSection = 'filter';+export type LayerPropertiesSection = 'filter' | 'adjustments';export interface LayerPropertiesRequest {layerId: string;