Skip to content

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

feat(layers): regenerate regions on raster layers

Josh Corbett4e61390a47cd
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index bf26e365c1..5d03c2c4b6 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -2628,7 +2628,8 @@
"hideModifiers": "Hide modifiers",
"showModifiers": "Show modifiers",
"addDenoiseLimit": "Add denoise limit",
- "addNoise": "Add noise"
+ "addNoise": "Add noise",
+ "addRegenerateRegion": "Add regenerate region"
},
"control": {
"apply": "Apply",
@@ -3065,12 +3066,16 @@
"denoise": "Denoise limit",
"denoiseHelp": "Caps how strongly generation may repaint the masked area.",
"noise": "Noise",
+ "regenerateRegion": "Regenerate region",
+ "removeRegion": "Remove regenerate region",
+ "regionHint": "Marks the area of this layer to regenerate. It rides the layer and joins the inpaint coverage while the layer is enabled.",
"noiseHelp": "Adds noise inside the masked area before generation.",
"removeDenoise": "Remove denoise limit",
"removeNoise": "Remove noise",
"brightnessContrast": "Brightness/Contrast",
"duplicateAdjustment": "Duplicate adjustment",
"renameAdjustment": "Rename adjustment",
+ "renameRegion": "Rename region",
"moveDown": "Move down",
"moveUp": "Move up",
"removeAdjustment": "Remove adjustment",
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
index 3f397b9c3b..aa9ee23e22 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/contracts.ts
@@ -236,10 +236,23 @@ export interface CanvasMaskContract {
offset?: { x: number; y: number };
}
+/**
+ * A raster layer's attached regenerate region: coverage in the PARENT's local
+ * space (it rides the layer's transform), unioned into generation's inpaint
+ * coverage while the layer contributes. Singleton, like a mask's noise
+ * modifier; absent ⇒ never added.
+ */
+export interface CanvasLayerRegionContract {
+ isEnabled: boolean;
+ name?: string;
+ mask: CanvasMaskContract;
+}
+
export interface CanvasRasterLayerContractV2 extends CanvasLayerBaseContract {
type: 'raster';
source: CanvasLayerSourceContract;
adjustments?: CanvasAdjustmentsContract;
+ inpaint?: CanvasLayerRegionContract;
isTransparencyLocked?: boolean;
filter?: { type: string; settings: Record<string, unknown> };
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
index a7d9e9b55e..6f07553c74 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/document-model/documentModel.test.ts
@@ -756,6 +756,34 @@ describe('createDocumentModel', () => {
expect(rawDispatch.canvas.document).toBe(project.canvas.document);
});
+ it('round-trips a layer regenerate region through add, toggle and null-remove', () => {
+ const project = projectWith(flat(), 'r1');
+ const inpaint = {
+ isEnabled: true,
+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' as const } },
+ };
+ const added = roundTrip(project, {
+ before: { inpaint: null, layerType: 'raster' },
+ config: { inpaint, layerType: 'raster' },
+ id: 'r1',
+ type: 'patch-config',
+ });
+ const toggled = roundTrip(added.after, {
+ before: { inpaint, layerType: 'raster' },
+ config: { inpaint: { ...inpaint, isEnabled: false }, layerType: 'raster' },
+ id: 'r1',
+ type: 'patch-config',
+ });
+ const removed = roundTrip(toggled.after, {
+ before: { inpaint: { ...inpaint, isEnabled: false }, layerType: 'raster' },
+ config: { inpaint: null, layerType: 'raster' },
+ id: 'r1',
+ type: 'patch-config',
+ });
+ const layer = getDocumentLeaves(removed.after.canvas.document).find((leaf) => leaf.id === 'r1')!;
+ expect(Object.hasOwn(layer, 'inpaint')).toBe(false);
+ });
+
it('round-trips a mask modifier through add, toggle and null-remove with passing postconditions', () => {
const project = projectWith(flat(), 'i1');
const noise = { isEnabled: true, level: 0.25 };
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
index 7acf9be42d..5e3c277d84 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/mutationContracts.ts
@@ -7,6 +7,7 @@
import type { ProjectEvent } from '@workbench/projectEventContracts';
import type {
+ CanvasLayerRegionContract,
CanvasAdjustmentsContract,
CanvasControlAdapterContract,
CanvasControlLayerContract,
@@ -36,6 +37,8 @@ export type CanvasLayerConfigPatch =
| {
layerType: 'raster';
adjustments?: CanvasAdjustmentsContract;
+ /** `null` removes the region; absent leaves it untouched. */
+ inpaint?: CanvasLayerRegionContract | null;
isTransparencyLocked?: boolean;
filter?: CanvasRasterLayerContractV2['filter'];
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
index 12b22e3199..f6ebc4c90b 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.test.ts
@@ -104,6 +104,21 @@ describe('loadCanvasState', () => {
});
});
+ it('round-trips a layer regenerate region and drops a malformed one without failing the layer', () => {
+ const inpaint = {
+ isEnabled: true,
+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' }, offset: { x: 4, y: -2 } },
+ name: 'Face',
+ };
+ const loaded = load(withNodes([{ ...createEmptyPaintLayer('Region', 'region'), inpaint }]));
+ const layer = loaded.document.stacks.raster[0];
+ expect(layer?.type === 'raster' ? layer.inpaint : null).toEqual(inpaint);
+
+ const malformed = load(withNodes([{ ...createEmptyPaintLayer('Bad', 'bad'), inpaint: { isEnabled: 'yes' } }]));
+ const badLayer = malformed.document.stacks.raster[0];
+ expect(badLayer?.type === 'raster' ? badLayer.inpaint : null).toBeUndefined();
+ });
+
it('round-trips group adjustments in the raster stack, strips them from overlay groups, and drops a malformed group stack', () => {
const stack = [{ brightness: 0.1, contrast: 0, id: 'ga1', isEnabled: true, type: 'brightness-contrast' }];
const rasterGroup = {
diff --git a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
index 8c363422f6..df2bd35766 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasMigration.ts
@@ -207,6 +207,7 @@ const zCanvasLayer = z.discriminatedUnion('type', [
zLayerBase.extend({
// A pre-stack adjustments OBJECT is dropped rather than failing the document.
adjustments: zAdjustments.optional().catch(undefined),
+ inpaint: z.object({ isEnabled: z.boolean(), mask: zMask, name: z.string().optional() }).optional().catch(undefined),
filter: zFilter.optional(),
isTransparencyLocked: z.boolean().optional(),
source: zLayerSource,
diff --git a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
index c3f2ea61e1..6760d4dfbd 100644
--- a/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvasProjectMutations.ts
@@ -537,12 +537,17 @@ const patchLayerConfig = (layer: CanvasNodeContract, config: CanvasLayerConfigPa
};
}
if (layer.type === 'raster' && config.layerType === 'raster') {
- return {
+ const next = {
...layer,
...(Object.hasOwn(config, 'adjustments') ? { adjustments: config.adjustments } : {}),
+ ...(Object.hasOwn(config, 'inpaint') && config.inpaint !== null ? { inpaint: config.inpaint } : {}),
...(Object.hasOwn(config, 'isTransparencyLocked') ? { isTransparencyLocked: config.isTransparencyLocked } : {}),
...(Object.hasOwn(config, 'filter') ? { filter: config.filter } : {}),
};
+ if (Object.hasOwn(config, 'inpaint') && config.inpaint === null) {
+ delete next.inpaint;
+ }
+ return next;
}
if (layer.type === 'control' && config.layerType === 'control') {
return {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildMenu.tsx
index cb566f7edb..722a2c1642 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildMenu.tsx
@@ -17,7 +17,13 @@ import { useTranslation } from 'react-i18next';
import type { LayerRowCommands, LayerSurfaceAnchor } from './layerRowCommands';
-import { isOrderedChildKind, layerChildRemoveLabelKey, type ProjectedChildRow } from './layerChildRows';
+import { isRenameableChildKind } from './LayerChildRow';
+import {
+ isOrderedChildKind,
+ layerChildRemoveLabelKey,
+ layerChildRenameLabelKey,
+ type ProjectedChildRow,
+} from './layerChildRows';
const ChildMenuItem = MenuActionItem;
@@ -73,15 +79,17 @@ export const LayerChildMenu = ({
value="toggle"
onSelect={handleToggle}
/>
+ {isRenameableChildKind(child.kind) ? (
+ <ChildMenuItem
+ disabled={editingLocked}
+ icon={PencilIcon}
+ label={t(layerChildRenameLabelKey(child.kind))}
+ value="rename"
+ onSelect={handleRename}
+ />
+ ) : null}
{ordered ? (
<>
- <ChildMenuItem
- disabled={editingLocked}
- icon={PencilIcon}
- label={t('widgets.layers.modifiers.renameAdjustment')}
- value="rename"
- onSelect={handleRename}
- />
<ChildMenuItem
disabled={editingLocked}
icon={CopyIcon}
@@ -90,14 +98,14 @@ export const LayerChildMenu = ({
onSelect={handleDuplicate}
/>
<ChildMenuItem
- disabled={editingLocked || child.posInSet <= 1}
+ disabled={editingLocked || (child.orderedPosInSet ?? 1) <= 1}
icon={ArrowUpIcon}
label={t('widgets.layers.modifiers.moveUp')}
value="move-up"
onSelect={handleMoveUp}
/>
<ChildMenuItem
- disabled={editingLocked || child.posInSet >= child.setSize}
+ disabled={editingLocked || (child.orderedPosInSet ?? 0) >= (child.orderedSetSize ?? 0)}
icon={ArrowDownIcon}
label={t('widgets.layers.modifiers.moveDown')}
value="move-down"
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
index 5ccc15af14..4a21155c40 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerChildRow.tsx
@@ -4,6 +4,7 @@ import { Box, HStack, Icon, Input, Text } from '@chakra-ui/react';
import { useDraggable, useDroppable } from '@dnd-kit/core';
import {
ApertureIcon,
+ WandSparklesIcon,
ContrastIcon,
DropletIcon,
GaugeIcon,
@@ -39,6 +40,7 @@ const CHILD_ROW_GLYPHS: Record<LayerChildRowKind, LucideIcon> = {
'adjustment-hue': RainbowIcon,
'adjustment-invert': ContrastIcon,
'adjustment-levels': SlidersVerticalIcon,
+ 'layer-region': WandSparklesIcon,
'mask-denoise': GaugeIcon,
'mask-noise': WavesIcon,
'reference-image': ImageIcon,
@@ -49,7 +51,8 @@ export const isDraggableChildKind = (kind: LayerChildRowKind): boolean =>
kind === 'reference-image' || isOrderedChildKind(kind);
/** Kinds whose rows carry a user-given name: adjustment entries. */
-export const isRenameableChildKind = isOrderedChildKind;
+export const isRenameableChildKind = (kind: LayerChildRowKind): boolean =>
+ kind === 'layer-region' || isOrderedChildKind(kind);
/** The row's display name: its custom name, a reference image's number, or its kind's name. */
export const childRowName = (child: ProjectedChildRow, t: (key: string) => string): string =>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
index 4c52d8453b..ac3fe7c234 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerContextMenu.tsx
@@ -88,6 +88,7 @@ import { copyBlobToClipboard, saveLayerToAssets } from './layerExportActions';
import { canGroupSelection, groupLayers } from './layerGroupCommands';
import { resolveMenuTargetForRender } from './layerMenuState';
import {
+ DEFAULT_INPAINT_MASK_FILL,
convertRasterToControl,
convertRasterToInpaintMask,
convertRasterToRegionalGuidance,
@@ -736,6 +737,23 @@ const LayerMenu = ({
[commitPrepared, layer, t]
);
+ const handleAddLayerRegion = useCallback(() => {
+ if (layer.type !== 'raster' || layer.inpaint) {
+ return;
+ }
+ commitPrepared(t('widgets.layers.actions.addRegenerateRegion'), (model) =>
+ model.prepare({
+ before: { inpaint: null, layerType: 'raster' },
+ config: {
+ inpaint: { isEnabled: true, mask: { bitmap: null, fill: { ...DEFAULT_INPAINT_MASK_FILL } } },
+ layerType: 'raster',
+ },
+ id: layer.id,
+ type: 'patch-config',
+ })
+ );
+ }, [commitPrepared, layer, t]);
+
const handleAddAdjustment = useCallback(
(type: CanvasAdjustmentEntry['type']) => {
if (layer.type !== 'raster') {
@@ -775,6 +793,7 @@ const LayerMenu = ({
const effects = useMemo<LayerContextActionEffects>(
() => ({
addAdjustment: handleAddAdjustment,
+ addLayerRegion: handleAddLayerRegion,
addMaskModifier: handleAddMaskModifier,
addReferenceImage: handleAddReferenceImage,
booleanMerge: handleBooleanRaster,
@@ -817,6 +836,7 @@ const LayerMenu = ({
convert,
getActionLabel,
handleAddAdjustment,
+ handleAddLayerRegion,
handleAddMaskModifier,
handleAddReferenceImage,
handleBooleanRaster,
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx
new file mode 100644
index 0000000000..2f8b4884e7
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayerRegionSettings.tsx
@@ -0,0 +1,145 @@
+import type { SelectValueChangeDetails } from '@chakra-ui/react';
+import type { CanvasMaskFillContract, CanvasRasterLayerContractV2 } from '@workbench/canvas-engine/api';
+import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps';
+
+import { createListCollection, HStack, Stack, Text } from '@chakra-ui/react';
+import { ColorPicker, Field, Select } from '@platform/ui';
+import { type ColorSamplerEngine, useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
+import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
+import { useCallback, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { applyStructuralPreview } from './layerOps';
+
+const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
+ 'solid',
+ 'grid',
+ 'crosshatch',
+ 'diagonal',
+ 'horizontal',
+ 'vertical',
+];
+
+const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const;
+
+interface LayerRegionSettingsProps {
+ engine: (CanvasStructuralEngine & CanvasPreparedEngine & ColorSamplerEngine) | null;
+ layer: CanvasRasterLayerContractV2;
+}
+
+/** The regenerate region's dedicated Properties editor: its overlay fill color and style. */
+export const LayerRegionSettings = ({ engine, layer }: LayerRegionSettingsProps) => {
+ const { t } = useTranslation();
+ const commitPrepared = usePreparedCommit(engine);
+ const sampleColor = useColorSampler(engine);
+ const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);
+ const region = layer.inpaint;
+
+ const styleCollection = useMemo(
+ () =>
+ createListCollection({
+ items: MASK_FILL_STYLES.map((style) => ({
+ label: t(`widgets.layers.maskFill.styles.${style}`),
+ value: style,
+ })),
+ }),
+ [t]
+ );
+
+ const commitFill = useCallback(
+ (next: CanvasMaskFillContract, before: CanvasMaskFillContract) => {
+ if (!region) {
+ return;
+ }
+ commitPrepared(t('widgets.layers.maskFill.fill'), (model) =>
+ model.prepare({
+ before: { inpaint: { ...region, mask: { ...region.mask, fill: before } }, layerType: 'raster' },
+ config: { inpaint: { ...region, mask: { ...region.mask, fill: next } }, layerType: 'raster' },
+ id: layer.id,
+ type: 'patch-config',
+ })
+ );
+ },
+ [commitPrepared, layer.id, region, t]
+ );
+
+ const handleColorChange = useCallback(
+ (hex: string) => {
+ if (!region) {
+ return;
+ }
+ if (
+ !applyStructuralPreview(engine, {
+ config: {
+ inpaint: { ...region, mask: { ...region.mask, fill: { ...region.mask.fill, color: hex } } },
+ layerType: 'raster',
+ },
+ id: layer.id,
+ type: 'updateCanvasLayerConfig',
+ })
+ ) {
+ return;
+ }
+ fillBeforeRef.current ??= region.mask.fill;
+ },
+ [engine, layer.id, region]
+ );
+
+ const handleColorChangeEnd = useCallback(
+ (hex: string) => {
+ if (!region) {
+ return;
+ }
+ const before = fillBeforeRef.current ?? region.mask.fill;
+ fillBeforeRef.current = null;
+ commitFill({ ...before, color: hex }, before);
+ },
+ [commitFill, region]
+ );
+
+ const handleStyleChange = useCallback(
+ ({ value }: SelectValueChangeDetails) => {
+ const style = value[0] as CanvasMaskFillContract['style'] | undefined;
+ if (region && style && style !== region.mask.fill.style) {
+ commitFill({ ...region.mask.fill, style }, region.mask.fill);
+ }
+ },
+ [commitFill, region]
+ );
+
+ const styleValue = useMemo(() => [region?.mask.fill.style ?? 'solid'], [region?.mask.fill.style]);
+ if (!region) {
+ return null;
+ }
+ const fill = region.mask.fill;
+
+ return (
+ <Stack gap="2">
+ <HStack gap="2">
+ <Field flexShrink="0" label={t('widgets.layers.maskFill.color')}>
+ <ColorPicker
+ aria-label={t('widgets.layers.maskFill.color')}
+ value={fill.color}
+ onSampleColor={sampleColor}
+ onValueChange={handleColorChange}
+ onValueChangeEnd={handleColorChangeEnd}
+ />
+ </Field>
+ <Field flex="1" label={t('widgets.layers.maskFill.style')} minW="0">
+ <Select
+ aria-label={t('widgets.layers.maskFill.style')}
+ collection={styleCollection}
+ positioning={SELECT_POSITIONING}
+ size="xs"
+ value={styleValue}
+ valueText={t(`widgets.layers.maskFill.styles.${fill.style}`)}
+ onValueChange={handleStyleChange}
+ />
+ </Field>
+ </HStack>
+ <Text color="fg.muted" fontSize="xs">
+ {t('widgets.layers.modifiers.regionHint')}
+ </Text>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
index b105d6cbae..6e0ddfb775 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersTree.tsx
@@ -32,6 +32,7 @@ import { ChildDragGhost, isRenameableChildKind, LayerChildRow } from './LayerChi
import {
layerChildDropCommand,
layerChildRemoveLabelKey,
+ layerChildRenameLabelKey,
layerChildRowCommand,
layerChildRowKey,
projectLayerChildRows,
@@ -527,7 +528,7 @@ export const LayersTree = ({
renameChild: (child, name) => {
const command = layerChildRowCommand(latest.current.document, child, { name, type: 'rename' });
if (command) {
- runStructural(t('widgets.layers.modifiers.renameAdjustment'), command);
+ runStructural(t(layerChildRenameLabelKey(child.kind)), command);
}
},
select: (id, modifiers: LayerSelectionModifiers) => {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts
index 7bfd38502c..df8b8a4363 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.test.ts
@@ -440,3 +440,97 @@ describe('layerChildDropCommand id collisions', () => {
).toBeNull();
});
});
+
+describe('layer regenerate region child row', () => {
+ const region = (overrides = {}) => ({
+ isEnabled: true,
+ mask: { bitmap: null, fill: { color: '#e07575', style: 'diagonal' as const } },
+ ...overrides,
+ });
+ const rasterWithRegion = (overrides = {}) => layerContract('r1', 'raster', { inpaint: region(overrides) });
+ const row = (document: ReturnType<typeof documentFrom>) =>
+ buildLayerStackRows(document.stacks, new Set()).raster.rows.find((r) => r.id === 'r1')!;
+
+ it('projects the region above the adjustment rows with a combined set', () => {
+ const document = documentFrom([
+ layerContract('r1', 'raster', {
+ adjustments: [{ id: 'a1', isEnabled: true, type: 'invert' }],
+ inpaint: region({ name: 'Face' }),
+ }),
+ ]);
+ const rows = projectLayerChildRows(row(document).vm);
+ expect(rows.map((r) => [r.kind, r.itemId, r.posInSet, r.setSize, r.customName])).toEqual([
+ ['layer-region', 'inpaint', 1, 2, 'Face'],
+ ['adjustment-invert', 'a1', 2, 2, null],
+ ]);
+ expect(rows[0]?.orderedPosInSet).toBeUndefined();
+ expect(rows[1]).toMatchObject({ orderedPosInSet: 1, orderedSetSize: 1 });
+ });
+
+ it('refuses an adjustment drop landing above the region row', () => {
+ const document = documentFrom([
+ layerContract('r1', 'raster', {
+ adjustments: [
+ { id: 'a1', isEnabled: true, type: 'invert' },
+ { id: 'a2', isEnabled: true, type: 'invert' },
+ ],
+ inpaint: region(),
+ }),
+ ]);
+ const child = { itemId: 'a2', kind: 'adjustment-invert' as const, layerId: 'r1' };
+ expect(layerChildDropCommand(document, child, { beforeItemId: 'inpaint', layerId: 'r1' })).toBeNull();
+ const landed = layerChildDropCommand(document, child, { beforeItemId: 'a1', layerId: 'r1' });
+ expect(landed).toMatchObject({ config: { adjustments: [{ id: 'a2' }, { id: 'a1' }] } });
+ });
+
+ it('routes a persisted adjustment whose id is "inpaint" to the adjustments when no region exists', () => {
+ const document = documentFrom([
+ layerContract('r1', 'raster', { adjustments: [{ id: 'inpaint', isEnabled: true, type: 'invert' }] }),
+ ]);
+ expect(getLayerChildItem(document, 'r1', 'inpaint')).toEqual({ isEnabled: true, kind: 'adjustment-invert' });
+ const toggled = layerChildRowCommand(
+ document,
+ { itemId: 'inpaint', layerId: 'r1' },
+ {
+ isEnabled: false,
+ type: 'set-enabled',
+ }
+ );
+ expect(toggled).toMatchObject({ config: { adjustments: [{ id: 'inpaint', isEnabled: false }] } });
+ });
+
+ it('hides a foreign "inpaint"-id adjustment row while a region exists', () => {
+ const document = documentFrom([
+ layerContract('r1', 'raster', {
+ adjustments: [
+ { id: 'inpaint', isEnabled: true, type: 'invert' },
+ { id: 'a1', isEnabled: true, type: 'invert' },
+ ],
+ inpaint: region(),
+ }),
+ ]);
+ const rows = projectLayerChildRows(row(document).vm);
+ expect(rows.map((r) => [r.kind, r.itemId, r.posInSet, r.setSize])).toEqual([
+ ['layer-region', 'inpaint', 1, 2],
+ ['adjustment-invert', 'a1', 2, 2],
+ ]);
+ });
+
+ it('resolves, toggles, renames, and null-removes the singleton; move and duplicate refuse', () => {
+ const document = documentFrom([rasterWithRegion()]);
+ expect(getLayerChildItem(document, 'r1', 'inpaint')).toEqual({ isEnabled: true, kind: 'layer-region' });
+
+ const target = { itemId: 'inpaint', layerId: 'r1' };
+ const toggled = layerChildRowCommand(document, target, { isEnabled: false, type: 'set-enabled' });
+ expect(toggled).toMatchObject({ config: { inpaint: { isEnabled: false }, layerType: 'raster' }, id: 'r1' });
+
+ const renamed = layerChildRowCommand(document, target, { name: 'Sky', type: 'rename' });
+ expect(renamed).toMatchObject({ config: { inpaint: { name: 'Sky' } } });
+
+ const removed = layerChildRowCommand(document, target, { type: 'remove' });
+ expect(removed).toMatchObject({ config: { inpaint: null, layerType: 'raster' } });
+
+ expect(layerChildRowCommand(document, target, { direction: 1, type: 'move' })).toBeNull();
+ expect(layerChildRowCommand(document, target, { newId: 'x', type: 'duplicate' })).toBeNull();
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
index a63eb66ee6..144c0033be 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerChildRows.ts
@@ -24,6 +24,7 @@ export type LayerChildRowKind =
| 'reference-image'
| 'mask-noise'
| 'mask-denoise'
+ | 'layer-region'
| 'adjustment-brightness-contrast'
| 'adjustment-exposure'
| 'adjustment-levels'
@@ -56,6 +57,7 @@ const CHILD_ROW_NAME_KEYS: Record<Exclude<LayerChildRowKind, 'reference-image'>,
'adjustment-hue': 'widgets.layers.adjustments.hue',
'adjustment-invert': 'widgets.layers.adjustments.invert',
'adjustment-levels': 'widgets.layers.adjustments.levels',
+ 'layer-region': 'widgets.layers.modifiers.regenerateRegion',
'mask-denoise': 'widgets.layers.modifiers.denoise',
'mask-noise': 'widgets.layers.modifiers.noise',
};
@@ -92,6 +94,8 @@ export const isOrderedChildKind = (kind: LayerChildRowKind): boolean => kind.sta
/** The synthetic item ids of a mask's singleton modifiers. */
export const MASK_NOISE_ITEM_ID = 'noise';
export const MASK_DENOISE_ITEM_ID = 'denoise';
+/** The synthetic item id of a raster layer's singleton regenerate region. */
+export const LAYER_REGION_ITEM_ID = 'inpaint';
export interface ProjectedChildRow {
/** Tree key, also the row's DOM id: `child:{layerId}:{itemId}`. */
@@ -104,6 +108,9 @@ export interface ProjectedChildRow {
readonly depth: number;
readonly posInSet: number;
readonly setSize: number;
+ /** Position among the layer's ordered (reorderable) rows only; absent on singleton rows. */
+ readonly orderedPosInSet?: number;
+ readonly orderedSetSize?: number;
readonly isEnabled: boolean;
/** The owning layer and its ancestors are enabled; a gated dot when not. */
readonly parentContributing: boolean;
@@ -220,20 +227,47 @@ export const projectLayerChildRows = (vm: SemanticNode): readonly ProjectedChild
}));
} else if (node.type === 'inpaint_mask' && (node.noise || node.denoise)) {
rows = maskModifierRows(vm, node);
- } else if ((node.type === 'raster' || node.type === 'group') && node.adjustments && node.adjustments.length > 0) {
- const setSize = node.adjustments.length;
- rows = node.adjustments.map((adjustment, index): ProjectedChildRow => ({
- ...baseRow(vm),
- customName: adjustment.name ?? null,
- detail: adjustmentDetail(adjustment),
- image: null,
- isEnabled: adjustment.isEnabled,
- itemId: adjustment.id,
- key: layerChildRowKey(node.id, adjustment.id),
- kind: ADJUSTMENT_KIND_OF[adjustment.type],
- posInSet: index + 1,
- setSize,
- }));
+ } else if (
+ (node.type === 'raster' || node.type === 'group') &&
+ ((node.adjustments && node.adjustments.length > 0) || (node.type === 'raster' && node.inpaint))
+ ) {
+ const region = node.type === 'raster' ? node.inpaint : undefined;
+ // A foreign adjustment claiming the region's reserved item id would alias its row key.
+ const adjustments = (node.adjustments ?? []).filter((entry) => !region || entry.id !== LAYER_REGION_ITEM_ID);
+ const setSize = adjustments.length + (region ? 1 : 0);
+ const regionRows: ProjectedChildRow[] = region
+ ? [
+ {
+ ...baseRow(vm),
+ customName: region.name ?? null,
+ detail: null,
+ image: null,
+ isEnabled: region.isEnabled,
+ itemId: LAYER_REGION_ITEM_ID,
+ key: layerChildRowKey(node.id, LAYER_REGION_ITEM_ID),
+ kind: 'layer-region',
+ posInSet: 1,
+ setSize,
+ },
+ ]
+ : [];
+ rows = [
+ ...regionRows,
+ ...adjustments.map((adjustment, index): ProjectedChildRow => ({
+ ...baseRow(vm),
+ customName: adjustment.name ?? null,
+ detail: adjustmentDetail(adjustment),
+ image: null,
+ isEnabled: adjustment.isEnabled,
+ itemId: adjustment.id,
+ key: layerChildRowKey(node.id, adjustment.id),
+ kind: ADJUSTMENT_KIND_OF[adjustment.type],
+ orderedPosInSet: index + 1,
+ orderedSetSize: adjustments.length,
+ posInSet: regionRows.length + index + 1,
+ setSize,
+ })),
+ ];
} else {
return EMPTY_CHILD_ROWS;
}
@@ -262,12 +296,19 @@ export const getLayerChildItem = (
}
const owner = layer ?? adjustmentOwnerNode(document, layerId);
if (owner && (owner.type === 'raster' || owner.type === 'group')) {
+ if (owner.type === 'raster' && itemId === LAYER_REGION_ITEM_ID && owner.inpaint) {
+ return { isEnabled: owner.inpaint.isEnabled, kind: 'layer-region' };
+ }
const entry = owner.adjustments?.find((candidate) => candidate.id === itemId);
return entry ? { isEnabled: entry.isEnabled, kind: ADJUSTMENT_KIND_OF[entry.type] } : null;
}
return null;
};
+/** The i18n key naming a child row's rename, for menus and history entries alike. */
+export const layerChildRenameLabelKey = (kind: LayerChildRowKind): string =>
+ kind === 'layer-region' ? 'widgets.layers.modifiers.renameRegion' : 'widgets.layers.modifiers.renameAdjustment';
+
/** The i18n key naming a child row's removal, for menus and history entries alike. */
export const layerChildRemoveLabelKey = (kind: LayerChildRowKind): string => {
switch (kind) {
@@ -277,6 +318,8 @@ export const layerChildRemoveLabelKey = (kind: LayerChildRowKind): string => {
return 'widgets.layers.modifiers.removeNoise';
case 'mask-denoise':
return 'widgets.layers.modifiers.removeDenoise';
+ case 'layer-region':
+ return 'widgets.layers.modifiers.removeRegion';
case 'adjustment-brightness-contrast':
case 'adjustment-exposure':
case 'adjustment-levels':
@@ -327,6 +370,14 @@ export const layerChildDropCommand = (
if (!entry) {
return null;
}
+ // The region row always renders above the adjustments; nothing lands before it.
+ if (
+ target.beforeItemId === LAYER_REGION_ITEM_ID &&
+ sourceOwner.type === 'raster' &&
+ sourceOwner.inpaint !== undefined
+ ) {
+ return null;
+ }
const next = insertAt(
before.filter((candidate) => candidate.id !== child.itemId),
entry,
@@ -448,6 +499,33 @@ export const layerChildRowCommand = (
};
}
const owner = layer?.type === 'raster' ? layer : layer ? null : adjustmentOwnerNode(document, target.layerId);
+ if (owner?.type === 'raster' && target.itemId === LAYER_REGION_ITEM_ID && owner.inpaint) {
+ const current = owner.inpaint;
+ if (action.type === 'move' || action.type === 'duplicate') {
+ return null;
+ }
+ let next: typeof current | null;
+ if (action.type === 'remove') {
+ next = null;
+ } else if (action.type === 'set-enabled') {
+ if (current.isEnabled === action.isEnabled) {
+ return null;
+ }
+ next = { ...current, isEnabled: action.isEnabled };
+ } else {
+ if ((current.name ?? null) === action.name) {
+ return null;
+ }
+ const { name: _cleared, ...rest } = current;
+ next = action.name === null ? rest : { ...current, name: action.name };
+ }
+ return {
+ before: { inpaint: current, layerType: 'raster' },
+ config: { inpaint: next, layerType: 'raster' },
+ id: target.layerId,
+ type: 'patch-config',
+ };
+ }
if (owner) {
const before = owner.adjustments ?? [];
const index = before.findIndex((entry) => entry.id === target.itemId);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
index 976ad1746f..57061df84f 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.test.ts
@@ -90,6 +90,7 @@ const makeState = (
const makeEffects = (): LayerContextActionEffects => ({
addAdjustment: vi.fn(),
+ addLayerRegion: vi.fn(),
addMaskModifier: vi.fn(),
addReferenceImage: vi.fn(),
booleanMerge: vi.fn(() => Promise.resolve()),
@@ -462,6 +463,7 @@ describe('getLayerContextActions', () => {
'add-hsl',
'add-hue',
'add-invert',
+ 'add-regenerate-region',
'save-to-assets',
'copy-to-clipboard',
'crop-to-bbox',
@@ -547,6 +549,7 @@ describe('getLayerContextActions', () => {
'add-hsl',
'add-hue',
'add-invert',
+ 'add-regenerate-region',
'filter',
'select-object',
'run-workflow',
@@ -626,6 +629,7 @@ describe('getLayerContextActions', () => {
'add-hsl',
'add-hue',
'add-invert',
+ 'add-regenerate-region',
'save-to-assets',
'copy-to-clipboard',
'crop-to-bbox',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
index fa8ed008cb..5e673446cf 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextActions.ts
@@ -17,6 +17,7 @@ import {
} from '@workbench/canvas-engine/api';
import {
ApertureIcon,
+ WandSparklesIcon,
ArrowDownIcon,
ArrowDownToLineIcon,
ArrowUpIcon,
@@ -54,6 +55,7 @@ import { canConvertRasterControl, canMergeLayerDown } from './layerOps';
export type LayerContextActionId =
| 'add-reference-image'
| 'add-noise'
+ | 'add-regenerate-region'
| 'add-denoise-limit'
| 'add-brightness-contrast'
| 'add-exposure'
@@ -150,6 +152,7 @@ export interface LayerContextActionEffects {
addReferenceImage(): void;
addMaskModifier(field: 'noise' | 'denoise'): void;
addAdjustment(type: CanvasAdjustmentEntry['type']): void;
+ addLayerRegion(): void;
mergeDown(): void;
toggleVisibility(): void;
toggleHidden(): void;
@@ -545,6 +548,18 @@ export const LAYER_CONTEXT_ACTION_DEFINITIONS: readonly LayerContextActionDefini
section: 'primary',
supportedLayerTypes: REGIONAL_ONLY,
},
+ {
+ defaultLabel: 'Add regenerate region',
+ handler: ({ effects }) => effects.addLayerRegion(),
+ icon: WandSparklesIcon,
+ id: 'add-regenerate-region',
+ isEnabled: isLayerMutable,
+ isVisible: (context) => context.layer.type === 'raster' && context.layer.inpaint === undefined,
+ labelKey: 'widgets.layers.actions.addRegenerateRegion',
+ order: 32,
+ section: 'primary',
+ supportedLayerTypes: RASTER_ONLY,
+ },
{
defaultLabel: 'Add noise',
handler: ({ effects }) => effects.addMaskModifier('noise'),
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
index d91a4eec7c..8a0cc7f316 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/layerContextMenuLayout.test.ts
@@ -88,6 +88,7 @@ describe('getLayerContextMenuLayout', () => {
'rename',
'fit-to-bbox',
'add-adjustment(add-brightness-contrast,add-exposure,add-levels,add-curves,add-hsl,add-hue,add-invert)',
+ 'add-regenerate-region',
'filter',
'select-object',
'run-workflow',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
index 3884f6c133..676f1ed1d5 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
@@ -9,6 +9,7 @@ import { AdjustmentSettings } from '@workbench/widgets/layers/AdjustmentSettings
import { ControlLayerSettings } from '@workbench/widgets/layers/ControlLayerSettings';
import { InpaintMaskSettings } from '@workbench/widgets/layers/InpaintMaskSettings';
import {
+ LAYER_REGION_ITEM_ID,
adjustmentChildKind,
childRowNameKey,
MASK_DENOISE_ITEM_ID,
@@ -16,6 +17,7 @@ import {
type LayerChildRowKind,
} from '@workbench/widgets/layers/layerChildRows';
import { useLayerChildSelection } from '@workbench/widgets/layers/layerChildSelection';
+import { LayerRegionSettings } from '@workbench/widgets/layers/LayerRegionSettings';
import { MaskModifierSettings } from '@workbench/widgets/layers/MaskModifierSettings';
import { RasterLayerFilterSection } from '@workbench/widgets/layers/RasterLayerFilterSection';
import { ReferenceImageSettings } from '@workbench/widgets/layers/ReferenceImageSettings';
@@ -105,6 +107,13 @@ const resolveChildEditor = (
return { itemId: selection.itemId, kind: 'mask-denoise', subtitle: t('widgets.layers.modifiers.denoise') };
}
}
+ if (layer.type === 'raster' && selection.itemId === LAYER_REGION_ITEM_ID && layer.inpaint) {
+ return {
+ itemId: selection.itemId,
+ kind: 'layer-region',
+ subtitle: layer.inpaint.name ?? t(childRowNameKey('layer-region')),
+ };
+ }
if (layer.type === 'raster' || layer.type === 'group') {
const entry = layer.adjustments?.find((candidate) => candidate.id === selection.itemId);
if (entry) {
@@ -130,6 +139,9 @@ const ChildEditor = ({
if ((child.kind === 'mask-noise' || child.kind === 'mask-denoise') && node.type === 'inpaint_mask') {
return <MaskModifierSettings engine={engine} kind={child.kind} layer={node} />;
}
+ if (child.kind === 'layer-region' && node.type === 'raster') {
+ return <LayerRegionSettings engine={engine} layer={node} />;
+ }
if (child.kind.startsWith('adjustment-') && (node.type === 'raster' || node.type === 'group')) {
return <AdjustmentSettings engine={engine} entryId={child.itemId} layer={node} />;
}