Skip to content
Shaken UI
Sign in

Color Picker

Save

A swatch button that opens a saturation and brightness area, hue and opacity sliders, hex, RGB and HSL fields, an eyedropper, presets and recent colors.

Category
Forms
Version
0.1.1
Frameworks
Next.js, Vite + React
Styling
Tailwind CSS v4

Preview

Color Picker preview
hex
#0ea5e9cc
rgb
rgb(14 165 233 / 0.8)
hsl
hsl(199 89% 48% / 0.8)

Installation

npx @shakenui/cli add color-picker

Review the plan first. A dry run lists every file and package without changing anything:

npx @shakenui/cli add color-picker --dry-run

Usage

color-picker-example.tsx
"use client";

import { useState } from "react";
import { ColorPicker } from "@/components/shaken/ui/color-picker";

const labelColors = ["#ef4444", "#f59e0b", "#10b981", "#06b6d4", "#6366f1", "#a855f7", "#ec4899", "#71717a"];

export default function ColorPickerExample() {
  const [accent, setAccent] = useState("#6366f1");

  return (
    <div className="flex flex-wrap items-start justify-center gap-6">
      <div className="grid gap-1.5">
        <label htmlFor="brand-accent" className="text-sm font-medium text-zinc-950 dark:text-white">
          Brand accent
        </label>
        <ColorPicker id="brand-accent" value={accent} onValueChange={setAccent} alpha defaultRecent={["#0ea5e9", "#f43f5e"]} />
        <p className="max-w-64 text-xs text-zinc-500">
          Used for links and the primary button in the{" "}
          <span className="font-medium" style={{ color: accent }}>
            customer portal
          </span>
        </p>
      </div>
      <div className="grid gap-1.5">
        <label htmlFor="label-color" className="text-sm font-medium text-zinc-950 dark:text-white">
          Label color
        </label>
        <ColorPicker id="label-color" defaultValue="#10b981" presets={labelColors} />
      </div>
    </div>
  );
}

API

PropTypeDefaultDescription
value / defaultValue / onValueChangestring"#3b82f6"The color. Accepts hex, rgb() and hsl(); emits "#rrggbb", or "#rrggbbaa" when alpha is on and the color is translucent.
alphabooleanfalseAdds the opacity slider and channel.
presetsstring[]defaultColorPresetsSwatches under the controls, nine to a row. Pass [] to hide them.
eyeDropperbooleantrueShows the eyedropper button where the browser has the EyeDropper API.
defaultRecent / recentLimit / onRecentChangestring[] / number / (recent) => void[] / 8ColorPicker: the recent row. Closing the popover with a new color adds it.
disabled / name / id / aria-label / classNameboolean / string—ColorPicker: trigger state, a hidden input for forms, attributes, and trigger classes.
side / align"top" | "bottom" | "left" | "right" / "start" | "center" | "end""bottom" / "start"ColorPicker: popover placement.
ColorPanelcomponent—The surface on its own for inline use; also takes recent and previous (the color the preview compares against).
parseColor / toHex / hsvToRgb / rgbToHsv / hsvToHsl / hslToHsvfunctions—The color math, exported for reuse. No dependencies.

Accessibility

  • The trigger is a Base UI Popover trigger whose text is the hex value; Escape closes the popover and focus returns to it.
  • The area is a role="slider" with aria-roledescription "2D slider" and a value text such as "Saturation 72%, brightness 40%". Left and Right change saturation, Up and Down brightness, Shift for steps of 10%, Home and End and Page Up and Page Down jump to the edges.
  • Hue and Opacity are role="slider" with degrees and percent value texts; arrows step by 1 (Shift by 10), Home and End jump to the ends.
  • Every channel field has a name (Hex color, Red, Hue, Opacity); typing commits on Enter or blur and snaps back if invalid, Escape drops the edit, Up and Down step numeric channels. The format is a native select.
  • Swatches are buttons named by their hex value with aria-pressed on the current one. The preview's left half is a button that restores the previous color.
  • The eyedropper button is labeled "Pick a color from the screen" and only renders where the API exists.
  • The thumb lift and the crosshair guides animate only with motion allowed; with reduced motion they change without transitions.

Files

