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.

fix(canvas): keep the mask blur inside fitted frames on coarse grids

Josh Corbettbc5e755aa670
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
index abeefa809c..13bd95ffba 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/generate-panel.mdx
@@ -18,9 +18,9 @@ The **Size** section sets the width and height of the image.
* **Aspect ratio** offers common shapes: 21:9, 16:9, 3:2, 4:3, 1:1, 3:4, 2:3, 9:16 and 9:21, or **Free**. Choosing a ratio locks it, so changing the width changes the height to match. The lock button between the two fields locks or unlocks the current ratio.
* **Swap width and height** turns a landscape image into a portrait one and back.
* Each model has an optimal image area, typically about one megapixel for newer models and less for SD 1.5. The line under the fields shows the image's size in megapixels, marks the recommended size, and estimates the run time from your recent runs.
-* **Reset size**, the button beside **Swap width and height**, opens a menu. Each item shows the size it sets, and the item matching the current size is checked and unavailable:
+* **Reset size**, the button beside **Swap width and height**, opens a menu. Each item shows the size it sets, and the item matching the current size is checked; choosing it again changes nothing:
* **Square at native size** — a 1:1 square at the model's native size, such as 1024×1024 for SDXL and FLUX or 512×512 for SD 1.5, with the ratio locked.
- * **Optimal size for** the current ratio — the model's optimal area at the current aspect ratio.
+ * **Optimal size for** the current ratio — the model's optimal area at the current aspect ratio. It is absent at 1:1, where it would be the native square.
* **Model defaults** — the size set in the model's default settings. It appears only when the model sets one.
Right-clicking the width and height and choosing **Reset to model default** also resets the size this way. On the Canvas, these resets keep the generation frame centered on the same point; typing or dragging a new width or height resizes the frame from its top-left corner. Size resets are not canvas edits, so they do not appear in the canvas's undo history.
diff --git a/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx b/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx
index 7f9745a47c..8562ba2e3c 100644
--- a/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx
+++ b/docs/src/content/docs/Users Guide/04.Image Generation/parameters.mdx
@@ -54,7 +54,7 @@ The seed sets the starting noise, so the same model, prompt, seed and settings r
## Size
-Each model has an optimal image area, around one megapixel for most current models and less for SD 1.5. Results are best near that size; much larger images can repeat subjects or distort anatomy. Use **Reset size → Optimal size** in the Size section, and upscale afterwards for larger images.
+Each model has an optimal image area, around one megapixel for most current models and less for SD 1.5. Results are best near that size; much larger images can repeat subjects or distort anatomy. Use **Reset size → Optimal size for** *ratio* (for example **Optimal size for 3:2**) in the Size section, and upscale afterwards for larger images. At 1:1 that item is absent; use **Square at native size**, the model's optimal square.
## Denoising strength
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx
index 868d399ef7..3415b063cf 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.browser.test.tsx
@@ -311,7 +311,7 @@ describe('GenerateDimensionFields aspect ratio', () => {
describe('GenerateDimensionFields Reset size', () => {
const resetSizeButton = () => host?.querySelector<HTMLButtonElement>('button[aria-label="Reset size"]') ?? null;
- const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];
+ const menuItems = () => [...document.querySelectorAll<HTMLElement>('[role="menuitemradio"]')];
const menuItem = (label: string) => menuItems().find((item) => item.textContent?.startsWith(label)) ?? null;
const openMenu = () => settle(() => resetSizeButton()?.click());
// Zag selects on a real pointer release, which a synthetic click() does not send.
@@ -398,22 +398,44 @@ describe('GenerateDimensionFields Reset size', () => {
}
});
- it('marks the applied choices current and disabled, and drops an optimal size that is the native square', async () => {
+ it('checks the applied choice, keeps it reachable, and drops an optimal size that is the native square', async () => {
await render({ aspectRatioId: '1:1', aspectRatioIsLocked: true, aspectRatioValue: 1, height: 512, width: 512 });
await openMenu();
const square = menuItem('Square at native size');
- expect(square?.getAttribute('aria-current')).toBe('true');
- expect(square?.getAttribute('aria-disabled')).toBe('true');
+ expect(square?.getAttribute('aria-checked')).toBe('true');
+ expect(square?.hasAttribute('aria-disabled')).toBe(false);
expect(menuItems()).toHaveLength(1);
await unmountAndReset();
// The same size under a free ratio is not yet the locked square.
await render({ aspectRatioId: 'Free', aspectRatioIsLocked: false, aspectRatioValue: 1, height: 512, width: 512 });
await openMenu();
- expect(menuItem('Square at native size')?.hasAttribute('aria-current')).toBe(false);
- expect(menuItem('Square at native size')?.hasAttribute('aria-disabled')).toBe(false);
+ expect(menuItem('Square at native size')?.getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('lands the keyboard on the applied choice, and choosing it again changes nothing', async () => {
+ const { onResetSize } = await render({
+ aspectRatioId: '1:1',
+ aspectRatioIsLocked: true,
+ aspectRatioValue: 1,
+ height: 512,
+ width: 512,
+ });
+
+ resetSizeButton()?.focus();
+ await userEvent.keyboard('{Enter}');
+ await vi.waitFor(() => expect(document.activeElement?.getAttribute('role')).toBe('menu'));
+ await userEvent.keyboard('{ArrowDown}');
+ const square = menuItem('Square at native size');
+ await vi.waitFor(() => expect(square?.hasAttribute('data-highlighted')).toBe(true));
+ expect(document.activeElement?.getAttribute('aria-activedescendant')).toBe(square?.id);
+
+ await userEvent.keyboard('{Enter}');
+
+ await vi.waitFor(() => expect(menuItems()).toHaveLength(0));
+ expect(onResetSize).not.toHaveBeenCalled();
});
it('offers model defaults only for a model that sets its own size', async () => {
diff --git a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx
index fb172e331a..c6bed433a7 100644
--- a/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx
+++ b/invokeai/frontend/webv2/src/features/generation/ui/GenerateDimensionFields.tsx
@@ -101,16 +101,27 @@ interface ResetSizeChoice {
value: string;
label: string;
size: Dimensions;
- /** Already applied: shown checked and disabled. */
+ /** Already applied: shown checked, and choosing it again changes nothing. */
isCurrent: boolean;
onSelect: () => void;
}
-/** The ratio row's Reset size menu; each choice shows the size it sets. */
+/**
+ * The ratio row's Reset size menu; each choice shows the size it sets. The choices are radio items, so the applied one
+ * stays reachable and reads as checked, and an open menu always has an item to land on. Two choices can set the
+ * same size; the first of them is the checked one.
+ */
const ResetSizeMenu = ({ choices }: { choices: readonly ResetSizeChoice[] }) => {
const { t } = useTranslation();
const ids = useTooltipTriggerIds();
const label = t('widgets.generate.resetSize');
+ const current = choices.find((choice) => choice.isCurrent)?.value ?? '';
+ const onValueChange = ({ value }: { value: string }) => {
+ const choice = choices.find((candidate) => candidate.value === value);
+ if (choice && !choice.isCurrent) {
+ choice.onSelect();
+ }
+ };
return (
<Menu.Root ids={ids} positioning={RESET_SIZE_MENU_POSITIONING}>
@@ -124,32 +135,28 @@ const ResetSizeMenu = ({ choices }: { choices: readonly ResetSizeChoice[] }) =>
<Portal>
<Menu.Positioner>
<MenuContent minW="15rem">
- {choices.map((choice) => (
- <Menu.Item
- key={choice.value}
- aria-current={choice.isCurrent ? 'true' : undefined}
- disabled={choice.isCurrent}
- value={choice.value}
- onSelect={choice.onSelect}
- >
- <HStack gap="2" minW="0" w="full">
- <Icon
- as={CheckIcon}
- aria-hidden
- boxSize="3.5"
- color="fg.subtle"
- flexShrink={0}
- opacity={choice.isCurrent ? 1 : 0}
- />
- <Text flex="1" fontSize="md" truncate>
- {choice.label}
- </Text>
- <Text color="fg.subtle" flexShrink={0} fontSize="sm" fontVariantNumeric="tabular-nums">
- {`${choice.size.width}×${choice.size.height}`}
- </Text>
- </HStack>
- </Menu.Item>
- ))}
+ <Menu.RadioItemGroup value={current} onValueChange={onValueChange}>
+ {choices.map((choice) => (
+ <Menu.RadioItem key={choice.value} value={choice.value}>
+ <HStack gap="2" minW="0" w="full">
+ <Icon
+ as={CheckIcon}
+ aria-hidden
+ boxSize="3.5"
+ color="fg.subtle"
+ flexShrink={0}
+ opacity={choice.value === current ? 1 : 0}
+ />
+ <Text flex="1" fontSize="md" truncate>
+ {choice.label}
+ </Text>
+ <Text color="fg.subtle" flexShrink={0} fontSize="sm" fontVariantNumeric="tabular-nums">
+ {`${choice.size.width}×${choice.size.height}`}
+ </Text>
+ </HStack>
+ </Menu.RadioItem>
+ ))}
+ </Menu.RadioItemGroup>
</MenuContent>
</Menu.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx
index efa9907177..402195c595 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasHeaderActions.browser.test.tsx
@@ -1,3 +1,4 @@
+import type { CanvasLayerContract } from '@workbench/canvas-engine/contracts';
import type { CanvasEngine } from '@workbench/canvas-operations/createCanvasEngine';
import type { Project } from '@workbench/projectContracts';
import type { WidgetViewProps } from '@workbench/widgetContracts';
@@ -73,7 +74,7 @@ interface Registration {
}
/** A painted layer, so a cleared document differs from the one it replaced. */
-const paintedLayer = {
+const paintedLayer: CanvasLayerContract = {
blendMode: 'normal' as const,
id: 'painted',
isEnabled: true,
@@ -86,14 +87,17 @@ const paintedLayer = {
};
/**
- * Renders the actions on a fresh project, whose canvas is empty unless `withLayer`, recording the commands and
- * hotkeys they register.
+ * Renders the actions on a fresh project holding `layers` (none by default) and the canvas widget values
+ * `canvasValues`, recording the commands and hotkeys they register.
*/
-const renderActions = async ({ withLayer = false }: { withLayer?: boolean } = {}) => {
+const renderActions = async ({
+ canvasValues,
+ layers = [],
+}: { canvasValues?: Record<string, unknown>; layers?: CanvasLayerContract[] } = {}) => {
const initial = createInitialWorkbenchState();
const base = initial.projects[0]!;
const store = createWorkbenchStore(
- withLayer
+ layers.length > 0
? {
...initial,
projects: [
@@ -101,13 +105,16 @@ const renderActions = async ({ withLayer = false }: { withLayer?: boolean } = {}
...base,
canvas: {
...base.canvas,
- document: { ...base.canvas.document, stacks: stacksFrom([paintedLayer]) },
+ document: { ...base.canvas.document, stacks: stacksFrom(layers) },
},
},
],
}
: initial
);
+ if (canvasValues) {
+ store.commands.widgets.patchValues('canvas', canvasValues);
+ }
const projectId = store.getState().activeProjectId;
harness.store = store;
harness.engine = createCanvasEngine({
@@ -168,7 +175,7 @@ describe('CanvasHeaderActions clear canvas', () => {
});
it('replaces the document once confirmed, layers and all', async () => {
- const { store } = await renderActions({ withLayer: true });
+ const { store } = await renderActions({ layers: [paintedLayer] });
const before = store.getState().projects[0]!.canvas.documentRevision;
expect(store.getState().projects[0]!.canvas.document.stacks.raster).toHaveLength(1);
@@ -201,3 +208,27 @@ describe('CanvasHeaderActions clear canvas', () => {
await expect.element(confirmDialog()).toBeVisible();
});
});
+
+describe('CanvasHeaderActions fit frame to masks', () => {
+ it("pads the masks by the project's mask blur plus 8 before snapping outward to the grid", async () => {
+ const mask: CanvasLayerContract = {
+ blendMode: 'normal',
+ id: 'mask',
+ isEnabled: true,
+ isLocked: false,
+ mask: { bitmap: { height: 40, imageName: 'mask.png', width: 40 }, fill: { color: '#e07575', style: 'diagonal' } },
+ name: 'Mask',
+ opacity: 1,
+ transform: { rotation: 0, scaleX: 1, scaleY: 1, x: 100, y: 100 },
+ type: 'inpaint_mask',
+ };
+ const { store } = await renderActions({ canvasValues: { maskBlur: 40, snapToGrid: true }, layers: [mask] });
+
+ await page.getByRole('button', { exact: true, name: 'Fit frame to masks' }).click();
+
+ // Blur 40 pads 48: 52..188, on the default 8 px grid 48..192. The default blur 16 would give 72..168.
+ await expect
+ .poll(() => store.getState().projects[0]!.canvas.document.bbox)
+ .toEqual({ height: 144, width: 144, x: 48, y: 48 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx
index e3b73ace18..f8eea5c280 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.browser.test.tsx
@@ -52,6 +52,7 @@ beforeAll(async () => {
const TINT = '#e07575';
const PICKED = '#3a7bd5';
+type ShapeSource = Extract<CanvasLayerSourceContract, { type: 'shape' }>;
const SHAPE_SOURCE = {
fill: '#ff0000',
height: 10,
@@ -60,7 +61,7 @@ const SHAPE_SOURCE = {
strokeWidth: 2,
type: 'shape',
width: 10,
-} satisfies Extract<CanvasLayerSourceContract, { type: 'shape' }>;
+} satisfies ShapeSource;
const TEXT_SOURCE = {
align: 'left',
color: '#123456',
@@ -103,12 +104,15 @@ afterEach(async () => {
/**
* A real engine over a project holding a mask, a shape, a text layer and a paint layer, with `selected` selected. The feed's registered router is captured so tests drive picks the way the color-picker tool does.
*/
-const setup = async (selected: 'm0' | 'shape' | 'text' | 'paint', { withTintEditor = false } = {}) => {
+const setup = async (
+ selected: 'm0' | 'shape' | 'text' | 'paint',
+ { shapeSource = SHAPE_SOURCE, withTintEditor = false }: { shapeSource?: ShapeSource; withTintEditor?: boolean } = {}
+) => {
const store = createWorkbenchStore();
harness.store = store;
const projectId = store.getState().activeProjectId;
const layers: CanvasLayerContract[] = [
- layerContract('shape', 'raster', { name: 'Shape', source: SHAPE_SOURCE }),
+ layerContract('shape', 'raster', { name: 'Shape', source: shapeSource }),
layerContract('text', 'raster', { name: 'Text', source: TEXT_SOURCE }),
layerContract('paint', 'raster', { name: 'Paint' }),
layerContract('m0', 'inpaint_mask', { name: 'Mask' }),
@@ -276,6 +280,43 @@ describe('CanvasColorFeed Alt-pick routing', () => {
expect(sourceOf(view.layer('shape'))).toEqual(SHAPE_SOURCE);
});
+ it.each([
+ ['foreground', 'fill', { ...SHAPE_SOURCE, fill: null }],
+ ['background', 'stroke', { ...SHAPE_SOURCE, stroke: null }],
+ ] as const)(
+ 'leaves a selected shape’s %s-target %s off when the shape has none, and picks into the pair',
+ async (target, _field, shapeSource) => {
+ const view = await setup('shape', { shapeSource });
+ await act(() => view.store.commands.widgets.patchValues('canvas', { activeColorTarget: target }));
+
+ await view.pick(['#101010', PICKED], 'commit');
+
+ expect(sourceOf(view.layer('shape'))).toEqual(shapeSource);
+ expect(view.engine.history.getEntries().past).toEqual([]);
+ expect(view.canvasValues().activeColors).toMatchObject({ [target]: PICKED });
+ }
+ );
+
+ it('does not turn a shape’s stroke back on when it goes off mid-pick', async () => {
+ const view = await setup('shape');
+ await act(() => view.store.commands.widgets.patchValues('canvas', { activeColorTarget: 'background' }));
+ await act(() => view.router()('#101010', 'preview'));
+
+ const strokeless = { ...SHAPE_SOURCE, stroke: null };
+ await act(() =>
+ view.store.commands.canvas.apply(view.projectId, {
+ document: {
+ ...view.document(),
+ stacks: stacksFrom([layerContract('shape', 'raster', { name: 'Shape', source: strokeless })]),
+ },
+ type: 'replaceCanvasDocument',
+ })
+ );
+ await act(() => view.router()(PICKED, 'commit'));
+
+ expect(sourceOf(view.layer('shape'))).toEqual(strokeless);
+ });
+
it('writes a selected text layer’s color in one undo step', async () => {
const view = await setup('text');
await view.pick([PICKED], 'commit');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
index ed9bc6fe6d..583a40af96 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
@@ -34,7 +34,8 @@ type PickTarget =
/**
* Precedence: the armed mask tint while its mask is still selected; a selected shape (the foreground target writes
- * its fill, the background its stroke); a selected text layer; otherwise the pair.
+ * its fill, the background its stroke) when it has that slot; a selected text layer; otherwise the pair. A shape's
+ * off slot is no target, as in its own options, where the toggle alone turns a slot on.
*/
const resolvePickTarget = (engine: CanvasEngineHandle, canvasValues: Record<string, unknown>): PickTarget => {
const model = engine.document.model();
@@ -48,7 +49,10 @@ const resolvePickTarget = (engine: CanvasEngineHandle, canvasValues: Record<stri
}
const selected = document?.selectedLayerId ? (model?.getLayer(document.selectedLayerId) ?? null) : null;
if (selected?.type === 'raster' && selected.source.type === 'shape') {
- return { field: pairTarget === 'foreground' ? 'fill' : 'stroke', kind: 'shape', layerId: selected.id };
+ const field = pairTarget === 'foreground' ? 'fill' : 'stroke';
+ if (selected.source[field] !== null) {
+ return { field, kind: 'shape', layerId: selected.id };
+ }
}
if (selected?.type === 'raster' && selected.source.type === 'text') {
return { kind: 'text-layer', layerId: selected.id };
@@ -121,6 +125,10 @@ const ColorSampleRouting = ({ engine }: { engine: CanvasEngineHandle }) => {
return { ids: [target.layerId], status: 'missing' };
}
if (target.kind === 'shape' && layer.source.type === 'shape') {
+ // The slot can go off mid-pick (an undo, say); the pick never turns it back on.
+ if (layer.source[target.field] === null) {
+ return { status: 'unchanged' };
+ }
return model.prepare({ id: layer.id, source: { ...layer.source, [target.field]: hex }, type: 'patch-source' });
}
if (target.kind === 'text-layer' && layer.source.type === 'text') {
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts
index 495d60a251..b98f1318a6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.test.ts
@@ -118,8 +118,8 @@ describe('computeFitBboxToMasks', () => {
imageLayer('a', 0, 0, 500, 500), // ignored (not a mask)
inpaintMask('m', 100, 100, { height: 40, imageName: 'm-img', width: 40 }),
]);
- // mask bounds {100,100,40,40} → blur 0 pads 8 → {92,92,56,56} → grid 8 → {96,96,48,48}.
- expect(computeFitBboxToMasks(doc, 8, 0)).toEqual({ height: 48, width: 48, x: 96, y: 96 });
+ // mask bounds {100,100,40,40} → blur 0 pads 8 → 92..148 → grid 8 outward → 88..152.
+ expect(computeFitBboxToMasks(doc, 8, 0)).toEqual({ height: 64, width: 64, x: 88, y: 88 });
});
it('pads by the mask blur plus 8 so the feathered edge stays inside the frame', () => {
@@ -129,17 +129,60 @@ describe('computeFitBboxToMasks', () => {
expect(computeFitBboxToMasks(doc, 1, 0)).toEqual({ height: 116, width: 116, x: 192, y: 192 });
});
- it('grid-snaps the blur-padded rect inward', () => {
+ it('grid-snaps the blur-padded rect outward', () => {
const doc = docWith([inpaintMask('m', 100, 100, { height: 40, imageName: 'm-img', width: 40 })]);
- // Blur 16 pads 24 → {76,76,88,88}; grid 8 moves the origin up to 80 (+4) and floors 84 to 80.
- expect(computeFitBboxToMasks(doc, 8, 16)).toEqual({ height: 80, width: 80, x: 80, y: 80 });
+ // Blur 16 pads 24 → 76..164; grid 8 floors the origin to 72 and ceils the far edge to 168.
+ expect(computeFitBboxToMasks(doc, 8, 16)).toEqual({ height: 96, width: 96, x: 72, y: 72 });
+ });
+
+ /** The frame holds the whole feathered mask: its bounds grown by the blur on every side. */
+ const expectContainsFeather = (
+ frame: { x: number; y: number; width: number; height: number } | null,
+ mask: { x: number; y: number; width: number; height: number },
+ blur: number
+ ) => {
+ expect(frame).not.toBeNull();
+ expect(frame!.x).toBeLessThanOrEqual(mask.x - blur);
+ expect(frame!.y).toBeLessThanOrEqual(mask.y - blur);
+ expect(frame!.x + frame!.width).toBeGreaterThanOrEqual(mask.x + mask.width + blur);
+ expect(frame!.y + frame!.height).toBeGreaterThanOrEqual(mask.y + mask.height + blur);
+ };
+
+ it.each([
+ // Grid 16, mask 105..205: padded 81..229 snaps to 80..240. Inward snapping gave 96..224, cutting 89..96.
+ [16, 105, { height: 160, width: 160, x: 80, y: 80 }],
+ // Grid 32, mask 121..221: padded 97..245 snaps to 96..256. Inward snapping gave 128..224, cutting the mask itself.
+ [32, 121, { height: 160, width: 160, x: 96, y: 96 }],
+ ] as const)('keeps the blurred edge inside a grid-%i frame', (grid, origin, expected) => {
+ const mask = { height: 100, width: 100, x: origin, y: origin };
+ const doc = docWith([inpaintMask('m', origin, origin, { height: 100, imageName: 'm-img', width: 100 })]);
+
+ const frame = computeFitBboxToMasks(doc, grid, 16);
+
+ expect(frame).toEqual(expected);
+ expectContainsFeather(frame, mask, 16);
+ });
+
+ it('contains the feathered mask at every offset on 16 and 32 px grids', () => {
+ for (const grid of [16, 32]) {
+ for (let offset = 0; offset < grid; offset += 1) {
+ const mask = { height: 37, width: 53, x: 200 + offset, y: 300 - offset };
+ const doc = docWith([inpaintMask('m', mask.x, mask.y, { height: 37, imageName: 'm-img', width: 53 })]);
+ const frame = computeFitBboxToMasks(doc, grid, 16);
+
+ expectContainsFeather(frame, mask, 16);
+ for (const value of [frame!.x, frame!.y, frame!.width, frame!.height]) {
+ expect(value % grid).toBe(0);
+ }
+ }
+ }
});
it('excludes regional-guidance masks (legacy fits inpaint_mask only)', () => {
const regional = maskLayer('regional_guidance', 'rg', 400, 400, { height: 40, imageName: 'rg-img', width: 40 });
const doc = docWith([regional, inpaintMask('m', 100, 100, { height: 40, imageName: 'm-img', width: 40 })]);
// Identical to the inpaint-only fit above: the regional mask contributes nothing.
- expect(computeFitBboxToMasks(doc, 8, 0)).toEqual({ height: 48, width: 48, x: 96, y: 96 });
+ expect(computeFitBboxToMasks(doc, 8, 0)).toEqual({ height: 64, width: 64, x: 88, y: 88 });
// Regional masks alone ⇒ nothing to fit.
expect(computeFitBboxToMasks(docWith([regional]), 8, 0)).toBeNull();
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts
index 760d05101f..0352f53e2a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/fitBbox.ts
@@ -1,7 +1,7 @@
/**
- * Union enabled, renderable, nonempty layer bounds in document space. Mask fitting includes only inpaint masks and
- * pads by the mask blur plus {@link MASK_FIT_MARGIN}; snap inward with {@link fitRectToGrid}. Return null for no
- * content or a collapsed result.
+ * Union enabled, renderable, nonempty layer bounds in document space. Fitting to layers snaps inward with
+ * {@link fitRectToGrid}. Mask fitting includes only inpaint masks, pads by the mask blur plus {@link MASK_FIT_MARGIN}
+ * and snaps outward, so no grid cuts the feathered edge. Return null for no content or a collapsed result.
*/
import {
@@ -34,6 +34,16 @@ export const fitRectToGrid = (rect: Rect, gridSize: number): Rect => {
return { height, width, x, y };
};
+/** Snap outward: round origins down and far edges up, so the result contains `rect`. */
+const expandRectToGrid = (rect: Rect, gridSize: number): Rect => {
+ const g = gridSize > 1 ? gridSize : 1;
+ const x = Math.floor(rect.x / g) * g;
+ const y = Math.floor(rect.y / g) * g;
+ const width = Math.ceil((rect.x + rect.width) / g) * g - x;
+ const height = Math.ceil((rect.y + rect.height) / g) * g - y;
+ return { height, width, x, y };
+};
+
/** Union document bounds of enabled, renderable, nonempty layers matching predicate; return null when none qualify. */
export const unionRenderableBounds = (
doc: CanvasDocumentContractV3,
@@ -65,8 +75,9 @@ export const computeFitBboxToLayers = (doc: CanvasDocumentContractV3, gridSize:
};
/**
- * The grid-snapped frame that fits the visible INPAINT masks padded by `maskBlur` plus {@link MASK_FIT_MARGIN}, or
- * `null` when there are none. `maskBlur` is the project's clamped compositing mask blur.
+ * The grid-aligned frame that contains the visible INPAINT masks padded by `maskBlur` plus {@link MASK_FIT_MARGIN},
+ * or `null` when there are none. `maskBlur` is the project's clamped compositing mask blur. Snapping inward would cut
+ * up to a grid step less one pixel from each side, more than the margin on 16 and 32 px grids.
*/
export const computeFitBboxToMasks = (
doc: CanvasDocumentContractV3,
@@ -84,6 +95,5 @@ export const computeFitBboxToMasks = (
x: bounds.x - padding,
y: bounds.y - padding,
};
- const fitted = fitRectToGrid(expanded, gridSize);
- return isEmpty(fitted) ? null : fitted;
+ return expandRectToGrid(expanded, gridSize);
};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
index b37dd726e6..7427e0ec08 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.browser.test.tsx
@@ -58,22 +58,28 @@ const createEngine = () => {
return { engine: engine as unknown as ToolFooterProps['engine'], setPending };
};
+/** Renders the footer `width` px wide. */
+const renderFooter = async (engine: ToolFooterProps['engine'], width = 320) => {
+ const Footer = transformForm.footer!;
+ host = document.createElement('div');
+ host.style.width = `${width}px`;
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root!.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Footer engine={engine} isExternalInteractionLocked={false} />
+ </ChakraProvider>
+ </I18nextProvider>
+ )
+ );
+};
+
describe('Transform footer', () => {
it('says while a transform waits for its stroke to save, in a polite live region, and clears after', async () => {
const { engine, setPending } = createEngine();
- const Footer = transformForm.footer!;
- host = document.createElement('div');
- document.body.append(host);
- root = createRoot(host);
- await act(() =>
- root!.render(
- <I18nextProvider i18n={i18n}>
- <ChakraProvider value={system}>
- <Footer engine={engine} isExternalInteractionLocked={false} />
- </ChakraProvider>
- </I18nextProvider>
- )
- );
+ await renderFooter(engine);
const status = page.getByRole('status');
await expect.element(status).toBeInTheDocument();
await expect.element(status).toHaveTextContent('');
@@ -85,4 +91,17 @@ describe('Transform footer', () => {
await setPending(null);
await expect.element(status).toHaveTextContent('');
});
+
+ it('shows the whole status in a tooltip where a narrow pane truncates it', async () => {
+ const { engine, setPending } = createEngine();
+ await renderFooter(engine, 180);
+ await setPending('layer-1');
+ const status = page.getByRole('status');
+ const line = status.element() as HTMLElement;
+ expect(line.scrollWidth).toBeGreaterThan(line.clientWidth);
+
+ await status.getByText('Waiting for the stroke to save…').hover();
+
+ await expect.element(page.getByRole('tooltip')).toHaveTextContent('Waiting for the stroke to save…');
+ });
});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
index 507da527c9..51c9797d7b 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/geometryForm.tsx
@@ -10,6 +10,7 @@ import type {
import { Flex, Text } from '@chakra-ui/react';
import { AspectRatioLockButton, AspectRatioSelect } from '@features/generation/components';
import { ASPECT_RATIO_MAP, deriveAspectRatioId } from '@features/generation/settings';
+import { Tooltip } from '@platform/ui/Tooltip';
import { constrainBboxToRatio, lookupDocumentLeaf } from '@workbench/canvas-engine/api';
import {
useCanvasActiveTool,
@@ -266,11 +267,17 @@ const TransformFooter = ({ engine, isExternalInteractionLocked }: ToolFooterProp
const disabled = isExternalInteractionLocked || (!session && !hasFloat);
const onApply = useCallback(() => engine.layers.applyTransform(), [engine]);
const onCancel = useCallback(() => engine.layers.cancelTransform(), [engine]);
+ const pendingText = t('widgets.canvas.transformPending');
return (
<ApplyCancelBar applyDisabled={disabled} cancelDisabled={disabled} onApply={onApply} onCancel={onCancel}>
- {/* Always mounted, so screen readers hear the wait start and end as the live region's text changes. */}
+ {/* Always mounted, so screen readers hear the wait start and end as the live region's text changes. The
+ tooltip shows the whole line where a narrow pane truncates it. */}
<Text color="fg.muted" role="status" truncate>
- {isPending ? t('widgets.canvas.transformPending') : null}
+ {isPending ? (
+ <Tooltip content={pendingText}>
+ <span>{pendingText}</span>
+ </Tooltip>
+ ) : null}
</Text>
</ApplyCancelBar>
);