Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.
TypeScript ai-artartificial-intelligencegenerative-artimage-generationimg2imginpaintinglatent-diffusionlinuxmacosoutpaintingstable-diffusiontxt2imgwindows
feat(canvas): layer context actions registry
joshistoastbeeb2f0e2d3d
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsxindex 1aaa933e91..9a3635d262 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx@@ -1,5 +1,6 @@import type { CanvasEngine } from '@workbench/canvas-engine/engine';-import type { CanvasLayerContract } from '@workbench/types';+import type { GenerateReferenceImage } from '@workbench/generation/types';+import type { CanvasLayerContract, CanvasMaskContract } from '@workbench/types';import type { WorkbenchAction } from '@workbench/workbenchState';import type { LucideIcon } from 'lucide-react';import type { ComponentProps, Dispatch } from 'react';@@ -7,6 +8,9 @@ import type { ComponentProps, Dispatch } from 'react';import { HStack, Icon, Menu, Portal, Text } from '@chakra-ui/react';import { deleteLayerActions, duplicateLayerActions } from '@workbench/canvasLayerOps';import { IconButton, MenuContent, RenameDialog } from '@workbench/components/ui';+import { useModelsSelector } from '@workbench/models/modelsStore';+import { getProjectWidgetValues } from '@workbench/widgetState';+import { useActiveProjectSelector } from '@workbench/WorkbenchContext';import {ArrowDownIcon,ArrowDownToLineIcon,@@ -29,27 +33,50 @@ import { useTranslation } from 'react-i18next';import type { LayerMoveKind } from './layerGroups';-import { getGroupPosition, reorderWithinGroupByKind } from './layerGroups';+import { getLayerContextActions, type LayerContextAction, type LayerContextActionId } from './layerContextActions';+import { reorderWithinGroupByKind } from './layerGroups';import { resolveMenuTargetForRender } from './layerMenuState';import {applyStructural,- canConvertRasterControl,- canMergeLayerDown,convertRasterControlLayer,createLayerId,+ fitLayerTransformToBbox,+ getControlTransparencyEffectPatch,+ getInpaintDenoiseLimitPatch,+ getInpaintNoisePatch,+ getRegionalGuidanceAutoNegativePatch,+ getRegionalGuidanceNegativePromptPatch,+ getRegionalGuidancePositivePromptPatch,+ getRegionalGuidanceReferenceImagePatch,} from './layerOps';type MenuPositioning = ComponentProps<typeof Menu.Root>['positioning'];type MenuOpenChange = ComponentProps<typeof Menu.Root>['onOpenChange'];+type LayerConfigPatch =+ | { layerType: 'control'; withTransparencyEffect?: boolean }+ | {+ layerType: 'regional_guidance';+ mask?: Partial<CanvasMaskContract>;+ positivePrompt?: string | null;+ negativePrompt?: string | null;+ autoNegative?: boolean;+ referenceImages?: GenerateReferenceImage[];+ }+ | { layerType: 'inpaint_mask'; noiseLevel?: number; denoiseLimit?: number };+const PANEL_POSITIONING: MenuPositioning = { placement: 'bottom-end' };-// const layerBadgeKey = (layer: CanvasLayerContract): string => {-// if (layer.type === 'raster') {-// return layer.source.type === 'image' ? 'widgets.layers.types.image' : 'widgets.layers.types.paint';-// }-// return `widgets.layers.types.${layer.type}`;-// };+/** The main model's base, read from the generate widget values (drives regional ref-image support). */+const useSelectedModelBase = (): string | null => {+ const modelKey = useActiveProjectSelector((project) => {+ const values = getProjectWidgetValues(project, 'generate');+ const model = values?.model;+ return model && typeof model === 'object' && 'key' in model ? String((model as { key: unknown }).key) : null;+ });+ const models = useModelsSelector((snapshot) => snapshot.models);+ return useMemo(() => models.find((model) => model.key === modelKey)?.base ?? null, [models, modelKey]);+};interface LayerMenuProps {dispatch: Dispatch<WorkbenchAction>;@@ -108,6 +135,11 @@ const LayerMenu = ({onRenamingChange,}: LayerMenuProps) => {const { t } = useTranslation();+ 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 [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.@@ -120,20 +152,6 @@ const LayerMenu = ({[onRenamingChange]);- const groupPosition = getGroupPosition(layers, layer.id);- const canMoveForward = !!groupPosition && groupPosition.index > 0;- const canMoveBackward = !!groupPosition && groupPosition.index < groupPosition.count - 1;- const canMerge = canMergeLayerDown(layers, index, !!engine);- // "Rasterize layer" is offered only for parametric sources (shape/gradient/- // text), where the engine can bake the params to pixels. A polygon shape has- // no rasterizer yet, so it stays disabled.- const canRasterize =- !!engine &&- layer.type === 'raster' &&- (layer.source.type === 'gradient' ||- layer.source.type === 'text' ||- (layer.source.type === 'shape' && layer.source.kind !== 'polygon'));-const patchBase = useCallback((label: string, forward: Partial<CanvasLayerContract>, inverse: Partial<CanvasLayerContract>) => {applyStructural(@@ -147,6 +165,19 @@ const LayerMenu = ({[dispatch, engine, layer.id]);+ const patchConfig = useCallback(+ (label: string, forward: LayerConfigPatch, inverse: LayerConfigPatch) => {+ applyStructural(+ engine,+ dispatch,+ label,+ { config: forward, id: layer.id, type: 'updateCanvasLayerConfig' },+ { config: inverse, id: layer.id, type: 'updateCanvasLayerConfig' }+ );+ },+ [dispatch, engine, layer.id]+ );+const reorder = useCallback((kind: LayerMoveKind, label: string) => {const next = reorderWithinGroupByKind(layers, layer.id, kind);@@ -223,10 +254,6 @@ const LayerMenu = ({() => convert('raster', t('widgets.layers.actions.convertToRaster')),[convert, t]);- // raster↔control conversion is offered only for pixel-backed layers (image/paint- // raster sources, or a control layer). Parametric raster + mask layers cannot.- const canConvertToControl = layer.type === 'raster' && canConvertRasterControl(layer);- const canConvertToRaster = layer.type === 'control';const handleToggleVisibility = useCallback(() => {patchBase(@@ -249,6 +276,142 @@ const LayerMenu = ({[layer.name, patchBase, t]);+ const actions = useMemo(+ () => getLayerContextActions({ hasEngine: !!engine, index, layer, layers }),+ [engine, index, layer, layers]+ );+ const iconActions = useMemo(() => actions.filter((action) => action.group === 'icons'), [actions]);+ const actionGroups = useMemo(+ () =>+ LAYER_ACTION_GROUPS.map((group) => ({+ actions: actions.filter((action) => action.group === group),+ group,+ })).filter((entry) => entry.actions.length > 0),+ [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');+ }, [dispatch, engine, layer.id]);++ const handleFitToBbox = useCallback(() => {+ const transform = fitLayerTransformToBbox(layer, bbox, documentRect);+ if (!transform) {+ return;+ }+ patchBase(getActionLabel('fit-to-bbox'), { transform }, { transform: layer.transform });+ }, [bbox, documentRect, getActionLabel, layer, patchBase]);++ const handleLayerConfigAction = useCallback(+ (id: LayerContextActionId) => {+ if (id === 'control-transparency-effect' && layer.type === 'control') {+ const { forward, inverse } = getControlTransparencyEffectPatch(layer);+ patchConfig(getActionLabel(id), forward, inverse);+ } else if (id === 'regional-positive-prompt' && layer.type === 'regional_guidance') {+ const { forward, inverse } = getRegionalGuidancePositivePromptPatch(layer);+ patchConfig(getActionLabel(id), forward, inverse);+ } else if (id === 'regional-negative-prompt' && layer.type === 'regional_guidance') {+ const { forward, inverse } = getRegionalGuidanceNegativePromptPatch(layer);+ patchConfig(getActionLabel(id), forward, inverse);+ } else if (id === 'regional-reference-image' && layer.type === 'regional_guidance') {+ const { forward, inverse } = getRegionalGuidanceReferenceImagePatch(layer, base);+ patchConfig(getActionLabel(id), forward, inverse);+ } else if (id === 'regional-auto-negative' && layer.type === 'regional_guidance') {+ const { forward, inverse } = getRegionalGuidanceAutoNegativePatch(layer);+ patchConfig(getActionLabel(id), forward, inverse);+ } else if (id === 'inpaint-noise' && layer.type === 'inpaint_mask') {+ const { forward, inverse } = getInpaintNoisePatch(layer);+ patchConfig(getActionLabel(id), forward, inverse);+ } else if (id === 'inpaint-denoise-limit' && layer.type === 'inpaint_mask') {+ const { forward, inverse } = getInpaintDenoiseLimitPatch(layer);+ patchConfig(getActionLabel(id), forward, inverse);+ }+ },+ [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 'rasterize':+ handleRasterize();+ break;+ case 'convert-to-control':+ handleConvertToControl();+ break;+ case 'convert-to-raster':+ handleConvertToRaster();+ break;+ case 'merge-down':+ handleMerge();+ break;+ case 'toggle-visibility':+ handleToggleVisibility();+ break;+ case 'toggle-lock':+ handleToggleLock();+ break;+ case 'delete':+ handleDelete();+ break;+ default:+ handleLayerConfigAction(id);+ break;+ }+ },+ [+ handleConvertToControl,+ handleConvertToRaster,+ handleDelete,+ handleDuplicate,+ handleFitToBbox,+ handleLayerConfigAction,+ handleMerge,+ handleMoveBackward,+ handleMoveForward,+ handleMoveToBack,+ handleMoveToFront,+ handleRasterize,+ handleToggleLock,+ handleToggleVisibility,+ handleTransform,+ openRename,+ ]+ );+return (<><Menu.Root@@ -275,106 +438,13 @@ const LayerMenu = ({<Menu.Positioner><MenuContent minW="14rem" py="1"><HStack gap="1">- <LayerMenuIconItem- disabled={!canMoveForward}- icon={ArrowUpToLineIcon}- label={t('widgets.layers.actions.moveToFront')}- value="move-to-front"- onSelect={handleMoveToFront}- />- <LayerMenuIconItem- disabled={!canMoveForward}- icon={ArrowUpIcon}- label={t('widgets.layers.actions.moveForward')}- value="move-forward"- onSelect={handleMoveForward}- />- <LayerMenuIconItem- disabled={!canMoveBackward}- icon={ArrowDownIcon}- label={t('widgets.layers.actions.moveBackward')}- value="move-backward"- onSelect={handleMoveBackward}- />- <LayerMenuIconItem- disabled={!canMoveBackward}- icon={ArrowDownToLineIcon}- label={t('widgets.layers.actions.moveToBack')}- value="move-to-back"- onSelect={handleMoveToBack}- />- <LayerMenuIconItem- icon={CopyIcon}- label={t('widgets.layers.actions.duplicate')}- value="duplicate"- onSelect={handleDuplicate}- />- {/*<LayerMenuIconItem- color="fg.error"- icon={Trash2Icon}- label={t('widgets.layers.actions.delete')}- value="delete"- onSelect={handleDelete}- />*/}+ {iconActions.map((action) => (+ <LayerMenuIconActionItem key={action.id} action={action} handleAction={handleAction} t={t} />+ ))}</HStack>- <Menu.Separator borderColor="border.subtle" />- <LayerMenuItem- icon={PencilIcon}- label={t('widgets.layers.actions.rename')}- value="rename"- onSelect={openRename}- />- {canRasterize ? (- <LayerMenuItem- icon={ImageIcon}- label={t('widgets.layers.actions.rasterize')}- value="rasterize"- onSelect={handleRasterize}- />- ) : null}- {canConvertToControl ? (- <LayerMenuItem- icon={SlidersHorizontalIcon}- label={t('widgets.layers.actions.convertToControl')}- value="convert-to-control"- onSelect={handleConvertToControl}- />- ) : null}- {canConvertToRaster ? (- <LayerMenuItem- icon={ImageIcon}- label={t('widgets.layers.actions.convertToRaster')}- value="convert-to-raster"- onSelect={handleConvertToRaster}- />- ) : null}- <Menu.Separator borderColor="border.subtle" />- <LayerMenuItem- disabled={!canMerge}- icon={MergeIcon}- label={t('widgets.layers.actions.mergeDown')}- value="merge-down"- onSelect={handleMerge}- />- <LayerMenuItem- icon={layer.isEnabled ? EyeOffIcon : EyeIcon}- label={layer.isEnabled ? t('widgets.layers.actions.hide') : t('widgets.layers.actions.show')}- value="toggle-visibility"- onSelect={handleToggleVisibility}- />- <LayerMenuItem- icon={layer.isLocked ? LockOpenIcon : LockIcon}- label={layer.isLocked ? t('widgets.layers.actions.unlock') : t('widgets.layers.actions.lock')}- value="toggle-lock"- onSelect={handleToggleLock}- />- <LayerMenuItem- icon={Trash2Icon}- label={t('widgets.layers.actions.delete')}- value="delete"- onSelect={handleDelete}- color="fg.error"- />+ {actionGroups.map(({ actions, group }) => (+ <LayerMenuGroup key={group} actions={actions} handleAction={handleAction} t={t} />+ ))}</MenuContent></Menu.Positioner></Portal>@@ -498,8 +568,113 @@ export const CanvasLayerContextMenu = ({);};+const LAYER_ACTION_GROUPS: readonly LayerContextAction['group'][] = [+ 'edit',+ 'convert',+ 'layerConfig',+ 'state',+ 'danger',+];++const LAYER_ACTION_ICONS: Record<LayerContextActionId, LucideIcon> = {+ 'control-transparency-effect': SlidersHorizontalIcon,+ 'convert-to-control': SlidersHorizontalIcon,+ 'convert-to-raster': ImageIcon,+ delete: Trash2Icon,+ duplicate: CopyIcon,+ 'fit-to-bbox': ImageIcon,+ 'inpaint-denoise-limit': SlidersHorizontalIcon,+ 'inpaint-noise': SlidersHorizontalIcon,+ '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,+ 'toggle-lock': LockIcon,+ 'toggle-visibility': EyeIcon,+ transform: SlidersHorizontalIcon,+};+const stopPropagation = (event: { stopPropagation: () => void }): void => event.stopPropagation();+const LayerMenuGroup = ({+ actions,+ handleAction,+ t,+}: {+ actions: readonly LayerContextAction[];+ handleAction: (id: LayerContextActionId) => void;+ t: (key: string, options: { defaultValue: string }) => string;+}) => (+ <>+ <Menu.Separator borderColor="border.subtle" />+ {actions.map((action) => (+ <LayerMenuActionItem key={action.id} action={action} handleAction={handleAction} t={t} />+ ))}+ </>+);++const LayerMenuIconActionItem = ({+ action,+ handleAction,+ t,+}: {+ action: LayerContextAction;+ handleAction: (id: LayerContextActionId) => void;+ t: (key: string, options: { defaultValue: string }) => string;+}) => {+ const onSelect = useCallback(() => handleAction(action.id), [action.id, handleAction]);++ return (+ <LayerMenuIconItem+ disabled={action.isDisabled}+ icon={LAYER_ACTION_ICONS[action.id]}+ label={t(action.labelKey, { defaultValue: action.defaultLabel })}+ value={action.id}+ onSelect={onSelect}+ />+ );+};++const LayerMenuActionItem = ({+ action,+ handleAction,+ t,+}: {+ action: LayerContextAction;+ handleAction: (id: LayerContextActionId) => void;+ t: (key: string, options: { defaultValue: string }) => string;+}) => {+ const onSelect = useCallback(() => handleAction(action.id), [action.id, handleAction]);++ return (+ <LayerMenuItem+ color={action.tone === 'danger' ? 'fg.error' : undefined}+ disabled={action.isDisabled}+ icon={getLayerActionIcon(action)}+ label={t(action.labelKey, { defaultValue: action.defaultLabel })}+ value={action.id}+ onSelect={onSelect}+ />+ );+};++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.tsnew file mode 100644index 0000000000..90e8eb453e--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts@@ -0,0 +1,84 @@+import type { CanvasLayerContract, CanvasRasterLayerContractV2 } from '@workbench/types';++import { describe, expect, it } from 'vitest';++import { getLayerContextActions } from './layerContextActions';+import {+ createControlLayer,+ createEmptyPaintLayer,+ createInpaintMaskLayer,+ createRegionalGuidanceLayer,+} from './layerOps';++const paintLayer = (id: string, patch: Partial<CanvasRasterLayerContractV2> = {}): CanvasLayerContract => ({+ ...createEmptyPaintLayer(id, id),+ ...patch,+});++const idsFor = (layer: CanvasLayerContract, layers: readonly CanvasLayerContract[] = [layer], hasEngine = true) =>+ getLayerContextActions({ hasEngine, index: layers.indexOf(layer), layer, layers }).map((action) => action.id);++describe('getLayerContextActions', () => {+ it('keeps common actions available for a raster layer', () => {+ expect(idsFor(paintLayer('raster'))).toEqual(+ expect.arrayContaining([+ 'move-to-front',+ 'duplicate',+ 'rename',+ 'transform',+ 'fit-to-bbox',+ 'merge-down',+ 'delete',+ ])+ );+ });++ it('exposes only pixel-backed raster to control conversion', () => {+ const paint = paintLayer('paint');+ const text = paintLayer('text', {+ source: {+ align: 'left',+ color: '#fff',+ content: 'hello',+ fontFamily: 'Inter',+ fontSize: 32,+ fontWeight: 400,+ lineHeight: 1.2,+ type: 'text',+ },+ });++ expect(idsFor(paint)).toContain('convert-to-control');+ expect(idsFor(text)).not.toContain('convert-to-control');+ });++ it('exposes control-only transparency and raster conversion actions', () => {+ const layer = createControlLayer('Control', 'control');++ expect(idsFor(layer)).toEqual(expect.arrayContaining(['control-transparency-effect', 'convert-to-raster']));+ });++ it('exposes regional guidance add actions only for missing prompts', () => {+ const layer = { ...createRegionalGuidanceLayer('Region', 0, 'region'), positivePrompt: 'already' };++ expect(idsFor(layer)).toContain('regional-negative-prompt');+ expect(idsFor(layer)).toContain('regional-reference-image');+ expect(idsFor(layer)).toContain('regional-auto-negative');+ expect(idsFor(layer)).not.toContain('regional-positive-prompt');+ });++ it('exposes inpaint modifier add actions only for missing modifiers', () => {+ const layer = { ...createInpaintMaskLayer('Mask', 'mask'), noiseLevel: 0.25 };++ expect(idsFor(layer)).toContain('inpaint-denoise-limit');+ expect(idsFor(layer)).not.toContain('inpaint-noise');+ });++ 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 === 'merge-down')?.isDisabled).toBe(true);+ });+});diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.tsnew file mode 100644index 0000000000..5f46e5d94d--- /dev/null+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts@@ -0,0 +1,232 @@+import type { CanvasLayerContract } from '@workbench/types';++import { getGroupPosition } from './layerGroups';+import { canConvertRasterControl, canMergeLayerDown } from './layerOps';++export type LayerContextActionId =+ | 'move-to-front'+ | 'move-forward'+ | 'move-backward'+ | 'move-to-back'+ | 'duplicate'+ | 'rename'+ | 'transform'+ | 'fit-to-bbox'+ | 'rasterize'+ | 'convert-to-control'+ | 'convert-to-raster'+ | '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';++export type LayerContextActionGroup = 'icons' | 'edit' | 'convert' | 'layerConfig' | 'state' | 'danger';++export interface LayerContextActionContext {+ hasEngine: boolean;+ index: number;+ layer: CanvasLayerContract;+ layers: readonly CanvasLayerContract[];+}++export interface LayerContextAction {+ defaultLabel: string;+ group: LayerContextActionGroup;+ id: LayerContextActionId;+ isDisabled: boolean;+ labelKey: string;+ tone?: 'danger';+}++type LayerContextActionDefinition = Omit<LayerContextAction, 'isDisabled'> & {+ getDefaultLabel?: (ctx: LayerContextActionContext) => string;+ getLabelKey?: (ctx: LayerContextActionContext) => string;+ isDisabled?: (ctx: LayerContextActionContext) => boolean;+ isVisible?: (ctx: LayerContextActionContext) => boolean;+};++const isParametricRasterizable = (layer: CanvasLayerContract): boolean =>+ layer.type === 'raster' &&+ (layer.source.type === 'gradient' ||+ layer.source.type === 'text' ||+ (layer.source.type === 'shape' && layer.source.kind !== 'polygon'));++const groupPosition = (ctx: LayerContextActionContext) => getGroupPosition(ctx.layers, ctx.layer.id);++const canMoveForward = (ctx: LayerContextActionContext): boolean => {+ const position = groupPosition(ctx);+ return !!position && position.index > 0;+};++const canMoveBackward = (ctx: LayerContextActionContext): boolean => {+ const position = groupPosition(ctx);+ return !!position && position.index < position.count - 1;+};++export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefinition[] = [+ {+ defaultLabel: 'Move to front',+ group: 'icons',+ id: 'move-to-front',+ isDisabled: (ctx) => !canMoveForward(ctx),+ labelKey: 'widgets.layers.actions.moveToFront',+ },+ {+ defaultLabel: 'Move forward',+ group: 'icons',+ id: 'move-forward',+ isDisabled: (ctx) => !canMoveForward(ctx),+ labelKey: 'widgets.layers.actions.moveForward',+ },+ {+ defaultLabel: 'Move backward',+ group: 'icons',+ id: 'move-backward',+ isDisabled: (ctx) => !canMoveBackward(ctx),+ labelKey: 'widgets.layers.actions.moveBackward',+ },+ {+ defaultLabel: 'Move to back',+ group: 'icons',+ id: 'move-to-back',+ isDisabled: (ctx) => !canMoveBackward(ctx),+ labelKey: 'widgets.layers.actions.moveToBack',+ },+ { 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',+ id: 'transform',+ isDisabled: (ctx) => !ctx.hasEngine,+ labelKey: 'widgets.layers.actions.transform',+ },+ { defaultLabel: 'Fit to bbox', group: 'edit', id: 'fit-to-bbox', labelKey: 'widgets.layers.actions.fitToBbox' },+ {+ defaultLabel: 'Rasterize',+ group: 'convert',+ id: 'rasterize',+ isVisible: (ctx) => ctx.hasEngine && isParametricRasterizable(ctx.layer),+ labelKey: 'widgets.layers.actions.rasterize',+ },+ {+ defaultLabel: 'Convert to Control Layer',+ group: 'convert',+ id: 'convert-to-control',+ isVisible: (ctx) => ctx.layer.type === 'raster' && canConvertRasterControl(ctx.layer),+ labelKey: 'widgets.layers.actions.convertToControl',+ },+ {+ defaultLabel: 'Convert to Raster Layer',+ group: 'convert',+ id: 'convert-to-raster',+ isVisible: (ctx) => ctx.layer.type === 'control',+ labelKey: 'widgets.layers.actions.convertToRaster',+ },+ {+ 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: 'Merge down',+ group: 'state',+ id: 'merge-down',+ isDisabled: (ctx) => !canMergeLayerDown(ctx.layers, ctx.index, ctx.hasEngine),+ labelKey: 'widgets.layers.actions.mergeDown',+ },+ {+ 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',+ id: 'toggle-visibility',+ labelKey: 'widgets.layers.actions.toggleVisibility',+ },+ {+ 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',+ id: 'toggle-lock',+ labelKey: 'widgets.layers.actions.toggleLock',+ },+ { 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,+ id: definition.id,+ isDisabled: definition.isDisabled?.(ctx) ?? false,+ labelKey: definition.getLabelKey?.(ctx) ?? definition.labelKey,+ tone: definition.tone,+ }));diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.tsindex 18a5709a56..1c936e5757 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.test.ts@@ -17,6 +17,14 @@ import {createRegionalReferenceImage,DEFAULT_CONTROL_ADAPTER,DEFAULT_INPAINT_MASK_FILL,+ fitLayerTransformToBbox,+ getControlTransparencyEffectPatch,+ getInpaintDenoiseLimitPatch,+ getInpaintNoisePatch,+ getRegionalGuidanceAutoNegativePatch,+ getRegionalGuidanceNegativePromptPatch,+ getRegionalGuidancePositivePromptPatch,+ getRegionalGuidanceReferenceImagePatch,isMergeableRasterLayer,nextControlLayerName,nextInpaintMaskName,@@ -256,6 +264,64 @@ describe('canConvertRasterControl', () => {});});+describe('fitLayerTransformToBbox', () => {+ it('scales and positions a layer content rect into the bbox', () => {+ const layer = paintLayer('paint', {+ source: { bitmap: { height: 50, imageName: 'paint', width: 100 }, offset: { x: 20, y: 10 }, type: 'paint' },+ });++ expect(+ fitLayerTransformToBbox(layer, { height: 100, width: 200, x: 0, y: 0 }, { height: 512, width: 512, x: 0, y: 0 })+ ).toEqual({ rotation: 0, scaleX: 2, scaleY: 2, x: -40, y: -20 });+ });++ it('returns null for empty content', () => {+ expect(fitLayerTransformToBbox(createEmptyPaintLayer('empty'), { height: 512, width: 512, x: 0, y: 0 })).toBeNull();+ });+});++describe('menu patch helpers', () => {+ it('builds control transparency effect patches', () => {+ const layer = createControlLayer('control', 'c1');++ expect(getControlTransparencyEffectPatch(layer)).toEqual({+ forward: { layerType: 'control', withTransparencyEffect: false },+ inverse: { layerType: 'control', withTransparencyEffect: true },+ });+ });++ it('builds regional prompt and reference image patches', () => {+ const layer = createRegionalGuidanceLayer('region', 0, 'r1');++ expect(getRegionalGuidancePositivePromptPatch(layer)).toEqual({+ forward: { layerType: 'regional_guidance', positivePrompt: '' },+ inverse: { layerType: 'regional_guidance', positivePrompt: null },+ });+ expect(getRegionalGuidanceNegativePromptPatch(layer)).toEqual({+ forward: { layerType: 'regional_guidance', negativePrompt: '' },+ inverse: { layerType: 'regional_guidance', negativePrompt: null },+ });+ expect(getRegionalGuidanceAutoNegativePatch(layer)).toEqual({+ forward: { autoNegative: true, layerType: 'regional_guidance' },+ inverse: { autoNegative: false, layerType: 'regional_guidance' },+ });+ expect(getRegionalGuidanceReferenceImagePatch(layer, 'sdxl').forward.referenceImages).toHaveLength(1);+ });++ it('builds inpaint modifier patches', () => {+ const layer = createInpaintMaskLayer('mask', 'm1');++ expect(getInpaintNoisePatch(layer)).toEqual({+ forward: { layerType: 'inpaint_mask', noiseLevel: 0.25 },+ inverse: { layerType: 'inpaint_mask', noiseLevel: undefined },+ });+ expect(getInpaintDenoiseLimitPatch(layer)).toEqual({+ forward: { denoiseLimit: 0.8, layerType: 'inpaint_mask' },+ inverse: { denoiseLimit: undefined, layerType: 'inpaint_mask' },+ });+ });+});+describe('convertRasterControlLayer', () => {it('converts raster→control preserving source/id/name/transform and applying the default adapter', () => {const source = { image: { height: 48, imageName: 'pic', width: 64 }, type: 'image' } as const;diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.tsindex 1cc58227e5..eced561d53 100644--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerOps.ts@@ -6,12 +6,15 @@*/import type { CanvasEngine } from '@workbench/canvas-engine/engine';+import type { Rect } from '@workbench/canvas-engine/types';import type { GenerateReferenceImage } from '@workbench/generation/types';import type {CanvasBlendMode,CanvasControlAdapterContract,CanvasControlLayerContract,+ CanvasDocumentContractV2,CanvasInpaintMaskLayerContract,+ CanvasLayerBaseContract,CanvasLayerContract,CanvasRasterLayerContractV2,CanvasRegionalGuidanceLayerContract,@@ -19,7 +22,20 @@ import type {import type { WorkbenchAction } from '@workbench/workbenchState';import type { Dispatch } from 'react';-import { isMergeableRasterLayer } from '@workbench/canvas-engine/document/sources';+import { getSourceContentRect, isMergeableRasterLayer } from '@workbench/canvas-engine/document/sources';++type LayerTransform = CanvasLayerBaseContract['transform'];++type ControlConfigPatch = { layerType: 'control'; withTransparencyEffect?: boolean };+type RegionalGuidanceConfigPatch = {+ layerType: 'regional_guidance';+ positivePrompt?: string | null;+ negativePrompt?: string | null;+ autoNegative?: boolean;+ referenceImages?: CanvasRegionalGuidanceLayerContract['referenceImages'];+};+type InpaintMaskConfigPatch = { layerType: 'inpaint_mask'; noiseLevel?: number; denoiseLimit?: number };+type PatchPair<T> = { forward: T; inverse: T };/*** Re-exported so existing imports of `isMergeableRasterLayer` from this module@@ -289,6 +305,79 @@ export const createControlLayer = (name: string, id: string = createLayerId()):withTransparencyEffect: true,});+/** Returns the transform that fits the layer's unrotated local content into the bbox. */+export const fitLayerTransformToBbox = (+ layer: CanvasLayerContract,+ bbox: Rect,+ documentRect: Rect = bbox+): LayerTransform | null => {+ const doc = { height: documentRect.height, width: documentRect.width } as CanvasDocumentContractV2;+ const contentRect = getSourceContentRect(layer, doc);+ if (contentRect.width <= 0 || contentRect.height <= 0) {+ return null;+ }+ const scaleX = bbox.width / contentRect.width;+ const scaleY = bbox.height / contentRect.height;+ return {+ rotation: 0,+ scaleX,+ scaleY,+ x: bbox.x - contentRect.x * scaleX,+ y: bbox.y - contentRect.y * scaleY,+ };+};++export const getControlTransparencyEffectPatch = (+ layer: CanvasControlLayerContract+): PatchPair<ControlConfigPatch> => ({+ forward: { layerType: 'control', withTransparencyEffect: !layer.withTransparencyEffect },+ inverse: { layerType: 'control', withTransparencyEffect: layer.withTransparencyEffect },+});++export const getRegionalGuidancePositivePromptPatch = (+ layer: CanvasRegionalGuidanceLayerContract+): PatchPair<RegionalGuidanceConfigPatch> => ({+ forward: { layerType: 'regional_guidance', positivePrompt: layer.positivePrompt ?? '' },+ inverse: { layerType: 'regional_guidance', positivePrompt: layer.positivePrompt },+});++export const getRegionalGuidanceNegativePromptPatch = (+ layer: CanvasRegionalGuidanceLayerContract+): PatchPair<RegionalGuidanceConfigPatch> => ({+ forward: { layerType: 'regional_guidance', negativePrompt: layer.negativePrompt ?? '' },+ inverse: { layerType: 'regional_guidance', negativePrompt: layer.negativePrompt },+});++export const getRegionalGuidanceAutoNegativePatch = (+ layer: CanvasRegionalGuidanceLayerContract+): PatchPair<RegionalGuidanceConfigPatch> => ({+ forward: { autoNegative: !layer.autoNegative, layerType: 'regional_guidance' },+ inverse: { autoNegative: layer.autoNegative, layerType: 'regional_guidance' },+});++export const getRegionalGuidanceReferenceImagePatch = (+ layer: CanvasRegionalGuidanceLayerContract,+ base: string | null+): PatchPair<RegionalGuidanceConfigPatch> => ({+ forward: {+ layerType: 'regional_guidance',+ referenceImages: [...layer.referenceImages, createRegionalReferenceImage(base)],+ },+ inverse: { layerType: 'regional_guidance', referenceImages: layer.referenceImages },+});++export const getInpaintNoisePatch = (layer: CanvasInpaintMaskLayerContract): PatchPair<InpaintMaskConfigPatch> => ({+ forward: { layerType: 'inpaint_mask', noiseLevel: layer.noiseLevel === undefined ? 0.25 : undefined },+ inverse: { layerType: 'inpaint_mask', noiseLevel: layer.noiseLevel },+});++export const getInpaintDenoiseLimitPatch = (+ layer: CanvasInpaintMaskLayerContract+): PatchPair<InpaintMaskConfigPatch> => ({+ forward: { denoiseLimit: layer.denoiseLimit === undefined ? 0.8 : undefined, layerType: 'inpaint_mask' },+ inverse: { denoiseLimit: layer.denoiseLimit, layerType: 'inpaint_mask' },+});+/*** True when `layer` can be converted to a control layer (and vice-versa): only a* raster layer with a rasterizable image/paint source, or a control layer,diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.test.tsindex 0e948a5547..85cf5e739b 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import type { GenerateWidgetValues, MainModelConfig } from './generation/types';import type {CanvasControlLayerContract,+ CanvasInpaintMaskLayerContract,CanvasLayerContract,CanvasRasterLayerContractV2,GeneratedImageContract,@@ -1904,6 +1905,50 @@ describe('workbenchReducer canvas v2 layer reducers', () => {}});+ it('removes optional config fields when a patch explicitly sets them to undefined', () => {+ const configuredMask: CanvasInpaintMaskLayerContract = {+ blendMode: 'normal',+ denoiseLimit: 0.8,+ id: 'm',+ isEnabled: true,+ isLocked: false,+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' } },+ name: 'm',+ noiseLevel: 0.25,+ opacity: 1,+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 0, y: 0 },+ type: 'inpaint_mask',+ };+ let state = withCanvasLayers(createInitialWorkbenchState(), [+ configuredMask,+ { ...createControlLayer('ctrl'), filter: { settings: {}, type: 'canny' } },+ ]);++ state = workbenchReducer(state, {+ config: { denoiseLimit: undefined, layerType: 'inpaint_mask', noiseLevel: undefined },+ id: 'm',+ type: 'updateCanvasLayerConfig',+ });+ state = workbenchReducer(state, {+ config: { filter: undefined, layerType: 'control' },+ id: 'ctrl',+ type: 'updateCanvasLayerConfig',+ });++ const mask = getCanvas(state).document.layers[0];+ const control = getCanvas(state).document.layers[1];++ expect(mask?.type).toBe('inpaint_mask');+ if (mask?.type === 'inpaint_mask') {+ expect(mask.noiseLevel).toBeUndefined();+ expect(mask.denoiseLimit).toBeUndefined();+ }+ expect(control?.type).toBe('control');+ if (control?.type === 'control') {+ expect(control.filter).toBeUndefined();+ }+ });+it('converts a layer in place, preserving its id and z-order', () => {let state = withCanvasLayers(createInitialWorkbenchState(), [createRasterLayer('a'), createRasterLayer('b')]);const converted = createControlLayer('ignored-id');diff --git a/invokeai/frontend/webv2/src/workbench/workbenchState.ts b/invokeai/frontend/webv2/src/workbench/workbenchState.tsindex 4991ad302a..1c6537c463 100644--- a/invokeai/frontend/webv2/src/workbench/workbenchState.ts+++ b/invokeai/frontend/webv2/src/workbench/workbenchState.ts@@ -903,8 +903,8 @@ const applyCanvasLayerConfigPatch = (if (layer.type === 'raster' && config.layerType === 'raster') {return {...layer,- ...(config.adjustments !== undefined ? { adjustments: config.adjustments } : {}),- ...(config.isTransparencyLocked !== undefined ? { isTransparencyLocked: config.isTransparencyLocked } : {}),+ ...(Object.hasOwn(config, 'adjustments') ? { adjustments: config.adjustments } : {}),+ ...(Object.hasOwn(config, 'isTransparencyLocked') ? { isTransparencyLocked: config.isTransparencyLocked } : {}),};}@@ -912,8 +912,10 @@ const applyCanvasLayerConfigPatch = (return {...layer,...(config.adapter ? { adapter: { ...layer.adapter, ...config.adapter } } : {}),- ...(config.withTransparencyEffect !== undefined ? { withTransparencyEffect: config.withTransparencyEffect } : {}),- ...(config.filter !== undefined ? { filter: config.filter } : {}),+ ...(Object.hasOwn(config, 'withTransparencyEffect')+ ? { withTransparencyEffect: config.withTransparencyEffect }+ : {}),+ ...(Object.hasOwn(config, 'filter') ? { filter: config.filter } : {}),};}@@ -921,10 +923,10 @@ const applyCanvasLayerConfigPatch = (return {...layer,...(config.mask ? { mask: { ...layer.mask, ...config.mask } } : {}),- ...(config.positivePrompt !== undefined ? { positivePrompt: config.positivePrompt } : {}),- ...(config.negativePrompt !== undefined ? { negativePrompt: config.negativePrompt } : {}),- ...(config.autoNegative !== undefined ? { autoNegative: config.autoNegative } : {}),- ...(config.referenceImages !== undefined ? { referenceImages: config.referenceImages } : {}),+ ...(Object.hasOwn(config, 'positivePrompt') ? { positivePrompt: config.positivePrompt } : {}),+ ...(Object.hasOwn(config, 'negativePrompt') ? { negativePrompt: config.negativePrompt } : {}),+ ...(Object.hasOwn(config, 'autoNegative') ? { autoNegative: config.autoNegative } : {}),+ ...(Object.hasOwn(config, 'referenceImages') ? { referenceImages: config.referenceImages } : {}),};}@@ -932,8 +934,8 @@ const applyCanvasLayerConfigPatch = (return {...layer,...(config.mask ? { mask: { ...layer.mask, ...config.mask } } : {}),- ...(config.noiseLevel !== undefined ? { noiseLevel: config.noiseLevel } : {}),- ...(config.denoiseLimit !== undefined ? { denoiseLimit: config.denoiseLimit } : {}),+ ...(Object.hasOwn(config, 'noiseLevel') ? { noiseLevel: config.noiseLevel } : {}),+ ...(Object.hasOwn(config, 'denoiseLimit') ? { denoiseLimit: config.denoiseLimit } : {}),};}