Installed into src/components/shaken, or components/shaken when the project has no src directory.

  • src/components/shaken/ui/color-picker.tsxcolor-picker
  • Also installs popover@0.2.2registry dependency
  • npm packages: noneReact and Tailwind CSS v4 required

Source

The exact source the CLI installs, from /r/items/react/color-picker/0.1.1.json.

ui/color-picker.tsxShow
ui/color-picker.tsx
"use client";

import { type KeyboardEvent, type PointerEvent, type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { Popover, PopoverContent, PopoverTrigger } from "./popover";

function cx(...classes: (string | false | null | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}

// Color math. Everything is plain sRGB; channels are 0-255, hue 0-360, the rest 0-1.

export type Rgba = { r: number; g: number; b: number; a: number };
export type Hsva = { h: number; s: number; v: number; a: number };
export type Hsla = { h: number; s: number; l: number; a: number };

const clamp = (value: number, min = 0, max = 1) => Math.min(max, Math.max(min, value));

export function hsvToRgb({ h, s, v, a }: Hsva): Rgba {
  const f = (n: number) => {
    const k = (n + h / 60) % 6;
    return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));
  };
  return { r: Math.round(f(5) * 255), g: Math.round(f(3) * 255), b: Math.round(f(1) * 255), a };
}

export function rgbToHsv({ r, g, b, a }: Rgba, hueFallback = 0): Hsva {
  const [rn, gn, bn] = [r / 255, g / 255, b / 255];
  const max = Math.max(rn, gn, bn);
  const delta = max - Math.min(rn, gn, bn);
  let h = hueFallback;
  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: (h + 360) % 360, s: max === 0 ? 0 : delta / max, v: max, a };
}

export function hsvToHsl({ h, s, v, a }: Hsva): Hsla {
  const l = v * (1 - s / 2);
  return { h, s: l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l), l, a };
}

export function hslToHsv({ h, s, l, a }: Hsla): Hsva {
  const v = l + s * Math.min(l, 1 - l);
  return { h, s: v === 0 ? 0 : 2 * (1 - l / v), v, a };
}

const hex2 = (value: number) => Math.round(value).toString(16).padStart(2, "0");

/** "#rrggbb", or "#rrggbbaa" when `withAlpha` and the color is not opaque. */
export function toHex({ r, g, b, a }: Rgba, withAlpha = false) {
  return `#${hex2(r)}${hex2(g)}${hex2(b)}${withAlpha && a < 1 ? hex2(a * 255) : ""}`;
}

/** Reads #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba(), and hsl()/hsla(). Returns null for anything else. */
export function parseColor(input: string | null | undefined): Rgba | null {
  if (!input) return null;
  const value = input.trim().toLowerCase();
  const hex = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(value);
  if (hex) {
    let digits = hex[1]!;
    if (digits.length <= 4) digits = [...digits].map((char) => char + char).join("");
    const n = (index: number) => parseInt(digits.slice(index, index + 2), 16);
    return { r: n(0), g: n(2), b: n(4), a: digits.length === 8 ? Math.round((n(6) / 255) * 100) / 100 : 1 };
  }
  const fn = /^(rgba?|hsla?)\(([^)]+)\)$/.exec(value);
  if (!fn) return null;
  const parts = fn[2]!.split(/[\s,/]+/).filter(Boolean);
  if (parts.length < 3) return null;
  const num = (part: string, scale: number) => (part.endsWith("%") ? (parseFloat(part) / 100) * scale : parseFloat(part));
  const alpha = parts[3] !== undefined ? clamp(num(parts[3], 1)) : 1;
  if (fn[1]!.startsWith("rgb")) {
    const [r, g, b] = parts.slice(0, 3).map((part) => clamp(num(part, 255), 0, 255));
    if ([r, g, b].some((n) => Number.isNaN(n))) return null;
    return { r: Math.round(r!), g: Math.round(g!), b: Math.round(b!), a: alpha };
  }
  const h = parseFloat(parts[0]!);
  const s = clamp(parseFloat(parts[1]!) / 100);
  const l = clamp(parseFloat(parts[2]!) / 100);
  if ([h, s, l].some((n) => Number.isNaN(n))) return null;
  return hsvToRgb(hslToHsv({ h: ((h % 360) + 360) % 360, s, l, a: alpha }));
}

