Skip to content

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

feat(canvas): canvas eyedroppers on mask fill and infill pickers

Josh Corbett5d8e441028c5
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 222b91b153..4439be9d29 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,12 +2,12 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 841562,
+ "brotliBytes": 841574,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 840523,
+ "gzipBytes": 840585,
"imageRawBytes": 156376,
- "initialRawBytes": 1959074,
+ "initialRawBytes": 1959360,
"largestAssetRawBytes": 746376,
"otherAssetRawBytes": 0,
"ownedRawBytes": 70904,
@@ -291,12 +291,12 @@
]
},
"limits": {
- "brotliBytes": 849978,
+ "brotliBytes": 849990,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 848929,
+ "gzipBytes": 848991,
"imageRawBytes": 157940,
- "initialRawBytes": 1978665,
+ "initialRawBytes": 1978954,
"largestAssetRawBytes": 753840,
"otherAssetRawBytes": 0,
"ownedRawBytes": 70904,
@@ -309,15 +309,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 1102073,
+ "brotliBytes": 1102144,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 1097661,
+ "gzipBytes": 1097730,
"imageRawBytes": 156376,
- "initialRawBytes": 2749227,
+ "initialRawBytes": 2749535,
"largestAssetRawBytes": 746376,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 114618,
+ "ownedRawBytes": 114628,
"requestCount": 97,
"scriptRequestCount": 81,
"sourceOwners": [
@@ -933,15 +933,15 @@
]
},
"limits": {
- "brotliBytes": 1113094,
+ "brotliBytes": 1113166,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 1108638,
+ "gzipBytes": 1108708,
"imageRawBytes": 157940,
- "initialRawBytes": 2776720,
+ "initialRawBytes": 2777031,
"largestAssetRawBytes": 753840,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 114618,
+ "ownedRawBytes": 114628,
"requestCount": 97,
"scriptRequestCount": 81
},
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
index 14ac04f0ed..7fb4b481f2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.test.ts
@@ -724,6 +724,89 @@ describe('createCanvasEngine', () => {
engine.lifecycle.dispose();
});
+ it('settles a claimed color sample on release, after the sampling gesture ends', async () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const layer = {
+ ...rasterLayer('a'),
+ source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' as const },
+ };
+ const document = { ...makeDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ const overlay = createInputCanvas();
+ const screen = createInputCanvas();
+ engine.surface.attach(screen.element, overlay.element);
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+
+ let settled: string | null | undefined;
+ void engine.tools.requestColorSample().then((hex) => {
+ settled = hex;
+ });
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ await flushMicrotasks();
+ // The press stashes the sample; settling waits for the gesture to end so a
+ // structural commit in the caller's continuation is not gesture-refused.
+ expect(settled).toBeUndefined();
+
+ overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));
+ await flushMicrotasks();
+ expect(settled).toBe('#000000');
+ engine.lifecycle.dispose();
+ });
+
+ it('keeps a cancelled gesture’s claim pending and settles it from the retry gesture', async () => {
+ const raf = createControllableRaf();
+ vi.stubGlobal('requestAnimationFrame', raf.requestFrame);
+ vi.stubGlobal('cancelAnimationFrame', raf.cancelFrame);
+ const layer = {
+ ...rasterLayer('a'),
+ source: { bitmap: { height: 20, imageName: 'paint-pixels', width: 20 }, type: 'paint' as const },
+ };
+ const document = { ...makeDoc(), stacks: stacksFrom([layer]), selectedLayerId: layer.id };
+ const { projectId, store } = createReducerBackedStore(document);
+ const engine = createCanvasEngine({
+ backend: createTestStubRasterBackend(),
+ bitmapStore: createSpyBitmapStore(),
+ imageResolver: () => Promise.resolve(new Blob()),
+ projectId,
+ store,
+ });
+ const overlay = createInputCanvas();
+ const screen = createInputCanvas();
+ engine.surface.attach(screen.element, overlay.element);
+ raf.flush();
+ await flushMicrotasks();
+ raf.flush();
+
+ let settled: string | null | undefined;
+ void engine.tools.requestColorSample().then((hex) => {
+ settled = hex;
+ });
+ // A press stashes a color; the cancel discards that stash (so a dead
+ // gesture's color can never ride a later release — see the tool tests)
+ // without settling the claim, leaving the eyedropper armed for a retry.
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ overlay.fire('pointercancel', pointerAt(5, 5, { buttons: 0 }));
+ await flushMicrotasks();
+ expect(settled).toBeUndefined();
+
+ overlay.fire('pointerdown', pointerAt(5, 5));
+ overlay.fire('pointerup', pointerAt(5, 5, { buttons: 0 }));
+ await flushMicrotasks();
+ expect(settled).toBe('#000000');
+ engine.lifecycle.dispose();
+ });
+
it('returns stale when cooldown changes lifecycle generation during raster detachment', async () => {
const pending = createDeferred<Blob>();
const { store } = createReactiveStore(makeDoc());
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index 5361fc3cc4..a089c263f1 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1011,12 +1011,20 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
/**
* A one-shot color sample requested from outside the canvas — the color
* picker's eyedropper button. While one is pending, the color-picker tool
- * hands its next sample here instead of writing the brush color, and the tool
- * that was active beforehand is restored. Cancelled (resolving `null`) by
- * Escape, by any other tool switch, and by teardown, so the promise the
- * caller is awaiting can never dangle.
+ * hands its samples here instead of writing the brush color: press and drag
+ * stash the latest color (`sampledHex`), and the release settles the promise
+ * and restores the tool that was active beforehand. Settling on release, not
+ * press, matters — the pointer gesture is already over, so a caller that
+ * commits the sample through the document transaction seam is not refused as
+ * `gesture-active`. Cancelled (resolving `null`) by Escape, by any other tool
+ * switch, and by teardown, so the promise the caller is awaiting can never
+ * dangle.
*/
- let pendingColorSample: { previousToolId: ToolId; resolve: (hex: string | null) => void } | null = null;
+ let pendingColorSample: {
+ previousToolId: ToolId;
+ resolve: (hex: string | null) => void;
+ sampledHex: string | null;
+ } | null = null;
// Where unclaimed eyedropper samples land while a workbench is attached.
let colorSampleRouter: ((hex: string) => boolean) | null = null;
@@ -1070,11 +1078,21 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
openTextEdit: (layerId) => openTextEdit(layerId),
resolveColorSample: (hex) => {
if (pendingColorSample) {
- settleColorSample(hex, true);
+ pendingColorSample.sampledHex = hex;
return true;
}
return colorSampleRouter?.(hex) ?? false;
},
+ commitColorSample: () => {
+ if (pendingColorSample !== null && pendingColorSample.sampledHex !== null) {
+ settleColorSample(pendingColorSample.sampledHex, true);
+ }
+ },
+ discardColorSample: () => {
+ if (pendingColorSample !== null) {
+ pendingColorSample.sampledHex = null;
+ }
+ },
setLayerTransformOverride: (layerId, override) => {
if (override) {
transformOverrides.set(layerId, override);
@@ -1812,14 +1830,16 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
* Arms the eyedropper for one sample and resolves with the picked `#rrggbb`,
* or `null` if the user cancels. Backs the color picker's eyedropper button,
* which reads the composited document rather than the screen (and so works
- * outside Chromium, and sees through the window chrome).
+ * outside Chromium, and sees through the window chrome). The promise settles
+ * on pointer release, after the sampling gesture ends, so the caller may
+ * commit the color through the document transaction seam synchronously.
*/
const requestColorSample = (): Promise<string | null> => {
// A second request supersedes the first; the earlier caller gets a cancel.
settleColorSample(null, false);
return new Promise<string | null>((resolve) => {
- pendingColorSample = { previousToolId: interactionController.getActiveToolId(), resolve };
+ pendingColorSample = { previousToolId: interactionController.getActiveToolId(), resolve, sampledHex: null };
interactionController.setTool('colorPicker');
});
};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts
index 8d88b59948..2ae5b45078 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.test.ts
@@ -183,6 +183,40 @@ describe('color picker tool', () => {
expect(h.ctx.stores.brushOptions.get().color).toBe(defaultColor);
});
+ it('stashes claimed samples without writing brushOptions and commits on release', () => {
+ const h = createHarness(makeDoc());
+ const tool = createColorPickerTool();
+ const defaultColor = h.ctx.stores.brushOptions.get().color;
+ const claimed: string[] = [];
+ h.ctx.resolveColorSample = (hex) => {
+ claimed.push(hex);
+ return true;
+ };
+ const commit = vi.fn();
+ h.ctx.commitColorSample = commit;
+
+ down(tool, h.ctx, pointer(10, 10));
+ expect(claimed).toEqual(['#0a141e']);
+ expect(commit).not.toHaveBeenCalled();
+ expect(h.ctx.stores.brushOptions.get().color).toBe(defaultColor);
+
+ up(tool, h.ctx, pointer(10, 10, { buttons: 0 }));
+ expect(commit).toHaveBeenCalledTimes(1);
+ });
+
+ it('discards the stashed sample on gesture cancel and at each fresh press', () => {
+ const h = createHarness(makeDoc());
+ const tool = createColorPickerTool();
+ const discard = vi.fn();
+ h.ctx.discardColorSample = discard;
+
+ down(tool, h.ctx, pointer(10, 10));
+ expect(discard).toHaveBeenCalledTimes(1);
+
+ tool.onPointerCancel?.(h.ctx);
+ expect(discard).toHaveBeenCalledTimes(2);
+ });
+
it('never dispatches and never emits a committed stroke', () => {
const h = createHarness(makeDoc());
const tool = createColorPickerTool();
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
index 2cd0ef3391..91c81b7bde 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
@@ -63,10 +63,14 @@ export const createColorPickerTool = (): Tool => ({
ctx.setOverlayCursor(null);
ctx.invalidate({ overlay: true });
},
+ onPointerCancel: (ctx) => {
+ ctx.discardColorSample?.();
+ },
onPointerDown: (ctx, input) => {
if ((input.buttons & PRIMARY_BUTTON) === 0) {
return;
}
+ ctx.discardColorSample?.();
updateCursorRing(ctx, input);
pickColorAt(ctx, input);
},
@@ -78,5 +82,6 @@ export const createColorPickerTool = (): Tool => ({
},
onPointerUp: (ctx, input) => {
updateCursorRing(ctx, input);
+ ctx.commitColorSample?.();
},
});
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
index 1403c0b20e..9b311e48e2 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -172,6 +172,22 @@ export interface ToolContext {
* engine-standalone behavior. Absent in minimal test harnesses.
*/
resolveColorSample?(hex: string): boolean;
+ /**
+ * Settles a pending one-shot sample request with the latest color the
+ * gesture stashed via `resolveColorSample`. The color-picker tool calls this
+ * on pointer up — never mid-gesture — so the requester's promise resolves
+ * after the gesture ends and a structural commit in its continuation is not
+ * refused as `gesture-active`. No-op without a pending request or a stashed
+ * color.
+ */
+ commitColorSample?(): void;
+ /**
+ * Drops the color a pending sample request's gesture has stashed, without
+ * settling the request. The color-picker tool calls it when a gesture is
+ * cancelled and at the start of each fresh press, so a dead gesture's color
+ * can never be committed by a later release that sampled nothing.
+ */
+ discardColorSample?(): void;
/**
* Re-evaluates the active tool's CSS cursor and applies it to the input
* element. A tool calls this when its `cursor(ctx)` result changes off a plain
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx
index 08c237a085..3284037cde 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx
@@ -17,6 +17,7 @@ import type { CanvasCoherenceMode, CanvasInfillMethod } from '@workbench/widgets
import { Badge, createListCollection, NumberInput, Stack } from '@chakra-ui/react';
import { GenerationSettingsSection } from '@features/generation/components';
import { ColorPicker, Field, formatHexColor, parseHexColor, Select } from '@platform/ui';
+import { getCanvasEngine } from '@workbench/canvas-operations/api';
import {
CANVAS_COHERENCE_EDGE_SIZE_MAX,
CANVAS_COMPOSITING_KEYS,
@@ -24,7 +25,7 @@ import {
readCanvasCompositingSettings,
} from '@workbench/widgets/canvas/invoke/canvasCompositing';
import { getProjectWidgetValues } from '@workbench/widgetState';
-import { useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
+import { useActiveProjectId, useActiveProjectSelector, useWorkbenchCommands } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -41,6 +42,7 @@ const selectCanvasValues = (project: Parameters<typeof getProjectWidgetValues>[0
export const GenerateCanvasCompositingSection = () => {
const { t } = useTranslation();
const { widgets } = useWorkbenchCommands();
+ const projectId = useActiveProjectId();
const values = useActiveProjectSelector(selectCanvasValues);
const settings = useMemo(() => readCanvasCompositingSettings(values), [values]);
@@ -134,6 +136,13 @@ export const GenerateCanvasCompositingSection = () => {
[patch]
);
+ // The generate form outlives the canvas widget's engine lease, so the sampler
+ // peeks non-owningly at click time instead of holding an engine alive.
+ const handleSampleInfillColor = useCallback(
+ () => getCanvasEngine(projectId)?.tools.requestColorSample() ?? Promise.resolve(null),
+ [projectId]
+ );
+
const opt = (key: string) => t(`widgets.generate.compositingOptions.${key}`);
// The collapsed header carries the effective recipe — infill method and mask
@@ -170,6 +179,7 @@ export const GenerateCanvasCompositingSection = () => {
aria-label={opt('infillColorValue')}
value={infillColor}
withAlpha
+ onSampleColor={handleSampleInfillColor}
onValueChange={handleInfillColorChange}
/>
</Field>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts
index aef49e5195..8bdf4bd373 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts
@@ -8,7 +8,8 @@
* alongside a canvas hands this to `ColorPicker`'s `onSampleColor` instead.
*
* The returned callback is stable, which the `react-perf/jsx-no-new-*-as-prop`
- * rules require of anything passed straight into JSX.
+ * rules require of anything passed straight into JSX. Without an engine it
+ * returns `undefined`, so the picker keeps its screen-eyedropper fallback.
*/
import type { CanvasEngineToolCapability } from '@workbench/canvas-engine/api';
@@ -20,5 +21,7 @@ export interface ColorSamplerEngine {
readonly tools: Pick<CanvasEngineToolCapability, 'requestColorSample'>;
}
-export const useColorSampler = (engine: ColorSamplerEngine): (() => Promise<string | null>) =>
- useCallback(() => engine.tools.requestColorSample(), [engine]);
+export const useColorSampler = (engine: ColorSamplerEngine | null): (() => Promise<string | null>) | undefined => {
+ const sample = useCallback(() => engine?.tools.requestColorSample() ?? Promise.resolve(null), [engine]);
+ return engine ? sample : undefined;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsx
new file mode 100644
index 0000000000..9795a98ec3
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.browser.test.tsx
@@ -0,0 +1,143 @@
+import type {
+ CanvasInpaintMaskLayerContract,
+ CanvasMaskFillContract,
+ PreparedDocumentEdit,
+} from '@workbench/canvas-engine/api';
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import type { CanvasProjectMutation } from '@workbench/canvasProjectMutations';
+import type { ComponentProps } from 'react';
+
+import { ChakraProvider } from '@chakra-ui/react';
+import { applyThemeToRoot } from '@theme/applyTheme';
+import { system } from '@theme/system';
+import { createDocumentModel } from '@workbench/canvas-engine/api';
+import { stacksFrom } from '@workbench/canvas-engine/document-model/documentFixtures.testStub';
+import { createEmptyCanvasDocument } from '@workbench/canvasMigration';
+import { createInstance } from 'i18next';
+import { act, useMemo, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, describe, expect, it } from 'vitest';
+
+import { InpaintMaskSettings } from './InpaintMaskSettings';
+
+type Engine = ComponentProps<typeof InpaintMaskSettings>['engine'];
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({ fallbackLng: 'en', initAsync: false, lng: 'en', resources: {} });
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+
+const createLayer = (): CanvasInpaintMaskLayerContract =>
+ ({
+ id: 'mask-1',
+ isEnabled: true,
+ isLocked: false,
+ mask: { bitmap: null, fill: { color: '#ff0000', style: 'solid' } },
+ name: 'Inpaint Mask',
+ opacity: 1,
+ type: 'inpaint_mask',
+ }) as unknown as CanvasInpaintMaskLayerContract;
+
+const commits: { label: string; edit: PreparedDocumentEdit }[] = [];
+let sampleRequests = 0;
+
+const Harness = () => {
+ const [layer, setLayer] = useState(createLayer);
+
+ const engine = useMemo(() => {
+ const apply = (mutation: CanvasProjectMutation): boolean => {
+ const candidate = mutation as { type: string; config?: { mask?: { fill?: CanvasMaskFillContract } } };
+ const fill = candidate.config?.mask?.fill;
+ if (candidate.type === 'updateCanvasLayerConfig' && fill) {
+ setLayer((current) => ({ ...current, mask: { ...current.mask, fill } }));
+ }
+ return true;
+ };
+
+ return {
+ document: {
+ model: () =>
+ createDocumentModel(
+ { ...createEmptyCanvasDocument(), selectedLayerId: layer.id, stacks: stacksFrom([layer]) },
+ { editRevision: 0, projectId: 'test-project' }
+ ),
+ },
+ layers: {
+ applyStructuralPreview: apply,
+ commitPrepared: (label: string, edit: PreparedDocumentEdit) => {
+ commits.push({ edit, label });
+ return { status: apply(edit.forward) ? ('committed' as const) : ('dispatch-rejected' as const) };
+ },
+ },
+ tools: {
+ requestColorSample: () => {
+ sampleRequests += 1;
+ return Promise.resolve('#123456');
+ },
+ },
+ } as unknown as Engine;
+ // Rebuilt per layer change so the stub's model reflects the previewed layer, as the engine's does.
+ }, [layer]);
+
+ return <InpaintMaskSettings engine={engine} layer={layer} />;
+};
+
+const settle = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 30);
+ });
+ });
+
+const render = async () => {
+ applyThemeToRoot('classic');
+ host = document.createElement('div');
+ host.style.width = '260px';
+ document.body.append(host);
+ root = createRoot(host);
+
+ await settle(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+};
+
+afterEach(async () => {
+ commits.length = 0;
+ sampleRequests = 0;
+ await settle(() => root?.unmount());
+ host?.remove();
+ host = null;
+ root = null;
+});
+
+const forwardFill = (edit: PreparedDocumentEdit): CanvasMaskFillContract =>
+ (edit.forward as unknown as { config: { mask: { fill: CanvasMaskFillContract } } }).config.mask.fill;
+
+describe('mask fill eyedropper', () => {
+ it('samples the canvas through the engine and commits the picked fill color once', async () => {
+ await render();
+
+ const trigger = host!.querySelector<HTMLElement>('[aria-label="widgets.layers.maskFill.color"]')!;
+ await settle(() => trigger.click());
+
+ // With an engine present the picker offers the canvas sampler, not the screen eyedropper.
+ const sampleButton = document.querySelector<HTMLElement>('[aria-label="common.colorPicker.sampleFromCanvas"]');
+ expect(sampleButton).not.toBeNull();
+ await settle(() => sampleButton!.click());
+
+ expect(sampleRequests).toBe(1);
+ expect(commits).toHaveLength(1);
+ expect(forwardFill(commits[0]!.edit)).toEqual({ color: '#123456', style: 'solid' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
index 2ffa232029..590587bc42 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/InpaintMaskSettings.tsx
@@ -5,6 +5,7 @@ import type { CanvasStructuralEngine } from '@workbench/widgets/layers/layerOps'
import { createListCollection, HStack, Stack } from '@chakra-ui/react';
import { Button, ColorPicker, Field, IconButton, Select, Tooltip } from '@platform/ui';
import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';
+import { type ColorSamplerEngine, useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { PaletteIcon } from 'lucide-react';
import { useCallback, useMemo, useRef } from 'react';
@@ -23,7 +24,7 @@ const MASK_FILL_STYLES: readonly CanvasMaskFillContract['style'][] = [
];
interface InpaintMaskSettingsProps {
- engine: (CanvasStructuralEngine & CanvasPreparedEngine) | null;
+ engine: (CanvasStructuralEngine & CanvasPreparedEngine & ColorSamplerEngine) | null;
layer: CanvasInpaintMaskLayerContract;
}
@@ -37,6 +38,7 @@ interface InpaintMaskSettingsProps {
export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps) => {
const { t } = useTranslation();
const commitPrepared = usePreparedCommit(engine);
+ const sampleColor = useColorSampler(engine);
const fillBeforeRef = useRef<CanvasMaskFillContract | null>(null);
const fill = layer.mask.fill;
@@ -118,6 +120,7 @@ export const InpaintMaskSettings = ({ engine, layer }: InpaintMaskSettingsProps)
<ColorPicker
aria-label={colorAria}
value={fill.color}
+ onSampleColor={sampleColor}
onValueChange={handleColorChange}
onValueChangeEnd={handleColorChangeEnd}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
index ed08c84229..e9e2a01346 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/RegionalGuidanceSettings.tsx
@@ -12,6 +12,7 @@ import { PROMPT_ATTENTION_TARGET_PROPS, PromptTextarea } from '@features/generat
import { Button, ColorPicker, Field, Select, Tooltip } from '@platform/ui';
import { useWorkbenchPreferenceSelector } from '@workbench/settings/store';
import { armMaskTintTarget } from '@workbench/widgets/canvas/color-system/maskTintTarget';
+import { type ColorSamplerEngine, useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
import { type CanvasPreparedEngine, usePreparedCommit } from '@workbench/widgets/canvas/useStructuralCommit';
import { PaletteIcon } from 'lucide-react';
import { useCallback, useMemo, useRef, useState } from 'react';
@@ -43,7 +44,7 @@ const SELECT_POSITIONING = { placement: 'bottom-end', sameWidth: true } as const
const REGIONAL_PROMPT_HEIGHT_PX = 72;
interface RegionalGuidanceSettingsProps {
- engine: (CanvasStructuralEngine & CanvasPreparedEngine) | null;
+ engine: (CanvasStructuralEngine & CanvasPreparedEngine & ColorSamplerEngine) | null;
layer: CanvasRegionalGuidanceLayerContract;
}
@@ -59,6 +60,7 @@ interface RegionalGuidanceSettingsProps {
export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSettingsProps) => {
const { t } = useTranslation();
const commitPrepared = usePreparedCommit(engine);
+ const sampleColor = useColorSampler(engine);
const base = useSelectedModelBase();
const showSyntaxHighlighting = useWorkbenchPreferenceSelector(
(preferences) => preferences.showPromptSyntaxHighlighting
@@ -260,6 +262,7 @@ export const RegionalGuidanceSettings = ({ engine, layer }: RegionalGuidanceSett
<ColorPicker
aria-label={t('widgets.layers.maskFill.color')}
value={fill.color}
+ onSampleColor={sampleColor}
onValueChange={handleColorChange}
onValueChangeEnd={handleColorChangeEnd}
/>
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 fb45a58323..9acea00a64 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerSection.tsx
@@ -27,7 +27,10 @@ import { useTranslation } from 'react-i18next';
import { GroupSelectedNotice } from './GroupSelectedNotice';
import { PropertiesSection } from './PropertiesSection';
-type LayerSectionEngine = Pick<CanvasEngineHandle, 'document' | 'exports' | 'interaction' | 'layers' | 'projectId'>;
+type LayerSectionEngine = Pick<
+ CanvasEngineHandle,
+ 'document' | 'exports' | 'interaction' | 'layers' | 'projectId' | 'tools'
+>;
// Reference equality is exact: the document index hands back the same node
// object until the layer itself changes, and the section renders the whole