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): project color pair with a Color pane (K0-K2)

Josh Corbett936d00d82b87
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index f7b52595f8..c9d8f0b18f 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -179,7 +179,10 @@
"format": "Color format",
"sampleFromCanvas": "Pick a color from the canvas",
"sampleFromScreen": "Pick a color from the screen",
- "opacity": "Opacity (%)"
+ "opacity": "Opacity (%)",
+ "hue": "Hue",
+ "saturationValue": "Saturation and value",
+ "saturationValueText": "Saturation {{saturation}}%, value {{value}}%"
},
"configure": "Configure",
"copy": "Copy",
@@ -1535,7 +1538,9 @@
"upscale": "Upscale",
"versionStatus": "Version",
"workflow": "Workflow",
- "video": "Video"
+ "video": "Video",
+ "color": "Color",
+ "swatches": "Swatches"
},
"generate": {
"activeCount_one": "{{count}} active",
@@ -2226,7 +2231,9 @@
"toggleNonRasterLayers": "Hide control, guidance and mask layers",
"undo": "Undo canvas edit",
"groupLayers": "Group selected layers",
- "ungroupLayers": "Ungroup selected layers"
+ "ungroupLayers": "Ungroup selected layers",
+ "swapColors": "Swap foreground and background colors",
+ "resetColors": "Reset colors to black and white"
},
"contextMenu": {
"createError": "Couldn't create from BBox",
@@ -2982,6 +2989,32 @@
"expand": "Expand editor panes",
"resize": "Resize editor panes",
"tabs": "Layer editor panes"
+ },
+ "colorPane": {
+ "addToPalette": "Add current color to palette",
+ "background": "Background color",
+ "channels": {
+ "blue": "Blue",
+ "brightness": "Brightness",
+ "green": "Green",
+ "hex": "Hex color",
+ "hue": "Hue",
+ "lightness": "Lightness",
+ "red": "Red",
+ "saturation": "Saturation"
+ },
+ "collapse": "Collapse color pane",
+ "expand": "Expand color pane",
+ "foreground": "Foreground color",
+ "format": "Color value format",
+ "palette": "Project palette",
+ "pickerModeBox": "Switch to box picker",
+ "pickerModeWheel": "Switch to wheel picker",
+ "recents": "Recent colors",
+ "removeSwatchHint": "{{color}} — right-click or press Delete to remove",
+ "resize": "Resize color pane",
+ "swatches": "Swatches",
+ "tabs": "Color panes"
}
},
"gallery": {
diff --git a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx
index 58a294fd21..df60c9e2b5 100644
--- a/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx
+++ b/invokeai/frontend/webv2/src/platform/ui/ColorPicker.tsx
@@ -180,17 +180,21 @@ export const ColorPicker = ({
const isSwatchCommitArmed = useRef(false);
const [isOpen, setIsOpen] = useState(false);
+ const [isAwaitingEcho, setIsAwaitingEcho] = useState(false);
const [previousExternalValue, setPreviousExternalValue] = useState(value);
const [color, setColor] = useState<Color>(() => parseColor(value));
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`).
+ // something other than our own emit's round trip (see `shouldSyncExternalColor`).
if (value !== previousExternalValue) {
setPreviousExternalValue(value);
- if (shouldSyncExternalColor(value, previousExternalValue, lastEmittedValue)) {
+ if (shouldSyncExternalColor(value, previousExternalValue, lastEmittedValue, isAwaitingEcho)) {
setColor(parseColor(value));
}
+ if (isAwaitingEcho) {
+ setIsAwaitingEcho(false);
+ }
}
const emit = useCallback(
@@ -198,6 +202,7 @@ export const ColorPicker = ({
setColor(next);
const emitted = toEmitted(next);
setLastEmittedValue(emitted);
+ setIsAwaitingEcho(true);
onValueChange(emitted);
if (isEnd) {
recordRecentColor(emitted);
@@ -227,6 +232,7 @@ export const ColorPicker = ({
(details: ColorPickerValueChangeDetails) => {
const emitted = toEmitted(details.value);
setLastEmittedValue(emitted);
+ setIsAwaitingEcho(true);
recordRecentColor(emitted);
onValueChangeEnd?.(emitted);
},
diff --git a/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsx
new file mode 100644
index 0000000000..2139825fcf
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/HsvBoxPicker.tsx
@@ -0,0 +1,246 @@
+import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from 'react';
+
+import { Box, Stack } from '@chakra-ui/react';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { HsvColor } from './hsv';
+
+import { hsvToHex } from './hsv';
+
+const THUMB_SIZE_PX = 12;
+const HUE_STRIP_HEIGHT_PX = 12;
+const HUE_STEP = 2;
+const HUE_STEP_LARGE = 15;
+const SV_STEP = 0.02;
+const SV_STEP_LARGE = 0.1;
+
+const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));
+
+const THUMB_FOCUS_PROPS = { outline: '2px solid {colors.accent.solid}', outlineOffset: '2px' };
+
+const HUE_STRIP_CSS = {
+ background: 'linear-gradient(to right, red, yellow, lime, cyan, blue, magenta, red)',
+};
+
+/**
+ * The box-mode HSV picker: a saturation/value square under the hue, with a hue
+ * strip beneath — the layout the popover picker uses, sharing the wheel's
+ * `HsvColor` contract so the color pane can flip between the two. The square's
+ * shading is exact: white→hue across saturation, multiplied down to black by
+ * value, which is precisely two stacked linear gradients.
+ */
+export const HsvBoxPicker = ({
+ disabled = false,
+ heightPx = 140,
+ onChange,
+ onChangeEnd,
+ value,
+}: {
+ disabled?: boolean;
+ heightPx?: number;
+ onChange: (next: HsvColor) => void;
+ onChangeEnd?: (next: HsvColor) => void;
+ value: HsvColor;
+}) => {
+ const { t } = useTranslation();
+ const areaRef = useRef<HTMLDivElement>(null);
+ const stripRef = useRef<HTMLDivElement>(null);
+ const drag = useRef<AbortController | null>(null);
+
+ useEffect(() => () => drag.current?.abort(), []);
+
+ const beginDrag = useCallback(
+ (
+ event: ReactPointerEvent<HTMLDivElement>,
+ host: HTMLDivElement | null,
+ apply: (x: number, y: number) => HsvColor
+ ) => {
+ if (disabled || event.button !== 0 || !host) {
+ return;
+ }
+ event.preventDefault();
+ const controller = new AbortController();
+ drag.current?.abort();
+ drag.current = controller;
+ let latest = value;
+ const applyAt = (clientX: number, clientY: number): HsvColor => {
+ const bounds = host.getBoundingClientRect();
+ // A zero-size host mid-drag (a crushed pane) must not divide into NaN.
+ if (bounds.width <= 0 || bounds.height <= 0) {
+ return latest;
+ }
+ return apply(clamp01((clientX - bounds.left) / bounds.width), clamp01((clientY - bounds.top) / bounds.height));
+ };
+ latest = applyAt(event.clientX, event.clientY);
+ onChange(latest);
+ const move = (moveEvent: PointerEvent) => {
+ latest = applyAt(moveEvent.clientX, moveEvent.clientY);
+ onChange(latest);
+ };
+ const finish = () => {
+ controller.abort();
+ onChangeEnd?.(latest);
+ };
+ window.addEventListener('pointermove', move, { signal: controller.signal });
+ window.addEventListener('pointerup', finish, { signal: controller.signal });
+ window.addEventListener('pointercancel', finish, { signal: controller.signal });
+ },
+ [disabled, onChange, onChangeEnd, value]
+ );
+
+ const onAreaPointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) =>
+ beginDrag(event, areaRef.current, (x, y) => ({ ...value, s: x, v: 1 - y })),
+ [beginDrag, value]
+ );
+ const onStripPointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) =>
+ beginDrag(event, stripRef.current, (x) => ({ ...value, h: x * 359.999 })),
+ [beginDrag, value]
+ );
+
+ const step = useCallback(
+ (next: HsvColor) => {
+ onChange(next);
+ onChangeEnd?.(next);
+ },
+ [onChange, onChangeEnd]
+ );
+
+ const onAreaKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const size = event.shiftKey ? SV_STEP_LARGE : SV_STEP;
+ const next =
+ event.key === 'ArrowRight'
+ ? { ...value, s: clamp01(value.s + size) }
+ : event.key === 'ArrowLeft'
+ ? { ...value, s: clamp01(value.s - size) }
+ : event.key === 'ArrowUp'
+ ? { ...value, v: clamp01(value.v + size) }
+ : event.key === 'ArrowDown'
+ ? { ...value, v: clamp01(value.v - size) }
+ : undefined;
+ if (!next) {
+ return;
+ }
+ event.preventDefault();
+ step(next);
+ },
+ [step, value]
+ );
+ const onStripKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const size = event.shiftKey ? HUE_STEP_LARGE : HUE_STEP;
+ const delta =
+ event.key === 'ArrowRight' || event.key === 'ArrowUp'
+ ? size
+ : event.key === 'ArrowLeft' || event.key === 'ArrowDown'
+ ? -size
+ : undefined;
+ if (delta === undefined) {
+ return;
+ }
+ event.preventDefault();
+ step({ ...value, h: (value.h + delta + 360) % 360 });
+ },
+ [step, value]
+ );
+
+ const hex = hsvToHex(value);
+ const hueHex = hsvToHex({ h: value.h, s: 1, v: 1 });
+ const percent = (fraction: number): number => Math.round(fraction * 100);
+ const areaCss = useMemo(
+ () => ({
+ background: `linear-gradient(to top, black, transparent), linear-gradient(to right, white, ${hueHex})`,
+ }),
+ [hueHex]
+ );
+ const svThumbStyle = useMemo(
+ () => ({
+ backgroundColor: hex,
+ left: `calc(${clamp01(value.s) * 100}% - ${THUMB_SIZE_PX / 2}px)`,
+ top: `calc(${(1 - clamp01(value.v)) * 100}% - ${THUMB_SIZE_PX / 2}px)`,
+ }),
+ [hex, value.s, value.v]
+ );
+ const hueThumbStyle = useMemo(
+ () => ({
+ backgroundColor: hueHex,
+ left: `calc(${(value.h / 360) * 100}% - ${THUMB_SIZE_PX / 2}px)`,
+ }),
+ [hueHex, value.h]
+ );
+
+ return (
+ <Stack gap="2" opacity={disabled ? 0.5 : 1} w="full">
+ <Box
+ ref={areaRef}
+ aria-disabled={disabled || undefined}
+ aria-label={t('common.colorPicker.saturationValue')}
+ aria-valuemax={100}
+ aria-valuemin={0}
+ aria-valuenow={percent(value.v)}
+ aria-valuetext={t('common.colorPicker.saturationValueText', {
+ saturation: percent(value.s),
+ value: percent(value.v),
+ })}
+ cursor={disabled ? 'not-allowed' : 'crosshair'}
+ css={areaCss}
+ h={`${heightPx}px`}
+ position="relative"
+ touchAction="none"
+ role="slider"
+ rounded="sm"
+ tabIndex={disabled ? -1 : 0}
+ w="full"
+ _focusVisible={THUMB_FOCUS_PROPS}
+ onKeyDown={onAreaKeyDown}
+ onPointerDown={onAreaPointerDown}
+ >
+ <Box
+ border="2px solid white"
+ h={`${THUMB_SIZE_PX}px`}
+ pointerEvents="none"
+ position="absolute"
+ rounded="full"
+ shadow="0 0 0 1px rgba(0,0,0,0.6)"
+ style={svThumbStyle}
+ w={`${THUMB_SIZE_PX}px`}
+ />
+ </Box>
+ <Box
+ ref={stripRef}
+ aria-disabled={disabled || undefined}
+ aria-label={t('common.colorPicker.hue')}
+ aria-valuemax={359}
+ aria-valuemin={0}
+ aria-valuenow={Math.round(value.h) % 360}
+ cursor={disabled ? 'not-allowed' : 'ew-resize'}
+ css={HUE_STRIP_CSS}
+ h={`${HUE_STRIP_HEIGHT_PX}px`}
+ position="relative"
+ touchAction="none"
+ role="slider"
+ rounded="full"
+ tabIndex={disabled ? -1 : 0}
+ w="full"
+ _focusVisible={THUMB_FOCUS_PROPS}
+ onKeyDown={onStripKeyDown}
+ onPointerDown={onStripPointerDown}
+ >
+ <Box
+ border="2px solid white"
+ h={`${THUMB_SIZE_PX}px`}
+ pointerEvents="none"
+ position="absolute"
+ rounded="full"
+ shadow="0 0 0 1px rgba(0,0,0,0.6)"
+ style={hueThumbStyle}
+ top={`${(HUE_STRIP_HEIGHT_PX - THUMB_SIZE_PX) / 2}px`}
+ w={`${THUMB_SIZE_PX}px`}
+ />
+ </Box>
+ </Stack>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsx b/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsx
new file mode 100644
index 0000000000..b868719600
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/HsvWheelPicker.tsx
@@ -0,0 +1,320 @@
+import type { PointerEvent as ReactPointerEvent, KeyboardEvent as ReactKeyboardEvent } from 'react';
+
+import { Box, chakra } from '@chakra-ui/react';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { HsvColor, Point } from './hsv';
+
+import {
+ hsvToHex,
+ hsvToRgb,
+ hsvToTrianglePoint,
+ hueToWheelAngle,
+ pointToWheelAngle,
+ triangleCorners,
+ trianglePointToHsv,
+ wheelAngleToHue,
+} from './hsv';
+
+/** Ring thickness as a fraction of the wheel radius. */
+const RING_FRACTION = 0.16;
+/** Gap between the ring's inner edge and the triangle's circumradius. */
+const TRIANGLE_INSET_PX = 4;
+const THUMB_SIZE_PX = 12;
+const HUE_STEP = 2;
+const HUE_STEP_LARGE = 15;
+const SV_STEP = 0.02;
+const SV_STEP_LARGE = 0.1;
+
+const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));
+
+const THUMB_FOCUS_PROPS = { outline: '2px solid {colors.accent.solid}', outlineOffset: '2px' };
+
+/**
+ * The wheel-and-triangle HSV picker: a conic hue ring around a barycentric
+ * saturation/value triangle that points at the hue (the classic GIMP/Krita
+ * layout). Both thumbs are keyboard sliders; drags report live through
+ * `onChange` and settle through `onChangeEnd`. The triangle is painted
+ * per-pixel on a canvas so its shading matches the exact math the thumbs use.
+ */
+export const HsvWheelPicker = ({
+ diameterPx = 192,
+ disabled = false,
+ onChange,
+ onChangeEnd,
+ value,
+}: {
+ diameterPx?: number;
+ disabled?: boolean;
+ onChange: (next: HsvColor) => void;
+ onChangeEnd?: (next: HsvColor) => void;
+ value: HsvColor;
+}) => {
+ const { t } = useTranslation();
+ const radius = diameterPx / 2;
+ const ringWidth = radius * RING_FRACTION;
+ const triangleRadius = radius - ringWidth - TRIANGLE_INSET_PX;
+ const rootRef = useRef<HTMLDivElement>(null);
+ const triangleCanvasRef = useRef<HTMLCanvasElement>(null);
+ const drag = useRef<AbortController | null>(null);
+
+ useEffect(() => () => drag.current?.abort(), []);
+
+ // Repaint the triangle only when the hue (or geometry) changes; saturation
+ // and value only move the thumb. The corner geometry is hoisted out of the
+ // pixel loop, and the bitmap is painted at device resolution so the triangle
+ // stays as crisp as the CSS ring beside it.
+ useEffect(() => {
+ const canvas = triangleCanvasRef.current;
+ const ctx = canvas?.getContext('2d');
+ if (!canvas || !ctx || triangleRadius <= 0) {
+ return;
+ }
+ const scale = Math.min(globalThis.devicePixelRatio || 1, 2);
+ const size = Math.max(1, Math.ceil(triangleRadius * 2 * scale));
+ canvas.width = size;
+ canvas.height = size;
+ const image = ctx.createImageData(size, size);
+ const { data } = image;
+ const [hueCorner, whiteCorner, blackCorner] = triangleCorners(value.h, triangleRadius);
+ const v0x = whiteCorner.x - hueCorner.x;
+ const v0y = whiteCorner.y - hueCorner.y;
+ const v1x = blackCorner.x - hueCorner.x;
+ const v1y = blackCorner.y - hueCorner.y;
+ const inverseDenominator = 1 / (v0x * v1y - v1x * v0y);
+ // Roughly one CSS pixel of tolerance, expressed as a barycentric weight.
+ const tolerance = 1.25 / triangleRadius;
+ for (let y = 0; y < size; y += 1) {
+ for (let x = 0; x < size; x += 1) {
+ const px = x / scale - triangleRadius - hueCorner.x;
+ const py = y / scale - triangleRadius - hueCorner.y;
+ let weightWhite = (px * v1y - v1x * py) * inverseDenominator;
+ let weightBlack = (v0x * py - px * v0y) * inverseDenominator;
+ let weightHue = 1 - weightWhite - weightBlack;
+ if (weightHue < -tolerance || weightWhite < -tolerance || weightBlack < -tolerance) {
+ continue;
+ }
+ weightHue = Math.max(0, weightHue);
+ weightWhite = Math.max(0, weightWhite);
+ weightBlack = Math.max(0, weightBlack);
+ const total = weightHue + weightWhite + weightBlack;
+ const v = 1 - weightBlack / total;
+ const rgb = hsvToRgb({ h: value.h, s: v === 0 ? 0 : weightHue / total / v, v });
+ const offset = (y * size + x) * 4;
+ data[offset] = rgb.r;
+ data[offset + 1] = rgb.g;
+ data[offset + 2] = rgb.b;
+ data[offset + 3] = 255;
+ }
+ }
+ ctx.putImageData(image, 0, 0);
+ }, [triangleRadius, value.h]);
+
+ const toLocalPoint = useCallback(
+ (event: { clientX: number; clientY: number }): Point => {
+ const bounds = rootRef.current?.getBoundingClientRect();
+ if (!bounds) {
+ return { x: 0, y: 0 };
+ }
+ return { x: event.clientX - bounds.left - radius, y: event.clientY - bounds.top - radius };
+ },
+ [radius]
+ );
+
+ const beginDrag = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>, apply: (point: Point) => HsvColor) => {
+ event.preventDefault();
+ const controller = new AbortController();
+ drag.current?.abort();
+ drag.current = controller;
+ let latest = apply(toLocalPoint(event));
+ onChange(latest);
+ const move = (moveEvent: PointerEvent) => {
+ latest = apply(toLocalPoint(moveEvent));
+ onChange(latest);
+ };
+ const finish = () => {
+ controller.abort();
+ onChangeEnd?.(latest);
+ };
+ window.addEventListener('pointermove', move, { signal: controller.signal });
+ window.addEventListener('pointerup', finish, { signal: controller.signal });
+ window.addEventListener('pointercancel', finish, { signal: controller.signal });
+ },
+ [onChange, onChangeEnd, toLocalPoint]
+ );
+
+ const onPointerDown = useCallback(
+ (event: ReactPointerEvent<HTMLDivElement>) => {
+ if (disabled || event.button !== 0) {
+ return;
+ }
+ const point = toLocalPoint(event);
+ const distance = Math.hypot(point.x, point.y);
+ if (distance > radius) {
+ return;
+ }
+ // Each drag moves one axis: a hue drag keeps the s/v it started with and
+ // a triangle drag keeps its hue, so the other thumb never wanders.
+ if (distance >= radius - ringWidth - TRIANGLE_INSET_PX / 2) {
+ beginDrag(event, (p) => ({ ...value, h: wheelAngleToHue(pointToWheelAngle(p)) }));
+ } else {
+ beginDrag(event, (p) => trianglePointToHsv(p, value.h, triangleRadius));
+ }
+ },
+ [beginDrag, disabled, radius, ringWidth, toLocalPoint, triangleRadius, value]
+ );
+
+ const step = useCallback(
+ (next: HsvColor) => {
+ onChange(next);
+ onChangeEnd?.(next);
+ },
+ [onChange, onChangeEnd]
+ );
+
+ const onHueKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const size = event.shiftKey ? HUE_STEP_LARGE : HUE_STEP;
+ const delta =
+ event.key === 'ArrowRight' || event.key === 'ArrowUp'
+ ? size
+ : event.key === 'ArrowLeft' || event.key === 'ArrowDown'
+ ? -size
+ : undefined;
+ if (delta === undefined) {
+ return;
+ }
+ event.preventDefault();
+ step({ ...value, h: (value.h + delta + 360) % 360 });
+ },
+ [step, value]
+ );
+
+ const onTriangleKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLDivElement>) => {
+ const size = event.shiftKey ? SV_STEP_LARGE : SV_STEP;
+ const current = value;
+ const next =
+ event.key === 'ArrowRight'
+ ? { ...current, s: clamp01(current.s + size) }
+ : event.key === 'ArrowLeft'
+ ? { ...current, s: clamp01(current.s - size) }
+ : event.key === 'ArrowUp'
+ ? { ...current, v: clamp01(current.v + size) }
+ : event.key === 'ArrowDown'
+ ? { ...current, v: clamp01(current.v - size) }
+ : undefined;
+ if (!next) {
+ return;
+ }
+ event.preventDefault();
+ step(next);
+ },
+ [step, value]
+ );
+
+ const hueAngle = hueToWheelAngle(value.h);
+ const hueThumb: Point = {
+ x: Math.cos(hueAngle) * (radius - ringWidth / 2),
+ y: Math.sin(hueAngle) * (radius - ringWidth / 2),
+ };
+ const svThumb = hsvToTrianglePoint(value, triangleRadius);
+ const hex = hsvToHex(value);
+ const hueHex = hsvToHex({ h: value.h, s: 1, v: 1 });
+ const percent = (fraction: number): number => Math.round(fraction * 100);
+ const ringCss = useMemo(
+ () => ({
+ background: 'conic-gradient(from 90deg, red, yellow, lime, cyan, blue, magenta, red)',
+ mask: `radial-gradient(closest-side, transparent calc(100% - ${ringWidth}px), black calc(100% - ${ringWidth - 1}px))`,
+ }),
+ [ringWidth]
+ );
+ const svThumbStyle = useMemo(() => ({ backgroundColor: hex }), [hex]);
+ const hueThumbStyle = useMemo(() => ({ backgroundColor: hueHex }), [hueHex]);
+
+ return (
+ <Box
+ ref={rootRef}
+ cursor={disabled ? 'not-allowed' : 'crosshair'}
+ h={`${diameterPx}px`}
+ opacity={disabled ? 0.5 : 1}
+ position="relative"
+ touchAction="none"
+ w={`${diameterPx}px`}
+ onPointerDown={onPointerDown}
+ >
+ <Box
+ aria-disabled={disabled || undefined}
+ aria-label={t('common.colorPicker.hue')}
+ aria-valuemax={359}
+ aria-valuemin={0}
+ aria-valuenow={Math.round(value.h) % 360}
+ inset="0"
+ position="absolute"
+ role="slider"
+ rounded="full"
+ tabIndex={disabled ? -1 : 0}
+ css={ringCss}
+ _focusVisible={THUMB_FOCUS_PROPS}
+ onKeyDown={onHueKeyDown}
+ />
+ <chakra.canvas
+ ref={triangleCanvasRef}
+ h={`${triangleRadius * 2}px`}
+ left={`${radius - triangleRadius}px`}
+ pointerEvents="none"
+ position="absolute"
+ top={`${radius - triangleRadius}px`}
+ w={`${triangleRadius * 2}px`}
+ />
+ <Box
+ aria-disabled={disabled || undefined}
+ aria-label={t('common.colorPicker.saturationValue')}
+ aria-valuemax={100}
+ aria-valuemin={0}
+ aria-valuenow={percent(value.v)}
+ aria-valuetext={t('common.colorPicker.saturationValueText', {
+ saturation: percent(value.s),
+ value: percent(value.v),
+ })}
+ h={`${triangleRadius * 2}px`}
+ left={`${radius - triangleRadius}px`}
+ pointerEvents="none"
+ position="absolute"
+ role="slider"
+ rounded="full"
+ tabIndex={disabled ? -1 : 0}
+ top={`${radius - triangleRadius}px`}
+ w={`${triangleRadius * 2}px`}
+ _focusVisible={THUMB_FOCUS_PROPS}
+ onKeyDown={onTriangleKeyDown}
+ />
+ <Box
+ border="2px solid white"
+ h={`${THUMB_SIZE_PX}px`}
+ left={`${radius + svThumb.x - THUMB_SIZE_PX / 2}px`}
+ pointerEvents="none"
+ position="absolute"
+ rounded="full"
+ shadow="0 0 0 1px rgba(0,0,0,0.6)"
+ style={svThumbStyle}
+ top={`${radius + svThumb.y - THUMB_SIZE_PX / 2}px`}
+ w={`${THUMB_SIZE_PX}px`}
+ />
+ <Box
+ border="2px solid white"
+ h={`${THUMB_SIZE_PX}px`}
+ left={`${radius + hueThumb.x - THUMB_SIZE_PX / 2}px`}
+ pointerEvents="none"
+ position="absolute"
+ rounded="full"
+ shadow="0 0 0 1px rgba(0,0,0,0.6)"
+ style={hueThumbStyle}
+ top={`${radius + hueThumb.y - THUMB_SIZE_PX / 2}px`}
+ w={`${THUMB_SIZE_PX}px`}
+ />
+ </Box>
+ );
+};
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
index a3d03d10f2..810fceb4fb 100644
--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerStore.ts
@@ -4,8 +4,12 @@ export type ColorPickerFormat = 'hex' | 'rgb' | 'hsl' | 'hsb';
export const COLOR_PICKER_FORMATS: readonly ColorPickerFormat[] = ['hex', 'rgb', 'hsl', 'hsb'];
+/** How the color pane's picking surface renders: the HSV wheel+triangle or the box with a hue strip. */
+export type ColorPickerMode = 'wheel' | 'box';
+
const RECENTS_STORAGE_KEY = 'invokeai:v7:webv2:color-recents';
const FORMAT_STORAGE_KEY = 'invokeai:v7:webv2:color-format';
+const MODE_STORAGE_KEY = 'invokeai:v7:webv2:color-picker-mode';
const MAX_RECENTS = 12;
/**
@@ -33,6 +37,8 @@ export const DEFAULT_COLOR_SWATCHES: readonly string[] = [
const isColorPickerFormat = (value: unknown): value is ColorPickerFormat =>
typeof value === 'string' && (COLOR_PICKER_FORMATS as readonly string[]).includes(value);
+const isColorPickerMode = (value: unknown): value is ColorPickerMode => value === 'wheel' || value === 'box';
+
/**
* Reads a persisted string. Touching `localStorage` at all can throw
* (SecurityError when storage is disabled), not just `getItem` — both stay
@@ -82,6 +88,7 @@ const parseRecents = (raw: string | null): string[] => {
interface ColorPickerSnapshot {
format: ColorPickerFormat;
+ mode: ColorPickerMode;
recents: string[];
}
@@ -91,8 +98,15 @@ const readStoredFormat = (): ColorPickerFormat => {
return isColorPickerFormat(stored) ? stored : 'hex';
};
+const readStoredMode = (): ColorPickerMode => {
+ const stored = readStored(MODE_STORAGE_KEY);
+
+ return isColorPickerMode(stored) ? stored : 'wheel';
+};
+
const store = createExternalStore<ColorPickerSnapshot>({
format: readStoredFormat(),
+ mode: readStoredMode(),
recents: parseRecents(readStored(RECENTS_STORAGE_KEY)),
});
@@ -115,6 +129,13 @@ export const setColorPickerFormat = (format: ColorPickerFormat): void => {
writeStored(FORMAT_STORAGE_KEY, format);
};
+export const setColorPickerMode = (mode: ColorPickerMode): void => {
+ store.patchSnapshot({ mode });
+ writeStored(MODE_STORAGE_KEY, mode);
+};
+
+export const useColorPickerMode = (): ColorPickerMode => store.useSelector((snapshot) => snapshot.mode, Object.is);
+
export const useRecentColors = (): string[] => store.useSelector((snapshot) => snapshot.recents);
export const useColorPickerFormat = (): ColorPickerFormat =>
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts
index d13a562be8..efe392d85e 100644
--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.test.ts
@@ -4,7 +4,8 @@ import { shouldSyncExternalColor } from './colorPickerSync';
describe('shouldSyncExternalColor', () => {
it('does not sync when the external value is unchanged', () => {
- expect(shouldSyncExternalColor('#808080', '#808080', '#808080')).toBe(false);
+ expect(shouldSyncExternalColor('#808080', '#808080', '#808080', true)).toBe(false);
+ expect(shouldSyncExternalColor('#808080', '#808080', '#808080', false)).toBe(false);
});
it('does not sync when the external value changed to exactly what we last emitted (our own round trip)', () => {
@@ -12,49 +13,55 @@ describe('shouldSyncExternalColor', () => {
// S=0, we emit "#808080", the consumer stores it and passes it back as
// the new `value` prop -- that must not force a re-parse that would
// collapse the hue we're holding onto internally.
- expect(shouldSyncExternalColor('#808080', '#7f7f7f', '#808080')).toBe(false);
+ expect(shouldSyncExternalColor('#808080', '#7f7f7f', '#808080', true)).toBe(false);
+ });
+
+ it('syncs an external change back to the last-emitted value once its echo was consumed', () => {
+ // An X swap and swap back lands on the color we last emitted long after
+ // the echo settled; with no emit outstanding this is a genuine change.
+ expect(shouldSyncExternalColor('#808080', '#7f7f7f', '#808080', false)).toBe(true);
});
it('syncs when the external value changed to something other than what we last emitted', () => {
// A genuine external change (e.g. a programmatic reset, or a different
// control writing to the same underlying value) should still win.
- expect(shouldSyncExternalColor('#ff0000', '#808080', '#808080')).toBe(true);
+ expect(shouldSyncExternalColor('#ff0000', '#808080', '#808080', true)).toBe(true);
});
it('syncs on the very first divergence even if nothing has been emitted yet', () => {
- expect(shouldSyncExternalColor('#ff0000', '#000000', '#000000')).toBe(true);
+ expect(shouldSyncExternalColor('#ff0000', '#000000', '#000000', false)).toBe(true);
});
it('does not sync when the previous and external values are identical, regardless of last emitted', () => {
- expect(shouldSyncExternalColor('#123456', '#123456', '#abcdef')).toBe(false);
+ expect(shouldSyncExternalColor('#123456', '#123456', '#abcdef', true)).toBe(false);
});
it('treats a differently-cased echo of what we emitted as our own round trip', () => {
- expect(shouldSyncExternalColor('#FF0000', '#808080', '#ff0000')).toBe(false);
+ expect(shouldSyncExternalColor('#FF0000', '#808080', '#ff0000', true)).toBe(false);
});
it('treats a shorthand echo of what we emitted as our own round trip', () => {
- expect(shouldSyncExternalColor('#f00', '#808080', '#ff0000')).toBe(false);
+ expect(shouldSyncExternalColor('#f00', '#808080', '#ff0000', true)).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);
+ expect(shouldSyncExternalColor('#ff0000ff', '#808080', '#ff0000', true)).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);
+ expect(shouldSyncExternalColor('#ff000080', '#ff0000ff', '#ff0000ff', true)).toBe(true);
});
it('round-trips 8-digit values without re-syncing', () => {
- expect(shouldSyncExternalColor('#ff000080', '#ff0000ff', '#FF000080')).toBe(false);
+ expect(shouldSyncExternalColor('#ff000080', '#ff0000ff', '#FF000080', true)).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);
+ expect(shouldSyncExternalColor('transparent', 'currentColor', 'currentColor', true)).toBe(true);
+ expect(shouldSyncExternalColor('transparent', 'currentColor', 'transparent', true)).toBe(false);
});
});
diff --git a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts
index e38c86c006..c3932e9457 100644
--- a/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts
+++ b/invokeai/frontend/webv2/src/platform/ui/colorPickerSync.ts
@@ -13,6 +13,12 @@ import { normalizeHex } from './color';
* `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.
*
+ * The round trip is only swallowed while one is actually outstanding
+ * (`isAwaitingEcho`: armed by an emit, consumed by the next external change).
+ * Without that, an independent change that lands back on the last-emitted
+ * value — an X foreground/background swap and back is the everyday case —
+ * would be misread as our own echo and leave the swatch stale.
+ *
* 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
@@ -21,12 +27,14 @@ import { normalizeHex } from './color';
export const shouldSyncExternalColor = (
externalValue: string,
previousExternalValue: string,
- lastEmittedValue: string
+ lastEmittedValue: string,
+ isAwaitingEcho: boolean
): boolean => {
const external = normalizeHex(externalValue, externalValue);
- return (
- external !== normalizeHex(previousExternalValue, previousExternalValue) &&
- external !== normalizeHex(lastEmittedValue, lastEmittedValue)
- );
+ if (external === normalizeHex(previousExternalValue, previousExternalValue)) {
+ return false;
+ }
+
+ return !(isAwaitingEcho && external === normalizeHex(lastEmittedValue, lastEmittedValue));
};
diff --git a/invokeai/frontend/webv2/src/platform/ui/hsv.test.ts b/invokeai/frontend/webv2/src/platform/ui/hsv.test.ts
new file mode 100644
index 0000000000..35eed48892
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/hsv.test.ts
@@ -0,0 +1,110 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ hexToHsv,
+ hslToRgb,
+ hsvToHex,
+ hsvToRgb,
+ hsvToTrianglePoint,
+ hueToWheelAngle,
+ pointToWheelAngle,
+ rgbToHsl,
+ rgbToHsv,
+ triangleCorners,
+ trianglePointToHsv,
+ wheelAngleToHue,
+} from './hsv';
+
+const rgba = (r: number, g: number, b: number) => ({ a: 1, b, g, r });
+
+describe('rgb↔hsv', () => {
+ it('converts the primaries and greys', () => {
+ expect(rgbToHsv(rgba(255, 0, 0))).toEqual({ h: 0, s: 1, v: 1 });
+ expect(rgbToHsv(rgba(0, 255, 0))).toEqual({ h: 120, s: 1, v: 1 });
+ expect(rgbToHsv(rgba(0, 0, 255))).toEqual({ h: 240, s: 1, v: 1 });
+ expect(rgbToHsv(rgba(255, 255, 255))).toEqual({ h: 0, s: 0, v: 1 });
+ expect(rgbToHsv(rgba(0, 0, 0))).toEqual({ h: 0, s: 0, v: 0 });
+ });
+
+ it('round-trips a sweep of colors within one channel step', () => {
+ for (let h = 0; h < 360; h += 30) {
+ for (const s of [0.2, 0.6, 1]) {
+ for (const v of [0.2, 0.6, 1]) {
+ const rgb = hsvToRgb({ h, s, v });
+ const back = rgbToHsv(rgb);
+ const hueDelta = Math.min(Math.abs(back.h - h), 360 - Math.abs(back.h - h));
+ expect(hueDelta).toBeLessThan(1.5);
+ expect(back.s).toBeCloseTo(s, 1);
+ expect(back.v).toBeCloseTo(v, 1);
+ }
+ }
+ }
+ });
+
+ it('keeps the previous hue for greys and the previous saturation at black', () => {
+ expect(hexToHsv('#808080', { h: 200, s: 1, v: 0.4 }).h).toBe(200);
+ expect(hexToHsv('#000000', { h: 200, s: 0.7, v: 0.4 })).toEqual({ h: 200, s: 0.7, v: 0 });
+ expect(hexToHsv('#ff0000', { h: 200, s: 0.7, v: 0.4 })).toEqual({ h: 0, s: 1, v: 1 });
+ expect(hexToHsv('#00ff00')).toEqual({ h: 120, s: 1, v: 1 });
+ expect(hsvToHex({ h: 120, s: 1, v: 1 })).toBe('#00ff00');
+ });
+});
+
+describe('rgb↔hsl', () => {
+ it('converts landmarks and round-trips a sweep', () => {
+ expect(rgbToHsl(rgba(255, 0, 0))).toEqual({ h: 0, l: 0.5, s: 1 });
+ expect(rgbToHsl(rgba(255, 255, 255))).toEqual({ h: 0, l: 1, s: 0 });
+ expect(rgbToHsl(rgba(0, 0, 0))).toEqual({ h: 0, l: 0, s: 0 });
+ for (let h = 0; h < 360; h += 60) {
+ for (const s of [0.25, 0.75]) {
+ for (const l of [0.2, 0.5, 0.8]) {
+ const back = rgbToHsl(hslToRgb({ h, l, s }));
+ expect(back.l).toBeCloseTo(l, 1);
+ expect(back.s).toBeCloseTo(s, 1);
+ }
+ }
+ }
+ });
+});
+
+describe('wheel geometry', () => {
+ it('maps hue to ring angle and back', () => {
+ for (const hue of [0, 45, 120, 359]) {
+ expect(wheelAngleToHue(hueToWheelAngle(hue))).toBeCloseTo(hue, 5);
+ }
+ expect(pointToWheelAngle({ x: 1, y: 0 })).toBeCloseTo(0, 5);
+ expect(wheelAngleToHue(pointToWheelAngle({ x: 0, y: 1 }))).toBeCloseTo(90, 5);
+ });
+
+ it('puts the corners at the hue, white, and black positions', () => {
+ const [hueCorner, whiteCorner, blackCorner] = triangleCorners(0, 100);
+ expect(hueCorner.x).toBeCloseTo(100, 5);
+ expect(hueCorner.y).toBeCloseTo(0, 5);
+ expect(whiteCorner.x).toBeCloseTo(-50, 5);
+ expect(blackCorner.x).toBeCloseTo(-50, 5);
+ expect(whiteCorner.y).toBeCloseTo(86.6, 1);
+ expect(blackCorner.y).toBeCloseTo(-86.6, 1);
+ });
+
+ it('round-trips s/v through the triangle at several hues', () => {
+ for (const h of [0, 80, 200, 310]) {
+ for (const s of [0, 0.3, 0.7, 1]) {
+ for (const v of [0.1, 0.5, 1]) {
+ const back = trianglePointToHsv(hsvToTrianglePoint({ h, s, v }, 90), h, 90);
+ expect(back.v).toBeCloseTo(v, 5);
+ expect(back.s).toBeCloseTo(v === 0 ? 0 : s, 5);
+ }
+ }
+ }
+ });
+
+ it('clamps points outside the triangle onto it', () => {
+ const clamped = trianglePointToHsv({ x: 500, y: 0 }, 0, 90);
+ expect(clamped.s).toBeGreaterThanOrEqual(0);
+ expect(clamped.s).toBeLessThanOrEqual(1);
+ expect(clamped.v).toBeGreaterThanOrEqual(0);
+ expect(clamped.v).toBeLessThanOrEqual(1);
+ // Far past the hue corner lands on the pure hue.
+ expect(clamped).toMatchObject({ h: 0, s: 1, v: 1 });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/platform/ui/hsv.ts b/invokeai/frontend/webv2/src/platform/ui/hsv.ts
new file mode 100644
index 0000000000..ad657e2812
--- /dev/null
+++ b/invokeai/frontend/webv2/src/platform/ui/hsv.ts
@@ -0,0 +1,172 @@
+/**
+ * HSV math for the wheel-and-triangle color picker: RGB↔HSV conversion with
+ * sticky hue/saturation for the hue-agnostic greys, and the hue-ring/triangle
+ * geometry mapping. Pure functions, no React, no Chakra.
+ *
+ * The triangle follows the classic GIMP/Krita layout: it points at the hue on
+ * the ring, with the pure hue, white, and black at its corners; a color's
+ * position is the barycentric blend `hue·(s·v) + white·(v·(1−s)) + black·(1−v)`.
+ */
+
+import type { RgbaColor } from './color';
+
+import { formatHexColor, parseHexColor } from './color';
+
+/** `h` in degrees `[0, 360)`; `s`/`v` in `[0, 1]`. */
+export interface HsvColor {
+ h: number;
+ s: number;
+ v: number;
+}
+
+export interface Point {
+ x: number;
+ y: number;
+}
+
+const clamp01 = (value: number): number => Math.min(1, Math.max(0, value));
+
+const normalizeHue = (degrees: number): number => {
+ const wrapped = degrees % 360;
+ return wrapped < 0 ? wrapped + 360 : wrapped;
+};
+
+export const rgbToHsv = ({ b, g, r }: RgbaColor): HsvColor => {
+ const rn = r / 255;
+ const gn = g / 255;
+ const bn = b / 255;
+ const max = Math.max(rn, gn, bn);
+ const min = Math.min(rn, gn, bn);
+ const delta = max - min;
+ let h = 0;
+ if (delta > 0) {
+ if (max === rn) {
+ h = 60 * (((gn - bn) / delta) % 6);
+ } else if (max === gn) {
+ h = 60 * ((bn - rn) / delta + 2);
+ } else {
+ h = 60 * ((rn - gn) / delta + 4);
+ }
+ }
+ return { h: normalizeHue(h), s: max === 0 ? 0 : delta / max, v: max };
+};
+
+export const hsvToRgb = ({ h, s, v }: HsvColor): RgbaColor => {
+ const hue = normalizeHue(h);
+ const c = clamp01(v) * clamp01(s);
+ const x = c * (1 - Math.abs(((hue / 60) % 2) - 1));
+ const m = clamp01(v) - c;
+ const [rn, gn, bn] =
+ hue < 60
+ ? [c, x, 0]
+ : hue < 120
+ ? [x, c, 0]
+ : hue < 180
+ ? [0, c, x]
+ : hue < 240
+ ? [0, x, c]
+ : hue < 300
+ ? [x, 0, c]
+ : [c, 0, x];
+ return { a: 1, b: Math.round((bn + m) * 255), g: Math.round((gn + m) * 255), r: Math.round((rn + m) * 255) };
+};
+
+/** `h` in degrees `[0, 360)`; `s`/`l` in `[0, 1]`. */
+export interface HslColor {
+ h: number;
+ s: number;
+ l: number;
+}
+
+export const rgbToHsl = (color: RgbaColor): HslColor => {
+ const { h, s, v } = rgbToHsv(color);
+ const l = v * (1 - s / 2);
+ return { h, l, s: l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l) };
+};
+
+export const hslToRgb = ({ h, l, s }: HslColor): RgbaColor => {
+ const v = clamp01(l) + clamp01(s) * Math.min(clamp01(l), 1 - clamp01(l));
+ return hsvToRgb({ h, s: v === 0 ? 0 : 2 * (1 - clamp01(l) / v), v });
+};
+
+/**
+ * Parses a hex color into HSV, keeping the hue (and, at black, the saturation)
+ * from `previous` when the parsed color cannot express them: hex is
+ * hue-agnostic for greys, and without stickiness every grey would snap the
+ * wheel's hue thumb back to red.
+ */
+export const hexToHsv = (hex: string, previous?: HsvColor): HsvColor => {
+ const parsed = rgbToHsv(parseHexColor(hex));
+ if (!previous) {
+ return parsed;
+ }
+ return {
+ h: parsed.s === 0 ? previous.h : parsed.h,
+ s: parsed.v === 0 ? previous.s : parsed.s,
+ v: parsed.v,
+ };
+};
+
+export const hsvToHex = (hsv: HsvColor): string => formatHexColor(hsvToRgb(hsv));
+
+/** Screen-space angle (radians, y-down) of a hue on the ring; 0° hue sits at the right. */
+export const hueToWheelAngle = (hue: number): number => (normalizeHue(hue) * Math.PI) / 180;
+
+export const wheelAngleToHue = (angle: number): number => normalizeHue((angle * 180) / Math.PI);
+
+export const pointToWheelAngle = ({ x, y }: Point): number => {
+ const angle = Math.atan2(y, x);
+ return angle < 0 ? angle + 2 * Math.PI : angle;
+};
+
+/** The triangle's corners for `hue` on a ring of `radius`: pure hue, then white, then black. */
+export const triangleCorners = (hue: number, radius: number): [Point, Point, Point] => {
+ const corner = (offsetDegrees: number): Point => {
+ const angle = hueToWheelAngle(hue + offsetDegrees);
+ return { x: Math.cos(angle) * radius, y: Math.sin(angle) * radius };
+ };
+ return [corner(0), corner(120), corner(240)];
+};
+
+/** Where `{s, v}` sits inside the hue's triangle (center-relative coordinates). */
+export const hsvToTrianglePoint = (hsv: HsvColor, radius: number): Point => {
+ const [hueCorner, whiteCorner, blackCorner] = triangleCorners(hsv.h, radius);
+ const v = clamp01(hsv.v);
+ const s = clamp01(hsv.s);
+ const weightHue = s * v;
+ const weightWhite = v * (1 - s);
+ const weightBlack = 1 - v;
+ return {
+ x: hueCorner.x * weightHue + whiteCorner.x * weightWhite + blackCorner.x * weightBlack,
+ y: hueCorner.y * weightHue + whiteCorner.y * weightWhite + blackCorner.y * weightBlack,
+ };
+};
+
+/**
+ * The `{s, v}` for a center-relative point, clamped into the hue's triangle:
+ * barycentric weights are floored at zero and renormalized, so dragging
+ * outside any edge slides along it instead of escaping.
+ */
+export const trianglePointToHsv = (point: Point, hue: number, radius: number): HsvColor => {
+ const [hueCorner, whiteCorner, blackCorner] = triangleCorners(hue, radius);
+ // Solve the barycentric weights for `point` against the three corners.
+ const v0x = whiteCorner.x - hueCorner.x;
+ const v0y = whiteCorner.y - hueCorner.y;
+ const v1x = blackCorner.x - hueCorner.x;
+ const v1y = blackCorner.y - hueCorner.y;
+ const v2x = point.x - hueCorner.x;
+ const v2y = point.y - hueCorner.y;
+ const denominator = v0x * v1y - v1x * v0y;
+ let weightWhite = denominator === 0 ? 0 : (v2x * v1y - v1x * v2y) / denominator;
+ let weightBlack = denominator === 0 ? 0 : (v0x * v2y - v2x * v0y) / denominator;
+ let weightHue = 1 - weightWhite - weightBlack;
+ weightHue = Math.max(0, weightHue);
+ weightWhite = Math.max(0, weightWhite);
+ weightBlack = Math.max(0, weightBlack);
+ const total = weightHue + weightWhite + weightBlack;
+ weightHue /= total;
+ weightWhite /= total;
+ weightBlack /= total;
+ const v = 1 - weightBlack;
+ return { h: normalizeHue(hue), s: v === 0 ? 0 : weightHue / v, v };
+};
diff --git a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
index cb3b1cecc5..b0335a04e3 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/capabilities.ts
@@ -471,6 +471,14 @@ export interface CanvasEngineToolCapability extends CanvasToolCapability {
* tool either way. Backs the color picker's eyedropper button.
*/
requestColorSample(): Promise<string | null>;
+ /**
+ * Installs the sink for eyedropper samples no one-shot request claims: the
+ * workbench routes them to the active foreground/background target. Without
+ * a router (or when it declines with false) the sample lands in the brush
+ * color option — the engine-standalone behavior. Returns a dispose that
+ * uninstalls only this router, so a stale cleanup cannot evict a newer one.
+ */
+ setColorSampleRouter(router: (hex: string) => boolean): () => void;
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 975c4555f8..f09de9cc2c 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/engine.ts
@@ -1013,6 +1013,8 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
* caller is awaiting can never dangle.
*/
let pendingColorSample: { previousToolId: ToolId; resolve: (hex: string | null) => void } | null = null;
+ // Where unclaimed eyedropper samples land while a workbench is attached.
+ let colorSampleRouter: ((hex: string) => boolean) | null = null;
const toolContext: ToolContext = {
applyTransform: () => applyTransform(),
@@ -1063,11 +1065,11 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
openTextCreate: (docPoint) => openTextCreate(docPoint),
openTextEdit: (layerId) => openTextEdit(layerId),
resolveColorSample: (hex) => {
- if (!pendingColorSample) {
- return false;
+ if (pendingColorSample) {
+ settleColorSample(hex, true);
+ return true;
}
- settleColorSample(hex, true);
- return true;
+ return colorSampleRouter?.(hex) ?? false;
},
setLayerTransformOverride: (layerId, override) => {
if (override) {
@@ -2916,6 +2918,15 @@ export const createCanvasEngine = (opts: CanvasEngineOptions): CanvasEngineCoreC
handleEscapePriority,
onStrokeCommitted,
requestColorSample,
+ setColorSampleRouter: (router) => {
+ colorSampleRouter = router;
+ return () => {
+ // Compare-and-clear: a later installer must not be evicted by an earlier one's cleanup.
+ if (colorSampleRouter === router) {
+ colorSampleRouter = null;
+ }
+ };
+ },
setInteractionLocked,
};
const layersCapability: CanvasEngineLayerCapability = {
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 125b437f82..2cd0ef3391 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/colorPickerTool.ts
@@ -1,9 +1,10 @@
/**
* The color-picker tool: while held down (usually via the alt-hold temp-tool
* switch the pointer pipeline already drives — see `input/pointerPipeline.ts`),
- * it samples the composited document color under the cursor and writes it into
- * the brush color option, so releasing alt drops the user right back into
- * painting with the picked color. Sampling reads the layer cache directly
+ * it samples the composited document color under the cursor and hands it to
+ * `resolveColorSample` — in the app that lands in the active
+ * foreground/background target, so releasing alt drops the user right back
+ * into painting with the picked color. Sampling reads the layer cache directly
* through {@link sampleDocumentColor} — this tool never dispatches and never
* touches pixels.
*
@@ -31,9 +32,9 @@ const updateCursorRing = (ctx: ToolContext, input: PointerInput): void => {
};
/**
- * 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.
+ * Samples the composited color under `input` and offers it through
+ * `resolveColorSample` (one-shot claim, then the workbench router). The brush
+ * color option is only the engine-standalone fallback.
*/
const pickColorAt = (ctx: ToolContext, input: PointerInput): void => {
const doc = ctx.getDocument();
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 cd4ff53ed6..1403c0b20e 100644
--- a/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
+++ b/invokeai/frontend/webv2/src/workbench/canvas-engine/tools/tool.ts
@@ -164,11 +164,12 @@ export interface ToolContext {
/** 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.
+ * Hands a sampled color to whoever claims it: a one-shot request made from
+ * outside the canvas (a color picker's eyedropper button) wins first, then
+ * the workbench's persistent router (which writes the active
+ * foreground/background target). Returns whether anyone took it; only then
+ * does the color-picker tool fall back to writing the brush color — the
+ * engine-standalone behavior. Absent in minimal test harnesses.
*/
resolveColorSample?(hex: string): boolean;
/**
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
index cf1f857846..804788b90e 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.test.ts
@@ -35,6 +35,14 @@ describe('firstPartyHotkeyCatalog', () => {
expect(openSettings).toMatchObject({ allowInEditable: true, defaultKeys: ['mod+,'], implemented: true });
});
+ it('marks the color pair swap and reset as implemented on their classic keys', () => {
+ const swap = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.toggleFillColor');
+ const reset = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'canvas.setFillColorsToDefault');
+
+ expect(swap).toMatchObject({ defaultKeys: ['x'], implemented: true });
+ expect(reset).toMatchObject({ defaultKeys: ['d'], implemented: true });
+ });
+
it('keeps layout saving explicit and out of editable controls', () => {
const saveLayout = firstPartyHotkeyCatalog.find((hotkey) => hotkey.id === 'app.saveLayoutPreset');
diff --git a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
index 9a6219a105..7b7b9db9c4 100644
--- a/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
+++ b/invokeai/frontend/webv2/src/workbench/hotkeys/catalog.ts
@@ -42,6 +42,8 @@ const implemented = new Set([
'canvas.nextEntity',
'canvas.prevEntity',
'canvas.redo',
+ 'canvas.setFillColorsToDefault',
+ 'canvas.toggleFillColor',
'canvas.undo',
'gallery.clearSelection',
'gallery.deleteSelection',
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
index fe2b81673c..9fb8643058 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/CanvasWidgetView.tsx
@@ -49,6 +49,8 @@ import {
import { CanvasSurface } from './CanvasSurface';
import { CanvasSurfaceContextLayout } from './CanvasSurfaceContextLayout';
import { resolveCheckerColors } from './checkerColors';
+import { CanvasColorFeed } from './color-system/CanvasColorFeed';
+import { useActiveColorCommands } from './color-system/useActiveColors';
import { useCanvasOperation } from './engineStoreHooks';
import { executeCanvasImageDropImport } from './executeCanvasImageDropImport';
import { StagingBar } from './StagingBar';
@@ -132,6 +134,10 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
}
}, [engine, settings]);
+ // The pair↔engine bridge lives in a null child so per-pointermove pair
+ // edits never re-render this shell; the commands feed the X/D hotkeys below.
+ const colorCommands = useActiveColorCommands();
+
// The checkerboard fills the whole (unbounded) canvas, so its two square colors
// come from theme tokens rather than hardcoded greys. Resolve them from the live
// Chakra theme and feed them into the engine's checker-colors store; re-resolve
@@ -391,7 +397,9 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
pasteFromClipboard,
reportPreparedCommit: (outcome) => reportPreparedCommit(outcome, notify.error, t),
reportStructuralCommit: (result) => reportStructuralCommit(result, notify.error, t),
+ resetActiveColors: colorCommands.resetPair,
selectedLayerIds,
+ swapActiveColors: colorCommands.swapPair,
t,
});
});
@@ -430,6 +438,9 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
['canvas.invertSelection', t('widgets.canvas.commands.invertSelection'), ['mod+shift+i']],
['canvas.brushSizeDown', t('widgets.canvas.commands.decreaseBrushSize'), ['[']],
['canvas.brushSizeUp', t('widgets.canvas.commands.increaseBrushSize'), [']']],
+ // The active color pair: X swaps, D resets to black/white.
+ ['canvas.toggleFillColor', t('widgets.canvas.commands.swapColors'), ['x']],
+ ['canvas.setFillColorsToDefault', t('widgets.canvas.commands.resetColors'), ['d']],
// Move the selected layer: arrows nudge 1px, shift+arrows 10px.
['canvas.nudgeLeft', t('widgets.canvas.commands.nudgeLeft'), ['arrowleft']],
['canvas.nudgeRight', t('widgets.canvas.commands.nudgeRight'), ['arrowright']],
@@ -498,6 +509,7 @@ export const CanvasWidgetView = ({ runtime }: WidgetViewProps) => {
role="region"
w="full"
>
+ <CanvasColorFeed engine={engine} />
<CanvasSurfaceContextLayout surface={canvasSurface} onContextMenu={handleSurfaceContextMenu}>
<CanvasImageDropOverlay
isDocumentEditingLocked={interactionCapabilities.isDocumentEditingLocked}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
index 8af4789c28..6c1a91b26e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.test.ts
@@ -108,7 +108,9 @@ const contextOf = (overrides: Partial<CanvasHotkeyContext> = {}): CanvasHotkeyCo
isInteractionLocked: false,
notifyLayerDuplicateFailed: vi.fn(),
pasteFromClipboard,
+ resetActiveColors: vi.fn(),
selectedLayerIds: ['a'],
+ swapActiveColors: vi.fn(),
t: (key) => key,
...overrides,
});
@@ -595,3 +597,19 @@ describe('group selection', () => {
);
});
});
+
+describe('active color pair commands', () => {
+ it('routes X to swap and D to reset, even while interaction is locked', () => {
+ for (const isInteractionLocked of [false, true]) {
+ const swapCtx = contextOf({ isInteractionLocked });
+ executeCanvasHotkeyCommand('canvas.toggleFillColor', swapCtx);
+ expect(swapCtx.swapActiveColors).toHaveBeenCalledTimes(1);
+ expect(swapCtx.resetActiveColors).not.toHaveBeenCalled();
+
+ const resetCtx = contextOf({ isInteractionLocked });
+ executeCanvasHotkeyCommand('canvas.setFillColorsToDefault', resetCtx);
+ expect(resetCtx.resetActiveColors).toHaveBeenCalledTimes(1);
+ expect(resetCtx.dispatch).not.toHaveBeenCalled();
+ }
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
index 78eee8d8ce..7a32dcb9f8 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/canvasHotkeyCommands.ts
@@ -59,6 +59,10 @@ export interface CanvasHotkeyContext {
readonly selectedLayerIds: readonly string[];
readonly dispatch: CanvasProjectMutationDispatch;
readonly copySelection: (cut: boolean) => void;
+ /** Swaps the project foreground/background pair — a preference, never a document edit. */
+ readonly swapActiveColors: () => void;
+ /** Resets the pair to the black-on-white default. */
+ readonly resetActiveColors: () => void;
readonly pasteFromClipboard: () => void;
readonly notifyLayerDuplicateFailed: () => void;
readonly reportStructuralCommit: (result: StructuralCommitResult) => void;
@@ -97,6 +101,18 @@ export const executeCanvasHotkeyCommand = (commandId: string, ctx: CanvasHotkeyC
return;
}
+ // The color pair is a preference, not a document edit, so X/D stay live even
+ // while the surface is interaction-locked.
+ if (commandId === 'canvas.toggleFillColor') {
+ ctx.swapActiveColors();
+ return;
+ }
+
+ if (commandId === 'canvas.setFillColorsToDefault') {
+ ctx.resetActiveColors();
+ return;
+ }
+
if (ctx.isInteractionLocked) {
if (commandId === 'canvas.tool.view') {
engine?.tools.setTool('view');
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
new file mode 100644
index 0000000000..fa7b18d3fd
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/CanvasColorFeed.tsx
@@ -0,0 +1,44 @@
+import type { CanvasEngineHandle } from '@workbench/widgets/canvas/useCanvasEngine';
+
+import { useEffect } from 'react';
+
+import { useActiveColorCommands, useActiveColorPair } from './useActiveColors';
+
+/**
+ * The bridge between the active color pair and one engine, kept out of the
+ * canvas widget shell so per-pointermove pair edits (chip drags, eyedropper
+ * scrubs) re-render only this null component:
+ *
+ * - the pair owns painting color, and the engine's brush color is its mirror
+ * (the legacy field kept as a compatibility adapter), fed one-directionally
+ * like the view settings — strokes capture the color at gesture start, so a
+ * mid-stroke pair change cannot recolor half an edit;
+ * - unclaimed eyedropper samples route to the active foreground/background
+ * target instead of the brush option.
+ */
+export const CanvasColorFeed = ({ engine }: { engine: CanvasEngineHandle | null }) => {
+ const colorPair = useActiveColorPair();
+ const colorCommands = useActiveColorCommands();
+
+ useEffect(() => {
+ if (!engine) {
+ return;
+ }
+ const options = engine.interaction.get('brushOptions');
+ if (options.color !== colorPair.foreground) {
+ engine.interaction.set('brushOptions', { ...options, color: colorPair.foreground });
+ }
+ }, [engine, colorPair.foreground]);
+
+ useEffect(() => {
+ if (!engine) {
+ return;
+ }
+ return engine.tools.setColorSampleRouter((hex) => {
+ colorCommands.applySampledColor(hex);
+ return true;
+ });
+ }, [colorCommands, engine]);
+
+ return null;
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.test.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.test.ts
new file mode 100644
index 0000000000..1f575729db
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ areColorPairsEqual,
+ CANVAS_ACTIVE_COLORS_KEY,
+ CANVAS_ACTIVE_COLOR_TARGET_KEY,
+ CANVAS_COLOR_PALETTE_KEY,
+ DEFAULT_COLOR_PAIR,
+ MAX_COLOR_PALETTE_SIZE,
+ readActiveColorPair,
+ readActiveColorTarget,
+ readColorPalette,
+ swapColorPair,
+ withoutPaletteColor,
+ withPairColor,
+ withPaletteColor,
+} from './colorPair';
+
+describe('active color pair', () => {
+ it('defaults to black on white with a foreground target', () => {
+ expect(readActiveColorPair(undefined)).toEqual(DEFAULT_COLOR_PAIR);
+ expect(readActiveColorPair({})).toEqual(DEFAULT_COLOR_PAIR);
+ expect(readActiveColorTarget({})).toBe('foreground');
+ });
+
+ it('preserves an existing pair verbatim, so the read is idempotent', () => {
+ const values = { [CANVAS_ACTIVE_COLORS_KEY]: { background: '#112233', foreground: '#abcdef' } };
+ const first = readActiveColorPair(values);
+ expect(first).toEqual({ background: '#112233', foreground: '#abcdef' });
+ expect(readActiveColorPair({ [CANVAS_ACTIVE_COLORS_KEY]: first })).toEqual(first);
+ });
+
+ it('normalizes case and falls back per malformed field', () => {
+ expect(readActiveColorPair({ [CANVAS_ACTIVE_COLORS_KEY]: { background: 12, foreground: '#ABCDEF' } })).toEqual({
+ background: DEFAULT_COLOR_PAIR.background,
+ foreground: '#abcdef',
+ });
+ expect(readActiveColorPair({ [CANVAS_ACTIVE_COLORS_KEY]: 'nope' })).toEqual(DEFAULT_COLOR_PAIR);
+ expect(readActiveColorTarget({ [CANVAS_ACTIVE_COLOR_TARGET_KEY]: 'mask-tint' })).toBe('foreground');
+ expect(readActiveColorTarget({ [CANVAS_ACTIVE_COLOR_TARGET_KEY]: 'background' })).toBe('background');
+ });
+
+ it('flattens alpha bytes and rejects non-hex strings, so the pair stays opaque paint', () => {
+ expect(
+ readActiveColorPair({ [CANVAS_ACTIVE_COLORS_KEY]: { background: 'transparent', foreground: '#ff000080' } })
+ ).toEqual({ background: '#ffffff', foreground: '#ff0000' });
+ expect(withPairColor(DEFAULT_COLOR_PAIR, 'foreground', '#00ff0080').foreground).toBe('#00ff00');
+ });
+
+ it('swaps and writes targets without touching the other slot', () => {
+ const pair = { background: '#ffffff', foreground: '#ff0000' };
+ expect(swapColorPair(pair)).toEqual({ background: '#ff0000', foreground: '#ffffff' });
+ expect(withPairColor(pair, 'background', '#00FF00')).toEqual({ background: '#00ff00', foreground: '#ff0000' });
+ expect(withPairColor(pair, 'foreground', 'garbage').foreground).toBe('#ff0000');
+ expect(areColorPairsEqual(pair, { ...pair })).toBe(true);
+ });
+});
+
+describe('project palette', () => {
+ it('reads only well-formed unique colors up to the cap', () => {
+ expect(readColorPalette(undefined)).toEqual([]);
+ expect(readColorPalette({ [CANVAS_COLOR_PALETTE_KEY]: ['#FF0000', 7, '#ff0000', '#00ff00'] })).toEqual([
+ '#ff0000',
+ '#00ff00',
+ ]);
+ const oversized = Array.from(
+ { length: MAX_COLOR_PALETTE_SIZE + 5 },
+ (_, i) => `#${String(i).padStart(2, '0')}0000`
+ );
+ expect(readColorPalette({ [CANVAS_COLOR_PALETTE_KEY]: oversized })).toHaveLength(MAX_COLOR_PALETTE_SIZE);
+ });
+
+ it('appends new colors, keeps existing ones in place, and removes by value', () => {
+ expect(withPaletteColor(['#111111'], '#222222')).toEqual(['#111111', '#222222']);
+ expect(withPaletteColor(['#111111', '#222222'], '#111111')).toEqual(['#111111', '#222222']);
+ expect(withoutPaletteColor(['#111111', '#222222'], '#111111')).toEqual(['#222222']);
+ });
+
+ it('salvages only parseable entries and refuses additions past the cap', () => {
+ expect(readColorPalette({ [CANVAS_COLOR_PALETTE_KEY]: ['transparent', '#123', 12, '#ff000080'] })).toEqual([
+ '#112233',
+ '#ff0000',
+ ]);
+ const full = Array.from({ length: MAX_COLOR_PALETTE_SIZE }, (_, i) => `#${String(i).padStart(2, '0')}0000`);
+ expect(withPaletteColor(full, '#abcdef')).toEqual(full);
+ expect(withPaletteColor(['#111111'], 'garbage')).toEqual(['#111111']);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.ts
new file mode 100644
index 0000000000..2fcafb7684
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/colorPair.ts
@@ -0,0 +1,103 @@
+/**
+ * The project's active color pair — the desktop-editor foreground/background
+ * colors that seed painting and creation defaults. The pair is a preference:
+ * it persists in the canvas widget's per-project values, never in the document
+ * or its history, and changing it never rewrites selected content. Pure data +
+ * readers; no React, no engine imports — unit-testable in node.
+ */
+
+import { formatHexColor, normalizeHex, parseHexColor } from '@platform/ui/color';
+
+export type ActiveColorTarget = 'foreground' | 'background';
+
+export interface ActiveColorPair {
+ foreground: string;
+ background: string;
+}
+
+/** Persisted keys inside the canvas widget's `state.values`. */
+export const CANVAS_ACTIVE_COLORS_KEY = 'activeColors';
+export const CANVAS_ACTIVE_COLOR_TARGET_KEY = 'activeColorTarget';
+export const CANVAS_COLOR_PALETTE_KEY = 'colorPalette';
+
+export const MAX_COLOR_PALETTE_SIZE = 24;
+
+/** The classic reset pair; the foreground matches the brush default it seeds. */
+export const DEFAULT_COLOR_PAIR: ActiveColorPair = { background: '#ffffff', foreground: '#000000' };
+
+export const isActiveColorTarget = (value: unknown): value is ActiveColorTarget =>
+ value === 'foreground' || value === 'background';
+
+/** The pair and palette are opaque paint colors: parse or reject, and flatten any alpha byte. */
+const toOpaqueHex = (value: unknown): string | null => {
+ if (typeof value !== 'string' || normalizeHex(value, '') === '') {
+ return null;
+ }
+ return formatHexColor(parseHexColor(value));
+};
+
+const readColor = (value: unknown, fallback: string): string => toOpaqueHex(value) ?? fallback;
+
+/**
+ * The persisted widget values are untyped; anything malformed falls back per
+ * field, and an existing pair is preserved verbatim (idempotent migration).
+ */
+export const readActiveColorPair = (values: Record<string, unknown> | undefined): ActiveColorPair => {
+ const raw = values?.[CANVAS_ACTIVE_COLORS_KEY];
+ const pair = typeof raw === 'object' && raw !== null ? (raw as Partial<ActiveColorPair>) : {};
+ return {
+ background: readColor(pair.background, DEFAULT_COLOR_PAIR.background),
+ foreground: readColor(pair.foreground, DEFAULT_COLOR_PAIR.foreground),
+ };
+};
+
+export const readActiveColorTarget = (values: Record<string, unknown> | undefined): ActiveColorTarget => {
+ const raw = values?.[CANVAS_ACTIVE_COLOR_TARGET_KEY];
+ return isActiveColorTarget(raw) ? raw : 'foreground';
+};
+
+export const readColorPalette = (values: Record<string, unknown> | undefined): string[] => {
+ const raw = values?.[CANVAS_COLOR_PALETTE_KEY];
+ if (!Array.isArray(raw)) {
+ return [];
+ }
+ const palette: string[] = [];
+ for (const entry of raw) {
+ const color = toOpaqueHex(entry);
+ if (color === null || palette.length >= MAX_COLOR_PALETTE_SIZE || palette.includes(color)) {
+ continue;
+ }
+ palette.push(color);
+ }
+ return palette;
+};
+
+export const swapColorPair = (pair: ActiveColorPair): ActiveColorPair => ({
+ background: pair.foreground,
+ foreground: pair.background,
+});
+
+export const withPairColor = (pair: ActiveColorPair, target: ActiveColorTarget, color: string): ActiveColorPair => ({
+ ...pair,
+ [target]: toOpaqueHex(color) ?? pair[target],
+});
+
+/** Appends like an artist's palette; a color already present stays put, and a full palette refuses. */
+export const withPaletteColor = (palette: readonly string[], color: string): string[] => {
+ const normalized = toOpaqueHex(color);
+ if (normalized === null || palette.includes(normalized) || palette.length >= MAX_COLOR_PALETTE_SIZE) {
+ return [...palette];
+ }
+ return [...palette, normalized];
+};
+
+export const withoutPaletteColor = (palette: readonly string[], color: string): string[] => {
+ const normalized = toOpaqueHex(color);
+ return palette.filter((entry) => entry !== normalized);
+};
+
+export const areColorPairsEqual = (a: ActiveColorPair, b: ActiveColorPair): boolean =>
+ a.foreground === b.foreground && a.background === b.background;
+
+export const areColorPalettesEqual = (a: readonly string[], b: readonly string[]): boolean =>
+ a.length === b.length && a.every((entry, index) => entry === b[index]);
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.ts b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.ts
new file mode 100644
index 0000000000..174c89c2eb
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/canvas/color-system/useActiveColors.ts
@@ -0,0 +1,105 @@
+/**
+ * React bindings for the active color pair. Every surface that shows or edits
+ * the pair (the Color pane, the Properties chip mirror, the canvas hotkeys and
+ * eyedropper routing) reads and writes the one persisted copy in the canvas
+ * widget's project values through these hooks — no surface holds its own.
+ */
+
+import { getProjectWidgetValues } from '@workbench/widgetState';
+import { useActiveProjectSelector, useWorkbenchCommands, useWorkbenchQueries } from '@workbench/WorkbenchContext';
+import { useMemo } from 'react';
+
+import type { ActiveColorPair, ActiveColorTarget } from './colorPair';
+
+import {
+ areColorPairsEqual,
+ areColorPalettesEqual,
+ CANVAS_ACTIVE_COLOR_TARGET_KEY,
+ CANVAS_ACTIVE_COLORS_KEY,
+ CANVAS_COLOR_PALETTE_KEY,
+ DEFAULT_COLOR_PAIR,
+ readActiveColorPair,
+ readActiveColorTarget,
+ readColorPalette,
+ swapColorPair,
+ withoutPaletteColor,
+ withPairColor,
+ withPaletteColor,
+} from './colorPair';
+
+export const useActiveColorPair = (): ActiveColorPair =>
+ useActiveProjectSelector(
+ (project) => readActiveColorPair(getProjectWidgetValues(project, 'canvas')),
+ areColorPairsEqual
+ );
+
+export const useActiveColorTarget = (): ActiveColorTarget =>
+ useActiveProjectSelector((project) => readActiveColorTarget(getProjectWidgetValues(project, 'canvas')), Object.is);
+
+export const useColorPalette = (): string[] =>
+ useActiveProjectSelector(
+ (project) => readColorPalette(getProjectWidgetValues(project, 'canvas')),
+ areColorPalettesEqual
+ );
+
+export interface ActiveColorCommands {
+ addPaletteColor: (color: string) => void;
+ /** Writes an eyedropper result to whichever target is active. */
+ applySampledColor: (color: string) => void;
+ removePaletteColor: (color: string) => void;
+ resetPair: () => void;
+ setPairColor: (target: ActiveColorTarget, color: string) => void;
+ setTarget: (target: ActiveColorTarget) => void;
+ swapPair: () => void;
+}
+
+export const useActiveColorCommands = (): ActiveColorCommands => {
+ const { widgets } = useWorkbenchCommands();
+ const queries = useWorkbenchQueries();
+
+ return useMemo(() => {
+ const values = (): Record<string, unknown> => getProjectWidgetValues(queries.getSnapshot().activeProject, 'canvas');
+ // A no-op edit must not dispatch: the eyedropper re-samples per pointermove,
+ // and an unchanged patch would still mint a new project snapshot.
+ const patchPair = (current: ActiveColorPair, next: ActiveColorPair): void => {
+ if (!areColorPairsEqual(current, next)) {
+ widgets.patchValues('canvas', { [CANVAS_ACTIVE_COLORS_KEY]: next });
+ }
+ };
+ const patchPalette = (current: readonly string[], next: string[]): void => {
+ if (!areColorPalettesEqual(current, next)) {
+ widgets.patchValues('canvas', { [CANVAS_COLOR_PALETTE_KEY]: next });
+ }
+ };
+
+ return {
+ addPaletteColor: (color) => {
+ const palette = readColorPalette(values());
+ patchPalette(palette, withPaletteColor(palette, color));
+ },
+ applySampledColor: (color) => {
+ const current = values();
+ const pair = readActiveColorPair(current);
+ patchPair(pair, withPairColor(pair, readActiveColorTarget(current), color));
+ },
+ removePaletteColor: (color) => {
+ const palette = readColorPalette(values());
+ patchPalette(palette, withoutPaletteColor(palette, color));
+ },
+ resetPair: () => patchPair(readActiveColorPair(values()), { ...DEFAULT_COLOR_PAIR }),
+ setPairColor: (target, color) => {
+ const pair = readActiveColorPair(values());
+ patchPair(pair, withPairColor(pair, target, color));
+ },
+ setTarget: (target) => {
+ if (readActiveColorTarget(values()) !== target) {
+ widgets.patchValues('canvas', { [CANVAS_ACTIVE_COLOR_TARGET_KEY]: target });
+ }
+ },
+ swapPair: () => {
+ const pair = readActiveColorPair(values());
+ patchPair(pair, swapColorPair(pair));
+ },
+ };
+ }, [queries, widgets]);
+};
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 5ff705850b..a4c1317383 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
@@ -10,6 +10,7 @@ import { HStack } from '@chakra-ui/react';
import { ToggleIconButton } from '@platform/ui/Button';
import { ColorPicker } from '@platform/ui/ColorPicker';
import { MAX_BRUSH_SIZE, MIN_BRUSH_SIZE } from '@workbench/canvas-engine/api';
+import { useActiveColorCommands, useActiveColorPair } from '@workbench/widgets/canvas/color-system/useActiveColors';
import { useBrushOptions } from '@workbench/widgets/canvas/engineStoreHooks';
import {
ToolbarNumberField,
@@ -199,15 +200,17 @@ const BrushOpacity = ({ engine }: ToolbarRegionProps) => {
return <PaintOpacityControl opacity={options.opacity} setOpacity={setOpacity} />;
};
+/** A mirror of the project foreground, not brush-owned state: the pair feeds the engine's brush color. */
const BrushColor = ({ engine }: ToolbarRegionProps) => {
const { t } = useTranslation();
- const [options, set] = useBrushPatch(engine);
- const onColorChange = useCallback((color: string) => set({ color }), [set]);
+ const pair = useActiveColorPair();
+ const { setPairColor } = useActiveColorCommands();
+ const onColorChange = useCallback((color: string) => setPairColor('foreground', color), [setPairColor]);
const sampleColor = useColorSampler(engine);
return (
<ColorPicker
aria-label={t('widgets.canvas.toolOptions.brushColor')}
- value={options.color}
+ value={pair.foreground}
onSampleColor={sampleColor}
onValueChange={onColorChange}
/>
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
index 28c5e4e5eb..0c8423de6e 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/LayersWidgetView.tsx
@@ -12,7 +12,7 @@ import { LayersIcon } from 'lucide-react';
import { useCallback, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
-import type { LayerEditorPaneLayout } from './panes/editorPaneLayout';
+import type { LayerColorPaneLayout, LayerEditorPaneLayout } from './panes/editorPaneLayout';
import { LayerMultiSelectionActions } from './LayerMultiSelectionActions';
import { LAYER_PANEL_DEGRADE_THRESHOLD } from './layerPanelRows';
@@ -20,8 +20,13 @@ import { LayersPanelFooter } from './LayersPanelFooter';
import { LayersPanelHeader } from './LayersPanelHeader';
import { LayersTree } from './LayersTree';
import { buildLayerStackRows } from './layerTreeRows';
-import { areLayerEditorPaneLayoutsEqual, readLayerEditorPaneLayout } from './panes/editorPaneLayout';
-import { LayerEditorPanes } from './panes/LayerEditorPanes';
+import {
+ areColorPaneLayoutsEqual,
+ areLayerEditorPaneLayoutsEqual,
+ readColorPaneLayout,
+ readLayerEditorPaneLayout,
+} from './panes/editorPaneLayout';
+import { LayerColorPane, LayerEditorPanes } from './panes/LayerEditorPanes';
/**
* The layers panel: a fixed header (selected layer's opacity + blend mode, global denoising
@@ -73,9 +78,18 @@ export const LayersWidgetView = ({ runtime }: WidgetViewProps) => {
(next: LayerEditorPaneLayout) => runtime.state.patch({ editorPanes: next }),
[runtime.state]
);
+ const colorPaneLayout = useActiveProjectSelector(
+ (project) => readColorPaneLayout(project.widgetInstances[runtime.instanceId]?.state.values ?? {}),
+ areColorPaneLayoutsEqual
+ );
+ const handleColorPaneLayout = useCallback(
+ (next: LayerColorPaneLayout) => runtime.state.patch({ colorPane: next }),
+ [runtime.state]
+ );
return (
<Stack gap="1" h="full" minH="0">
+ <LayerColorPane layout={colorPaneLayout} onLayoutChange={handleColorPaneLayout} />
<LayersPanelHeader />
<LayerMultiSelectionActions
document={document}
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts
index edcdb7e213..307e8673a1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/manifest.ts
@@ -2,7 +2,7 @@ import type { WidgetManifest } from '@workbench/widgetContracts';
import { LayersIcon } from 'lucide-react';
-import { LAYER_EDITOR_PANE_DEFAULTS } from './panes/editorPaneLayout';
+import { COLOR_PANE_DEFAULTS, LAYER_EDITOR_PANE_DEFAULTS } from './panes/editorPaneLayout';
export const layersWidgetManifest: WidgetManifest = {
allowMultiple: false,
@@ -13,7 +13,7 @@ export const layersWidgetManifest: WidgetManifest = {
label: (t) => t('widgets.labels.layers'),
load: () => import('./implementation').then((module) => module.widgetImplementation),
state: {
- createInitial: () => ({ editorPanes: { ...LAYER_EDITOR_PANE_DEFAULTS } }),
+ createInitial: () => ({ colorPane: { ...COLOR_PANE_DEFAULTS }, editorPanes: { ...LAYER_EDITOR_PANE_DEFAULTS } }),
persistence: 'project',
version: 1,
},
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx
new file mode 100644
index 0000000000..6ace31c40d
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/ColorPane.tsx
@@ -0,0 +1,404 @@
+import type { ActiveColorTarget } from '@workbench/widgets/canvas/color-system/colorPair';
+import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
+
+import { Box, chakra, Flex, HStack, Input, Stack } from '@chakra-ui/react';
+import { IconButton } from '@platform/ui/Button';
+import { formatHexColor, normalizeHex, parseHexColor, type RgbaColor } from '@platform/ui/color';
+import {
+ COLOR_PICKER_FORMATS,
+ recordRecentColor,
+ setColorPickerFormat,
+ setColorPickerMode,
+ useColorPickerFormat,
+ useColorPickerMode,
+ type ColorPickerFormat,
+} from '@platform/ui/colorPickerStore';
+import { hexToHsv, hslToRgb, hsvToHex, rgbToHsl, type HsvColor } from '@platform/ui/hsv';
+import { HsvBoxPicker } from '@platform/ui/HsvBoxPicker';
+import { HsvWheelPicker } from '@platform/ui/HsvWheelPicker';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { Tooltip } from '@platform/ui/Tooltip';
+import {
+ useActiveColorCommands,
+ useActiveColorPair,
+ useActiveColorTarget,
+} from '@workbench/widgets/canvas/color-system/useActiveColors';
+import { ToolbarNumberField } from '@workbench/widgets/canvas/tool-presentation/ToolbarPrimitives';
+import { useCanvasEngine } from '@workbench/widgets/canvas/useCanvasEngine';
+import { ArrowLeftRightIcon, CircleIcon, PipetteIcon, RotateCcwIcon, SquareIcon } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const clamp = (value: number, min: number, max: number): number => Math.min(max, Math.max(min, value));
+
+const FORMAT_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };
+
+/**
+ * The color pane's workspace: the active foreground/background pair with an
+ * explicit target, one picking surface (wheel or box, remembered per user),
+ * and channel inputs in the shared picker format. The shelves live in the
+ * sibling Swatches pane. Everything edits the one persisted pair; nothing here
+ * owns color state of its own beyond the sticky HSV needed to keep hue through
+ * greys.
+ */
+export const ColorPane = () => {
+ const { t } = useTranslation();
+ const engine = useCanvasEngine();
+ const pair = useActiveColorPair();
+ const target = useActiveColorTarget();
+ const commands = useActiveColorCommands();
+ const mode = useColorPickerMode();
+ const activeHex = pair[target];
+
+ // The picker holds HSV so hue survives greys; it resyncs from the pair only
+ // when the pair changed to something the current HSV does not already mean.
+ const [hsv, setHsv] = useState<HsvColor>(() => hexToHsv(activeHex));
+ const [syncedHex, setSyncedHex] = useState(activeHex);
+ if (activeHex !== syncedHex) {
+ setSyncedHex(activeHex);
+ if (hsvToHex(hsv) !== activeHex) {
+ setHsv(hexToHsv(activeHex, hsv));
+ }
+ }
+
+ const applyHsv = useCallback(
+ (next: HsvColor) => {
+ setHsv(next);
+ const hex = hsvToHex(next);
+ setSyncedHex(hex);
+ commands.setPairColor(target, hex);
+ },
+ [commands, target]
+ );
+ // Held arrow keys commit per repeat; the recents shelf hears only the
+ // settled color, not two dozen intermediate hues. An immediate record (hex
+ // commit, pipette) supersedes the pending one, and unmount flushes it.
+ const pendingRecent = useRef<{ hex: string; timer: ReturnType<typeof setTimeout> } | null>(null);
+ const settlePendingRecent = useCallback((record: boolean) => {
+ if (!pendingRecent.current) {
+ return;
+ }
+ clearTimeout(pendingRecent.current.timer);
+ if (record) {
+ recordRecentColor(pendingRecent.current.hex);
+ }
+ pendingRecent.current = null;
+ }, []);
+ useEffect(() => () => settlePendingRecent(true), [settlePendingRecent]);
+ const commitHsv = useCallback(
+ (next: HsvColor) => {
+ applyHsv(next);
+ const hex = hsvToHex(next);
+ settlePendingRecent(false);
+ pendingRecent.current = { hex, timer: setTimeout(() => settlePendingRecent(true), 500) };
+ },
+ [applyHsv, settlePendingRecent]
+ );
+ const applyHex = useCallback(
+ (hex: string) => {
+ if (normalizeHex(hex, '') === '') {
+ return;
+ }
+ // Flattened like the pair itself, so a recent swatch always matches what it sets.
+ const opaque = formatHexColor(parseHexColor(hex));
+ settlePendingRecent(false);
+ commands.setPairColor(target, opaque);
+ recordRecentColor(opaque);
+ },
+ [commands, settlePendingRecent, target]
+ );
+ const sampleFromCanvas = useCallback(async () => {
+ if (!engine) {
+ return;
+ }
+ const hex = await engine.tools.requestColorSample();
+ if (hex) {
+ // Routed through the command so the target is read when the sample lands,
+ // not when the pipette was armed.
+ settlePendingRecent(false);
+ commands.applySampledColor(hex);
+ recordRecentColor(hex);
+ }
+ }, [commands, engine, settlePendingRecent]);
+ const toggleMode = useCallback(() => setColorPickerMode(mode === 'wheel' ? 'box' : 'wheel'), [mode]);
+ const modeLabel =
+ mode === 'wheel' ? t('widgets.layers.colorPane.pickerModeBox') : t('widgets.layers.colorPane.pickerModeWheel');
+
+ return (
+ <Scrollable h="full">
+ <Flex align="flex-start" gap="2.5" p="2">
+ <Box flexShrink={0} w="168px">
+ {mode === 'wheel' ? (
+ <HsvWheelPicker diameterPx={168} value={hsv} onChange={applyHsv} onChangeEnd={commitHsv} />
+ ) : (
+ <HsvBoxPicker heightPx={140} value={hsv} onChange={applyHsv} onChangeEnd={commitHsv} />
+ )}
+ </Box>
+ <Stack flex="1" gap="2" minW="0">
+ <HStack gap="1">
+ <TargetChips pair={pair} target={target} onSelectTarget={commands.setTarget} />
+ <Tooltip content={t('widgets.canvas.commands.swapColors')}>
+ <IconButton
+ aria-label={t('widgets.canvas.commands.swapColors')}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={commands.swapPair}
+ >
+ <ArrowLeftRightIcon size={14} />
+ </IconButton>
+ </Tooltip>
+ <Tooltip content={t('widgets.canvas.commands.resetColors')}>
+ <IconButton
+ aria-label={t('widgets.canvas.commands.resetColors')}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={commands.resetPair}
+ >
+ <RotateCcwIcon size={14} />
+ </IconButton>
+ </Tooltip>
+ <Box flex="1" />
+ {engine ? (
+ <Tooltip content={t('common.colorPicker.sampleFromCanvas')}>
+ <IconButton
+ aria-label={t('common.colorPicker.sampleFromCanvas')}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={sampleFromCanvas}
+ >
+ <PipetteIcon size={14} />
+ </IconButton>
+ </Tooltip>
+ ) : null}
+ <Tooltip content={modeLabel}>
+ <IconButton aria-label={modeLabel} color="fg.muted" size="2xs" variant="ghost" onClick={toggleMode}>
+ {mode === 'wheel' ? <SquareIcon size={14} /> : <CircleIcon size={14} />}
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ <ChannelFields activeHex={activeHex} hsv={hsv} onCommitHex={applyHex} onCommitHsv={commitHsv} />
+ </Stack>
+ </Flex>
+ </Scrollable>
+ );
+};
+
+const TargetChips = ({
+ onSelectTarget,
+ pair,
+ target,
+}: {
+ onSelectTarget: (target: ActiveColorTarget) => void;
+ pair: { foreground: string; background: string };
+ target: ActiveColorTarget;
+}) => {
+ const { t } = useTranslation();
+ return (
+ <HStack flexShrink={0} gap="1" mr="1">
+ <TargetChip
+ colorHex={pair.foreground}
+ isActive={target === 'foreground'}
+ label={t('widgets.layers.colorPane.foreground')}
+ target="foreground"
+ onSelect={onSelectTarget}
+ />
+ <TargetChip
+ colorHex={pair.background}
+ isActive={target === 'background'}
+ label={t('widgets.layers.colorPane.background')}
+ target="background"
+ onSelect={onSelectTarget}
+ />
+ </HStack>
+ );
+};
+
+const TargetChip = ({
+ colorHex,
+ isActive,
+ label,
+ onSelect,
+ target,
+}: {
+ colorHex: string;
+ isActive: boolean;
+ label: string;
+ onSelect: (target: ActiveColorTarget) => void;
+ target: ActiveColorTarget;
+}) => {
+ const style = useMemo(() => ({ backgroundColor: colorHex }), [colorHex]);
+ const select = useCallback(() => onSelect(target), [onSelect, target]);
+ return (
+ <chakra.button
+ aria-label={label}
+ aria-pressed={isActive}
+ borderColor={isActive ? 'accent.solid' : 'border'}
+ borderWidth="2px"
+ cursor="pointer"
+ h="6"
+ rounded="sm"
+ style={style}
+ title={colorHex}
+ type="button"
+ w="6"
+ onClick={select}
+ />
+ );
+};
+
+const CHANNEL_KEYS = {
+ hsb: ['hue', 'saturation', 'brightness'],
+ hsl: ['hue', 'saturation', 'lightness'],
+ rgb: ['red', 'green', 'blue'],
+} as const;
+
+const ChannelFields = ({
+ activeHex,
+ hsv,
+ onCommitHex,
+ onCommitHsv,
+}: {
+ activeHex: string;
+ hsv: HsvColor;
+ onCommitHex: (hex: string) => void;
+ onCommitHsv: (next: HsvColor) => void;
+}) => {
+ const { t } = useTranslation();
+ const format = useColorPickerFormat();
+ const cycleFormat = useCallback(() => {
+ const index = COLOR_PICKER_FORMATS.indexOf(format);
+ setColorPickerFormat(COLOR_PICKER_FORMATS[(index + 1) % COLOR_PICKER_FORMATS.length]!);
+ }, [format]);
+ const rgb = useMemo(() => parseHexColor(activeHex), [activeHex]);
+ const hsl = useMemo(() => rgbToHsl(rgb), [rgb]);
+ const channelValues: Record<Exclude<ColorPickerFormat, 'hex'>, [number, number, number]> = {
+ hsb: [Math.round(hsv.h) % 360, Math.round(hsv.s * 100), Math.round(hsv.v * 100)],
+ hsl: [Math.round(hsl.h) % 360, Math.round(hsl.s * 100), Math.round(hsl.l * 100)],
+ rgb: [rgb.r, rgb.g, rgb.b],
+ };
+ const commitChannel = useCallback(
+ (index: number, raw: number) => {
+ if (format === 'rgb') {
+ const next: RgbaColor = { ...parseHexColor(activeHex) };
+ const channel = (['r', 'g', 'b'] as const)[index]!;
+ next[channel] = clamp(Math.round(raw), 0, 255);
+ onCommitHex(formatHexColor(next));
+ return;
+ }
+ if (format === 'hsl') {
+ const current = rgbToHsl(parseHexColor(activeHex));
+ const next = {
+ // A grey parses hue-agnostic; seed from the sticky hue the wheel shows.
+ h: index === 0 ? clamp(raw, 0, 359.999) : current.s === 0 ? hsv.h : current.h,
+ l: index === 2 ? clamp(raw, 0, 100) / 100 : current.l,
+ s: index === 1 ? clamp(raw, 0, 100) / 100 : current.s,
+ };
+ onCommitHex(formatHexColor(hslToRgb(next)));
+ return;
+ }
+ onCommitHsv({
+ h: index === 0 ? clamp(raw, 0, 359.999) : hsv.h,
+ s: index === 1 ? clamp(raw, 0, 100) / 100 : hsv.s,
+ v: index === 2 ? clamp(raw, 0, 100) / 100 : hsv.v,
+ });
+ },
+ [activeHex, format, hsv, onCommitHex, onCommitHsv]
+ );
+
+ return (
+ <Flex gap="1" wrap="wrap">
+ <chakra.button
+ aria-label={t('widgets.layers.colorPane.format')}
+ color="fg.muted"
+ cursor="pointer"
+ flexShrink={0}
+ fontSize="2xs"
+ fontWeight="700"
+ px="1.5"
+ rounded="sm"
+ textTransform="uppercase"
+ type="button"
+ _hover={FORMAT_HOVER_PROPS}
+ onClick={cycleFormat}
+ >
+ {format}
+ </chakra.button>
+ {format === 'hex' ? (
+ <HexField hex={activeHex} onCommit={onCommitHex} />
+ ) : (
+ CHANNEL_KEYS[format].map((key, index) => (
+ <ChannelNumber
+ key={`${format}:${key}`}
+ index={index}
+ label={t(`widgets.layers.colorPane.channels.${key}`)}
+ value={channelValues[format][index]!}
+ onCommit={commitChannel}
+ />
+ ))
+ )}
+ </Flex>
+ );
+};
+
+const ChannelNumber = ({
+ index,
+ label,
+ onCommit,
+ value,
+}: {
+ index: number;
+ label: string;
+ onCommit: (index: number, raw: number) => void;
+ value: number;
+}) => {
+ const commit = useCallback(
+ ({ valueAsNumber }: { value: string; valueAsNumber: number }) => {
+ if (Number.isFinite(valueAsNumber)) {
+ onCommit(index, valueAsNumber);
+ }
+ },
+ [index, onCommit]
+ );
+ return (
+ <ToolbarNumberField aria-label={label} label={label.slice(0, 1)} value={String(value)} onValueCommit={commit} />
+ );
+};
+
+const HexField = ({ hex, onCommit }: { hex: string; onCommit: (hex: string) => void }) => {
+ const { t } = useTranslation();
+ const [draft, setDraft] = useState<string | null>(null);
+ const onChange = useCallback((event: { target: { value: string } }) => setDraft(event.target.value), []);
+ const commit = useCallback(() => {
+ if (draft !== null && normalizeHex(draft, '') !== '') {
+ onCommit(draft);
+ }
+ setDraft(null);
+ }, [draft, onCommit]);
+ const onKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ commit();
+ } else if (event.key === 'Escape') {
+ setDraft(null);
+ }
+ },
+ [commit]
+ );
+ return (
+ <Input
+ aria-label={t('widgets.layers.colorPane.channels.hex')}
+ flex="1"
+ fontFamily="mono"
+ fontSize="xs"
+ minW="24"
+ size="xs"
+ value={draft ?? hex}
+ onBlur={commit}
+ onChange={onChange}
+ onKeyDown={onKeyDown}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
index f00ae2de8d..5574f748e1 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.browser.test.tsx
@@ -28,12 +28,48 @@ import { I18nextProvider } from 'react-i18next';
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
import { page, userEvent } from 'vitest/browser';
-const harness = vi.hoisted(() => ({ engine: null as unknown, project: null as Project | null }));
-
-vi.mock('@workbench/WorkbenchContext', () => ({
- useActiveProjectSelector: (selector: (project: Project) => unknown) => selector(harness.project!),
- useOptionalWorkbenchCommands: () => null,
+const harness = vi.hoisted(() => ({
+ engine: null as unknown,
+ listeners: new Set<() => void>(),
+ project: null as Project | null,
}));
+
+vi.mock('@workbench/WorkbenchContext', async () => {
+ const { useSyncExternalStore } = await import('react');
+ const subscribe = (listener: () => void) => {
+ harness.listeners.add(listener);
+ return () => harness.listeners.delete(listener);
+ };
+ // Merges into the harness project's widget values and notifies, so pair
+ // edits re-render the way the real store does.
+ const patchValues = (typeId: string, values: Record<string, unknown>) => {
+ const project = harness.project!;
+ const entry = Object.entries(project.widgetInstances).find(([, instance]) => instance.typeId === typeId);
+ if (!entry) {
+ return;
+ }
+ const [instanceId, instance] = entry;
+ harness.project = {
+ ...project,
+ widgetInstances: {
+ ...project.widgetInstances,
+ [instanceId]: { ...instance, state: { ...instance.state, values: { ...instance.state.values, ...values } } },
+ },
+ };
+ harness.listeners.forEach((listener) => listener());
+ };
+ const commands = { widgets: { patchValues } };
+ const queries = { getSnapshot: () => ({ activeProject: harness.project! }) };
+ return {
+ useActiveProjectSelector: (selector: (project: Project) => unknown) => {
+ const project = useSyncExternalStore(subscribe, () => harness.project!);
+ return selector(project);
+ },
+ useOptionalWorkbenchCommands: () => null,
+ useWorkbenchCommands: () => commands,
+ useWorkbenchQueries: () => queries,
+ };
+});
vi.mock('@workbench/useCanvasProjectMutationDispatch', () => ({
useCanvasProjectMutationDispatch: () => () => true,
}));
@@ -41,9 +77,11 @@ vi.mock('@workbench/widgets/canvas/useCanvasEngine', () => ({ useCanvasEngine: (
import type { LayerEditorPaneLayout } from './editorPaneLayout';
+import { ColorPane } from './ColorPane';
import { LAYER_EDITOR_PANE_DEFAULTS } from './editorPaneLayout';
import { LayerEditorPanes } from './LayerEditorPanes';
import { PropertiesPane } from './PropertiesPane';
+import { SwatchesPane } from './SwatchesPane';
import { TransformPane } from './TransformPane';
const i18n = createInstance();
@@ -334,3 +372,50 @@ describe('Layer editor panes host', () => {
expect(document.activeElement).toBe(expand.element());
});
});
+
+describe('Color pane', () => {
+ const canvasValues = () => harness.project!.widgetInstances.canvas!.state.values as Record<string, unknown>;
+
+ it('shows the pair on the wheel and switches the editing target', async () => {
+ await mount(ColorPane);
+ await expect.element(page.getByRole('slider', { exact: true, name: 'Hue' })).toBeVisible();
+ const foreground = page.getByRole('button', { exact: true, name: 'Foreground color' });
+ const background = page.getByRole('button', { exact: true, name: 'Background color' });
+ await expect.element(foreground).toHaveAttribute('aria-pressed', 'true');
+ await act(async () => {
+ await userEvent.click(background);
+ });
+ await expect.element(background).toHaveAttribute('aria-pressed', 'true');
+ await expect.element(foreground).toHaveAttribute('aria-pressed', 'false');
+ });
+
+ it('swaps the pair from the chip row', async () => {
+ await mount(ColorPane);
+ await act(async () => {
+ await userEvent.click(page.getByRole('button', { exact: true, name: 'Swap foreground and background colors' }));
+ });
+ expect(canvasValues().activeColors).toEqual({ background: '#000000', foreground: '#ffffff' });
+ });
+
+ it('writes swatch picks to the active target', async () => {
+ await mount(SwatchesPane);
+ await act(async () => {
+ await userEvent.click(page.getByRole('button', { exact: true, name: '#e07575' }));
+ });
+ expect(canvasValues().activeColors).toMatchObject({ foreground: '#e07575' });
+ });
+
+ it('adds the current color to the project palette and removes it by right-click', async () => {
+ await mount(SwatchesPane);
+ await act(async () => {
+ await userEvent.click(page.getByRole('button', { exact: true, name: 'Add current color to palette' }));
+ });
+ expect(canvasValues().colorPalette).toEqual(['#000000']);
+ const paletteSwatch = page.getByRole('button', { exact: true, name: '#000000' }).last();
+ await act(() =>
+ paletteSwatch.element().dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true }))
+ );
+ await settle();
+ expect(canvasValues().colorPalette).toEqual([]);
+ });
+});
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx
index 5cb77de4be..3a26f24063 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/LayerEditorPanes.tsx
@@ -1,79 +1,108 @@
-import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent } from 'react';
+import type { KeyboardEvent as ReactKeyboardEvent, PointerEvent as ReactPointerEvent, ReactNode } from 'react';
import { Box, chakra, Flex, HStack, Icon, Text } from '@chakra-ui/react';
import { useMountEffect } from '@platform/react/useMountEffect';
import { IconButton } from '@platform/ui/Button';
import { Tooltip } from '@platform/ui/Tooltip';
import { ChevronDownIcon, ChevronUpIcon } from 'lucide-react';
-import { useCallback, useRef, useState } from 'react';
+import { useCallback, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { LayerEditorPaneId, LayerEditorPaneLayout } from './editorPaneLayout';
+import type {
+ LayerColorPaneId,
+ LayerColorPaneLayout,
+ LayerEditorPaneId,
+ LayerEditorPaneLayout,
+ PaneBlockLayout,
+} from './editorPaneLayout';
+import { ColorPane } from './ColorPane';
import {
+ clampColorPaneSize,
clampLayerEditorPaneSize,
+ COLOR_PANE_MAX_SIZE_PX,
+ COLOR_PANE_MIN_SIZE_PX,
LAYER_EDITOR_PANE_MAX_SIZE_PX,
LAYER_EDITOR_PANE_MIN_SIZE_PX,
} from './editorPaneLayout';
import { PropertiesPane } from './PropertiesPane';
+import { SwatchesPane } from './SwatchesPane';
import { TransformPane } from './TransformPane';
-/** The tab strip's height; the collapsed pane block is exactly this tall. */
+/** The tab strip's height; a collapsed pane block is exactly this tall. */
const STRIP_HEIGHT_PX = 40;
const RESIZE_STEP_PX = 16;
/** Parity with the shell panels: releasing at the floor stops there; collapse asks for a real push past it. */
const COLLAPSE_OVERSHOOT_PX = 80;
-const PANEL_ID = 'layer-editor-pane-panel';
const TAB_HOVER_PROPS = { bg: 'bg.muted', color: 'fg' };
const HANDLE_HOVER_PROPS = { bg: 'accent.solid', opacity: 0.45 };
const HANDLE_FOCUS_PROPS = { bg: 'accent.solid', opacity: 0.65, outline: '2px solid {colors.accent.solid}' };
-const PANES: ReadonlyArray<{ id: LayerEditorPaneId; labelKey: string }> = [
- { id: 'properties', labelKey: 'widgets.labels.properties' },
- { id: 'transform', labelKey: 'widgets.labels.transform' },
-];
+interface PaneBlockLabels {
+ collapse: string;
+ expand: string;
+ resize: string;
+ tabs: string;
+}
/**
- * The Layers widget's editor panes: a fixed block under the tree with one tab
- * per pane — the active tool's Properties and the selected layer's Transform.
- * The panes are part of the panel, not movable widgets; the block keeps a
- * preferred height, collapses to its strip, and persists through the widget's
- * project state.
+ * One fixed pane block of the Layers panel: a tab strip over a panel, with a
+ * preferred height, a resize separator on its inner edge, and collapse down to
+ * the strip. `edge` names which end of the panel the block is docked to — a
+ * top block grows downward and a bottom block grows upward. The panes are part
+ * of the panel, never movable widgets.
*/
-export const LayerEditorPanes = ({
+const LayerPaneBlock = ({
+ activePane,
+ blockId,
+ children,
+ clampSize,
+ edge,
+ labels,
layout,
+ maxSizePx,
+ minSizePx,
onLayoutChange,
+ onSelectPane,
+ panes,
}: {
- layout: LayerEditorPaneLayout;
- onLayoutChange: (next: LayerEditorPaneLayout) => void;
+ activePane: string;
+ blockId: string;
+ children: ReactNode;
+ clampSize: (next: number) => number;
+ edge: 'top' | 'bottom';
+ labels: PaneBlockLabels;
+ layout: PaneBlockLayout;
+ maxSizePx: number;
+ minSizePx: number;
+ onLayoutChange: (next: PaneBlockLayout) => void;
+ onSelectPane: (pane: string) => void;
+ panes: ReadonlyArray<{ id: string; label: string }>;
}) => {
- const { t } = useTranslation();
- const { activePane, isCollapsed, sizePx } = layout;
+ const { isCollapsed, sizePx } = layout;
// A drag previews the size locally; the store hears about it on release.
const [previewSizePx, setPreviewSizePx] = useState<number | null>(null);
const drag = useRef<AbortController | null>(null);
const toggleRef = useRef<HTMLButtonElement>(null);
+ // Toward the panel's middle: the direction a drag or grow-key moves the handle.
+ const growSign = edge === 'top' ? 1 : -1;
+ const panelId = `${blockId}-panel`;
useMountEffect(() => () => drag.current?.abort());
const patch = useCallback(
- (next: Partial<LayerEditorPaneLayout>) => onLayoutChange({ ...layout, ...next }),
+ (next: Partial<PaneBlockLayout>) => onLayoutChange({ ...layout, ...next }),
[layout, onLayoutChange]
);
const toggle = useCallback(() => patch({ isCollapsed: !isCollapsed }), [isCollapsed, patch]);
- const selectPane = useCallback(
- (pane: LayerEditorPaneId) =>
- patch(pane === activePane ? { isCollapsed: !isCollapsed } : { activePane: pane, isCollapsed: false }),
- [activePane, isCollapsed, patch]
- );
const commitSize = useCallback(
(next: number) => {
- const clamped = clampLayerEditorPaneSize(next);
+ const clamped = clampSize(next);
if (clamped !== sizePx) {
patch({ sizePx: clamped });
}
},
- [patch, sizePx]
+ [clampSize, patch, sizePx]
);
const onSeparatorPointerDown = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
@@ -89,13 +118,9 @@ export const LayerEditorPanes = ({
// The window listeners carry the drag without capture.
}
const move = (moveEvent: PointerEvent) => {
- latest = sizePx + (startY - moveEvent.clientY);
+ latest = sizePx + (moveEvent.clientY - startY) * growSign;
// Past the overshoot the preview snaps to the strip, so the release's collapse is never a surprise.
- setPreviewSizePx(
- latest <= LAYER_EDITOR_PANE_MIN_SIZE_PX - COLLAPSE_OVERSHOOT_PX
- ? STRIP_HEIGHT_PX
- : clampLayerEditorPaneSize(latest)
- );
+ setPreviewSizePx(latest <= minSizePx - COLLAPSE_OVERSHOOT_PX ? STRIP_HEIGHT_PX : clampSize(latest));
};
const finish = (apply: boolean) => () => {
controller.abort();
@@ -103,7 +128,7 @@ export const LayerEditorPanes = ({
if (!apply) {
return;
}
- if (latest <= LAYER_EDITOR_PANE_MIN_SIZE_PX - COLLAPSE_OVERSHOOT_PX) {
+ if (latest <= minSizePx - COLLAPSE_OVERSHOOT_PX) {
patch({ isCollapsed: true });
return;
}
@@ -113,34 +138,36 @@ export const LayerEditorPanes = ({
window.addEventListener('pointerup', finish(true), { signal: controller.signal });
window.addEventListener('pointercancel', finish(false), { signal: controller.signal });
},
- [commitSize, patch, sizePx]
+ [clampSize, commitSize, growSign, minSizePx, patch, sizePx]
);
const onSeparatorKeyDown = useCallback(
(event: ReactKeyboardEvent<HTMLDivElement>) => {
const step = event.shiftKey ? RESIZE_STEP_PX * 2 : RESIZE_STEP_PX;
+ const grow = edge === 'top' ? 'ArrowDown' : 'ArrowUp';
+ const shrink = edge === 'top' ? 'ArrowUp' : 'ArrowDown';
const change =
- event.key === 'ArrowUp'
+ event.key === grow
? step
- : event.key === 'ArrowDown'
+ : event.key === shrink
? -step
: event.key === 'End'
- ? LAYER_EDITOR_PANE_MAX_SIZE_PX - sizePx
+ ? maxSizePx - sizePx
: event.key === 'Home'
- ? LAYER_EDITOR_PANE_MIN_SIZE_PX - sizePx
+ ? minSizePx - sizePx
: undefined;
if (change === undefined) {
return;
}
event.preventDefault();
// A further collapse-ward step at the floor collapses; the separator unmounts, so focus moves to the strip first.
- if (change < 0 && sizePx <= LAYER_EDITOR_PANE_MIN_SIZE_PX) {
+ if (change < 0 && sizePx <= minSizePx) {
toggleRef.current?.focus();
patch({ isCollapsed: true });
return;
}
commitSize(sizePx + change);
},
- [commitSize, patch, sizePx]
+ [commitSize, edge, maxSizePx, minSizePx, patch, sizePx]
);
const focusSibling = useCallback((event: ReactKeyboardEvent<HTMLElement>) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight' && event.key !== 'Home' && event.key !== 'End') {
@@ -161,115 +188,259 @@ export const LayerEditorPanes = ({
tabs[next]?.focus();
}, []);
- const collapseLabel = isCollapsed ? t('widgets.layers.panes.expand') : t('widgets.layers.panes.collapse');
+ const collapseLabel = isCollapsed ? labels.expand : labels.collapse;
+ const collapseIcon =
+ edge === 'top' ? (isCollapsed ? ChevronDownIcon : ChevronUpIcon) : isCollapsed ? ChevronUpIcon : ChevronDownIcon;
+ const separator = !isCollapsed ? (
+ <Box flexShrink={0} h="1px" position="relative" zIndex="1">
+ <Box
+ aria-label={labels.resize}
+ aria-orientation="horizontal"
+ aria-valuemax={maxSizePx}
+ aria-valuemin={minSizePx}
+ aria-valuenow={sizePx}
+ cursor="ns-resize"
+ h="2"
+ left="0"
+ opacity="0"
+ position="absolute"
+ right="0"
+ role="separator"
+ tabIndex={0}
+ top="-4px"
+ transition="opacity var(--wb-motion-duration-fast) ease"
+ _focusVisible={HANDLE_FOCUS_PROPS}
+ _hover={HANDLE_HOVER_PROPS}
+ onKeyDown={onSeparatorKeyDown}
+ onPointerDown={onSeparatorPointerDown}
+ />
+ </Box>
+ ) : null;
+ const strip = (
+ <HStack align="center" flexShrink={0} gap="0.5" h={`${STRIP_HEIGHT_PX}px`} minW="0" px="1.5">
+ <HStack
+ aria-label={labels.tabs}
+ aria-orientation="horizontal"
+ flex="1"
+ gap="0.5"
+ minW="0"
+ overflow="hidden"
+ role="tablist"
+ onKeyDown={focusSibling}
+ >
+ {panes.map((pane) => (
+ <PaneTab
+ key={pane.id}
+ blockId={blockId}
+ id={pane.id}
+ isExpanded={!isCollapsed}
+ isSelected={pane.id === activePane}
+ label={pane.label}
+ onSelect={onSelectPane}
+ />
+ ))}
+ </HStack>
+ <Tooltip content={collapseLabel}>
+ <IconButton
+ ref={toggleRef}
+ aria-expanded={!isCollapsed}
+ aria-label={collapseLabel}
+ color="fg.muted"
+ size="2xs"
+ variant="ghost"
+ onClick={toggle}
+ >
+ <Icon as={collapseIcon} boxSize="3.5" />
+ </IconButton>
+ </Tooltip>
+ </HStack>
+ );
+ const panel = !isCollapsed ? (
+ <Box
+ aria-labelledby={`${blockId}-tab-${activePane}`}
+ flex="1"
+ id={panelId}
+ minH="0"
+ overflow="hidden"
+ role="tabpanel"
+ >
+ {children}
+ </Box>
+ ) : null;
return (
<Flex
borderColor="border.subtle"
- borderTopWidth="1px"
- data-layer-editor-panes={isCollapsed ? 'collapsed' : 'expanded'}
+ data-layer-pane-block={blockId}
+ data-pane-collapsed={isCollapsed ? '' : undefined}
direction="column"
flex={isCollapsed ? '0 0 auto' : `0 1 ${previewSizePx ?? sizePx}px`}
minH={`${STRIP_HEIGHT_PX}px`}
overflow="hidden"
+ {...(edge === 'top' ? { borderBottomWidth: '1px' } : { borderTopWidth: '1px' })}
>
- {!isCollapsed ? (
- <Box flexShrink={0} h="1px" position="relative" zIndex="1">
- <Box
- aria-label={t('widgets.layers.panes.resize')}
- aria-orientation="horizontal"
- aria-valuemax={LAYER_EDITOR_PANE_MAX_SIZE_PX}
- aria-valuemin={LAYER_EDITOR_PANE_MIN_SIZE_PX}
- aria-valuenow={sizePx}
- cursor="ns-resize"
- h="2"
- left="0"
- opacity="0"
- position="absolute"
- right="0"
- role="separator"
- tabIndex={0}
- top="-4px"
- transition="opacity var(--wb-motion-duration-fast) ease"
- _focusVisible={HANDLE_FOCUS_PROPS}
- _hover={HANDLE_HOVER_PROPS}
- onKeyDown={onSeparatorKeyDown}
- onPointerDown={onSeparatorPointerDown}
- />
- </Box>
- ) : null}
- <HStack align="center" flexShrink={0} gap="0.5" h={`${STRIP_HEIGHT_PX}px`} minW="0" px="1.5">
- <HStack
- aria-label={t('widgets.layers.panes.tabs')}
- aria-orientation="horizontal"
- flex="1"
- gap="0.5"
- minW="0"
- overflow="hidden"
- role="tablist"
- onKeyDown={focusSibling}
- >
- {PANES.map((pane) => (
- <PaneTab
- key={pane.id}
- id={pane.id}
- isExpanded={!isCollapsed}
- isSelected={pane.id === activePane}
- label={t(pane.labelKey)}
- onSelect={selectPane}
- />
- ))}
- </HStack>
- <Tooltip content={collapseLabel}>
- <IconButton
- ref={toggleRef}
- aria-expanded={!isCollapsed}
- aria-label={collapseLabel}
- color="fg.muted"
- size="2xs"
- variant="ghost"
- onClick={toggle}
- >
- <Icon as={isCollapsed ? ChevronUpIcon : ChevronDownIcon} boxSize="3.5" />
- </IconButton>
- </Tooltip>
- </HStack>
- {!isCollapsed ? (
- <Box
- aria-labelledby={`layer-editor-pane-tab-${activePane}`}
- flex="1"
- id={PANEL_ID}
- minH="0"
- overflow="hidden"
- role="tabpanel"
- >
- {activePane === 'transform' ? <TransformPane /> : <PropertiesPane />}
- </Box>
- ) : null}
+ {edge === 'top' ? (
+ <>
+ {strip}
+ {panel}
+ {separator}
+ </>
+ ) : (
+ <>
+ {separator}
+ {strip}
+ {panel}
+ </>
+ )}
</Flex>
);
};
+const EDITOR_PANES: ReadonlyArray<{ id: LayerEditorPaneId; labelKey: string }> = [
+ { id: 'properties', labelKey: 'widgets.labels.properties' },
+ { id: 'transform', labelKey: 'widgets.labels.transform' },
+];
+
+/**
+ * The editor panes under the tree: the active tool's Properties and the
+ * selected layer's Transform, persisted through the widget's project state.
+ */
+export const LayerEditorPanes = ({
+ layout,
+ onLayoutChange,
+}: {
+ layout: LayerEditorPaneLayout;
+ onLayoutChange: (next: LayerEditorPaneLayout) => void;
+}) => {
+ const { t } = useTranslation();
+ const { activePane } = layout;
+ const panes = useMemo(() => EDITOR_PANES.map(({ id, labelKey }) => ({ id, label: t(labelKey) })), [t]);
+ const labels = useMemo<PaneBlockLabels>(
+ () => ({
+ collapse: t('widgets.layers.panes.collapse'),
+ expand: t('widgets.layers.panes.expand'),
+ resize: t('widgets.layers.panes.resize'),
+ tabs: t('widgets.layers.panes.tabs'),
+ }),
+ [t]
+ );
+ const onSelectPane = useCallback(
+ (pane: string) =>
+ onLayoutChange(
+ pane === layout.activePane
+ ? { ...layout, isCollapsed: !layout.isCollapsed }
+ : { ...layout, activePane: pane as LayerEditorPaneId, isCollapsed: false }
+ ),
+ [layout, onLayoutChange]
+ );
+ const onBlockLayoutChange = useCallback(
+ (next: PaneBlockLayout) => onLayoutChange({ ...layout, ...next }),
+ [layout, onLayoutChange]
+ );
+
+ return (
+ <LayerPaneBlock
+ activePane={activePane}
+ blockId="layer-editor-pane"
+ clampSize={clampLayerEditorPaneSize}
+ edge="bottom"
+ labels={labels}
+ layout={layout}
+ maxSizePx={LAYER_EDITOR_PANE_MAX_SIZE_PX}
+ minSizePx={LAYER_EDITOR_PANE_MIN_SIZE_PX}
+ onLayoutChange={onBlockLayoutChange}
+ onSelectPane={onSelectPane}
+ panes={panes}
+ >
+ {activePane === 'transform' ? <TransformPane /> : <PropertiesPane />}
+ </LayerPaneBlock>
+ );
+};
+
+const COLOR_PANES: ReadonlyArray<{ id: LayerColorPaneId; labelKey: string }> = [
+ { id: 'color', labelKey: 'widgets.labels.color' },
+ { id: 'swatches', labelKey: 'widgets.labels.swatches' },
+];
+
+/**
+ * The color panes above the tree: the project foreground/background pair with
+ * its picker and channels, and the swatch shelves as a sibling tab — the
+ * layers panel's persistent color workspace.
+ */
+export const LayerColorPane = ({
+ layout,
+ onLayoutChange,
+}: {
+ layout: LayerColorPaneLayout;
+ onLayoutChange: (next: LayerColorPaneLayout) => void;
+}) => {
+ const { t } = useTranslation();
+ const { activePane } = layout;
+ const panes = useMemo(() => COLOR_PANES.map(({ id, labelKey }) => ({ id, label: t(labelKey) })), [t]);
+ const labels = useMemo<PaneBlockLabels>(
+ () => ({
+ collapse: t('widgets.layers.colorPane.collapse'),
+ expand: t('widgets.layers.colorPane.expand'),
+ resize: t('widgets.layers.colorPane.resize'),
+ tabs: t('widgets.layers.colorPane.tabs'),
+ }),
+ [t]
+ );
+ const onSelectPane = useCallback(
+ (pane: string) =>
+ onLayoutChange(
+ pane === layout.activePane
+ ? { ...layout, isCollapsed: !layout.isCollapsed }
+ : { ...layout, activePane: pane as LayerColorPaneId, isCollapsed: false }
+ ),
+ [layout, onLayoutChange]
+ );
+ const onBlockLayoutChange = useCallback(
+ (next: PaneBlockLayout) => onLayoutChange({ ...layout, ...next }),
+ [layout, onLayoutChange]
+ );
+
+ return (
+ <LayerPaneBlock
+ activePane={activePane}
+ blockId="layer-color-pane"
+ clampSize={clampColorPaneSize}
+ edge="top"
+ labels={labels}
+ layout={layout}
+ maxSizePx={COLOR_PANE_MAX_SIZE_PX}
+ minSizePx={COLOR_PANE_MIN_SIZE_PX}
+ onLayoutChange={onBlockLayoutChange}
+ onSelectPane={onSelectPane}
+ panes={panes}
+ >
+ {activePane === 'swatches' ? <SwatchesPane /> : <ColorPane />}
+ </LayerPaneBlock>
+ );
+};
+
const PaneTab = ({
+ blockId,
id,
isExpanded,
isSelected,
label,
onSelect,
}: {
- id: LayerEditorPaneId;
+ blockId: string;
+ id: string;
/** Collapsed keeps the selected tab focusable and selected; only the shown look changes. */
isExpanded: boolean;
isSelected: boolean;
label: string;
- onSelect: (pane: LayerEditorPaneId) => void;
+ onSelect: (pane: string) => void;
}) => {
const select = useCallback(() => onSelect(id), [id, onSelect]);
const isShown = isSelected && isExpanded;
return (
<chakra.button
- aria-controls={isShown ? PANEL_ID : undefined}
+ aria-controls={isShown ? `${blockId}-panel` : undefined}
aria-selected={isSelected}
bg={isShown ? 'bg.emphasized' : 'transparent'}
color={isShown ? 'fg' : 'fg.muted'}
@@ -278,7 +449,7 @@ const PaneTab = ({
fontSize="xs"
fontWeight="600"
h="7"
- id={`layer-editor-pane-tab-${id}`}
+ id={`${blockId}-tab-${id}`}
px="2.5"
role="tab"
rounded="md"
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx
new file mode 100644
index 0000000000..a9330b14b0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/SwatchesPane.tsx
@@ -0,0 +1,183 @@
+import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent, ReactNode } from 'react';
+
+import { chakra, Flex, HStack, Stack, Text } from '@chakra-ui/react';
+import { IconButton } from '@platform/ui/Button';
+import { formatHexColor, normalizeHex, parseHexColor } from '@platform/ui/color';
+import { DEFAULT_COLOR_SWATCHES, recordRecentColor, useRecentColors } from '@platform/ui/colorPickerStore';
+import { Scrollable } from '@platform/ui/Scrollable';
+import { Tooltip } from '@platform/ui/Tooltip';
+import { MAX_COLOR_PALETTE_SIZE } from '@workbench/widgets/canvas/color-system/colorPair';
+import {
+ useActiveColorCommands,
+ useActiveColorPair,
+ useActiveColorTarget,
+ useColorPalette,
+} from '@workbench/widgets/canvas/color-system/useActiveColors';
+import { PlusIcon } from 'lucide-react';
+import { useCallback, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+/**
+ * The swatches pane: the workbench defaults, the account's recent colors, and
+ * the project palette. A pick writes the active foreground/background target —
+ * the shelves share the Color pane's one persisted pair and own nothing.
+ */
+export const SwatchesPane = () => {
+ const { t } = useTranslation();
+ const pair = useActiveColorPair();
+ const target = useActiveColorTarget();
+ const palette = useColorPalette();
+ const commands = useActiveColorCommands();
+ const recents = useRecentColors();
+ const activeHex = pair[target];
+
+ const applyHex = useCallback(
+ (hex: string) => {
+ if (normalizeHex(hex, '') === '') {
+ return;
+ }
+ // Flattened like the pair itself, so a pick (even of a legacy alpha
+ // recent) records what it actually sets.
+ const opaque = formatHexColor(parseHexColor(hex));
+ commands.setPairColor(target, opaque);
+ recordRecentColor(opaque);
+ },
+ [commands, target]
+ );
+ const addToPalette = useCallback(() => commands.addPaletteColor(activeHex), [activeHex, commands]);
+ const removeFromPalette = useCallback((color: string) => commands.removePaletteColor(color), [commands]);
+ const canAddToPalette = !palette.includes(activeHex) && palette.length < MAX_COLOR_PALETTE_SIZE;
+ const addButton = useMemo(
+ () => (
+ <Tooltip content={t('widgets.layers.colorPane.addToPalette')}>
+ <IconButton
+ aria-label={t('widgets.layers.colorPane.addToPalette')}
+ color="fg.muted"
+ disabled={!canAddToPalette}
+ size="2xs"
+ variant="ghost"
+ onClick={addToPalette}
+ >
+ <PlusIcon size={14} />
+ </IconButton>
+ </Tooltip>
+ ),
+ [addToPalette, canAddToPalette, t]
+ );
+
+ return (
+ <Scrollable h="full">
+ <Stack gap="2.5" p="2">
+ <SwatchShelf
+ activeHex={activeHex}
+ colors={DEFAULT_COLOR_SWATCHES}
+ label={t('widgets.layers.colorPane.swatches')}
+ onPick={applyHex}
+ />
+ {recents.length > 0 ? (
+ <SwatchShelf
+ activeHex={activeHex}
+ colors={recents}
+ label={t('widgets.layers.colorPane.recents')}
+ onPick={applyHex}
+ />
+ ) : null}
+ <SwatchShelf
+ activeHex={activeHex}
+ colors={palette}
+ label={t('widgets.layers.colorPane.palette')}
+ trailing={addButton}
+ onPick={applyHex}
+ onRemove={removeFromPalette}
+ />
+ </Stack>
+ </Scrollable>
+ );
+};
+
+const SwatchShelf = ({
+ activeHex,
+ colors,
+ label,
+ onPick,
+ onRemove,
+ trailing,
+}: {
+ activeHex: string;
+ colors: readonly string[];
+ label: string;
+ onPick: (hex: string) => void;
+ onRemove?: (hex: string) => void;
+ trailing?: ReactNode;
+}) => (
+ <Stack gap="1.5">
+ <HStack justify="space-between" minH="5">
+ <Text color="fg.muted" fontSize="2xs" fontWeight="600" textTransform="uppercase">
+ {label}
+ </Text>
+ {trailing}
+ </HStack>
+ <Flex aria-label={label} gap="1" role="group" wrap="wrap">
+ {colors.map((color) => (
+ <Swatch key={color} color={color} isActive={color === activeHex} onPick={onPick} onRemove={onRemove} />
+ ))}
+ </Flex>
+ </Stack>
+);
+
+const Swatch = ({
+ color,
+ isActive,
+ onPick,
+ onRemove,
+}: {
+ color: string;
+ isActive: boolean;
+ onPick: (hex: string) => void;
+ onRemove?: (hex: string) => void;
+}) => {
+ const { t } = useTranslation();
+ const style = useMemo(() => ({ backgroundColor: color }), [color]);
+ const pick = useCallback(() => onPick(color), [color, onPick]);
+ const onContextMenu = useCallback(
+ (event: ReactMouseEvent<HTMLButtonElement>) => {
+ if (onRemove) {
+ event.preventDefault();
+ onRemove(color);
+ }
+ },
+ [color, onRemove]
+ );
+ const onKeyDown = useCallback(
+ (event: ReactKeyboardEvent<HTMLButtonElement>) => {
+ if (onRemove && (event.key === 'Delete' || event.key === 'Backspace')) {
+ event.preventDefault();
+ // The button unmounts on removal; keep the keyboard user on the shelf.
+ const sibling = (event.currentTarget.nextElementSibling ??
+ event.currentTarget.previousElementSibling) as HTMLElement | null;
+ sibling?.focus();
+ onRemove(color);
+ }
+ },
+ [color, onRemove]
+ );
+
+ return (
+ <chakra.button
+ aria-label={color}
+ aria-pressed={isActive}
+ borderColor={isActive ? 'accent.solid' : 'border.subtle'}
+ borderWidth="1px"
+ cursor="pointer"
+ h="6"
+ rounded="sm"
+ style={style}
+ title={onRemove ? t('widgets.layers.colorPane.removeSwatchHint', { color }) : color}
+ type="button"
+ w="6"
+ onClick={pick}
+ onContextMenu={onContextMenu}
+ onKeyDown={onKeyDown}
+ />
+ );
+};
diff --git a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts
index 64d909a96f..b5f8fa63d6 100644
--- a/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts
+++ b/invokeai/frontend/webv2/src/workbench/widgets/layers/panes/editorPaneLayout.ts
@@ -1,13 +1,17 @@
-/** Pure layout contract for the Layers widget's editor panes; the manifest seeds it, so no React here. */
+/** Pure layout contracts for the Layers widget's pane blocks; the manifest seeds them, so no React here. */
export type LayerEditorPaneId = 'properties' | 'transform';
-export interface LayerEditorPaneLayout {
- activePane: LayerEditorPaneId;
+/** What every pane block persists: its preferred height and whether it is collapsed to its strip. */
+export interface PaneBlockLayout {
isCollapsed: boolean;
sizePx: number;
}
+export interface LayerEditorPaneLayout extends PaneBlockLayout {
+ activePane: LayerEditorPaneId;
+}
+
export const LAYER_EDITOR_PANE_MIN_SIZE_PX = 140;
export const LAYER_EDITOR_PANE_MAX_SIZE_PX = 560;
@@ -38,3 +42,44 @@ export const readLayerEditorPaneLayout = (values: Record<string, unknown>): Laye
export const areLayerEditorPaneLayoutsEqual = (a: LayerEditorPaneLayout, b: LayerEditorPaneLayout): boolean =>
a.activePane === b.activePane && a.isCollapsed === b.isCollapsed && a.sizePx === b.sizePx;
+
+export type LayerColorPaneId = 'color' | 'swatches';
+
+export interface LayerColorPaneLayout extends PaneBlockLayout {
+ activePane: LayerColorPaneId;
+}
+
+export const COLOR_PANE_MIN_SIZE_PX = 160;
+export const COLOR_PANE_MAX_SIZE_PX = 560;
+
+export const COLOR_PANE_DEFAULTS: LayerColorPaneLayout = {
+ activePane: 'color',
+ isCollapsed: false,
+ sizePx: 236,
+};
+
+/** Defaults from the unreleased taller layouts; a stored exact match adopts the current default. */
+const LEGACY_COLOR_PANE_DEFAULT_SIZES = new Set([300, 420]);
+
+export const clampColorPaneSize = (sizePx: number): number =>
+ Math.min(COLOR_PANE_MAX_SIZE_PX, Math.max(COLOR_PANE_MIN_SIZE_PX, Math.round(sizePx)));
+
+const isColorPaneId = (value: unknown): value is LayerColorPaneId => value === 'color' || value === 'swatches';
+
+export const readColorPaneLayout = (values: Record<string, unknown>): LayerColorPaneLayout => {
+ const raw = values.colorPane;
+ const layout = typeof raw === 'object' && raw !== null ? (raw as Partial<LayerColorPaneLayout>) : {};
+ return {
+ activePane: isColorPaneId(layout.activePane) ? layout.activePane : COLOR_PANE_DEFAULTS.activePane,
+ isCollapsed: typeof layout.isCollapsed === 'boolean' ? layout.isCollapsed : COLOR_PANE_DEFAULTS.isCollapsed,
+ sizePx:
+ typeof layout.sizePx === 'number' &&
+ Number.isFinite(layout.sizePx) &&
+ !LEGACY_COLOR_PANE_DEFAULT_SIZES.has(layout.sizePx)
+ ? clampColorPaneSize(layout.sizePx)
+ : COLOR_PANE_DEFAULTS.sizePx,
+ };
+};
+
+export const areColorPaneLayoutsEqual = (a: LayerColorPaneLayout, b: LayerColorPaneLayout): boolean =>
+ a.activePane === b.activePane && a.isCollapsed === b.isCollapsed && a.sizePx === b.sizePx;