function sameColor(a: string | null | undefined, b: string | null | undefined) {
  const x = parseColor(a);
  const y = parseColor(b);
  return !!x && !!y && toHex(x, true) === toHex(y, true);
}

/** Nine swatches, one row: two neutrals and seven hues. */
export const defaultColorPresets = ["#09090b", "#a1a1aa", "#ef4444", "#f59e0b", "#10b981", "#06b6d4", "#3b82f6", "#8b5cf6", "#ec4899"];

type Format = "hex" | "rgb" | "hsl";

// Two rows of light and dark squares, drawn under anything with transparency.
const checker = "repeating-conic-gradient(rgb(0 0 0 / 0.09) 0% 25%, transparent 0% 50%) 50% / 8px 8px";

function useDrag(onMove: (x: number, y: number) => void, onEnd?: () => void) {
  const [dragging, setDragging] = useState(false);
  function move(event: PointerEvent<HTMLElement>) {
    const rect = event.currentTarget.getBoundingClientRect();
    onMove(clamp((event.clientX - rect.left) / rect.width), clamp((event.clientY - rect.top) / rect.height));
  }
  return {
    dragging,
    handlers: {
      onPointerDown(event: PointerEvent<HTMLElement>) {
        if (event.button !== 0) return;
        event.preventDefault();
        event.currentTarget.setPointerCapture(event.pointerId);
        event.currentTarget.focus({ preventScroll: true });
        setDragging(true);
        move(event);
      },
      onPointerMove(event: PointerEvent<HTMLElement>) {
        if (event.currentTarget.hasPointerCapture(event.pointerId)) move(event);
      },
      onPointerUp(event: PointerEvent<HTMLElement>) {
        if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;
        event.currentTarget.releasePointerCapture(event.pointerId);
        setDragging(false);
        onEnd?.();
      },
      onPointerCancel() {
        setDragging(false);
      },
    },
  };
}

export interface ColorPanelProps {
  /** The color as hex. Accepts any CSS color `parseColor` reads. */
  value?: string;
  defaultValue?: string;
  /** Called with "#rrggbb", or "#rrggbbaa" when alpha is on and the color is translucent. */
  onValueChange?: (value: string) => void;
  /** Adds an opacity slider and channel. */
  alpha?: boolean;
  /** Swatches under the controls. Pass `[]` to hide them. */
  presets?: string[];
  /** Recently used colors, newest first. */
  recent?: string[];
  /** Shows the eyedropper button in browsers that have the EyeDropper API. */
  eyeDropper?: boolean;
  /** The color the preview compares against; clicking its half restores it. Defaults to the first value. */
  previous?: string;
  className?: string;
}

/**
 * The picker surface on its own: a saturation and brightness area, a hue slider, an optional
 * alpha slider, hex, RGB and HSL fields, an eyedropper, and swatches. Every control works from
 * the keyboard; arrow keys move the area's thumb (Shift for bigger steps).
 */
