fix(web): share accessible color picker controls (#12355)

This commit is contained in:
Julius Marminge authored and GitHub committed 2026-09-17 20:42:30 -07:00
1 parent cc39ec1008
commit 994654198d
7 files changed
+616 -331

No files matched your search

@@ -21,6 +21,7 @@ import { Input } from "../ui/input";
import { RadioGroup } from "../ui/radio-group";
import { toastManager } from "../ui/toast";
import { DRIVER_OPTION_BY_VALUE, DRIVER_OPTIONS } from "./providerDriverMeta";
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
import { ProviderSettingsForm, deriveProviderSettingsFields } from "./ProviderSettingsForm";
import { WizardPanel, WizardPopup, WizardHeader, WizardFooter } from "../ui/wizard";
import {
@@ -338,12 +339,11 @@ export function AddProviderInstanceDialog({
<div className={cn("grid gap-2", wizardStep !== 1 && "hidden")}>
<span className="text-xs font-medium text-foreground">Accent color</span>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<input
type="color"
value={normalizeProviderAccentColor(accentColor) ?? PROVIDER_ACCENT_SWATCHES[0]}
onChange={(event) => setAccentColor(event.target.value)}
aria-label="Provider instance accent color"
className="h-8 w-10 cursor-pointer rounded-xl border border-input bg-background p-0.5"
<ProviderAccentColorPicker
displayName={label || driverOption.label}
value={accentColor || undefined}
onCommit={setAccentColor}
layout="inline"
/>
<div className="flex flex-wrap gap-1.5">
{PROVIDER_ACCENT_SWATCHES.map((swatch) => {
@@ -1,8 +1,11 @@
"use client";
import { PipetteIcon, XIcon } from "lucide-react";
import { useCallback, useEffect, useMemo, useRef, useState, type PointerEvent } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color";
import { ColorHueSlider, ColorSaturationValuePlane } from "../ui/color-picker";
import { Input } from "../ui/input";
import { Button } from "../ui/button";
import { Popover, PopoverClose, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { normalizeProviderAccentColor } from "../../providerInstances";
@@ -10,149 +13,40 @@ import { cn } from "../../lib/utils";
const FALLBACK_ACCENT_COLOR = "#2563eb";
function clamp(value: number, min = 0, max = 1) {
return Math.min(max, Math.max(min, value));
}
function hexToHsv(hex: string) {
const normalized = normalizeProviderAccentColor(hex) ?? FALLBACK_ACCENT_COLOR;
const numeric = Number.parseInt(normalized.slice(1), 16);
const red = ((numeric >> 16) & 255) / 255;
const green = ((numeric >> 8) & 255) / 255;
const blue = (numeric & 255) / 255;
const max = Math.max(red, green, blue);
const min = Math.min(red, green, blue);
const delta = max - min;
let hue = 0;
if (delta !== 0) {
if (max === red) {
hue = ((green - blue) / delta) % 6;
} else if (max === green) {
hue = (blue - red) / delta + 2;
} else {
hue = (red - green) / delta + 4;
}
hue *= 60;
if (hue < 0) hue += 360;
}
return {
h: hue,
s: max === 0 ? 0 : delta / max,
v: max,
};
}
function hsvToHex(hue: number, saturation: number, value: number) {
const chroma = value * saturation;
const x = chroma * (1 - Math.abs(((hue / 60) % 2) - 1));
const match = value - chroma;
const [red, green, blue] =
hue < 60
? [chroma, x, 0]
: hue < 120
? [x, chroma, 0]
: hue < 180
? [0, chroma, x]
: hue < 240
? [0, x, chroma]
: hue < 300
? [x, 0, chroma]
: [chroma, 0, x];
return `#${[red, green, blue]
.map((channel) =>
Math.round((channel + match) * 255)
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
}
function ProviderCustomColorPanel(props: {
readonly value: string;
readonly onCommit: (value: string) => void;
}) {
const { onCommit } = props;
const initialHsv = useMemo(() => hexToHsv(props.value), [props.value]);
const [hsv, setHsv] = useState(initialHsv);
const [hsv, setHsv] = useState(() => hexToHsv(props.value));
const currentColor = hsvToHex(hsv.h, hsv.s, hsv.v);
const [hexDraft, setHexDraft] = useState<string | null>(null);
const commitHsv = useCallback(
(nextHsv: typeof hsv) => {
(nextHsv: HsvColor) => {
setHsv(nextHsv);
onCommit(hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v));
},
[onCommit],
);
const updateFromPlane = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const bounds = event.currentTarget.getBoundingClientRect();
const saturation = clamp((event.clientX - bounds.left) / bounds.width);
const value = 1 - clamp((event.clientY - bounds.top) / bounds.height);
commitHsv({ ...hsv, s: saturation, v: value });
},
[commitHsv, hsv],
);
const updateFromHue = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const bounds = event.currentTarget.getBoundingClientRect();
commitHsv({ ...hsv, h: clamp((event.clientX - bounds.left) / bounds.width) * 360 });
},
[commitHsv, hsv],
);
const handlePointerDown = (handler: (event: PointerEvent<HTMLDivElement>) => void) => {
return (event: PointerEvent<HTMLDivElement>) => {
event.currentTarget.setPointerCapture(event.pointerId);
handler(event);
};
};
return (
<div className="w-56 bg-popover">
<div
className="relative h-36 cursor-crosshair touch-none"
style={{
backgroundColor: `hsl(${hsv.h} 100% 50%)`,
backgroundImage:
"linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)",
}}
onPointerDown={handlePointerDown(updateFromPlane)}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
updateFromPlane(event);
}
}}
>
<span
className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.35)]"
style={{ left: `${hsv.s * 100}%`, top: `${(1 - hsv.v) * 100}%` }}
/>
</div>
<ColorSaturationValuePlane
label="Accent color"
value={hsv}
onChange={commitHsv}
variant="edge"
/>
<div className="grid gap-3 p-3">
<div
className="relative h-3 cursor-pointer touch-none rounded-full"
style={{
background: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
}}
onPointerDown={handlePointerDown(updateFromHue)}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) {
updateFromHue(event);
}
}}
>
<span
className="pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.35)]"
style={{ left: `${(hsv.h / 360) * 100}%`, backgroundColor: currentColor }}
/>
</div>
<input
<ColorHueSlider
label="Accent color hue"
value={hsv.h}
onChange={(h) => commitHsv({ ...hsv, h })}
/>
<Input
nativeInput
size="sm"
value={hexDraft ?? currentColor}
onChange={(event) => {
const nextColor = event.currentTarget.value;
@@ -162,7 +56,7 @@ function ProviderCustomColorPanel(props: {
props.onCommit(nextColor);
}}
onBlur={() => setHexDraft(null)}
className="h-8 rounded-md border border-input bg-background px-2 font-mono text-xs text-foreground outline-none transition-colors focus:border-ring"
className="font-mono text-xs"
aria-label="Custom hex accent color"
spellCheck={false}
/>
@@ -1,7 +1,8 @@
import type { KeyboardEvent, PointerEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette";
import { cn } from "../../lib/utils";
import { hexToHsv, hsvToHex, type HsvColor } from "../../lib/color";
import { ColorHueSlider, ColorSaturationValuePlane } from "../ui/color-picker";
import { Input } from "../ui/input";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
@@ -27,16 +28,6 @@ export function getThemeRoleLabel(role: ThemeColorRole): string {
return role.replace(/([A-Z])/g, " $1").replace(/^./, (character) => character.toUpperCase());
}
type ThemeColorHsv = {
h: number;
s: number;
v: number;
};
function clampThemeColor(value: number, min = 0, max = 1) {
return Math.min(max, Math.max(min, value));
}
/**
* The picker remains an sRGB/hex adapter over the OKLCH palette engine. Alpha
* is preserved separately and re-attached on commit so adjusting hue or
@@ -52,63 +43,6 @@ function normalizeThemePickerColor(value: string): string {
return (themeColorToHex(value) ?? "#000000").slice(0, 7);
}
function themeHexToHsv(hex: string): ThemeColorHsv {
const normalized = normalizeThemePickerColor(hex);
const numeric = Number.parseInt(normalized.slice(1), 16);
const red = ((numeric >> 16) & 255) / 255;
const green = ((numeric >> 8) & 255) / 255;
const blue = (numeric & 255) / 255;
const max = Math.max(red, green, blue);
const min = Math.min(red, green, blue);
const delta = max - min;
let hue = 0;
if (delta !== 0) {
if (max === red) {
hue = ((green - blue) / delta) % 6;
} else if (max === green) {
hue = (blue - red) / delta + 2;
} else {
hue = (red - green) / delta + 4;
}
hue *= 60;
if (hue < 0) hue += 360;
}
return {
h: hue,
s: max === 0 ? 0 : delta / max,
v: max,
};
}
function themeHsvToHex(hue: number, saturation: number, value: number) {
const normalizedHue = ((hue % 360) + 360) % 360;
const chroma = value * saturation;
const x = chroma * (1 - Math.abs(((normalizedHue / 60) % 2) - 1));
const match = value - chroma;
const [red, green, blue] =
normalizedHue < 60
? [chroma, x, 0]
: normalizedHue < 120
? [x, chroma, 0]
: normalizedHue < 180
? [0, chroma, x]
: normalizedHue < 240
? [0, x, chroma]
: normalizedHue < 300
? [x, 0, chroma]
: [chroma, 0, x];
return `#${[red, green, blue]
.map((channel) =>
Math.round((channel + match) * 255)
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
}
function themeHexToRgb(hex: string) {
const numeric = Number.parseInt(normalizeThemePickerColor(hex).slice(1), 16);
return [numeric >> 16, (numeric >> 8) & 255, numeric & 255] as const;
@@ -148,12 +82,11 @@ function ThemeColorPickerPanel({
}) {
const normalizedValue = normalizeThemePickerColor(value);
const alphaSuffix = themePickerAlphaSuffix(value);
const [hsv, setHsv] = useState(() => themeHexToHsv(normalizedValue));
const [hsv, setHsv] = useState(() => hexToHsv(normalizedValue));
const [hexDraft, setHexDraft] = useState(normalizedValue);
const [rgbDraft, setRgbDraft] = useState(() => themeRgbValue(normalizedValue));
const [isDragging, setIsDragging] = useState(false);
const isEditingTextRef = useRef(false);
const currentColor = themeHsvToHex(hsv.h, hsv.s, hsv.v);
const currentColor = hsvToHex(hsv.h, hsv.s, hsv.v);
const currentRgb = themeRgbValue(currentColor);
useEffect(() => {
@@ -167,9 +100,9 @@ function ThemeColorPickerPanel({
// Keep the current hue/saturation when the incoming value is just our own
// change echoed back; hex → HSV is lossy for greys, white, and black.
setHsv((current) =>
themeHsvToHex(current.h, current.s, current.v) === normalizedValue
hsvToHex(current.h, current.s, current.v) === normalizedValue
? current
: themeHexToHsv(normalizedValue),
: hexToHsv(normalizedValue),
);
}, [normalizedValue]);
@@ -203,9 +136,9 @@ function ThemeColorPickerPanel({
}, []);
const commitHsv = useCallback(
(nextHsv: ThemeColorHsv) => {
(nextHsv: HsvColor) => {
setHsv(nextHsv);
const nextColor = themeHsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);
const nextColor = hsvToHex(nextHsv.h, nextHsv.s, nextHsv.v);
setHexDraft(nextColor);
setRgbDraft(themeRgbValue(nextColor));
scheduleCommit(nextColor + alphaSuffix);
@@ -213,69 +146,10 @@ function ThemeColorPickerPanel({
[alphaSuffix, scheduleCommit],
);
const updateFromPlane = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const bounds = event.currentTarget.getBoundingClientRect();
const saturation = clampThemeColor((event.clientX - bounds.left) / bounds.width);
const value = 1 - clampThemeColor((event.clientY - bounds.top) / bounds.height);
commitHsv({ ...hsv, s: saturation, v: value });
},
[commitHsv, hsv],
);
const updateFromHue = useCallback(
(event: PointerEvent<HTMLDivElement>) => {
const bounds = event.currentTarget.getBoundingClientRect();
const hue = clampThemeColor((event.clientX - bounds.left) / bounds.width) * 360;
commitHsv({ ...hsv, h: hue });
},
[commitHsv, hsv],
);
const handleHueKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
const step = event.shiftKey ? 10 : 1;
const direction = event.key === "ArrowRight" || event.key === "ArrowUp" ? 1 : -1;
if (!["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(event.key)) return;
event.preventDefault();
commitHsv({ ...hsv, h: (hsv.h + direction * step + 360) % 360 });
};
const handlePlaneKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(event.key)) return;
event.preventDefault();
const step = event.shiftKey ? 0.1 : 0.02;
const nextHsv = { ...hsv };
if (event.key === "ArrowLeft") nextHsv.s = clampThemeColor(hsv.s - step);
if (event.key === "ArrowRight") nextHsv.s = clampThemeColor(hsv.s + step);
if (event.key === "ArrowUp") nextHsv.v = clampThemeColor(hsv.v + step);
if (event.key === "ArrowDown") nextHsv.v = clampThemeColor(hsv.v - step);
commitHsv(nextHsv);
};
const handlePointerDown = (handler: (event: PointerEvent<HTMLDivElement>) => void) => {
return (event: PointerEvent<HTMLDivElement>) => {
event.currentTarget.setPointerCapture(event.pointerId);
setIsDragging(true);
handler(event);
};
};
const stopDragging = () => {
setIsDragging(false);
flushPendingCommit();
};
// Thumbs travel inside the control by half their own size so they never
// clip at the extremes; movement only animates for keyboard steps and
// click-to-jump, never while dragging.
const thumbTransition = isDragging
? undefined
: "left 80ms linear, top 80ms linear, background-color 80ms linear";
const handleHexChange = (nextValue: string) => {
setHexDraft(nextValue);
if (!/^#[0-9a-f]{6}$/i.test(nextValue)) return;
const nextHsv = themeHexToHsv(nextValue);
const nextHsv = hexToHsv(nextValue);
setHsv(nextHsv);
setRgbDraft(themeRgbValue(nextValue));
onChange(nextValue.toLowerCase());
@@ -285,7 +159,7 @@ function ThemeColorPickerPanel({
setRgbDraft(nextValue);
const nextColor = themeRgbToHex(nextValue);
if (!nextColor) return;
setHsv(themeHexToHsv(nextColor));
setHsv(hexToHsv(nextColor));
setHexDraft(nextColor);
// RGB cannot express alpha, so a commit keeps the incoming suffix just
// like the plane and hue controls do.
@@ -305,68 +179,18 @@ function ThemeColorPickerPanel({
/>
</div>
<div className="grid gap-3 px-3 pb-3 pt-3">
<div
aria-label={`${label} saturation and brightness`}
aria-valuetext={`saturation ${Math.round(hsv.s * 100)}%, brightness ${Math.round(hsv.v * 100)}%`}
className="relative h-32 cursor-crosshair touch-none overflow-hidden rounded-lg outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover"
role="slider"
style={{
backgroundColor: `hsl(${hsv.h} 100% 50%)`,
backgroundImage:
"linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)",
}}
tabIndex={0}
onKeyDown={handlePlaneKeyDown}
onLostPointerCapture={stopDragging}
onPointerDown={handlePointerDown(updateFromPlane)}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) updateFromPlane(event);
}}
onPointerUp={stopDragging}
>
<span
className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.4)]"
style={{
left: `calc(${hsv.s} * (100% - 0.75rem) + 0.375rem)`,
top: `calc(${1 - hsv.v} * (100% - 0.75rem) + 0.375rem)`,
transition: thumbTransition,
}}
/>
</div>
<div
aria-label={`${label} hue`}
aria-valuemax={360}
aria-valuemin={0}
aria-valuenow={Math.round(hsv.h)}
className="relative flex h-6 cursor-pointer touch-none items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover"
role="slider"
tabIndex={0}
onKeyDown={handleHueKeyDown}
onLostPointerCapture={stopDragging}
onPointerDown={handlePointerDown(updateFromHue)}
onPointerMove={(event) => {
if (event.currentTarget.hasPointerCapture(event.pointerId)) updateFromHue(event);
}}
onPointerUp={stopDragging}
>
<span
aria-hidden
className="h-2.5 w-full rounded-full shadow-[inset_0_0_0_1px_rgb(0_0_0_/_12%)]"
style={{
background: "linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)",
}}
/>
<span
className="pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.4)]"
style={{
left: `calc(${hsv.h / 360} * (100% - 1rem) + 0.5rem)`,
// The ball shows the pure hue so it stays visually anchored to
// the track; the header swatch carries the full current color.
backgroundColor: `hsl(${hsv.h} 100% 50%)`,
transition: thumbTransition,
}}
/>
</div>
<ColorSaturationValuePlane
label={label}
value={hsv}
onChange={commitHsv}
onInteractionEnd={flushPendingCommit}
/>
<ColorHueSlider
label={`${label} hue`}
value={hsv.h}
onChange={(h) => commitHsv({ ...hsv, h })}
onInteractionEnd={flushPendingCommit}
/>
<div className="grid grid-cols-[1fr_1.2fr] gap-2">
<label className="grid min-w-0 gap-1">
<span className="px-1 text-[10px] font-semibold uppercase tracking-[0.08em] text-muted-foreground">
@@ -0,0 +1,256 @@
import { act, type ReactNode, type ReactElement } from "react";
import { create, type ReactTestRenderer } from "react-test-renderer";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
// Render popover content without portals so these tests exercise picker input
// and persistence behavior without starting a browser.
vi.mock("../ui/popover", () => ({
Popover: ({ children }: { children: ReactNode }) => children,
PopoverPopup: ({ children }: { children: ReactNode }) => children,
PopoverTrigger: () => null,
PopoverClose: () => null,
}));
vi.mock("../ui/tooltip", () => ({
Tooltip: ({ children }: { children: ReactNode }) => children,
TooltipTrigger: ({ render }: { render: ReactElement }) => render,
TooltipPopup: () => null,
}));
import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker";
import { ThemeColorField } from "./ThemeColorPicker";
let renderer: ReactTestRenderer | undefined;
let nextFrameId = 0;
const frames = new Map<number, FrameRequestCallback>();
beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {
frames.set(++nextFrameId, callback);
return nextFrameId;
});
vi.stubGlobal("cancelAnimationFrame", (id: number) => frames.delete(id));
});
afterEach(async () => {
await act(async () => renderer?.unmount());
renderer = undefined;
frames.clear();
vi.useRealTimers();
vi.unstubAllGlobals();
});
function slider(label: string) {
return renderer!.root.find(
(node) =>
(node.props.role === "slider" || node.props.type === "range") &&
node.props["aria-label"] === label,
);
}
function plane(label: string) {
return renderer!.root.findByProps({ role: "group", "aria-label": label });
}
async function key(label: string, key: string, shiftKey = false) {
const preventDefault = vi.fn();
await act(async () => slider(label).props.onKeyDown({ key, shiftKey, preventDefault }));
return preventDefault;
}
function pointer(clientX: number, clientY = 0, pointerId = 1) {
return {
button: 0,
clientX,
clientY,
pointerId,
currentTarget: {
focus: vi.fn(),
setPointerCapture: vi.fn(),
getBoundingClientRect: () => ({ left: 0, top: 0, width: 100, height: 100 }),
},
};
}
async function frame() {
await act(async () => {
const pending = [...frames.values()];
frames.clear();
for (const callback of pending) callback(0);
});
}
describe("shared color controls in settings", () => {
it("adjusts each provider color axis independently and reports the value being changed", async () => {
const onCommit = vi.fn();
await act(async () => {
renderer = create(
<ProviderAccentColorPicker displayName="Codex" value="#ff0000" onCommit={onCommit} />,
);
});
const hue = "Accent color hue";
const saturation = "Accent color saturation";
const brightness = "Accent color brightness";
expect(await key(hue, "ArrowLeft")).toHaveBeenCalledOnce();
expect(slider(hue).props["aria-valuenow"]).toBe(359);
await key(hue, "ArrowRight");
expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
await key(saturation, "ArrowRight", true);
await key(brightness, "ArrowUp", true);
expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
await key(brightness, "ArrowDown", true);
expect(onCommit).toHaveBeenLastCalledWith("#e60000");
expect(slider(brightness).props.value).toBe(90);
expect(slider(brightness).props["aria-valuetext"]).toBe("90%");
expect(slider(saturation).props.value).toBe(100);
// Up/Down on saturation must adjust the reported saturation, not brightness.
await key(saturation, "ArrowDown", true);
expect(onCommit).toHaveBeenLastCalledWith("#e61717");
expect(slider(saturation).props.value).toBe(90);
expect(slider(saturation).props["aria-valuetext"]).toBe("90%");
await key(saturation, "ArrowUp", true);
expect(onCommit).toHaveBeenLastCalledWith("#e60000");
// Left/Right on brightness must likewise leave saturation unchanged.
await key(brightness, "ArrowLeft", true);
expect(onCommit).toHaveBeenLastCalledWith("#cc0000");
await key(brightness, "ArrowRight", true);
expect(onCommit).toHaveBeenLastCalledWith("#e60000");
onCommit.mockClear();
expect(await key(saturation, "Tab")).not.toHaveBeenCalled();
expect(await key(brightness, "Tab")).not.toHaveBeenCalled();
expect(onCommit).not.toHaveBeenCalled();
});
it("supports Home/End and clamps each axis without changing the other", async () => {
const onCommit = vi.fn();
await act(async () => {
renderer = create(
<ProviderAccentColorPicker displayName="Codex" value="#ff0000" onCommit={onCommit} />,
);
});
const saturation = "Accent color saturation";
const brightness = "Accent color brightness";
await key(saturation, "Home");
await key(saturation, "ArrowLeft");
expect(slider(saturation).props.value).toBe(0);
expect(onCommit).toHaveBeenLastCalledWith("#ffffff");
await key(brightness, "Home");
await key(brightness, "ArrowDown");
expect(slider(brightness).props.value).toBe(0);
expect(onCommit).toHaveBeenLastCalledWith("#000000");
await key(saturation, "End");
expect(slider(saturation).props.value).toBe(100);
expect(slider(brightness).props.value).toBe(0);
await key(brightness, "End");
await key(brightness, "ArrowUp");
expect(onCommit).toHaveBeenLastCalledWith("#ff0000");
await key(saturation, "ArrowLeft");
expect(slider(saturation).props.value).toBe(98);
expect(onCommit).toHaveBeenLastCalledWith("#ff0505");
});
it("persists independent native range changes through theme batching with alpha", async () => {
const onChange = vi.fn();
await act(async () => {
renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);
});
const saturation = "Accent color saturation";
const brightness = "Accent color brightness";
await act(async () =>
slider(saturation).props.onChange({ currentTarget: { valueAsNumber: 50 } }),
);
await act(async () =>
slider(brightness).props.onChange({ currentTarget: { valueAsNumber: 50 } }),
);
expect(onChange).not.toHaveBeenCalled();
expect(frames.size).toBe(1);
await frame();
expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#80404080");
await key(brightness, "ArrowDown", true);
await frame();
expect(onChange).toHaveBeenLastCalledWith("accent", "#66333380");
expect(slider(saturation).props.value).toBe(50);
});
it("batches theme drag updates and flushes the final color with alpha on pointer release", async () => {
const onChange = vi.fn();
await act(async () => {
renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);
});
const hue = "Accent color hue";
await act(async () => slider(hue).props.onPointerDown(pointer(25)));
await act(async () => slider(hue).props.onPointerMove(pointer(50)));
expect(onChange).not.toHaveBeenCalled();
expect(frames.size).toBe(1);
// A second pointer cannot change or end the active drag.
await act(async () => slider(hue).props.onPointerMove(pointer(75, 0, 2)));
await act(async () => slider(hue).props.onPointerUp(pointer(75, 0, 2)));
expect(onChange).not.toHaveBeenCalled();
await act(async () => slider(hue).props.onPointerUp(pointer(50)));
expect(onChange).toHaveBeenCalledExactlyOnceWith("accent", "#00ffff80");
await act(async () => slider(hue).props.onLostPointerCapture(pointer(50)));
await frame();
expect(onChange).toHaveBeenCalledTimes(1);
});
it("clamps out-of-bounds drags and flushes theme changes on cancellation and unmount", async () => {
const onChange = vi.fn();
await act(async () => {
renderer = create(<ThemeColorField role="accent" value="#ff000080" onChange={onChange} />);
});
const planeLabel = "Accent color saturation and brightness";
await act(async () => plane(planeLabel).props.onPointerDown(pointer(-50, -50)));
await act(async () => plane(planeLabel).props.onPointerCancel(pointer(-50, -50)));
expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff80");
await act(async () => plane(planeLabel).props.onPointerDown(pointer(150, 150)));
await act(async () => renderer!.unmount());
renderer = undefined;
expect(onChange).toHaveBeenLastCalledWith("accent", "#00000080");
expect(frames.size).toBe(0);
});
it("preserves the selected hue when a grey color is echoed back from theme settings", async () => {
const onChange = vi.fn();
const render = (value: string) => (
<ThemeColorField role="accent" value={value} onChange={onChange} />
);
await act(async () => {
renderer = create(render("#ff0000"));
});
const hue = "Accent color hue";
const planeLabel = "Accent color saturation and brightness";
await key(hue, "ArrowRight", true);
await act(async () => plane(planeLabel).props.onPointerDown(pointer(0, 0)));
await frame();
expect(onChange).toHaveBeenLastCalledWith("accent", "#ffffff");
await act(async () => renderer!.update(render("#ffffff")));
expect(slider(hue).props["aria-valuenow"]).toBe(10);
});
it("keeps provider debounce at the consumer and commits pending color on unmount", async () => {
vi.useFakeTimers();
const onCommit = vi.fn();
await act(async () => {
renderer = create(
<ProviderAccentColorPicker
displayName="Codex"
value="#ff0000"
onCommit={onCommit}
commitDelayMs={250}
/>,
);
});
const hue = "Accent color hue";
await key(hue, "ArrowRight", true);
await key(hue, "ArrowRight", true);
expect(onCommit).not.toHaveBeenCalled();
await act(async () => vi.advanceTimersByTime(250));
expect(onCommit).toHaveBeenCalledExactlyOnceWith("#ff5500");
await key(hue, "ArrowRight", true);
await act(async () => renderer!.unmount());
renderer = undefined;
expect(onCommit).toHaveBeenLastCalledWith("#ff8000");
await act(async () => vi.advanceTimersByTime(250));
expect(onCommit).toHaveBeenCalledTimes(2);
});
});
+225
View File
@@ -0,0 +1,225 @@
import {
useId,
useRef,
useState,
type KeyboardEvent,
type PointerEvent,
type RefObject,
} from "react";
import type { HsvColor } from "../../lib/color";
import { cn } from "../../lib/utils";
function clamp(value: number) {
return Math.min(1, Math.max(0, value));
}
/** Keep pointer capture and drag completion consistent across color controls. */
function useColorDrag(
update: (event: PointerEvent<HTMLDivElement>) => void,
onInteractionEnd?: () => void,
focusTarget?: RefObject<HTMLElement | null>,
) {
const [isDragging, setIsDragging] = useState(false);
const pointerId = useRef<number | null>(null);
const stopDragging = (event: PointerEvent<HTMLDivElement>) => {
if (pointerId.current !== event.pointerId) return;
pointerId.current = null;
setIsDragging(false);
onInteractionEnd?.();
};
return {
// The thumb stays inside the control at its extremes, and only animates
// keyboard adjustments, never continuous pointer movement.
thumbTransition: isDragging
? undefined
: "left 80ms linear, top 80ms linear, background-color 80ms linear",
handlers: {
onPointerDown(event: PointerEvent<HTMLDivElement>) {
if (pointerId.current !== null || event.button !== 0) return;
pointerId.current = event.pointerId;
(focusTarget?.current ?? event.currentTarget).focus({ preventScroll: true });
event.currentTarget.setPointerCapture(event.pointerId);
setIsDragging(true);
update(event);
},
onPointerMove(event: PointerEvent<HTMLDivElement>) {
if (pointerId.current === event.pointerId) update(event);
},
onPointerUp: stopDragging,
onPointerCancel: stopDragging,
onLostPointerCapture: stopDragging,
},
};
}
type ColorControlProps<T> = {
label: string;
value: T;
onChange: (value: T) => void;
/** Flush pending consumer updates when pointer interaction finishes. */
onInteractionEnd?: () => void;
className?: string;
};
export function ColorSaturationValuePlane({
label,
value,
onChange,
onInteractionEnd,
className,
variant = "inset",
}: ColorControlProps<HsvColor> & { variant?: "inset" | "edge" }) {
const instructionsId = useId();
const saturationRef = useRef<HTMLInputElement>(null);
const { handlers, thumbTransition } = useColorDrag(
(event) => {
const bounds = event.currentTarget.getBoundingClientRect();
if (!bounds.width || !bounds.height) return;
onChange({
...value,
s: clamp((event.clientX - bounds.left) / bounds.width),
v: 1 - clamp((event.clientY - bounds.top) / bounds.height),
});
},
onInteractionEnd,
saturationRef,
);
const handleKeyDown = (event: KeyboardEvent<HTMLInputElement>, axis: "s" | "v") => {
const step = event.shiftKey ? 0.1 : 0.02;
let nextValue: number;
switch (event.key) {
case "ArrowRight":
case "ArrowUp":
nextValue = clamp(value[axis] + step);
break;
case "ArrowLeft":
case "ArrowDown":
nextValue = clamp(value[axis] - step);
break;
case "Home":
nextValue = 0;
break;
case "End":
nextValue = 1;
break;
default:
return;
}
event.preventDefault();
onChange({ ...value, [axis]: nextValue });
};
return (
<div
aria-label={`${label} saturation and brightness`}
role="group"
className={cn(
"relative cursor-crosshair touch-none overflow-hidden bg-[linear-gradient(to_top,#000,transparent),linear-gradient(to_right,#fff,transparent)] has-[:focus-visible]:ring-2 has-[:focus-visible]:ring-ring has-[:focus-visible]:ring-offset-2 has-[:focus-visible]:ring-offset-popover",
variant === "edge" ? "h-36 rounded-none" : "h-32 rounded-lg",
className,
)}
style={{
backgroundColor: `hsl(${value.h} 100% 50%)`,
}}
{...handlers}
>
<span id={instructionsId} className="sr-only">
Use arrow keys to adjust the focused value. Hold Shift for larger steps. Use Home and End
for the minimum and maximum. Press Tab to move between saturation and brightness.
</span>
{(
[
["s", "Saturation"],
["v", "Brightness"],
] as const
).map(([axis, axisLabel]) => (
<label key={axis} className="contents">
<input
ref={axis === "s" ? saturationRef : undefined}
type="range"
min={0}
max={100}
step="any"
value={value[axis] * 100}
aria-label={`${label} ${axisLabel.toLowerCase()}`}
aria-describedby={instructionsId}
aria-valuetext={`${Math.round(value[axis] * 100)}%`}
className="peer sr-only"
onKeyDown={(event) => handleKeyDown(event, axis)}
onChange={(event) =>
onChange({ ...value, [axis]: event.currentTarget.valueAsNumber / 100 })
}
/>
<span
aria-hidden
className="pointer-events-none invisible absolute bottom-2 left-2 z-10 rounded bg-popover px-1.5 py-0.5 text-xs text-popover-foreground peer-focus-visible:visible"
>
{axisLabel} {Math.round(value[axis] * 100)}%
</span>
</label>
))}
<span
className="pointer-events-none absolute size-3 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.4)]"
style={{
left: `calc(${value.s} * (100% - 0.75rem) + 0.375rem)`,
top: `calc(${1 - value.v} * (100% - 0.75rem) + 0.375rem)`,
transition: thumbTransition,
}}
/>
</div>
);
}
export function ColorHueSlider({
label,
value,
onChange,
onInteractionEnd,
className,
}: ColorControlProps<number>) {
const { handlers, thumbTransition } = useColorDrag((event) => {
const bounds = event.currentTarget.getBoundingClientRect();
if (!bounds.width) return;
onChange(clamp((event.clientX - bounds.left) / bounds.width) * 360);
}, onInteractionEnd);
const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
if (!["ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(event.key)) return;
event.preventDefault();
const step = event.shiftKey ? 10 : 1;
const direction = event.key === "ArrowRight" || event.key === "ArrowUp" ? 1 : -1;
onChange((value + direction * step + 360) % 360);
};
return (
<div
aria-label={label}
aria-valuemax={360}
aria-valuemin={0}
aria-valuenow={Math.round(value)}
className={cn(
"relative flex h-6 cursor-pointer touch-none items-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-popover",
className,
)}
role="slider"
tabIndex={0}
onKeyDown={handleKeyDown}
{...handlers}
>
<span
aria-hidden
className="h-2.5 w-full rounded-full bg-[linear-gradient(to_right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)] shadow-[inset_0_0_0_1px_rgb(0_0_0_/_12%)]"
/>
<span
className="pointer-events-none absolute top-1/2 size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.4)]"
style={{
left: `calc(${value / 360} * (100% - 1rem) + 0.5rem)`,
backgroundColor: `hsl(${value} 100% 50%)`,
transition: thumbTransition,
}}
/>
</div>
);
}
+24
View File
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vite-plus/test";
import { hexToHsv, hsvToHex } from "./color";
describe("picker color conversion", () => {
it.each(["#000000", "#ffffff", "#808080", "#ff0000", "#00ff00", "#0000ff", "#2563eb"])(
"round trips %s through HSV without changing the persisted color",
(hex) => {
const { h, s, v } = hexToHsv(hex);
expect(hsvToHex(h, s, v)).toBe(hex);
},
);
it("wraps hue at the slider boundary and across keyboard steps", () => {
expect(hsvToHex(360, 1, 1)).toBe("#ff0000");
expect(hsvToHex(720, 1, 1)).toBe("#ff0000");
expect(hsvToHex(-60, 1, 1)).toBe("#ff00ff");
});
it("represents black and greys without undefined saturation", () => {
expect(hexToHsv("#000000")).toEqual({ h: 0, s: 0, v: 0 });
expect(hexToHsv("#ffffff")).toEqual({ h: 0, s: 0, v: 1 });
});
});
+62
View File
@@ -0,0 +1,62 @@
export type HsvColor = {
h: number;
s: number;
v: number;
};
/** Convert a normalized six-digit sRGB hex color to HSV. */
export function hexToHsv(hex: string): HsvColor {
const numeric = Number.parseInt(hex.slice(1), 16);
const red = ((numeric >> 16) & 255) / 255;
const green = ((numeric >> 8) & 255) / 255;
const blue = (numeric & 255) / 255;
const max = Math.max(red, green, blue);
const min = Math.min(red, green, blue);
const delta = max - min;
let hue = 0;
if (delta !== 0) {
if (max === red) {
hue = ((green - blue) / delta) % 6;
} else if (max === green) {
hue = (blue - red) / delta + 2;
} else {
hue = (red - green) / delta + 4;
}
hue *= 60;
if (hue < 0) hue += 360;
}
return {
h: hue,
s: max === 0 ? 0 : delta / max,
v: max,
};
}
export function hsvToHex(hue: number, saturation: number, value: number) {
const normalizedHue = ((hue % 360) + 360) % 360;
const chroma = value * saturation;
const x = chroma * (1 - Math.abs(((normalizedHue / 60) % 2) - 1));
const match = value - chroma;
const [red, green, blue] =
normalizedHue < 60
? [chroma, x, 0]
: normalizedHue < 120
? [x, chroma, 0]
: normalizedHue < 180
? [0, chroma, x]
: normalizedHue < 240
? [0, x, chroma]
: normalizedHue < 300
? [x, 0, chroma]
: [chroma, 0, x];
return `#${[red, green, blue]
.map((channel) =>
Math.round((channel + match) * 255)
.toString(16)
.padStart(2, "0"),
)
.join("")}`;
}