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(webv2): rebuild the color picker with swatches, modes, and alpha

joshistoast93c2bb8c08cc
diff --git a/invokeai/frontend/webv2/performance/architecture-baseline.json b/invokeai/frontend/webv2/performance/architecture-baseline.json
index 40493e80a3..07204f34aa 100644
--- a/invokeai/frontend/webv2/performance/architecture-baseline.json
+++ b/invokeai/frontend/webv2/performance/architecture-baseline.json
@@ -2,15 +2,15 @@
"build": {
"launchpad": {
"baseline": {
- "brotliBytes": 799495,
+ "brotliBytes": 803542,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 799588,
+ "gzipBytes": 803372,
"imageRawBytes": 156376,
- "initialRawBytes": 1835695,
- "largestAssetRawBytes": 737757,
+ "initialRawBytes": 1845192,
+ "largestAssetRawBytes": 738008,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 57878,
+ "ownedRawBytes": 57912,
"requestCount": 31,
"scriptRequestCount": 15,
"sourceOwners": [
@@ -202,6 +202,8 @@
"source:src/platform/ui/ToggleDot.tsx",
"source:src/platform/ui/Toolbar.tsx",
"source:src/platform/ui/Tooltip.tsx",
+ "source:src/platform/ui/color.ts",
+ "source:src/platform/ui/colorPickerStore.ts",
"source:src/platform/ui/colorPickerSync.ts",
"source:src/platform/ui/index.ts",
"source:src/platform/ui/theme/applyTheme.ts",
@@ -239,15 +241,15 @@
]
},
"limits": {
- "brotliBytes": 807490,
+ "brotliBytes": 811578,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 807584,
+ "gzipBytes": 811406,
"imageRawBytes": 157940,
- "initialRawBytes": 1854052,
- "largestAssetRawBytes": 745135,
+ "initialRawBytes": 1863644,
+ "largestAssetRawBytes": 745389,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 57878,
+ "ownedRawBytes": 57912,
"requestCount": 31,
"scriptRequestCount": 15
},
@@ -257,15 +259,15 @@
},
"editor": {
"baseline": {
- "brotliBytes": 987794,
+ "brotliBytes": 992040,
"cssRawBytes": 2159,
"fontRawBytes": 219480,
- "gzipBytes": 986463,
+ "gzipBytes": 990650,
"imageRawBytes": 156376,
- "initialRawBytes": 2413642,
- "largestAssetRawBytes": 737757,
+ "initialRawBytes": 2423127,
+ "largestAssetRawBytes": 738008,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 110895,
+ "ownedRawBytes": 110881,
"requestCount": 72,
"scriptRequestCount": 56,
"sourceOwners": [
@@ -590,6 +592,8 @@
"source:src/platform/ui/ToggleDot.tsx",
"source:src/platform/ui/Toolbar.tsx",
"source:src/platform/ui/Tooltip.tsx",
+ "source:src/platform/ui/color.ts",
+ "source:src/platform/ui/colorPickerStore.ts",
"source:src/platform/ui/colorPickerSync.ts",
"source:src/platform/ui/index.ts",
"source:src/platform/ui/theme/applyTheme.ts",
@@ -745,15 +749,15 @@
]
},
"limits": {
- "brotliBytes": 997672,
+ "brotliBytes": 1001961,
"cssRawBytes": 2181,
"fontRawBytes": 221675,
- "gzipBytes": 996328,
+ "gzipBytes": 1000557,
"imageRawBytes": 157940,
- "initialRawBytes": 2437779,
- "largestAssetRawBytes": 745135,
+ "initialRawBytes": 2447359,
+ "largestAssetRawBytes": 745389,
"otherAssetRawBytes": 0,
- "ownedRawBytes": 110895,
+ "ownedRawBytes": 110881,
"requestCount": 72,
"scriptRequestCount": 56
},
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 03162d9cb7..f976d1d35e 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -172,6 +172,12 @@
"openSelector": "Open selector",
"searchSchedulers": "Search schedulers…",
"close": "Close",
+ "colorPicker": {
+ "format": "Color format",
+ "sampleFromCanvas": "Pick a color from the canvas",
+ "sampleFromScreen": "Pick a color from the screen",
+ "opacity": "Opacity (%)"
+ },
"configure": "Configure",
"copy": "Copy",
"crop": "Crop",
@@ -838,6 +844,7 @@
"components": "Components",
"compositing": "Compositing",
"compositingOptions": {
+ "infillColorValue": "Infill color",
"infillMethod": "Infill method",
"infillMethods": {
"patchmatch": "PatchMatch",
@@ -1551,12 +1558,10 @@
"gradientAngle": "Angle",
"gradientEdit": "Edit gradient",
"gradientEnd": "End",
- "gradientEndOpacity": "End opacity",
"gradientKind": "Gradient type",
"gradientLinear": "Linear",
"gradientRadial": "Radial",
"gradientStart": "Start",
- "gradientStartOpacity": "Start opacity",
"invertSelection": "Invert",
"lassoFreehand": "Freehand",
"lassoHint": "Draw a shape to select. Shift adds, Alt subtracts.",
diff --git a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
index bd1e88c37e..95ccc50cf2 100644
--- a/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
+++ b/invokeai/frontend/webv2/src/features/workflow/ui/fields/WorkflowFieldInput.tsx
@@ -12,7 +12,7 @@ import {
registerAccountOwnedResource,
type AccountScope,
} from '@platform/state/accountLifecycle';
-import { Button, Combobox, ResizableTextarea, Select } from '@platform/ui';
+import { Button, ColorPicker, Combobox, formatHexColor, parseHexColor, ResizableTextarea, Select } from '@platform/ui';
import { lazy, Suspense, useCallback, useEffect, useMemo, useState, type ChangeEvent } from 'react';
const ModelSelect = lazy(() => import('@features/models/react').then((module) => ({ default: module.ModelSelect })));
@@ -420,78 +420,41 @@ const ImageInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {
);
};
-const COLOR_CHANNELS = ['r', 'g', 'b', 'a'] as const;
-
-const ColorInput = ({ id, invalid, onChange, value }: WorkflowFieldInputProps) => {
- const color = useMemo(
- () => (typeof value === 'object' && value !== null ? value : {}) as Partial<Record<string, number>>,
- [value]
- );
+/**
+ * Workflow `ColorField` values carry alpha as a `[0, 255]` integer, unlike
+ * every other color in the app (and unlike `RgbaColor`, whose alpha is a unit
+ * float). The scaling stays local to this adapter rather than pushing a second
+ * alpha convention into `@platform/ui`'s color helpers.
+ */
+const toColorFieldValue = (color: string): Record<string, number> => {
+ const { a, b, g, r } = parseHexColor(color);
- return (
- <HStack gap="1" w="full">
- {COLOR_CHANNELS.map((channel) => (
- <ColorChannelInput
- key={channel}
- channel={channel}
- color={color}
- id={id}
- invalid={invalid}
- onChange={onChange}
- />
- ))}
- </HStack>
- );
+ return { a: Math.round(a * 255), b, g, r };
};
-const ColorChannelInput = ({
- channel,
- color,
- id,
- invalid,
- onChange,
-}: {
- channel: (typeof COLOR_CHANNELS)[number];
- color: Partial<Record<string, number>>;
- id?: string;
- invalid?: boolean;
- onChange: (value: unknown) => void;
-}) => {
- const ariaLabel = useMemo(() => `Color ${channel.toUpperCase()}`, [channel]);
- const placeholder = channel.toUpperCase();
- const onInputChange = useCallback(
- (event: ChangeEvent<HTMLInputElement>) => {
- const parsed = toFiniteNumber(event.currentTarget.value);
+const fromColorFieldValue = (value: unknown): string => {
+ const channels = (typeof value === 'object' && value !== null ? value : {}) as Partial<Record<string, number>>;
- if (parsed !== null) {
- onChange({
- a: 255,
- b: 0,
- g: 0,
- r: 0,
- ...color,
- [channel]: Math.min(255, Math.max(0, Math.round(parsed))),
- });
- }
+ return formatHexColor(
+ {
+ a: (channels.a ?? 255) / 255,
+ b: channels.b ?? 0,
+ g: channels.g ?? 0,
+ r: channels.r ?? 0,
},
- [channel, color, onChange]
+ { alpha: true }
);
+};
+
+const ColorInput = ({ invalid, onChange, value }: WorkflowFieldInputProps) => {
+ const color = fromColorFieldValue(value);
+ const handleChange = useCallback((next: string) => onChange(toColorFieldValue(next)), [onChange]);
return (
- <Input
- aria-label={ariaLabel}
- className="nodrag"
- id={id ? `${id}-color-${channel}-input` : undefined}
- max="255"
- min="0"
- placeholder={placeholder}
- size="xs"
- type="number"
- value={typeof color[channel] === 'number' ? color[channel] : ''}
- w="full"
- {...invalidProps(invalid)}
- onChange={onInputChange}
- />
+ // `nodrag` keeps a click on the swatch from panning the node canvas.
+ <HStack className="nodrag" gap="2" w="full" {...invalidProps(invalid)}>
+ <ColorPicker aria-label="Color" value={color} withAlpha withValueText onValueChange={handleChange} />
+ </HStack>
);
};
diff --git a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.browser.test.tsx b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.browser.test.tsx
new file mode 100644
index 0000000000..1c53751a86
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.browser.test.tsx
@@ -0,0 +1,263 @@
+/* oxlint-disable react-perf/jsx-no-new-function-as-prop */
+import { ChakraProvider } from '@chakra-ui/react';
+import { system } from '@theme/system';
+import { createInstance } from 'i18next';
+import { act, useState } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { ColorPicker } from './ColorPicker';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ fallbackLng: 'en',
+ initAsync: false,
+ lng: 'en',
+ resources: {
+ en: {
+ translation: {
+ common: {
+ colorPicker: {
+ format: 'Color format',
+ opacity: 'Opacity (%)',
+ sampleFromCanvas: 'Pick a color from the canvas',
+ sampleFromScreen: 'Pick a color from the screen',
+ },
+ },
+ },
+ },
+ },
+});
+
+let host: HTMLDivElement | null = null;
+let root: Root | null = null;
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+const interact = (action: () => void): Promise<void> =>
+ act(async () => {
+ action();
+ await new Promise<void>((resolve) => {
+ globalThis.setTimeout(resolve, 50);
+ });
+ });
+
+interface HarnessProps {
+ initialValue: string;
+ swatches?: boolean | readonly string[];
+ withAlpha?: boolean;
+ onChange: (value: string) => void;
+ onChangeEnd: (value: string) => void;
+}
+
+const Harness = ({ initialValue, onChange, onChangeEnd, swatches, withAlpha }: HarnessProps) => {
+ const [value, setValue] = useState(initialValue);
+
+ return (
+ <ColorPicker
+ aria-label="Fill color"
+ swatches={swatches}
+ value={value}
+ withAlpha={withAlpha}
+ onValueChange={(next) => {
+ setValue(next);
+ onChange(next);
+ }}
+ onValueChangeEnd={onChangeEnd}
+ />
+ );
+};
+
+const renderPicker = async (props: Omit<HarnessProps, 'onChange' | 'onChangeEnd'>) => {
+ host = document.createElement('div');
+ document.body.append(host);
+ root = createRoot(host);
+ const onChange = vi.fn();
+ const onChangeEnd = vi.fn();
+
+ await interact(() => {
+ root?.render(
+ <I18nextProvider i18n={i18n}>
+ <ChakraProvider value={system}>
+ <Harness {...props} onChange={onChange} onChangeEnd={onChangeEnd} />
+ </ChakraProvider>
+ </I18nextProvider>
+ );
+ });
+
+ const trigger = host.querySelector<HTMLButtonElement>('[data-scope="color-picker"][data-part="trigger"]')!;
+
+ return { onChange, onChangeEnd, trigger };
+};
+
+const openPicker = async (trigger: HTMLButtonElement) => {
+ await interact(() => trigger.click());
+};
+
+const querySwatchTriggers = (): HTMLButtonElement[] =>
+ Array.from(document.querySelectorAll<HTMLButtonElement>('[data-part="swatch-trigger"]'));
+
+const queryChannelInputs = (): HTMLInputElement[] =>
+ Array.from(document.querySelectorAll<HTMLInputElement>('[data-part="channel-input"]'));
+
+beforeEach(() => {
+ window.localStorage.clear();
+});
+
+afterEach(async () => {
+ await interact(() => root?.unmount());
+ document.querySelectorAll('[data-scope="color-picker"][data-part="positioner"]').forEach((el) => el.remove());
+ document.querySelectorAll('[data-scope="menu"][data-part="positioner"]').forEach((el) => el.remove());
+ host?.remove();
+ host = null;
+ root = null;
+ window.localStorage.clear();
+});
+
+describe('ColorPicker', () => {
+ it('opens a popover with an area, hue slider, channel inputs, and swatches', async () => {
+ const { trigger } = await renderPicker({ initialValue: '#ff0000' });
+ await openPicker(trigger);
+
+ expect(document.querySelector('[data-part="area"]')).not.toBeNull();
+ expect(document.querySelector('[data-part="channel-slider"][data-channel="hue"]')).not.toBeNull();
+ expect(queryChannelInputs().length).toBeGreaterThan(0);
+ expect(querySwatchTriggers().length).toBeGreaterThan(0);
+ });
+
+ it('emits both a change and a commit when a swatch is picked', async () => {
+ // Zag's SwatchTrigger only reports a value change; without the component's
+ // explicit commit, every undo-recording consumer would drop swatch picks.
+ const { onChange, onChangeEnd, trigger } = await renderPicker({
+ initialValue: '#000000',
+ swatches: ['#ff0000', '#00ff00'],
+ });
+ await openPicker(trigger);
+
+ const [, green] = querySwatchTriggers();
+ await interact(() => green?.click());
+
+ expect(onChange).toHaveBeenLastCalledWith('#00ff00');
+ expect(onChangeEnd).toHaveBeenLastCalledWith('#00ff00');
+ });
+
+ it('emits 6-digit hex by default and 8-digit under withAlpha', async () => {
+ const opaque = await renderPicker({ initialValue: '#000000', swatches: ['#ff0000'] });
+ await openPicker(opaque.trigger);
+ await interact(() => querySwatchTriggers()[0]?.click());
+ expect(opaque.onChange).toHaveBeenLastCalledWith('#ff0000');
+
+ await interact(() => root?.unmount());
+ host?.remove();
+
+ const alpha = await renderPicker({ initialValue: '#000000ff', swatches: ['#ff0000'], withAlpha: true });
+ await openPicker(alpha.trigger);
+ await interact(() => querySwatchTriggers()[0]?.click());
+ expect(alpha.onChange).toHaveBeenLastCalledWith('#ff0000ff');
+ });
+
+ it('takes the alpha a swatch carries, so recents restore their transparency', async () => {
+ const { onChange, trigger } = await renderPicker({
+ initialValue: '#000000ff',
+ swatches: ['#ff000080'],
+ withAlpha: true,
+ });
+ await openPicker(trigger);
+ await interact(() => querySwatchTriggers()[0]?.click());
+
+ expect(onChange).toHaveBeenLastCalledWith('#ff000080');
+ });
+
+ it('shows an alpha slider only under withAlpha', async () => {
+ const opaque = await renderPicker({ initialValue: '#ff0000' });
+ await openPicker(opaque.trigger);
+ expect(document.querySelector('[data-part="channel-slider"][data-channel="alpha"]')).toBeNull();
+
+ await interact(() => root?.unmount());
+ host?.remove();
+
+ const alpha = await renderPicker({ initialValue: '#ff0000ff', withAlpha: true });
+ await openPicker(alpha.trigger);
+ expect(document.querySelector('[data-part="channel-slider"][data-channel="alpha"]')).not.toBeNull();
+ });
+
+ it('cycles formats through HEX/RGB/HSL/HSB without changing the value', async () => {
+ const { onChange, trigger } = await renderPicker({ initialValue: '#ff0000', swatches: false });
+ await openPicker(trigger);
+
+ const formatTrigger = () => document.querySelector<HTMLButtonElement>('[aria-label="Color format"]')!;
+
+ // HEX renders a single text field.
+ expect(formatTrigger().textContent).toBe('HEX');
+ expect(queryChannelInputs()).toHaveLength(1);
+
+ // RGB renders one field per channel.
+ await interact(() => formatTrigger().click());
+ expect(formatTrigger().textContent).toBe('RGB');
+ expect(queryChannelInputs()).toHaveLength(3);
+
+ await interact(() => formatTrigger().click());
+ expect(formatTrigger().textContent).toBe('HSL');
+ expect(queryChannelInputs()).toHaveLength(3);
+
+ await interact(() => formatTrigger().click());
+ expect(formatTrigger().textContent).toBe('HSB');
+
+ // Back to the start, and cycling never emitted a value change.
+ await interact(() => formatTrigger().click());
+ expect(formatTrigger().textContent).toBe('HEX');
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ it('edits opacity as a whole percentage rather than a unit float', async () => {
+ // Zag's own alpha channel input renders `0.501`; the picker replaces it.
+ const { onChange, trigger } = await renderPicker({
+ initialValue: '#ff000080',
+ swatches: false,
+ withAlpha: true,
+ });
+ await openPicker(trigger);
+
+ const opacity = document.querySelector<HTMLInputElement>('[aria-label="Opacity (%)"]')!;
+ expect(opacity.value).toBe('50');
+
+ const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')?.set;
+ await interact(() => {
+ setValue?.call(opacity, '25');
+ opacity.dispatchEvent(new InputEvent('input', { bubbles: true, data: '25', inputType: 'insertText' }));
+ });
+
+ expect(onChange).toHaveBeenLastCalledWith('#ff000040');
+ });
+
+ it('offers the opacity field only under withAlpha', async () => {
+ const opaque = await renderPicker({ initialValue: '#ff0000', swatches: false });
+ await openPicker(opaque.trigger);
+ expect(document.querySelector('[aria-label="Opacity (%)"]')).toBeNull();
+
+ await interact(() => root?.unmount());
+ host?.remove();
+
+ const alpha = await renderPicker({ initialValue: '#ff0000ff', swatches: false, withAlpha: true });
+ await openPicker(alpha.trigger);
+ expect(document.querySelector('[aria-label="Opacity (%)"]')).not.toBeNull();
+ });
+
+ it('records committed colors as recents and offers them alongside the defaults', async () => {
+ const first = await renderPicker({ initialValue: '#000000', swatches: ['#123456'] });
+ await openPicker(first.trigger);
+ const defaultCount = querySwatchTriggers().length;
+ await interact(() => querySwatchTriggers()[0]?.click());
+
+ await interact(() => root?.unmount());
+ host?.remove();
+
+ // A picker using the default palette should now surface the committed color.
+ const second = await renderPicker({ initialValue: '#000000' });
+ await openPicker(second.trigger);
+ const values = querySwatchTriggers().map((swatch) => swatch.getAttribute('data-value'));
+
+ expect(defaultCount).toBe(1);
+ expect(values).toContain('#123456');
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx
index e9b0b39d42..b63d165513 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx
@@ -1,92 +1,393 @@
import type { Color, ColorPickerValueChangeDetails } from '@chakra-ui/react';
-import type { ComponentProps } from 'react';
+import type { ChangeEvent, ComponentProps } from 'react';
-import { ColorPicker as ChakraColorPicker, parseColor, Portal } from '@chakra-ui/react';
-import { useCallback, useState } from 'react';
+import {
+ ColorPicker as ChakraColorPicker,
+ getColorChannels,
+ HStack,
+ Icon,
+ Input,
+ parseColor,
+ Portal,
+ Stack,
+ Text,
+} from '@chakra-ui/react';
+import { Pipette } from 'lucide-react';
+import { useCallback, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import type { ColorPickerFormat } from './colorPickerStore';
+
+import { IconButton } from './Button';
+import { normalizeHex } from './color';
+import {
+ COLOR_PICKER_FORMATS,
+ DEFAULT_COLOR_SWATCHES,
+ recordRecentColor,
+ setColorPickerFormat,
+ useColorPickerFormat,
+ useRecentColors,
+} from './colorPickerStore';
import { shouldSyncExternalColor } from './colorPickerSync';
export type ColorPickerSize = NonNullable<ComponentProps<typeof ChakraColorPicker.Root>['size']>;
+export type { ColorPickerFormat };
+
+/**
+ * Machine formats behind each presented format. `hex` and `rgb` share `rgba`,
+ * so switching between them changes only which inputs render — never the value.
+ */
+const MACHINE_FORMAT: Record<ColorPickerFormat, 'rgba' | 'hsla' | 'hsba'> = {
+ hex: 'rgba',
+ hsb: 'hsba',
+ hsl: 'hsla',
+ rgb: 'rgba',
+};
+
+/**
+ * The checkerboard behind transparent colors. This is a CSS *length* (it drives
+ * `background-size` on a conic gradient), not a size token — passing `"xs"`
+ * yields an invalid `background-size` and the gradient renders once, stretched,
+ * instead of tiling. Chakra's own default is `0.6rem`.
+ */
+const TRANSPARENCY_CHECK_SIZE = '0.5rem';
+
+/**
+ * Swatches wrap into as many even columns as the popover actually fits.
+ *
+ * `auto-fill` rather than a fixed `repeat(10, …)`: the swatch holds a fixed
+ * `--swatch-size` from the size variant, so a fixed column count overflows the
+ * popover the moment the swatch, the gap, or the content width changes — which
+ * is exactly what happened at ten columns in a 224px popover. Deriving the
+ * count from the available width instead makes that arithmetic unrepresentable.
+ */
+const SWATCH_GROUP_CSS = {
+ display: 'grid',
+ gap: '1',
+ gridTemplateColumns: 'repeat(auto-fill, minmax(var(--swatch-size, 1.25rem), 1fr))',
+};
+
+const CHANNEL_ROW_CSS = { '& input': { minW: '0' } };
+const SLIDER_STACK_CSS = { minW: '0' };
+
export interface ColorPickerProps {
- /** The current color, as a `#rrggbb` (or any CSS-parseable) string. */
- value: string;
- /** Called with the new `#rrggbb` hex string as the user drags the area/slider or edits the hex input. */
- onValueChange: (hex: string) => void;
- /**
- * Called with the final `#rrggbb` hex when an interaction ends (pointer up on
- * the area/slider, or the hex input committing). Consumers that record undo
- * history use this to collapse a whole drag into one entry, mirroring the
- * `Slider` `onValueChangeEnd` pattern.
- */
- onValueChangeEnd?: (hex: string) => void;
/** Accessible label for the swatch trigger button. */
'aria-label': string;
+ disabled?: boolean;
size?: ColorPickerSize;
+ /**
+ * The swatch row: `true` (default) shows the workbench palette followed by
+ * recently committed colors, `false` hides it, and an array supplies an
+ * explicit palette instead.
+ */
+ swatches?: boolean | readonly string[];
+ /** The current color, as a `#rrggbb` (or `#rrggbbaa` under `withAlpha`) string. */
+ value: string;
+ /**
+ * Accept and emit `#rrggbbaa`, and show the alpha slider, alpha channel
+ * input, and a transparency checkerboard behind the trigger swatch.
+ */
+ withAlpha?: boolean;
+ /**
+ * Offer the browser's screen eyedropper. Chromium-only — the trigger is
+ * omitted entirely where `EyeDropper` is unavailable rather than rendering a
+ * button that does nothing. Ignored when `onSampleColor` is supplied.
+ */
+ withEyeDropper?: boolean;
+ /** Show the current value as text beside the trigger swatch. */
+ withValueText?: boolean;
+ /** Called as the user drags the area/sliders or edits a channel input. */
+ onValueChange: (value: string) => void;
+ /**
+ * Called with the final value when an interaction ends (pointer up on the
+ * area/slider, a channel input committing, or a swatch being picked).
+ * Consumers that record undo history use this to collapse a whole drag into
+ * one entry, mirroring the `Slider` `onValueChangeEnd` pattern.
+ */
+ onValueChangeEnd?: (value: string) => void;
+ /**
+ * Sample a color from somewhere the picker cannot reach itself — the canvas
+ * passes a sampler backed by its own eyedropper tool, which reads the
+ * composited document rather than the screen. Replaces the browser
+ * eyedropper when present. Resolves `null` when the user cancels.
+ */
+ onSampleColor?: () => Promise<string | null>;
}
+/**
+ * The colour channels a format exposes. Alpha is always dropped — it gets its
+ * own percentage field ({@link AlphaInput}) rather than Zag's unit-float one,
+ * and it belongs at the end of the row regardless of which format is showing.
+ */
+const useChannels = (format: ColorPickerFormat) =>
+ useMemo(() => getColorChannels(MACHINE_FORMAT[format]).filter((channel) => channel !== 'alpha'), [format]);
+
+/**
+ * Cycles HEX → RGB → HSL → HSB.
+ *
+ * A dropdown would name all four up front, but it has to portal out of the
+ * picker's own popover, and opening it reads as an outside interaction that
+ * dismisses the picker. Ark's built-in `FormatTrigger` cycles for the same
+ * reason; this keeps that behavior on workbench chrome.
+ */
+const FormatTrigger = ({
+ format,
+ onFormatChange,
+}: {
+ format: ColorPickerFormat;
+ onFormatChange: (format: ColorPickerFormat) => void;
+}) => {
+ const { t } = useTranslation();
+ const handleClick = useCallback(() => {
+ const index = COLOR_PICKER_FORMATS.indexOf(format);
+ onFormatChange(COLOR_PICKER_FORMATS[(index + 1) % COLOR_PICKER_FORMATS.length]);
+ }, [format, onFormatChange]);
+
+ return (
+ // `subtle` rather than `ghost`: a bare label beside two filled inputs reads
+ // as a caption, not something you can click to change the units.
+ <IconButton
+ aria-label={t('common.colorPicker.format')}
+ flexShrink="0"
+ fontSize="2xs"
+ fontWeight="medium"
+ size="xs"
+ variant="subtle"
+ w="10"
+ onClick={handleClick}
+ >
+ {format.toUpperCase()}
+ </IconButton>
+ );
+};
+
+/**
+ * A swatch that also reports a commit. Zag's `SwatchTrigger` sets the value and
+ * fires `onValueChange`, but never `onValueChangeEnd` — without this, every
+ * consumer that records undo history on commit (mask fills, shapes, gradients)
+ * would silently drop swatch picks from their history.
+ *
+ * The commit is *armed* here rather than emitted: Zag's own value change runs
+ * after this handler, so emitting directly would put the commit before the
+ * change and leave undo entries recording the pre-swatch color.
+ */
+const CommittingSwatch = ({ value, onArmCommit }: { value: string; onArmCommit: () => void }) => (
+ <ChakraColorPicker.SwatchTrigger value={value} onClick={onArmCommit}>
+ <ChakraColorPicker.Swatch value={value}>
+ <ChakraColorPicker.SwatchIndicator boxSize="2.5" />
+ </ChakraColorPicker.Swatch>
+ </ChakraColorPicker.SwatchTrigger>
+);
+
+/**
+ * Opacity as a whole percentage.
+ *
+ * Zag's own alpha `ChannelInput` renders the raw unit float — a field reading
+ * `0.501` next to a hex triplet is noise, and nobody types opacity that way.
+ * This edits the same channel in the units the rest of the app uses (layer
+ * opacity, brush opacity) and commits on blur so a drag-free edit is one entry.
+ */
+const AlphaInput = ({
+ alpha,
+ onAlphaChange,
+ onAlphaCommit,
+}: {
+ alpha: number;
+ onAlphaChange: (alpha: number) => void;
+ onAlphaCommit: () => void;
+}) => {
+ const { t } = useTranslation();
+ const [draft, setDraft] = useState<string | null>(null);
+ const handleChange = useCallback(
+ (event: ChangeEvent<HTMLInputElement>) => {
+ const raw = event.currentTarget.value;
+ setDraft(raw);
+ const parsed = Number.parseInt(raw, 10);
+ if (Number.isFinite(parsed)) {
+ onAlphaChange(Math.min(100, Math.max(0, parsed)) / 100);
+ }
+ },
+ [onAlphaChange]
+ );
+ const handleBlur = useCallback(() => {
+ setDraft(null);
+ onAlphaCommit();
+ }, [onAlphaCommit]);
+
+ return (
+ <Input
+ aria-label={t('common.colorPicker.opacity')}
+ className="colorPicker__channelInput"
+ flexShrink="0"
+ inputMode="numeric"
+ size="xs"
+ value={draft ?? String(Math.round(alpha * 100))}
+ w="12"
+ onBlur={handleBlur}
+ onChange={handleChange}
+ />
+ );
+};
+
/**
* Workbench color picker: a compact swatch trigger that opens a popover with a
- * saturation/hue area and a hex input. Wraps Chakra v3's composed
- * `ColorPicker.*` parts (chrome comes from the built-in `colorPicker` slot
- * recipe, which already reads workbench semantic tokens) — this is the single
- * import point, kept to exactly what `BrushOptions` needs.
+ * saturation/value area, hue and alpha sliders, an eyedropper, switchable
+ * HEX/RGB/HSL/HSB channel inputs, and a swatch row of the workbench palette
+ * plus recently committed colors. Composed from Chakra v3's `ColorPicker.*`
+ * parts; chrome comes from the `colorPicker` slot-recipe override in
+ * `theme/recipes.ts`.
*
* Internally, the picker's controlled value is kept as a full Chakra/Zag
* `Color` (which preserves hue/saturation independent of RGB), not a hex
* string — see `shouldSyncExternalColor` for why. The external API stays
- * hex-string based; hex is only produced at the `onValueChange` emit boundary.
+ * string based; hex is only produced at the emit boundary.
*/
export const ColorPicker = ({
'aria-label': ariaLabel,
+ disabled,
+ onSampleColor,
onValueChange,
onValueChangeEnd,
- size = 'xs',
+ size,
+ swatches = true,
value,
+ withAlpha = false,
+ withEyeDropper = true,
+ withValueText = false,
}: ColorPickerProps) => {
+ const { t } = useTranslation();
+ const format = useColorPickerFormat();
+ const recents = useRecentColors();
+ const channels = useChannels(format);
+
+ // Zag emits uppercase hex; the workbench stores and compares lowercase.
+ const toEmitted = useCallback(
+ (color: Color) => color.toString(withAlpha ? 'hexa' : 'hex').toLowerCase(),
+ [withAlpha]
+ );
+
+ const isSwatchCommitArmed = useRef(false);
+ const [isOpen, setIsOpen] = useState(false);
const [previousExternalValue, setPreviousExternalValue] = useState(value);
const [color, setColor] = useState<Color>(() => parseColor(value));
- const [lastEmittedHex, setLastEmittedHex] = useState(() => color.toString('hex'));
+ const [lastEmittedValue, setLastEmittedValue] = useState(() => toEmitted(color));
// Sync external -> internal only when the prop genuinely changed to
// something other than what we last emitted (see `shouldSyncExternalColor`).
if (value !== previousExternalValue) {
setPreviousExternalValue(value);
- if (shouldSyncExternalColor(value, previousExternalValue, lastEmittedHex)) {
+ if (shouldSyncExternalColor(value, previousExternalValue, lastEmittedValue)) {
setColor(parseColor(value));
}
}
+ const emit = useCallback(
+ (next: Color, isEnd: boolean) => {
+ setColor(next);
+ const emitted = toEmitted(next);
+ setLastEmittedValue(emitted);
+ onValueChange(emitted);
+ if (isEnd) {
+ recordRecentColor(emitted);
+ onValueChangeEnd?.(emitted);
+ }
+ },
+ [onValueChange, onValueChangeEnd, toEmitted]
+ );
+
const handleValueChange = useCallback(
(details: ColorPickerValueChangeDetails) => {
- setColor(details.value);
- const hex = details.value.toString('hex');
- setLastEmittedHex(hex);
- onValueChange(hex);
+ // A swatch pick is both a change and a commit; Zag only reports the
+ // change, so `CommittingSwatch` arms the commit and it lands here in the
+ // right order.
+ const isCommit = isSwatchCommitArmed.current;
+ isSwatchCommitArmed.current = false;
+ emit(details.value, isCommit);
},
- [onValueChange]
+ [emit]
);
+ const armSwatchCommit = useCallback(() => {
+ isSwatchCommitArmed.current = true;
+ }, []);
+
const handleValueChangeEnd = useCallback(
(details: ColorPickerValueChangeDetails) => {
- onValueChangeEnd?.(details.value.toString('hex'));
+ const emitted = toEmitted(details.value);
+ setLastEmittedValue(emitted);
+ recordRecentColor(emitted);
+ onValueChangeEnd?.(emitted);
},
- [onValueChangeEnd]
+ [onValueChangeEnd, toEmitted]
+ );
+
+ const alpha = withAlpha ? color.getChannelValue('alpha') : 1;
+
+ const handleAlphaChange = useCallback(
+ (next: number) => emit(color.withChannelValue('alpha', next) as Color, false),
+ [color, emit]
);
+ const handleAlphaCommit = useCallback(() => {
+ recordRecentColor(lastEmittedValue);
+ onValueChangeEnd?.(lastEmittedValue);
+ }, [lastEmittedValue, onValueChangeEnd]);
+
+ const handleOpenChange = useCallback((details: { open: boolean }) => setIsOpen(details.open), []);
+
+ const handleSampleColor = useCallback(async () => {
+ if (!onSampleColor) {
+ return;
+ }
+ // Get out of the way so the user can see (and click) what they're sampling.
+ setIsOpen(false);
+ const sampled = await onSampleColor();
+ if (sampled) {
+ emit(parseColor(sampled), true);
+ }
+ }, [emit, onSampleColor]);
+
+ const swatchList = useMemo(() => {
+ if (Array.isArray(swatches)) {
+ return swatches as readonly string[];
+ }
+ if (!swatches) {
+ return [];
+ }
+
+ const seen = new Set(DEFAULT_COLOR_SWATCHES.map((entry) => normalizeHex(entry)));
+
+ return [...DEFAULT_COLOR_SWATCHES, ...recents.filter((entry) => !seen.has(normalizeHex(entry)))];
+ }, [recents, swatches]);
+
+ // The browser eyedropper is Chromium-only; omit the trigger where it would
+ // do nothing. A canvas-backed sampler always wins when one is supplied.
+ const canUseScreenEyeDropper = withEyeDropper && typeof window !== 'undefined' && 'EyeDropper' in window;
+
return (
<ChakraColorPicker.Root
+ disabled={disabled}
+ format={MACHINE_FORMAT[format]}
lazyMount
+ open={isOpen}
size={size}
unmountOnExit
value={color}
+ onOpenChange={handleOpenChange}
onValueChange={handleValueChange}
onValueChangeEnd={handleValueChangeEnd}
>
<ChakraColorPicker.Control>
<ChakraColorPicker.Trigger aria-label={ariaLabel} data-fit-content>
+ {withAlpha ? <ChakraColorPicker.TransparencyGrid size={TRANSPARENCY_CHECK_SIZE} /> : null}
<ChakraColorPicker.ValueSwatch />
</ChakraColorPicker.Trigger>
+ {withValueText ? (
+ <Text color="fg.muted" fontSize="xs" fontVariantNumeric="tabular-nums">
+ {lastEmittedValue}
+ </Text>
+ ) : null}
</ChakraColorPicker.Control>
<Portal>
<ChakraColorPicker.Positioner>
@@ -95,11 +396,68 @@ export const ColorPicker = ({
<ChakraColorPicker.AreaBackground />
<ChakraColorPicker.AreaThumb />
</ChakraColorPicker.Area>
- <ChakraColorPicker.ChannelSlider channel="hue">
- <ChakraColorPicker.ChannelSliderTrack />
- <ChakraColorPicker.ChannelSliderThumb />
- </ChakraColorPicker.ChannelSlider>
- <ChakraColorPicker.Input />
+
+ <HStack align="center" gap="2">
+ {onSampleColor ? (
+ <IconButton
+ aria-label={t('common.colorPicker.sampleFromCanvas')}
+ size="xs"
+ variant="ghost"
+ onClick={handleSampleColor}
+ >
+ <Icon as={Pipette} boxSize="4" />
+ </IconButton>
+ ) : canUseScreenEyeDropper ? (
+ // `EyeDropperTrigger` is a bare Ark part, not an IconButton —
+ // rendered directly it has no icon and drops `variant`/`size`
+ // onto the DOM as raw attributes, collapsing to a 0x0 button.
+ // `asChild` puts the machine's behavior on workbench chrome, so
+ // both eyedropper branches look identical.
+ <ChakraColorPicker.EyeDropperTrigger asChild>
+ <IconButton aria-label={t('common.colorPicker.sampleFromScreen')} size="xs" variant="ghost">
+ <Icon as={Pipette} boxSize="4" />
+ </IconButton>
+ </ChakraColorPicker.EyeDropperTrigger>
+ ) : null}
+ <Stack css={SLIDER_STACK_CSS} flex="1" gap="1.5">
+ <ChakraColorPicker.ChannelSlider channel="hue">
+ <ChakraColorPicker.ChannelSliderTrack />
+ <ChakraColorPicker.ChannelSliderThumb />
+ </ChakraColorPicker.ChannelSlider>
+ {withAlpha ? (
+ <ChakraColorPicker.ChannelSlider channel="alpha">
+ <ChakraColorPicker.TransparencyGrid size={TRANSPARENCY_CHECK_SIZE} />
+ <ChakraColorPicker.ChannelSliderTrack />
+ <ChakraColorPicker.ChannelSliderThumb />
+ </ChakraColorPicker.ChannelSlider>
+ ) : null}
+ </Stack>
+ </HStack>
+
+ <HStack css={CHANNEL_ROW_CSS} gap="1">
+ <FormatTrigger format={format} onFormatChange={setColorPickerFormat} />
+ {format === 'hex' ? (
+ <ChakraColorPicker.ChannelInput channel="hex" flex="1" />
+ ) : (
+ channels.map((channel) => <ChakraColorPicker.ChannelInput key={channel} channel={channel} flex="1" />)
+ )}
+ {withAlpha ? (
+ <AlphaInput alpha={alpha} onAlphaChange={handleAlphaChange} onAlphaCommit={handleAlphaCommit} />
+ ) : null}
+ </HStack>
+
+ {swatchList.length > 0 ? (
+ <ChakraColorPicker.SwatchGroup
+ borderColor="border.subtle"
+ borderTopWidth="1px"
+ css={SWATCH_GROUP_CSS}
+ pt="2"
+ >
+ {swatchList.map((swatch) => (
+ <CommittingSwatch key={swatch} value={swatch} onArmCommit={armSwatchCommit} />
+ ))}
+ </ChakraColorPicker.SwatchGroup>
+ ) : null}
</ChakraColorPicker.Content>
</ChakraColorPicker.Positioner>
</Portal>
diff --git a/invokeai/frontend/webv2/src/platform/ui/color.test.ts b/invokeai/frontend/webv2/src/platform/ui/color.test.ts
new file mode 100644
index 0000000000..3b576175ad
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/color.test.ts
@@ -0,0 +1,124 @@
+import { describe, expect, it } from 'vitest';
+
+import { BLACK, formatHexColor, joinHexAlpha, normalizeHex, parseHexColor, splitHexAlpha } from './color';
+
+describe('parseHexColor', () => {
+ it('parses 6-digit hex as opaque', () => {
+ expect(parseHexColor('#ff8000')).toEqual({ a: 1, b: 0, g: 128, r: 255 });
+ });
+
+ it('parses 8-digit hex, scaling alpha to [0, 1]', () => {
+ expect(parseHexColor('#ff8000ff')).toEqual({ a: 1, b: 0, g: 128, r: 255 });
+ expect(parseHexColor('#ff800000')).toEqual({ a: 0, b: 0, g: 128, r: 255 });
+ expect(parseHexColor('#00000080').a).toBeCloseTo(128 / 255, 5);
+ });
+
+ it('expands 3- and 4-digit shorthand', () => {
+ expect(parseHexColor('#f80')).toEqual({ a: 1, b: 0, g: 136, r: 255 });
+ expect(parseHexColor('#f800')).toEqual({ a: 0, b: 0, g: 136, r: 255 });
+ });
+
+ it('accepts uppercase and a missing leading hash, and trims', () => {
+ expect(parseHexColor(' FF8000 ')).toEqual({ a: 1, b: 0, g: 128, r: 255 });
+ expect(parseHexColor('#FF8000')).toEqual(parseHexColor('#ff8000'));
+ });
+
+ it('falls back for garbage, wrong-length, and non-hex input', () => {
+ // 5 and 7 digits are truncated/mistyped values, not shorthand.
+ for (const value of ['', '#', 'rebeccapurple', '#ff', '#ff800', '#ff80000', '#ggghhh', 'var(--x)']) {
+ expect(parseHexColor(value)).toEqual(BLACK);
+ }
+ });
+
+ it('uses the supplied fallback', () => {
+ const white = { a: 1, b: 255, g: 255, r: 255 };
+ expect(parseHexColor('nope', white)).toEqual(white);
+ });
+});
+
+describe('formatHexColor', () => {
+ it('emits 6-digit hex by default and 8-digit under `alpha`', () => {
+ const color = { a: 0.5, b: 0, g: 128, r: 255 };
+ expect(formatHexColor(color)).toBe('#ff8000');
+ expect(formatHexColor(color, { alpha: true })).toBe('#ff800080');
+ });
+
+ it('emits lowercase', () => {
+ expect(formatHexColor({ a: 1, b: 255, g: 255, r: 255 })).toBe('#ffffff');
+ });
+
+ it('clamps out-of-range and non-finite channels', () => {
+ expect(formatHexColor({ a: 2, b: -5, g: 999, r: 300 }, { alpha: true })).toBe('#ffff00ff');
+ expect(formatHexColor({ a: Number.NaN, b: 0, g: 0, r: Number.NaN }, { alpha: true })).toBe('#000000ff');
+ });
+
+ it('rounds fractional channels', () => {
+ expect(formatHexColor({ a: 1, b: 0, g: 0, r: 127.6 })).toBe('#800000');
+ });
+});
+
+describe('round-trips', () => {
+ it('preserves 6-digit hex', () => {
+ for (const hex of ['#000000', '#ffffff', '#e07575', '#799ddb']) {
+ expect(formatHexColor(parseHexColor(hex))).toBe(hex);
+ }
+ });
+
+ it('preserves 8-digit hex', () => {
+ for (const hex of ['#00000000', '#ffffffff', '#e0757580', '#799ddb01']) {
+ expect(formatHexColor(parseHexColor(hex), { alpha: true })).toBe(hex);
+ }
+ });
+});
+
+describe('splitHexAlpha / joinHexAlpha', () => {
+ it('splits an 8-digit hex into rgb and unit alpha', () => {
+ expect(splitHexAlpha('#ff800080')).toEqual({ alpha: 128 / 255, hex: '#ff8000' });
+ });
+
+ it('treats a 6-digit hex as fully opaque', () => {
+ expect(splitHexAlpha('#ff8000')).toEqual({ alpha: 1, hex: '#ff8000' });
+ });
+
+ it('joins back to 8-digit hex', () => {
+ expect(joinHexAlpha('#ff8000', 1)).toBe('#ff8000ff');
+ expect(joinHexAlpha('#ff8000', 0)).toBe('#ff800000');
+ });
+
+ it('clamps alpha when joining', () => {
+ expect(joinHexAlpha('#ff8000', 5)).toBe('#ff8000ff');
+ expect(joinHexAlpha('#ff8000', -1)).toBe('#ff800000');
+ });
+
+ it('survives a split/join round trip', () => {
+ const original = '#12345678';
+ const { alpha, hex } = splitHexAlpha(original);
+ expect(joinHexAlpha(hex, alpha)).toBe(original);
+ });
+
+ it('ignores any alpha already on the rgb argument', () => {
+ expect(joinHexAlpha('#ff800000', 1)).toBe('#ff8000ff');
+ });
+});
+
+describe('normalizeHex', () => {
+ it('lowercases and expands shorthand', () => {
+ expect(normalizeHex('#FF8000')).toBe('#ff8000');
+ // Shorthand doubles each nibble: `f80` → `ff8800`.
+ expect(normalizeHex('F80')).toBe('#ff8800');
+ });
+
+ it('drops a fully-opaque alpha but keeps a partial one', () => {
+ expect(normalizeHex('#ff8000ff')).toBe('#ff8000');
+ expect(normalizeHex('#ff800080')).toBe('#ff800080');
+ });
+
+ it('returns the fallback verbatim for non-hex input', () => {
+ expect(normalizeHex('transparent', 'transparent')).toBe('transparent');
+ expect(normalizeHex('nope')).toBe('#000000');
+ });
+
+ it('makes case-different values comparable', () => {
+ expect(normalizeHex('#FF0000')).toBe(normalizeHex('#ff0000'));
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/color.ts b/invokeai/frontend/webv2/src/platform/ui/color.ts
new file mode 100644
index 0000000000..cffe7718fd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/color.ts
@@ -0,0 +1,127 @@
+/**
+ * Hex-string ↔ object color conversion for the workbench.
+ *
+ * The canonical object form is {@link RgbaColor}: `r`/`g`/`b` are integers in
+ * `[0, 255]` and `a` is a unit float in `[0, 1]`. That matches the generation
+ * settings' `infillColorValue` and the legacy app's `zRgbaColor`, so those
+ * consumers adapt with no extra arithmetic. The one consumer that differs —
+ * workflow `ColorField`, whose alpha is `[0, 255]` — scales at its own call
+ * site rather than forcing a second alpha convention through here.
+ *
+ * Parsing is deliberately tolerant: these values come from persisted documents,
+ * node fields, and hand-typed input, so anything unparseable falls back rather
+ * than throwing. Formatting always emits lowercase with a leading `#`.
+ *
+ * Pure module — no React, no Chakra, no DOM.
+ */
+
+/** An RGBA color. `r`/`g`/`b` are `[0, 255]` integers; `a` is a `[0, 1]` float. */
+export interface RgbaColor {
+ r: number;
+ g: number;
+ b: number;
+ a: number;
+}
+
+export interface FormatHexColorOptions {
+ /** Emit `#rrggbbaa` instead of `#rrggbb`. */
+ alpha?: boolean;
+}
+
+/** Opaque black — the fallback for anything unparseable. */
+export const BLACK: RgbaColor = { a: 1, b: 0, g: 0, r: 0 };
+
+/** `#rgb`, `#rgba`, `#rrggbb`, or `#rrggbbaa`, with an optional leading `#`. */
+const HEX_PATTERN = /^#?([0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
+
+const clampChannel = (value: number): number => {
+ if (!Number.isFinite(value)) {
+ return 0;
+ }
+
+ return Math.min(255, Math.max(0, Math.round(value)));
+};
+
+const clampAlpha = (value: number): number => {
+ if (!Number.isFinite(value)) {
+ return 1;
+ }
+
+ return Math.min(1, Math.max(0, value));
+};
+
+const toHexByte = (value: number): string => clampChannel(value).toString(16).padStart(2, '0');
+
+/** Expands a shorthand nibble (`f`) into a byte (`ff`). */
+const expandNibble = (nibble: string): number => parseInt(`${nibble}${nibble}`, 16);
+
+/** Parses any supported hex form, or `null` when the input is not one. */
+const tryParseHexColor = (value: string): RgbaColor | null => {
+ const match = HEX_PATTERN.exec(value.trim());
+
+ if (!match) {
+ return null;
+ }
+
+ const digits = match[1];
+
+ if (digits.length <= 4) {
+ return {
+ a: digits.length === 4 ? expandNibble(digits[3]) / 255 : 1,
+ b: expandNibble(digits[2]),
+ g: expandNibble(digits[1]),
+ r: expandNibble(digits[0]),
+ };
+ }
+
+ return {
+ a: digits.length === 8 ? parseInt(digits.slice(6, 8), 16) / 255 : 1,
+ b: parseInt(digits.slice(4, 6), 16),
+ g: parseInt(digits.slice(2, 4), 16),
+ r: parseInt(digits.slice(0, 2), 16),
+ };
+};
+
+/**
+ * Parses any supported hex form into an {@link RgbaColor}. Returns `fallback`
+ * (opaque black by default) for input that is not a 3/4/6/8-digit hex string.
+ */
+export const parseHexColor = (value: string, fallback: RgbaColor = BLACK): RgbaColor =>
+ tryParseHexColor(value) ?? fallback;
+
+/** Formats an {@link RgbaColor} as `#rrggbb`, or `#rrggbbaa` when `alpha` is set. */
+export const formatHexColor = (color: RgbaColor, options?: FormatHexColorOptions): string => {
+ const rgb = `#${toHexByte(color.r)}${toHexByte(color.g)}${toHexByte(color.b)}`;
+
+ return options?.alpha ? `${rgb}${toHexByte(clampAlpha(color.a) * 255)}` : rgb;
+};
+
+/**
+ * Splits a color into its `#rrggbb` part and a `[0, 1]` alpha, for consumers
+ * that store the two separately (gradient stops used to do this inline).
+ */
+export const splitHexAlpha = (value: string): { hex: string; alpha: number } => {
+ const color = parseHexColor(value);
+
+ return { alpha: color.a, hex: formatHexColor(color) };
+};
+
+/** Recombines a `#rrggbb` and a `[0, 1]` alpha into `#rrggbbaa`. */
+export const joinHexAlpha = (hex: string, alpha: number): string =>
+ formatHexColor({ ...parseHexColor(hex), a: clampAlpha(alpha) }, { alpha: true });
+
+/**
+ * Normalizes any supported hex form to lowercase `#rrggbb`, or `#rrggbbaa` when
+ * the input carries a non-opaque alpha. Used to compare values that may differ
+ * only in case or shorthand. Unparseable input returns `fallback` verbatim, so
+ * callers can pass through non-hex CSS colors untouched.
+ */
+export const normalizeHex = (value: string, fallback: string = '#000000'): string => {
+ const color = tryParseHexColor(value);
+
+ if (!color) {
+ return fallback;
+ }
+
+ return formatHexColor(color, { alpha: color.a < 1 });
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
new file mode 100644
index 0000000000..d25d4058bf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
@@ -0,0 +1,138 @@
+/**
+ * Shared state behind every {@link ColorPicker}: the default swatch palette, a
+ * most-recently-used list of committed colors, and the preferred channel
+ * format.
+ *
+ * Both persisted values are per browser rather than per account or project —
+ * like the command palette's frecency record, a picker's muscle memory should
+ * not reset when the user switches projects. Storage failures (quota, private
+ * mode, blocked cookies) are non-fatal: the picker still works, it just forgets.
+ */
+
+import { createExternalStore } from '@platform/state/externalStore';
+
+/** The channel layouts the picker can present. */
+export type ColorPickerFormat = 'hex' | 'rgb' | 'hsl' | 'hsb';
+
+export const COLOR_PICKER_FORMATS: readonly ColorPickerFormat[] = ['hex', 'rgb', 'hsl', 'hsb'];
+
+const RECENTS_STORAGE_KEY = 'invokeai:v7:webv2:color-recents';
+const FORMAT_STORAGE_KEY = 'invokeai:v7:webv2:color-format';
+const MAX_RECENTS = 12;
+
+/**
+ * The workbench palette: neutrals plus the regional-guidance mask hues, so a
+ * brush color and a mask fill picked from defaults read as one system.
+ *
+ * These values intentionally duplicate `REGIONAL_GUIDANCE_FILL_COLORS` in the
+ * canvas engine. `platform/` may not import `workbench/` (`platform-independence`)
+ * and the engine may not import back out (`canvas-engine-independence`), so a
+ * shared constant would have to live in a third module owned by neither.
+ */
+export const DEFAULT_COLOR_SWATCHES: readonly string[] = [
+ '#000000',
+ '#ffffff',
+ '#808080',
+ '#e07575',
+ '#dc9065',
+ '#fae150',
+ '#83d683',
+ '#799ddb',
+ '#a178d6',
+ '#d58bca',
+];
+
+const isColorPickerFormat = (value: unknown): value is ColorPickerFormat =>
+ typeof value === 'string' && (COLOR_PICKER_FORMATS as readonly string[]).includes(value);
+
+/**
+ * Reads a persisted string. Touching `localStorage` at all can throw
+ * (SecurityError when storage is disabled), not just `getItem` — both stay
+ * inside the guard.
+ */
+const readStored = (key: string): string | null => {
+ if (typeof window === 'undefined') {
+ return null;
+ }
+
+ try {
+ return window.localStorage.getItem(key);
+ } catch {
+ return null;
+ }
+};
+
+const writeStored = (key: string, value: string): void => {
+ if (typeof window === 'undefined') {
+ return;
+ }
+
+ try {
+ window.localStorage.setItem(key, value);
+ } catch {
+ // Quota or private-mode failures are non-fatal; these are conveniences.
+ }
+};
+
+const parseRecents = (raw: string | null): string[] => {
+ if (!raw) {
+ return [];
+ }
+
+ try {
+ const parsed = JSON.parse(raw) as unknown;
+
+ if (!Array.isArray(parsed)) {
+ return [];
+ }
+
+ return parsed.filter((item): item is string => typeof item === 'string').slice(0, MAX_RECENTS);
+ } catch {
+ return [];
+ }
+};
+
+interface ColorPickerSnapshot {
+ format: ColorPickerFormat;
+ recents: string[];
+}
+
+const readStoredFormat = (): ColorPickerFormat => {
+ const stored = readStored(FORMAT_STORAGE_KEY);
+
+ return isColorPickerFormat(stored) ? stored : 'hex';
+};
+
+const store = createExternalStore<ColorPickerSnapshot>({
+ format: readStoredFormat(),
+ recents: parseRecents(readStored(RECENTS_STORAGE_KEY)),
+});
+
+/**
+ * Promotes `color` to the front of the recents list. Callers record on commit
+ * (`onValueChangeEnd`) only — recording every drag frame would fill the list
+ * with the colors swept through on the way to the chosen one.
+ */
+export const recordRecentColor = (color: string): void => {
+ const normalized = color.toLowerCase();
+ const { recents } = store.getSnapshot();
+
+ if (recents[0] === normalized) {
+ return;
+ }
+
+ const next = [normalized, ...recents.filter((entry) => entry !== normalized)].slice(0, MAX_RECENTS);
+
+ store.patchSnapshot({ recents: next });
+ writeStored(RECENTS_STORAGE_KEY, JSON.stringify(next));
+};
+
+export const setColorPickerFormat = (format: ColorPickerFormat): void => {
+ store.patchSnapshot({ format });
+ writeStored(FORMAT_STORAGE_KEY, format);
+};
+
+export const useRecentColors = (): string[] => store.useSelector((snapshot) => snapshot.recents);
+
+export const useColorPickerFormat = (): ColorPickerFormat =>
+ store.useSelector((snapshot) => snapshot.format, Object.is);
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts
index 013b8bfb20..d13a562be8 100644
--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts
@@ -28,4 +28,33 @@ describe('shouldSyncExternalColor', () => {
it('does not sync when the previous and external values are identical, regardless of last emitted', () => {
expect(shouldSyncExternalColor('#123456', '#123456', '#abcdef')).toBe(false);
});
+
+ it('treats a differently-cased echo of what we emitted as our own round trip', () => {
+ expect(shouldSyncExternalColor('#FF0000', '#808080', '#ff0000')).toBe(false);
+ });
+
+ it('treats a shorthand echo of what we emitted as our own round trip', () => {
+ expect(shouldSyncExternalColor('#f00', '#808080', '#ff0000')).toBe(false);
+ });
+
+ it('treats an opaque 8-digit echo of a 6-digit emit as our own round trip', () => {
+ expect(shouldSyncExternalColor('#ff0000ff', '#808080', '#ff0000')).toBe(false);
+ });
+
+ it('syncs when only the alpha differs', () => {
+ // Under `withAlpha`, a consumer changing just the opacity is a real
+ // external change even though the RGB triplet is untouched.
+ expect(shouldSyncExternalColor('#ff000080', '#ff0000ff', '#ff0000ff')).toBe(true);
+ });
+
+ it('round-trips 8-digit values without re-syncing', () => {
+ expect(shouldSyncExternalColor('#ff000080', '#ff0000ff', '#FF000080')).toBe(false);
+ });
+
+ it('passes non-hex values through without treating them as equal', () => {
+ // Fallback-verbatim normalization means unparseable values still compare
+ // as themselves rather than collapsing to a shared sentinel.
+ expect(shouldSyncExternalColor('transparent', 'currentColor', 'currentColor')).toBe(true);
+ expect(shouldSyncExternalColor('transparent', 'currentColor', 'transparent')).toBe(false);
+ });
});
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts
index 784eed98ff..e38c86c006 100644
--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts
@@ -1,18 +1,32 @@
+import { normalizeHex } from './color';
+
/**
* True when `externalValue` (the latest `value` prop given to `ColorPicker`)
* should be re-parsed into the picker's internal `Color`, versus kept as-is.
*
- * We only want to re-sync from the external hex string when it reflects a
- * change the consumer made independently of the picker (e.g. a programmatic
- * reset) — not the round trip of the hex the picker *just emitted itself* via
+ * We only want to re-sync from the external string when it reflects a change
+ * the consumer made independently of the picker (e.g. a programmatic reset) —
+ * not the round trip of the value the picker *just emitted itself* via
* `onValueChange`. That round trip loses hue information for any grey/black/
* white color (saturation or value = 0, where hex/RGB is hue-agnostic), so
* re-parsing it on every render would snap the hue thumb back to whatever
* `parseColor` yields for an indeterminate hue — the picker would only ever
* be able to *emit* a new hue at S=0, never actually keep it.
+ *
+ * Values are compared after normalization, so a consumer that stores or echoes
+ * back a differently-cased or shorthand form of the same color (`#FF0000` for
+ * `#ff0000`, `#f00` for `#ff0000`, `#ff0000ff` for `#ff0000`) does not count as
+ * an independent change and does not clobber the internal hue.
*/
export const shouldSyncExternalColor = (
externalValue: string,
previousExternalValue: string,
- lastEmittedHex: string
-): boolean => externalValue !== previousExternalValue && externalValue !== lastEmittedHex;
+ lastEmittedValue: string
+): boolean => {
+ const external = normalizeHex(externalValue, externalValue);
+
+ return (
+ external !== normalizeHex(previousExternalValue, previousExternalValue) &&
+ external !== normalizeHex(lastEmittedValue, lastEmittedValue)
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/index.ts b/invokeai/frontend/webv2/src/platform/ui/index.ts
index 4dd7b61375..562fc819f7 100644
--- a/invokeai/frontend/webv2/src/platform/ui/index.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/index.ts
@@ -1,4 +1,5 @@
export * from './Button';
+export * from './color';
export * from './ColorPicker';
export * from './Combobox';
export * from './ConfirmDialog';
diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
index e4bac9614f..39cd5f5b6c 100644
--- a/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/theme/recipes.ts
@@ -432,6 +432,98 @@ export const progressCircleSlotRecipe = defineSlotRecipe({
},
});
+/**
+ * Color picker chrome: the popover surface, area, sliders, swatches, and
+ * channel inputs, aligned with the rest of the workbench controls. This was the
+ * last built-in still rendering Chakra's stock chrome, so it was the only
+ * control that did not track the active theme.
+ *
+ * Extends the default rather than replacing it: the stock recipe folds
+ * `colorSwatchRecipe.base` into `swatch` and `inputRecipe.base` into
+ * `channelInput`, and its `size` variants are what define `--swatch-size`,
+ * `--slider-height`, and `--thumb-size`. Replacing wholesale renders every
+ * thumb and swatch at zero size — the same failure the tooltip recipe above
+ * documents for `--arrow-size`.
+ */
+export const colorPickerSlotRecipe = defineSlotRecipe({
+ ...chakraSlotRecipes.colorPicker,
+ base: {
+ ...chakraSlotRecipes.colorPicker.base,
+ content: {
+ ...chakraSlotRecipes.colorPicker.base?.content,
+ ...dropdownContent,
+ // Wide enough for a full ten-swatch row at its natural size; narrower and
+ // the swatches, the format button, and the channel inputs all crowd.
+ gap: '2',
+ p: '2',
+ width: '64',
+ },
+ area: {
+ ...chakraSlotRecipes.colorPicker.base?.area,
+ // Denser than the stock 180px, which dwarfs the workbench tool bars.
+ height: '140px',
+ // Hairline ring so the area does not float on the light theme's surface.
+ boxShadow: 'inset 0 0 0 1px {colors.border.subtle}',
+ },
+ areaThumb: {
+ ...chakraSlotRecipes.colorPicker.base?.areaThumb,
+ // The white ring alone disappears on light colors; the outer hairline
+ // keeps the thumb legible across the whole area.
+ boxShadow: '0 0 0 1px {colors.border.image}',
+ },
+ channelSliderThumb: {
+ ...chakraSlotRecipes.colorPicker.base?.channelSliderThumb,
+ boxShadow: '0 0 0 1px {colors.border.image}',
+ },
+ channelSliderTrack: {
+ ...chakraSlotRecipes.colorPicker.base?.channelSliderTrack,
+ // Stock hardcodes rgba(0,0,0,0.1), which vanishes on the dark ramps.
+ boxShadow: 'inset 0 0 0 1px {colors.border.subtle}',
+ },
+ swatch: {
+ ...chakraSlotRecipes.colorPicker.base?.swatch,
+ borderRadius: 'l1',
+ // Without a hairline, white and fully transparent swatches are invisible.
+ boxShadow: 'inset 0 0 0 1px {colors.border.image}',
+ },
+ swatchTrigger: {
+ ...chakraSlotRecipes.colorPicker.base?.swatchTrigger,
+ borderColor: 'transparent',
+ borderRadius: 'l1',
+ borderWidth: '1px',
+ transitionDuration: 'fast',
+ transitionProperty: 'border-color',
+ _hover: { borderColor: 'border.emphasized' },
+ _focusVisible: {
+ outline: '2px solid',
+ outlineColor: 'accent.solid',
+ outlineOffset: '1px',
+ },
+ },
+ channelInput: {
+ ...chakraSlotRecipes.colorPicker.base?.channelInput,
+ ...formControlInteraction,
+ fontVariantNumeric: 'tabular-nums',
+ px: '1',
+ textAlign: 'center',
+ },
+ channelText: {
+ ...chakraSlotRecipes.colorPicker.base?.channelText,
+ color: 'fg.subtle',
+ textStyle: '2xs',
+ },
+ transparencyGrid: {
+ ...chakraSlotRecipes.colorPicker.base?.transparencyGrid,
+ borderRadius: 'inherit',
+ },
+ },
+ defaultVariants: {
+ ...chakraSlotRecipes.colorPicker.defaultVariants,
+ // Workbench density — stock defaults to `md`.
+ size: 'xs',
+ },
+});
+
/* -------------------------------------------------------------------------- *
* Reusable UI recipes (consumed through Platform UI wrappers)
* -------------------------------------------------------------------------- */
diff --git a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts b/invokeai/frontend/webv2/src/platform/ui/theme/system.ts
index 2dc4dd7058..c31c2eeddd 100644
--- a/invokeai/frontend/webv2/src/platform/ui/theme/system.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/theme/system.ts
@@ -1,6 +1,7 @@
import { createSystem, defaultConfig, defineConfig } from '@chakra-ui/react';
import {
+ colorPickerSlotRecipe,
comboboxSlotRecipe,
dialogSlotRecipe,
inputRecipe,
@@ -281,6 +282,7 @@ const config = defineConfig({
textarea: textareaRecipe,
},
slotRecipes: {
+ colorPicker: colorPickerSlotRecipe,
combobox: comboboxSlotRecipe,
dialog: dialogSlotRecipe,
menu: menuSlotRecipe,
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index 4b5d84a777..8907038760 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -342,6 +342,13 @@ export interface CanvasEngineToolCapability extends CanvasToolCapability {
canTargetLayerFromContextMenu(): boolean;
handleEscapePriority(options: { gestureWasActive: boolean }): void;
onStrokeCommitted(listener: (event: StrokeCommittedEvent) => void): () => void;
+ /**
+ * Arms the eyedropper for a single sample of the composited document,
+ * resolving with the picked `#rrggbb` or `null` if the user cancels (Escape,
+ * another tool, or the engine going away). Restores the previously active
+ * tool either way. Backs the color picker's eyedropper button.
+ */
+ requestColorSample(): Promise<string | null>;
setInteractionLocked(locked: boolean): void;
}
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
index aa16f04d47..84186d5f1e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -866,6 +866,16 @@ 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.
+ */
+ let pendingColorSample: { previousToolId: ToolId; resolve: (hex: string | null) => void } | null = null;
+
const toolContext: ToolContext = {
applyTransform: () => applyTransform(),
backend,
@@ -908,6 +918,13 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
getSamInteraction: () => stores.samInteraction.get(),
openTextCreate: (docPoint) => openTextCreate(docPoint),
openTextEdit: (layerId) => openTextEdit(layerId),
+ resolveColorSample: (hex) => {
+ if (!pendingColorSample) {
+ return false;
+ }
+ settleColorSample(hex, true);
+ return true;
+ },
setLayerTransformOverride: (layerId, override) => {
if (override) {
transformOverrides.set(layerId, override);
@@ -1583,8 +1600,47 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
stepBrushSize: stepActiveBrushSize,
updateCursor,
});
- const setTool = (toolId: ToolId, options?: { temporary?: boolean }): void =>
+ /**
+ * Settles a pending one-shot color sample. `restoreTool` puts the user back
+ * on whatever they were holding before reaching for the eyedropper; callers
+ * that are themselves switching tools skip it, so the switch they asked for
+ * wins rather than being immediately undone.
+ */
+ const settleColorSample = (hex: string | null, restoreTool: boolean): void => {
+ const pending = pendingColorSample;
+ if (!pending) {
+ return;
+ }
+ pendingColorSample = null;
+ pending.resolve(hex);
+ if (restoreTool) {
+ interactionController.setTool(pending.previousToolId);
+ }
+ };
+
+ const setTool = (toolId: ToolId, options?: { temporary?: boolean }): void => {
+ // Any move off the eyedropper abandons the sample the caller is awaiting.
+ if (toolId !== 'colorPicker') {
+ settleColorSample(null, false);
+ }
interactionController.setTool(toolId, options);
+ };
+
+ /**
+ * 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).
+ */
+ 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 };
+ interactionController.setTool('colorPicker');
+ });
+ };
/**
* The engine's Escape priority ladder, run by the pointer pipeline AFTER it
@@ -1598,6 +1654,12 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
* wiring and node tests (the real DOM keydown listener can't run in node-env).
*/
const handleEscapePriority = ({ gestureWasActive }: { gestureWasActive: boolean }): void => {
+ // An armed eyedropper is the most recent thing the user opted into, so it
+ // is the first thing Escape takes back.
+ if (pendingColorSample) {
+ settleColorSample(null, true);
+ return;
+ }
if (stores.textEditSession.get()) {
cancelTextEdit();
return;
@@ -2181,6 +2243,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
// Drop any guarded filter previews outright — the engine is going away, so
// there's no render loop left to invalidate for them.
cleanup.run(() => antsAnimator.stop());
+ // No render loop left to sample with; release any awaited eyedropper.
+ cleanup.run(() => settleColorSample(null, false));
cleanup.run(() => activeTool()?.onDeactivate?.(toolContext));
cleanup.run(unsubscribeViewport);
cleanup.run(unsubscribeBrushOptions);
@@ -2537,6 +2601,7 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
canTargetLayerFromContextMenu,
handleEscapePriority,
onStrokeCommitted,
+ requestColorSample,
setInteractionLocked,
};
const layersCapability: CanvasEngineLayerCapability = {
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 8c5ff82348..2c0558a4e4 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
@@ -207,4 +207,43 @@ describe('color picker tool', () => {
const tool = createColorPickerTool();
expect(tool.cursor?.({} as ToolContext)).toBe('crosshair');
});
+
+ describe('one-shot color sample requests', () => {
+ it('hands the sample to a pending request instead of the brush color', () => {
+ const h = createHarness(makeDoc());
+ const tool = createColorPickerTool();
+ const defaultColor = h.ctx.stores.brushOptions.get().color;
+ const resolveColorSample = vi.fn(() => true);
+ h.ctx.resolveColorSample = resolveColorSample;
+
+ down(tool, h.ctx, pointer(10, 10));
+
+ expect(resolveColorSample).toHaveBeenCalledWith('#0a141e');
+ expect(h.ctx.stores.brushOptions.get().color).toBe(defaultColor);
+ });
+
+ it('falls through to the brush color when no request is pending', () => {
+ // The alt-hold flow: `resolveColorSample` exists but reports nothing armed.
+ const h = createHarness(makeDoc());
+ const tool = createColorPickerTool();
+ const resolveColorSample = vi.fn(() => false);
+ h.ctx.resolveColorSample = resolveColorSample;
+
+ down(tool, h.ctx, pointer(10, 10));
+
+ expect(resolveColorSample).toHaveBeenCalledWith('#0a141e');
+ expect(h.ctx.stores.brushOptions.get().color).toBe('#0a141e');
+ });
+
+ it('does not consult a request when there is nothing to sample', () => {
+ const h = createHarness(null);
+ const tool = createColorPickerTool();
+ const resolveColorSample = vi.fn(() => true);
+ h.ctx.resolveColorSample = resolveColorSample;
+
+ down(tool, h.ctx, pointer(10, 10));
+
+ expect(resolveColorSample).not.toHaveBeenCalled();
+ });
+ });
});
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 6d0b0cf5b2..125b437f82 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
@@ -30,7 +30,11 @@ const updateCursorRing = (ctx: ToolContext, input: PointerInput): void => {
ctx.invalidate({ overlay: true });
};
-/** Samples the composited color under `input` and writes it into the brush color option, if pickable. */
+/**
+ * Samples the composited color under `input`. A one-shot request made from
+ * outside the canvas (a color picker's eyedropper) claims the sample first;
+ * otherwise it lands in the brush color option as it always has.
+ */
const pickColorAt = (ctx: ToolContext, input: PointerInput): void => {
const doc = ctx.getDocument();
if (!doc) {
@@ -41,6 +45,9 @@ const pickColorAt = (ctx: ToolContext, input: PointerInput): void => {
return;
}
const hex = rgbaToHex(sample.r, sample.g, sample.b);
+ if (ctx.resolveColorSample?.(hex)) {
+ return;
+ }
const opts = ctx.stores.brushOptions.get();
if (hex !== opts.color) {
ctx.stores.brushOptions.set({ ...opts, color: hex });
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 02096fe0c1..fcd380d39d 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -150,6 +150,14 @@ export interface ToolContext {
getSamInteraction?(): SamInteractionState | null;
/** Sets (or clears) the brush cursor ring drawn on the overlay. */
setOverlayCursor(cursor: OverlayCursor | null): void;
+ /**
+ * Hands a sampled color to a one-shot request made from outside the canvas
+ * (a color picker's eyedropper button), returning whether one was pending.
+ * The color-picker tool calls this before falling through to its default
+ * behavior of writing the brush color, so the alt-hold flow is unaffected.
+ * Absent in minimal test harnesses.
+ */
+ resolveColorSample?(hex: string): boolean;
/**
* 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 82f4775f2a..83fd182ee1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/GenerateCanvasCompositingSection.tsx
@@ -16,7 +16,7 @@ import type { CanvasCoherenceMode, CanvasInfillMethod } from '@workbench/widgets
import { createListCollection, NumberInput, Stack } from '@chakra-ui/react';
import { GenerationSettingsSection } from '@features/generation/components';
-import { Field, Select } from '@platform/ui';
+import { ColorPicker, Field, formatHexColor, parseHexColor, Select } from '@platform/ui';
import {
CANVAS_COHERENCE_EDGE_SIZE_MAX,
CANVAS_COMPOSITING_KEYS,
@@ -121,6 +121,17 @@ export const GenerateCanvasCompositingSection = () => {
[patch]
);
+ // `infillColorValue` is already `{ r, g, b }` 0-255 plus a unit alpha, which
+ // is exactly the shape the platform color helpers speak.
+ const infillColor = formatHexColor(settings.infillColorValue, { alpha: true });
+
+ const handleInfillColorChange = useCallback(
+ (color: string) => {
+ patch({ [CANVAS_COMPOSITING_KEYS.infillColorValue]: parseHexColor(color) });
+ },
+ [patch]
+ );
+
const opt = (key: string) => t(`widgets.generate.compositingOptions.${key}`);
return (
@@ -137,6 +148,16 @@ export const GenerateCanvasCompositingSection = () => {
onValueChange={handleInfillChange}
/>
</Field>
+ {settings.infillMethod === 'color' ? (
+ <Field label={opt('infillColorValue')}>
+ <ColorPicker
+ aria-label={opt('infillColorValue')}
+ value={infillColor}
+ withAlpha
+ onValueChange={handleInfillColorChange}
+ />
+ </Field>
+ ) : null}
<Field label={opt('coherenceMode')}>
<Select
aria-label={opt('coherenceMode')}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx
index 95c20092ba..75d129db76 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/BrushOptions.tsx
@@ -4,6 +4,7 @@ import { HStack, NumberInput } from '@chakra-ui/react';
import { ColorPicker, Slider, ToggleIconButton } from '@platform/ui';
import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/api';
import { useBrushOptions } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
import { DropletIcon, PenLineIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -69,6 +70,7 @@ export const BrushOptions = ({ engine }: ToolOptionsComponentProps) => {
(hex: string) => engine.interaction.set('brushOptions', { ...options, color: hex }),
[engine, options]
);
+ const sampleColor = useColorSampler(engine);
const onPressureWidthToggle = useCallback(
(checked: boolean) => engine.interaction.set('brushOptions', { ...options, pressureAffectsWidth: checked }),
@@ -85,6 +87,7 @@ export const BrushOptions = ({ engine }: ToolOptionsComponentProps) => {
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.brushColor')}
value={options.color}
+ onSampleColor={sampleColor}
onValueChange={onColorChange}
/>
<HStack align="center" gap="1.5">
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx
index 958ee5ccee..8d0677490a 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/GradientOptions.tsx
@@ -4,6 +4,7 @@ import type { CanvasLayerSourceContract, GradientStop, GradientToolOptions } fro
import { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/react';
import { ColorPicker, Select } from '@platform/ui';
import { useGradientOptions } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -21,35 +22,17 @@ interface SelectedGradient {
const SELECT_POSITIONING = { placement: 'top-start', sameWidth: false } as const;
const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;
-const clamp01 = (v: number): number => Math.min(1, Math.max(0, v));
-
-/** Splits a stop color into a `#rrggbb` part (for the picker) and an alpha in [0,1]. */
-const splitColor = (color: string): { rgb: string; alpha: number } => {
- const match = /^#([0-9a-f]{6})([0-9a-f]{2})?$/i.exec(color.trim());
- if (match) {
- return { alpha: match[2] !== undefined ? parseInt(match[2], 16) / 255 : 1, rgb: `#${match[1]}` };
- }
- return { alpha: 1, rgb: '#000000' };
-};
-
-/** Recombines a `#rrggbb` and an alpha into an `#rrggbbaa` string. */
-const joinColor = (rgb: string, alpha: number): string => {
- const a = Math.round(clamp01(alpha) * 255)
- .toString(16)
- .padStart(2, '0');
- return `${rgb}${a}`;
-};
-
/**
* Gradient tool options: kind (linear/radial), angle (degrees), and a MINIMAL
- * two-stop editor — start/end color with per-stop opacity. Edits set defaults
- * for the next created gradient AND apply to a selected gradient layer (colors
- * commit one history entry on interaction end; discrete edits commit at once).
- * A full multi-stop editor is a follow-up.
+ * two-stop editor — start/end color, each carrying its own alpha. Edits set
+ * defaults for the next created gradient AND apply to a selected gradient layer
+ * (colors commit one history entry on interaction end; discrete edits commit at
+ * once). A full multi-stop editor is a follow-up.
*/
export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
const options = useGradientOptions(engine);
+ const sampleColor = useColorSampler(engine);
const selected = useActiveProjectSelector(
(project): SelectedGradient | null => {
@@ -70,8 +53,6 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
const stops = selected ? selected.source.stops : options.stops;
const start = stops[0] ?? { color: '#000000ff', offset: 0 };
const end = stops[stops.length - 1] ?? { color: '#ffffffff', offset: 1 };
- const startParts = splitColor(start.color);
- const endParts = splitColor(end.color);
const kindCollection = useMemo(
() =>
@@ -130,39 +111,14 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
[applyGradient, kind, stops]
);
- const onStartColorChange = useCallback(
- (hex: string) => setStopColor(0, joinColor(hex, startParts.alpha), false),
- [setStopColor, startParts.alpha]
- );
- const onStartColorEnd = useCallback(
- (hex: string) => setStopColor(0, joinColor(hex, startParts.alpha), true),
- [setStopColor, startParts.alpha]
- );
- const onStartOpacity = useCallback(
- ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {
- if (Number.isFinite(valueAsNumber)) {
- setStopColor(0, joinColor(startParts.rgb, clamp01(valueAsNumber / 100)), true);
- }
- },
- [setStopColor, startParts.rgb]
- );
+ const onStartColorChange = useCallback((color: string) => setStopColor(0, color, false), [setStopColor]);
+ const onStartColorEnd = useCallback((color: string) => setStopColor(0, color, true), [setStopColor]);
const onEndColorChange = useCallback(
- (hex: string) => setStopColor(lastIndex, joinColor(hex, endParts.alpha), false),
- [endParts.alpha, lastIndex, setStopColor]
- );
- const onEndColorEnd = useCallback(
- (hex: string) => setStopColor(lastIndex, joinColor(hex, endParts.alpha), true),
- [endParts.alpha, lastIndex, setStopColor]
- );
- const onEndOpacity = useCallback(
- ({ valueAsNumber }: ChakraNumberInput.ValueChangeDetails) => {
- if (Number.isFinite(valueAsNumber)) {
- setStopColor(lastIndex, joinColor(endParts.rgb, clamp01(valueAsNumber / 100)), true);
- }
- },
- [endParts.rgb, lastIndex, setStopColor]
+ (color: string) => setStopColor(lastIndex, color, false),
+ [lastIndex, setStopColor]
);
+ const onEndColorEnd = useCallback((color: string) => setStopColor(lastIndex, color, true), [lastIndex, setStopColor]);
return (
<HStack align="center" gap="3">
@@ -203,21 +159,12 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
</Text>
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.gradientStart')}
- value={startParts.rgb}
+ value={start.color}
+ withAlpha
+ onSampleColor={sampleColor}
onValueChange={onStartColorChange}
onValueChangeEnd={onStartColorEnd}
/>
- <NumberInput.Root
- max={100}
- min={0}
- size="xs"
- value={String(Math.round(startParts.alpha * 100))}
- w="4rem"
- onValueChange={onStartOpacity}
- >
- <NumberInput.Control />
- <NumberInput.Input aria-label={t('widgets.canvas.toolOptions.gradientStartOpacity')} fontSize="xs" />
- </NumberInput.Root>
</HStack>
<HStack align="center" gap="1.5">
@@ -226,21 +173,12 @@ export const GradientOptions = ({ engine }: ToolOptionsComponentProps) => {
</Text>
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.gradientEnd')}
- value={endParts.rgb}
+ value={end.color}
+ withAlpha
+ onSampleColor={sampleColor}
onValueChange={onEndColorChange}
onValueChangeEnd={onEndColorEnd}
/>
- <NumberInput.Root
- max={100}
- min={0}
- size="xs"
- value={String(Math.round(endParts.alpha * 100))}
- w="4rem"
- onValueChange={onEndOpacity}
- >
- <NumberInput.Control />
- <NumberInput.Input aria-label={t('widgets.canvas.toolOptions.gradientEndOpacity')} fontSize="xs" />
- </NumberInput.Root>
</HStack>
</HStack>
);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
index be25dd31a0..792451d657 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/ShapeOptions.tsx
@@ -5,6 +5,7 @@ import { createListCollection, HStack, NumberInput, Text } from '@chakra-ui/reac
import { ColorPicker, Select, ToggleIconButton } from '@platform/ui';
import { MAX_SHAPE_STROKE_WIDTH } from '@workbench/canvas-engine/api';
import { useShapeOptions } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { PaintBucketIcon, SquareIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -36,6 +37,7 @@ const SELECT_TRIGGER_PROPS = { minW: '6rem' } as const;
export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
const options = useShapeOptions(engine);
+ const sampleColor = useColorSampler(engine);
const selected = useActiveProjectSelector(
(project): SelectedShape | null => {
@@ -151,6 +153,7 @@ export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.shapeFill')}
value={fill}
+ onSampleColor={sampleColor}
onValueChange={onFillChange}
onValueChangeEnd={onFillChangeEnd}
/>
@@ -169,6 +172,7 @@ export const ShapeOptions = ({ engine }: ToolOptionsComponentProps) => {
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.shapeStroke')}
value={stroke}
+ onSampleColor={sampleColor}
onValueChange={onStrokeChange}
onValueChangeEnd={onStrokeChangeEnd}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx
index e2e2eb9ea4..8a3ae57e02 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/tool-options/TextOptions.tsx
@@ -10,6 +10,7 @@ import {
TEXT_FONT_WEIGHTS,
} from '@workbench/canvas-engine/api';
import { useTextEditSession, useTextOptions } from '@workbench/widgets/canvas/engineStoreHooks';
+import { useColorSampler } from '@workbench/widgets/canvas/useColorSampler';
import { useActiveProjectSelector } from '@workbench/WorkbenchContext';
import { AlignCenterIcon, AlignLeftIcon, AlignRightIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
@@ -87,6 +88,7 @@ const AlignButton = ({
export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {
const { t } = useTranslation();
const options = useTextOptions(engine);
+ const sampleColor = useColorSampler(engine);
const session = useTextEditSession(engine);
const selected = useActiveProjectSelector(
@@ -254,6 +256,7 @@ export const TextOptions = ({ engine }: ToolOptionsComponentProps) => {
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.textColor')}
value={color}
+ onSampleColor={sampleColor}
onValueChange={onColorChange}
onValueChangeEnd={onColorChangeEnd}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts
new file mode 100644
index 0000000000..aef49e5195
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/useColorSampler.ts
@@ -0,0 +1,24 @@
+/**
+ * Binds a color picker's eyedropper to the canvas.
+ *
+ * The browser's `EyeDropper` API only reads the composited *screen*, which is
+ * Chromium-only and picks up whatever chrome happens to sit over the canvas.
+ * The engine already owns a better sampler — the color-picker tool reads the
+ * composited document through the layer cache — so any picker rendered
+ * 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.
+ */
+
+import type { CanvasEngineToolCapability } from '@workbench/canvas-engine/api';
+
+import { useCallback } from 'react';
+
+/** The narrowest engine slice this needs, so callers holding a `Pick<>` still fit. */
+export interface ColorSamplerEngine {
+ readonly tools: Pick<CanvasEngineToolCapability, 'requestColorSample'>;
+}
+
+export const useColorSampler = (engine: ColorSamplerEngine): (() => Promise<string | null>) =>
+ useCallback(() => engine.tools.requestColorSample(), [engine]);