export function ColorPanel({
  value: valueProp,
  defaultValue = "#3b82f6",
  onValueChange,
  alpha = false,
  presets = defaultColorPresets,
  recent = [],
  eyeDropper = true,
  previous: previousProp,
  className,
}: ColorPanelProps) {
  const [hsva, setHsva] = useState<Hsva>(() => rgbToHsv(parseColor(valueProp ?? defaultValue) ?? { r: 59, g: 130, b: 246, a: 1 }));
  const lastEmitted = useRef<string | null>(null);
  const [initial] = useState(() => valueProp ?? defaultValue);
  const previous = previousProp ?? initial;

  // An outside change replaces the color; hue survives grays so the area does not jump to red.
  useEffect(() => {
    if (valueProp === undefined || sameColor(valueProp, lastEmitted.current)) return;
    const rgba = parseColor(valueProp);
    if (rgba) setHsva((current) => rgbToHsv(rgba, current.h));
  }, [valueProp]);

  const rgba = hsvToRgb(hsva);
  const hex = toHex(rgba, alpha);

  function update(next: Hsva) {
    const normalized = { ...next, a: alpha ? next.a : 1 };
    setHsva(normalized);
    const out = toHex(hsvToRgb(normalized), alpha);
    if (out === lastEmitted.current) return;
    lastEmitted.current = out;
    onValueChange?.(out);
  }

  function apply(color: string) {
    const parsed = parseColor(color);
    if (parsed) update(rgbToHsv(parsed, hsva.h));
  }

  const [canDrop, setCanDrop] = useState(false);
  useEffect(() => setCanDrop(typeof window !== "undefined" && "EyeDropper" in window), []);

  async function pickFromScreen() {
    try {
      const Dropper = (window as unknown as { EyeDropper: new () => { open: () => Promise<{ sRGBHex: string }> } }).EyeDropper;
      const result = await new Dropper().open();
      const parsed = parseColor(result.sRGBHex);
      if (parsed) update(rgbToHsv({ ...parsed, a: hsva.a }, hsva.h));
    } catch {
      // Escape closes the dropper without a color.
    }
  }

  return (
    <div data-slot="color-panel" className={cx("grid w-full max-w-[16.5rem] gap-3 text-sm text-zinc-950 dark:text-white", className)}>
      <SaturationArea hsva={hsva} onChange={update} />
      <div className="flex items-center gap-3">
        <PreviewSwatch previous={previous} current={hex} onRevert={() => apply(previous)} />
        <div className="grid flex-1 gap-2.5">
          <ChannelSlider
            label="Hue"
            value={hsva.h}
            max={360}
            unit="°"
            track="linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%)"
            thumbColor={`hsl(${hsva.h} 100% 50%)`}
            onChange={(h) => update({ ...hsva, h })}
          />
          {alpha ? (
            <ChannelSlider
              label="Opacity"
              value={Math.round(hsva.a * 100)}
              max={100}
              unit="%"
              checkered
              track={`linear-gradient(to right, rgb(${rgba.r} ${rgba.g} ${rgba.b} / 0), rgb(${rgba.r} ${rgba.g} ${rgba.b}))`}
              thumbColor={`rgb(${rgba.r} ${rgba.g} ${rgba.b} / ${hsva.a})`}
              onChange={(a) => update({ ...hsva, a: a / 100 })}
            />
          ) : null}
        </div>
      </div>
      <ColorFields hsva={hsva} alpha={alpha} onChange={update}>
        {eyeDropper && canDrop ? (
          <button
            type="button"
            aria-label="Pick a color from the screen"
            onClick={pickFromScreen}
            className={cx(
              "inline-flex size-8 shrink-0 items-center justify-center rounded-lg border border-zinc-950/12 text-zinc-600 dark:border-white/15 dark:text-zinc-400",
              "transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none",
              "hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] hover:text-zinc-950 dark:hover:border-white/25 dark:hover:bg-white/[0.06] dark:hover:text-white",
              "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
            )}
          >
            <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="size-4">
              <path d="m9.5 4.5 2 2M3 13l.75-2.25L10 4.5a1.4 1.4 0 0 1 2 0v0a1.4 1.4 0 0 1 0 2L5.25 12.25 3 13Z" />
              <path d="m11 2.75 2.25 2.25" />
            </svg>
          </button>
        ) : null}
      </ColorFields>
      {presets.length > 0 ? <SwatchRow label="Presets" colors={presets} current={hex} onPick={apply} /> : null}
      {recent.length > 0 ? <SwatchRow label="Recent" colors={recent} current={hex} onPick={apply} /> : null}
    </div>
  );
}

function SaturationArea({ hsva, onChange }: { hsva: Hsva; onChange: (next: Hsva) => void }) {
  const [keyboard, setKeyboard] = useState(false);
  const { dragging, handlers } = useDrag((x, y) => onChange({ ...hsva, s: x, v: 1 - y }));
  const { r, g, b } = hsvToRgb({ ...hsva, a: 1 });
  const active = dragging || keyboard;

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    const delta = event.shiftKey ? 0.1 : 0.01;
    const moves: Record<string, Partial<Hsva>> = {
      ArrowLeft: { s: clamp(hsva.s - delta) },
      ArrowRight: { s: clamp(hsva.s + delta) },
      ArrowUp: { v: clamp(hsva.v + delta) },
      ArrowDown: { v: clamp(hsva.v - delta) },
      Home: { s: 0 },
      End: { s: 1 },
      PageUp: { v: 1 },
      PageDown: { v: 0 },
    };
    const move = moves[event.key];
    if (!move) return;
    event.preventDefault();
    setKeyboard(true);
    onChange({ ...hsva, ...move });
  }

  return (
    <div
      role="slider"
      tabIndex={0}
      aria-label="Saturation and brightness"
      aria-roledescription="2D slider"
      aria-valuemin={0}
      aria-valuemax={100}
      aria-valuenow={Math.round(hsva.s * 100)}
      aria-valuetext={`Saturation ${Math.round(hsva.s * 100)}%, brightness ${Math.round(hsva.v * 100)}%`}
      onKeyDown={onKeyDown}
      onBlur={() => setKeyboard(false)}
      onPointerDown={(event) => {
        setKeyboard(false);
        handlers.onPointerDown(event);
      }}
      onPointerMove={handlers.onPointerMove}
      onPointerUp={handlers.onPointerUp}
      onPointerCancel={handlers.onPointerCancel}
      className={cx(
        "group relative h-36 cursor-crosshair touch-none rounded-lg outline-hidden select-none",
        "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
      )}
      style={{ background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${hsva.h} 100% 50%))` }}
    >
      <span aria-hidden="true" className="pointer-events-none absolute inset-0 rounded-lg shadow-[inset_0_0_0_1px_rgb(0_0_0/0.08)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.1)]" />
      {/* Hairline guides through the thumb, shown while dragging or stepping with keys. */}
      <span aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden rounded-lg mix-blend-difference">
        <span
          className={cx("absolute inset-x-0 h-px bg-white/45 transition-opacity duration-150 ease-out motion-reduce:transition-none", active ? "opacity-100" : "opacity-0")}
          style={{ top: `${(1 - hsva.v) * 100}%` }}
        />
        <span
          className={cx("absolute inset-y-0 w-px bg-white/45 transition-opacity duration-150 ease-out motion-reduce:transition-none", active ? "opacity-100" : "opacity-0")}
          style={{ left: `${hsva.s * 100}%` }}
        />
      </span>
      <span
        aria-hidden="true"
        className="pointer-events-none absolute size-0"
        style={{ left: `${hsva.s * 100}%`, top: `${(1 - hsva.v) * 100}%` }}
      >
        <Thumb color={`rgb(${r} ${g} ${b})`} active={dragging} />
      </span>
    </div>
  );
}

/** A white ring with a dark hairline outside, so it reads on any color; it lifts slightly while held. */
function Thumb({ color, active, checkered }: { color: string; active: boolean; checkered?: boolean }) {
  return (
    <span
      className={cx(
        "absolute top-0 left-0 block 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.22),0_1px_3px_rgb(0_0_0/0.25)]",
        "transition-[scale,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
        active && "motion-safe:scale-125 shadow-[0_0_0_1px_rgb(0_0_0/0.22),0_3px_10px_rgb(0_0_0/0.3)]",
      )}
      style={{ background: checkered ? `linear-gradient(${color}, ${color}), ${checker}, #fff` : color }}
    />
  );
}

function ChannelSlider({
  label,
  value,
  max,
  unit,
  track,
  thumbColor,
  checkered,
  onChange,
}: {
  label: string;
  value: number;
  max: number;
  unit: string;
  track: string;
  thumbColor: string;
  checkered?: boolean;
  onChange: (value: number) => void;
}) {
  const { dragging, handlers } = useDrag((x) => onChange(Math.round(x * max)));

  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {
    const delta = event.shiftKey ? 10 : 1;
    const moves: Record<string, number> = {
      ArrowLeft: value - delta,
      ArrowDown: value - delta,
      ArrowRight: value + delta,
      ArrowUp: value + delta,
      PageDown: value - 10,
      PageUp: value + 10,
      Home: 0,
      End: max,
    };
    const next = moves[event.key];
    if (next === undefined) return;
    event.preventDefault();
    onChange(Math.min(max, Math.max(0, next)));
  }

  return (
    <div
      role="slider"
      tabIndex={0}
      aria-label={label}
      aria-valuemin={0}
      aria-valuemax={max}
      aria-valuenow={Math.round(value)}
      aria-valuetext={`${Math.round(value)}${unit}`}
      onKeyDown={onKeyDown}
      {...handlers}
      className="relative h-3 cursor-pointer touch-none rounded-full outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500"
      style={{ background: checkered ? `${track}, ${checker}, #fff` : track }}
    >
      <span aria-hidden="true" className="pointer-events-none absolute inset-0 rounded-full shadow-[inset_0_0_0_1px_rgb(0_0_0/0.08)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.1)]" />
      {/* The thumb's center travels from 6px in at each end, so it never hangs past the track. */}
      <span aria-hidden="true" className="pointer-events-none absolute inset-y-0 right-1.5 left-1.5">
        <span className="absolute top-1/2 size-0" style={{ left: `${(value / max) * 100}%` }}>
          <Thumb color={thumbColor} active={dragging} checkered={checkered} />
        </span>
      </span>
    </div>
  );
}

function PreviewSwatch({ previous, current, onRevert }: { previous: string; current: string; onRevert: () => void }) {
  const changed = !sameColor(previous, current);
  return (
    <div className="relative grid size-10 shrink-0 grid-cols-2 overflow-hidden rounded-lg" style={{ background: `${checker}, #fff` }}>
      <button
        type="button"
        aria-label={`Restore previous color ${previous}`}
        disabled={!changed}
        onClick={onRevert}
        className="outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 disabled:cursor-default"
        style={{ background: previous }}
      />
      <span aria-hidden="true" className="transition-[background-color] duration-150 ease-out motion-reduce:transition-none" style={{ background: current }} />
      <span aria-hidden="true" className="pointer-events-none absolute inset-0 rounded-lg shadow-[inset_0_0_0_1px_rgb(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.12)]" />
    </div>
  );
}

function ColorFields({ hsva, alpha, onChange, children }: { hsva: Hsva; alpha: boolean; onChange: (next: Hsva) => void; children?: ReactNode }) {
  const [format, setFormat] = useState<Format>("hex");
  const rgba = hsvToRgb(hsva);
  const hsla = hsvToHsl(hsva);
  const percent = (value: number) => Math.round(value * 100);

  const channels: { label: string; value: number; max: number; set: (n: number) => Hsva }[] =
    format === "rgb"
      ? [
          { label: "Red", value: rgba.r, max: 255, set: (r) => rgbToHsv({ ...rgba, r }, hsva.h) },
          { label: "Green", value: rgba.g, max: 255, set: (g) => rgbToHsv({ ...rgba, g }, hsva.h) },
          { label: "Blue", value: rgba.b, max: 255, set: (b) => rgbToHsv({ ...rgba, b }, hsva.h) },
        ]
      : [
          { label: "Hue", value: Math.round(hsla.h), max: 360, set: (h) => hslToHsv({ ...hsla, h }) },
          { label: "Saturation", value: percent(hsla.s), max: 100, set: (s) => hslToHsv({ ...hsla, s: s / 100 }) },
          { label: "Lightness", value: percent(hsla.l), max: 100, set: (l) => hslToHsv({ ...hsla, l: l / 100 }) },
        ];
  if (alpha) channels.push({ label: "Opacity", value: percent(hsva.a), max: 100, set: (a) => ({ ...hsva, a: a / 100 }) });

  return (
    <div className="flex items-center gap-1.5">
      <div className="relative shrink-0">
        <select
          aria-label="Color format"
          value={format}
          onChange={(event) => setFormat(event.target.value as Format)}
          className={cx(
            "h-8 appearance-none rounded-lg border border-zinc-950/12 bg-white ps-2 pe-6 text-xs font-medium text-zinc-700",
            "dark:border-white/15 dark:bg-black dark:text-zinc-300",
            "transition-[border-color] duration-150 ease-out hover:border-zinc-950/20 dark:hover:border-white/25 motion-reduce:transition-none",
            "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
          )}
        >
          <option value="hex">Hex</option>
          <option value="rgb">RGB</option>
          <option value="hsl">HSL</option>
        </select>
        <svg aria-hidden="true" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" className="pointer-events-none absolute top-1/2 right-1.5 size-3 -translate-y-1/2 text-zinc-500">
          <path d="m5 6.5 3-3 3 3M5 9.5l3 3 3-3" />
        </svg>
      </div>
      {format === "hex" ? (
        <TextChannel
          label="Hex color"
          value={toHex(rgba, alpha).slice(1).toUpperCase()}
          prefix="#"
          onCommit={(text) => {
            const parsed = parseColor(`#${text.replace(/^#/, "")}`);
            if (parsed) onChange(rgbToHsv(alpha ? parsed : { ...parsed, a: 1 }, hsva.h));
          }}
        />
      ) : (
        channels.map((channel) => (
          <TextChannel
            key={channel.label}
            label={channel.label}
            value={String(channel.value)}
            numeric={channel.max}
            onCommit={(text) => {
              const n = Number(text);
              if (text.trim() !== "" && Number.isFinite(n)) onChange(channel.set(Math.min(channel.max, Math.max(0, Math.round(n)))));
            }}
          />
        ))
      )}
      {children}
    </div>
  );
}

/** A small text field that keeps what you type until Enter or blur, then commits or snaps back. */
function TextChannel({
  label,
  value,
  prefix,
  numeric,
  onCommit,
}: {
  label: string;
  value: string;
  prefix?: string;
  numeric?: number;
  onCommit: (text: string) => void;
}) {
  const [draft, setDraft] = useState<string | null>(null);

  function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {
    if (event.key === "Enter") {
      onCommit(event.currentTarget.value);
      setDraft(null);
    } else if (event.key === "Escape" && draft !== null) {
      event.stopPropagation();
      setDraft(null);
    } else if (numeric !== undefined && (event.key === "ArrowUp" || event.key === "ArrowDown")) {
      event.preventDefault();
      const step = (event.shiftKey ? 10 : 1) * (event.key === "ArrowUp" ? 1 : -1);
      onCommit(String(Math.min(numeric, Math.max(0, Number(value) + step))));
      setDraft(null);
    }
  }

  return (
    <label
      className={cx(
        "flex h-8 min-w-0 flex-1 items-center rounded-lg border border-zinc-950/12 bg-white px-2 dark:border-white/15 dark:bg-black",
        "transition-[border-color] duration-150 ease-out focus-within:border-zinc-950/30 hover:border-zinc-950/20 dark:focus-within:border-white/35 dark:hover:border-white/25 motion-reduce:transition-none",
        "has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-sky-500",
      )}
    >
      {prefix ? <span className="text-xs text-zinc-500">{prefix}</span> : null}
      <input
        aria-label={label}
        title={label}
        value={draft ?? value}
        inputMode={numeric !== undefined ? "numeric" : "text"}
        spellCheck={false}
        autoComplete="off"
        maxLength={numeric !== undefined ? 3 : 9}
        onChange={(event) => setDraft(event.target.value)}
        onFocus={(event) => event.currentTarget.select()}
        onBlur={(event) => {
          if (draft !== null) onCommit(event.currentTarget.value);
          setDraft(null);
        }}
        onKeyDown={onKeyDown}
        className="w-full min-w-0 bg-transparent font-mono text-xs text-zinc-950 tabular-nums outline-hidden dark:text-white"
      />
    </label>
  );
}

function SwatchRow({ label, colors, current, onPick }: { label: string; colors: string[]; current: string; onPick: (color: string) => void }) {
  return (
    <div role="group" aria-label={label} className="grid gap-1.5">
      <span aria-hidden="true" className="text-xs font-medium text-zinc-500">
        {label}
      </span>
      <div className="grid grid-cols-9 gap-1.5">
        {colors.map((color) => {
          const selected = sameColor(color, current);
          return (
            <button
              key={color}
              type="button"
              aria-label={color}
              aria-pressed={selected}
              title={color}
              onClick={() => onPick(color)}
              className={cx(
                "relative size-[22px] rounded-md",
                "transition-[scale] duration-150 ease-out motion-safe:hover:scale-110 motion-safe:active:scale-95 motion-reduce:transition-none",
                "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500",
              )}
              style={{ background: `linear-gradient(${color}, ${color}), ${checker}, #fff` }}
            >
              <span aria-hidden="true" className="absolute inset-0 rounded-md shadow-[inset_0_0_0_1px_rgb(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.14)]" />
              {/* The current swatch gets a ring in the page color, set off by a hairline. */}
              <span
                aria-hidden="true"
                className={cx(
                  "absolute -inset-[3px] rounded-[9px] shadow-[0_0_0_1.5px_rgb(9_9_11)] dark:shadow-[0_0_0_1.5px_white]",
                  "transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none",
                  selected ? "scale-100 opacity-100" : "scale-90 opacity-0",
                )}
              />
            </button>
          );
        })}
      </div>
    </div>
  );
}

export interface ColorPickerProps extends Omit<ColorPanelProps, "recent" | "previous" | "className"> {
  /** Colors already in the recent row, newest first. */
  defaultRecent?: string[];
  /** How many recent colors to keep. */
  recentLimit?: number;
  /** Called when the recent list changes, for example to persist it. */
  onRecentChange?: (recent: string[]) => void;
  /** Turns the trigger off. */
  disabled?: boolean;
  /** Submits the value under this name with a hidden input. */
  name?: string;
  /** Accessible name for the trigger; its text already includes the color. */
  "aria-label"?: string;
  id?: string;
  /** Classes for the trigger. */
  className?: string;
  side?: "top" | "bottom" | "left" | "right";
  align?: "start" | "center" | "end";
}

/**
 * A swatch button that opens the `ColorPanel` in a popover. The color changes live while you
 * pick; closing the popover with a new color adds it to the recent row.
 */
export function ColorPicker({
  value: valueProp,
  defaultValue = "#3b82f6",
  onValueChange,
  defaultRecent = [],
  recentLimit = 8,
  onRecentChange,
  disabled,
  name,
  id,
  className,
  side = "bottom",
  align = "start",
  alpha,
  "aria-label": ariaLabel,
  ...panel
}: ColorPickerProps) {
  const [inner, setInner] = useState(defaultValue);
  const value = valueProp ?? inner;
  const [open, setOpen] = useState(false);
  const [recent, setRecent] = useState(defaultRecent);
  const [openedWith, setOpenedWith] = useState(value);
  const rgba = useMemo(() => parseColor(value), [value]);

  function onChange(next: string) {
    if (valueProp === undefined) setInner(next);
    onValueChange?.(next);
  }

  function onOpenChange(next: boolean) {
    if (next) setOpenedWith(value);
    else if (!sameColor(value, openedWith)) {
      const list = [value, ...recent.filter((color) => !sameColor(color, value))].slice(0, recentLimit);
      setRecent(list);
      onRecentChange?.(list);
    }
    setOpen(next);
  }

  const label = rgba ? toHex(rgba, alpha).toUpperCase() : value;

  return (
    <Popover open={open} onOpenChange={onOpenChange}>
      <PopoverTrigger
        id={id}
        disabled={disabled}
        aria-label={ariaLabel ? `${ariaLabel}, ${label}` : undefined}
        className={cx(
          "inline-flex h-9 w-fit items-center gap-2 rounded-lg border border-zinc-950/12 bg-white ps-1.5 pe-3 text-sm text-zinc-950 shadow-[0_1px_2px_rgb(0_0_0/0.04)]",
          "dark:border-white/15 dark:bg-black dark:text-white dark:shadow-none",
          "transition-[background-color,border-color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none",
          "hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:hover:border-white/25 dark:hover:bg-white/[0.06]",
          "data-[popup-open]:border-zinc-950/20 dark:data-[popup-open]:border-white/25",
          "focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500 disabled:pointer-events-none disabled:opacity-45",
          className,
        )}
      >
        <span aria-hidden="true" className="relative size-6 overflow-hidden rounded-md" style={{ background: `linear-gradient(${value}, ${value}), ${checker}, #fff` }}>
          <span className="absolute inset-0 rounded-md shadow-[inset_0_0_0_1px_rgb(0_0_0/0.1)] dark:shadow-[inset_0_0_0_1px_rgb(255_255_255/0.14)]" />
        </span>
        <span className="font-mono text-xs tabular-nums">{label}</span>
      </PopoverTrigger>
      <PopoverContent side={side} align={align} className="w-auto p-3">
        <ColorPanel {...panel} alpha={alpha} value={value} onValueChange={onChange} recent={recent} previous={openedWith} />
      </PopoverContent>
      {name ? <input type="hidden" name={name} value={value} /> : null}
    </Popover>
  );
}