{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-picker",
  "type": "registry:ui",
  "title": "Color picker",
  "description": "A color picker with a saturation and brightness area, hue and alpha sliders, hex, RGB and HSL inputs, an eyedropper, preset swatches and recent colors. Keyboard and touch friendly, controlled or uncontrolled, no extra packages.",
  "author": "DressCode UI <https://dresscodeui.com>",
  "dependencies": [
    "lucide-react@^1.73.0"
  ],
  "registryDependencies": [
    "button",
    "input",
    "select"
  ],
  "files": [
    {
      "path": "registry/dresscode/components/color-picker/ui/color-picker.tsx",
      "type": "registry:ui",
      "content": "\"use client\"\n\n// Color picker: a saturation/brightness area, a hue slider, an optional alpha slider, hex, RGB and\n// HSL inputs, an eyedropper (where the browser has one), preset swatches and recent colors.\n// Compose the parts inside <ColorPicker>; it works controlled (value, onValueChange) or uncontrolled\n// (defaultValue). The value is a hex string: #rrggbb, or #rrggbbaa when `alpha` is on and the color\n// is translucent. The conversions are below and exported, with a WCAG contrast helper.\n// Built for shadcn/ui; the frame, labels and inputs read only the theme's variables.\nimport * as React from \"react\"\nimport { CheckIcon, PipetteIcon } from \"lucide-react\"\n\nimport { Button } from \"@/components/ui/button\"\nimport { Input } from \"@/components/ui/input\"\nimport { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from \"@/components/ui/select\"\nimport { cn } from \"@/lib/utils\"\n\n// ---------------------------------------------------------------------------------------------\n// Color math\n\n/** h 0-360, s and v 0-100, a 0-1 */\ntype Hsva = { h: number; s: number; v: number; a: number }\n/** r, g and b 0-255, a 0-1 */\ntype Rgba = { r: number; g: number; b: number; a: number }\n/** h 0-360, s and l 0-100, a 0-1 */\ntype Hsla = { h: number; s: number; l: number; a: number }\ntype ColorFormat = \"hex\" | \"rgb\" | \"hsl\"\n\nconst clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n))\nconst round = (n: number, digits = 0) => {\n  const p = 10 ** digits\n  return Math.round(n * p) / p\n}\n\nfunction hsvaToRgba({ h, s, v, a }: Hsva): Rgba {\n  const S = s / 100\n  const V = v / 100\n  const f = (n: number) => {\n    const k = (n + h / 60) % 6\n    return Math.round((V - V * S * Math.max(0, Math.min(k, 4 - k, 1))) * 255)\n  }\n  return { r: f(5), g: f(3), b: f(1), a }\n}\n\nfunction rgbaToHsva({ r, g, b, a }: Rgba): Hsva {\n  const R = r / 255\n  const G = g / 255\n  const B = b / 255\n  const max = Math.max(R, G, B)\n  const d = max - Math.min(R, G, B)\n  let h = 0\n  if (d) {\n    if (max === R) h = ((G - B) / d) % 6\n    else if (max === G) h = (B - R) / d + 2\n    else h = (R - G) / d + 4\n    h *= 60\n    if (h < 0) h += 360\n  }\n  return { h, s: max ? (d / max) * 100 : 0, v: max * 100, a }\n}\n\nfunction hsvaToHsla({ h, s, v, a }: Hsva): Hsla {\n  const S = s / 100\n  const V = v / 100\n  const l = V * (1 - S / 2)\n  const sl = l === 0 || l === 1 ? 0 : (V - l) / Math.min(l, 1 - l)\n  return { h, s: sl * 100, l: l * 100, a }\n}\n\nfunction hslaToHsva({ h, s, l, a }: Hsla): Hsva {\n  const S = s / 100\n  const L = l / 100\n  const v = L + S * Math.min(L, 1 - L)\n  return { h, s: v === 0 ? 0 : 2 * (1 - L / v) * 100, v: v * 100, a }\n}\n\nconst hex2 = (n: number) => Math.round(n).toString(16).padStart(2, \"0\")\nconst HEX = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i\n\nfunction parseHex(input: string): Rgba | null {\n  const m = HEX.exec(input.trim())\n  if (!m) return null\n  const x = m[1].length <= 4 ? [...m[1]].map((c) => c + c).join(\"\") : m[1]\n  const n = (i: number) => parseInt(x.slice(i, i + 2), 16)\n  return { r: n(0), g: n(2), b: n(4), a: x.length === 8 ? round(n(6) / 255, 3) : 1 }\n}\n\n/** Reads #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba() and hsl()/hsla() (comma or space syntax). */\nfunction parseColor(input: string | null | undefined): Hsva | null {\n  if (!input) return null\n  const s = input.trim().toLowerCase()\n  const hex = parseHex(s)\n  if (hex) return rgbaToHsva(hex)\n  const fn = /^(rgba?|hsla?)\\(([^)]*)\\)$/.exec(s)\n  if (!fn) return null\n  const parts = fn[2].split(/[\\s,/]+/).filter(Boolean)\n  if (parts.length < 3 || parts.length > 4) return null\n  const num = (p: string, scale: number) => (p.endsWith(\"%\") ? (parseFloat(p) / 100) * scale : parseFloat(p))\n  const a = parts[3] === undefined ? 1 : clamp(num(parts[3], 1), 0, 1)\n  if (fn[1].startsWith(\"rgb\")) {\n    const [r, g, b] = parts.slice(0, 3).map((p) => clamp(num(p, 255), 0, 255))\n    if (![r, g, b, a].every(Number.isFinite)) return null\n    return rgbaToHsva({ r, g, b, a })\n  }\n  const h = parseFloat(parts[0])\n  const [sat, l] = parts.slice(1, 3).map((p) => clamp(parseFloat(p), 0, 100))\n  if (![h, sat, l, a].every(Number.isFinite)) return null\n  return hslaToHsva({ h: ((h % 360) + 360) % 360, s: sat, l, a })\n}\n\n/** The color as #rrggbb, #rrggbbaa, rgb()/rgba() or hsl()/hsla(). */\nfunction formatColor(color: Hsva, format: ColorFormat | \"hex8\" = \"hex\"): string {\n  const { r, g, b, a } = hsvaToRgba(color)\n  const alpha = round(a, 2)\n  if (format === \"hex\") return `#${hex2(r)}${hex2(g)}${hex2(b)}`\n  if (format === \"hex8\") return `#${hex2(r)}${hex2(g)}${hex2(b)}${hex2(a * 255)}`\n  if (format === \"rgb\") return alpha < 1 ? `rgba(${r}, ${g}, ${b}, ${alpha})` : `rgb(${r}, ${g}, ${b})`\n  const hsl = hsvaToHsla(color)\n  const body = `${Math.round(hsl.h) % 360}, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%`\n  return alpha < 1 ? `hsla(${body}, ${alpha})` : `hsl(${body})`\n}\n\n/** What the picker emits: #rrggbb, or #rrggbbaa when alpha is allowed and the color is translucent. */\nconst toValue = (color: Hsva, alpha: boolean) => (alpha && color.a < 1 ? formatColor(color, \"hex8\") : formatColor(color))\n\n/** Every way of writing a color, for readouts and copy buttons. */\nfunction getColorDetails(color: string | Hsva) {\n  const hsva = typeof color === \"string\" ? (parseColor(color) ?? { h: 0, s: 0, v: 0, a: 1 }) : color\n  return {\n    hex: formatColor(hsva, \"hex\"),\n    hex8: formatColor(hsva, \"hex8\"),\n    rgb: formatColor(hsva, \"rgb\"),\n    hsl: formatColor(hsva, \"hsl\"),\n    alpha: round(hsva.a, 2),\n    hsva,\n    rgba: hsvaToRgba(hsva),\n    hsla: hsvaToHsla(hsva),\n  }\n}\ntype ColorDetails = ReturnType<typeof getColorDetails>\n\nconst linear = (c: number) => {\n  const s = c / 255\n  return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4\n}\nconst luminance = ({ r, g, b }: Rgba) => 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)\n\n/** WCAG 2 contrast ratio, 1 to 21. A translucent foreground is laid over the background first. */\nfunction getContrastRatio(foreground: string, background: string): number {\n  const bgColor = parseColor(background)\n  const fgColor = parseColor(foreground)\n  if (!bgColor || !fgColor) return 1\n  const bg = hsvaToRgba({ ...bgColor, a: 1 })\n  const fgRaw = hsvaToRgba(fgColor)\n  const mix = (f: number, b: number) => f * fgRaw.a + b * (1 - fgRaw.a)\n  const fg = { r: mix(fgRaw.r, bg.r), g: mix(fgRaw.g, bg.g), b: mix(fgRaw.b, bg.b), a: 1 }\n  const [hi, lo] = [luminance(fg), luminance(bg)].sort((x, y) => y - x)\n  return (hi + 0.05) / (lo + 0.05)\n}\n\n/** Whichever of two text colors reads better on the background. */\nfunction getReadableTextColor(background: string, light = \"#ffffff\", dark = \"#0a0a0a\") {\n  return getContrastRatio(light, background) >= getContrastRatio(dark, background) ? light : dark\n}\n\nconst HUE_NAMES: [number, string][] = [\n  [15, \"red\"],\n  [40, \"orange\"],\n  [65, \"yellow\"],\n  [90, \"lime\"],\n  [150, \"green\"],\n  [175, \"teal\"],\n  [200, \"cyan\"],\n  [250, \"blue\"],\n  [280, \"indigo\"],\n  [310, \"purple\"],\n  [335, \"pink\"],\n]\nconst hueName = (h: number) => HUE_NAMES.find(([max]) => h < max)?.[1] ?? \"red\"\n\n/** Grays and black have no hue (and black no saturation): keep the previous ones so the thumbs stay put. */\nfunction keepHue(next: Hsva, prev: Hsva): Hsva {\n  return { ...next, h: next.s < 0.5 || next.v < 0.5 ? prev.h : next.h, s: next.v < 0.5 ? prev.s : next.s }\n}\n\n/** A checkerboard from the theme, behind anything translucent. */\nconst CHECKER =\n  \"repeating-conic-gradient(color-mix(in oklch, var(--foreground) 22%, var(--background)) 0 25%, var(--background) 0 50%)\"\n\n// ---------------------------------------------------------------------------------------------\n// State\n\ntype CommitOptions = { recent?: boolean }\ntype ColorPickerContextValue = {\n  color: Hsva\n  value: string\n  alpha: boolean\n  format: ColorFormat\n  setFormat: (format: ColorFormat) => void\n  setColor: (color: Hsva) => void\n  commit: (color: Hsva, options?: CommitOptions) => void\n  recent: string[]\n  id: string\n}\n\nconst ColorPickerContext = React.createContext<ColorPickerContextValue | null>(null)\n\nfunction useColorPicker() {\n  const ctx = React.useContext(ColorPickerContext)\n  if (!ctx) throw new Error(\"Color picker parts must be inside <ColorPicker>\")\n  return ctx\n}\n\nfunction useControllable<T>(prop: T | undefined, initial: T, onChange?: (value: T) => void) {\n  const [inner, setInner] = React.useState(initial)\n  const controlled = prop !== undefined\n  const set = React.useCallback(\n    (next: T) => {\n      if (!controlled) setInner(next)\n      onChange?.(next)\n    },\n    [controlled, onChange],\n  )\n  return [controlled ? prop : inner, set] as const\n}\n\ntype ColorPickerProps = Omit<React.ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  /** Any CSS hex, rgb() or hsl() color. */\n  value?: string\n  defaultValue?: string\n  /** While the color changes (every drag step and keystroke). */\n  onValueChange?: (value: string, details: ColorDetails) => void\n  /** When the person settles on a color: end of a drag, Enter or blur in an input, a swatch, the eyedropper. */\n  onValueCommit?: (value: string) => void\n  /** Allow translucent colors: shows ColorPickerAlpha and the A inputs, and emits #rrggbbaa. */\n  alpha?: boolean\n  format?: ColorFormat\n  defaultFormat?: ColorFormat\n  onFormatChange?: (format: ColorFormat) => void\n  recentColors?: string[]\n  defaultRecentColors?: string[]\n  onRecentColorsChange?: (colors: string[]) => void\n  maxRecentColors?: number\n}\n\nfunction ColorPicker({\n  value,\n  defaultValue = \"#2563eb\",\n  onValueChange,\n  onValueCommit,\n  alpha = false,\n  format: formatProp,\n  defaultFormat = \"hex\",\n  onFormatChange,\n  recentColors,\n  defaultRecentColors = [],\n  onRecentColorsChange,\n  maxRecentColors = 8,\n  className,\n  children,\n  ...props\n}: ColorPickerProps) {\n  const id = React.useId()\n  const [color, setColorState] = React.useState<Hsva>(() => {\n    const parsed = parseColor(value ?? defaultValue) ?? { h: 0, s: 0, v: 0, a: 1 }\n    return alpha ? parsed : { ...parsed, a: 1 }\n  })\n  // Follow the value prop, but keep our own hue and saturation when it is the color we already show.\n  const [syncedValue, setSyncedValue] = React.useState(value)\n  if (value !== syncedValue) {\n    setSyncedValue(value)\n    const parsed = parseColor(value)\n    if (parsed && toValue(parsed, alpha) !== toValue(color, alpha)) setColorState(keepHue(alpha ? parsed : { ...parsed, a: 1 }, color))\n  }\n  const [format, setFormat] = useControllable(formatProp, defaultFormat, onFormatChange)\n  const [recent, setRecent] = useControllable(recentColors, defaultRecentColors, onRecentColorsChange)\n  const current = toValue(color, alpha)\n\n  const setColor = (next: Hsva) => {\n    const n = alpha ? next : { ...next, a: 1 }\n    setColorState(n)\n    const v = toValue(n, alpha)\n    if (v !== current) onValueChange?.(v, getColorDetails(n))\n  }\n  const commit = (next: Hsva, { recent: addToRecent = true }: CommitOptions = {}) => {\n    const v = toValue(alpha ? next : { ...next, a: 1 }, alpha)\n    onValueCommit?.(v)\n    if (addToRecent) setRecent([v, ...recent.filter((c) => c.toLowerCase() !== v)].slice(0, maxRecentColors))\n  }\n\n  return (\n    <ColorPickerContext.Provider value={{ color, value: current, alpha, format, setFormat, setColor, commit, recent, id }}>\n      <div\n        role=\"group\"\n        aria-label=\"Color picker\"\n        data-slot=\"color-picker\"\n        className={cn(\"flex w-full min-w-0 flex-col gap-3\", className)}\n        {...props}\n      >\n        {children}\n      </div>\n    </ColorPickerContext.Provider>\n  )\n}\n\n// ---------------------------------------------------------------------------------------------\n// Area and sliders\n\nconst thumbClass =\n  \"pointer-events-none absolute 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.3),0_1px_3px_rgb(0_0_0/0.35)] outline-none focus-visible:ring-3 focus-visible:ring-ring/60\"\n\n/** Pointer dragging with capture: works for mouse, pen and touch. */\nfunction useDrag(onMove: (x: number, y: number) => void, onEnd: () => void) {\n  const dragging = React.useRef(false)\n  const at = (e: React.PointerEvent<HTMLElement>) => {\n    const r = e.currentTarget.getBoundingClientRect()\n    onMove(clamp((e.clientX - r.left) / r.width, 0, 1), clamp((e.clientY - r.top) / r.height, 0, 1))\n  }\n  const end = () => {\n    if (!dragging.current) return\n    dragging.current = false\n    onEnd()\n  }\n  return {\n    onPointerDown: (e: React.PointerEvent<HTMLElement>) => {\n      if (e.button !== 0) return\n      e.preventDefault()\n      e.currentTarget.setPointerCapture(e.pointerId)\n      dragging.current = true\n      ;(e.currentTarget.querySelector(\"[role=slider]\") as HTMLElement | null)?.focus({ preventScroll: true })\n      at(e)\n    },\n    onPointerMove: (e: React.PointerEvent<HTMLElement>) => {\n      if (dragging.current) at(e)\n    },\n    onPointerUp: end,\n    onPointerCancel: end,\n    onLostPointerCapture: end,\n  }\n}\n\n/** Arrow keys move by 1, Shift + arrows by 10; Page Up/Down by 10; Home/End jump to the ends. */\nfunction stepFromKey(e: React.KeyboardEvent): { x: number; y: number; jump?: \"min\" | \"max\" } | null {\n  const step = e.shiftKey ? 10 : 1\n  switch (e.key) {\n    case \"ArrowLeft\":\n      return { x: -step, y: 0 }\n    case \"ArrowRight\":\n      return { x: step, y: 0 }\n    case \"ArrowUp\":\n      return { x: 0, y: step }\n    case \"ArrowDown\":\n      return { x: 0, y: -step }\n    case \"PageUp\":\n      return { x: 0, y: 10 }\n    case \"PageDown\":\n      return { x: 0, y: -10 }\n    case \"Home\":\n      return { x: 0, y: 0, jump: \"min\" }\n    case \"End\":\n      return { x: 0, y: 0, jump: \"max\" }\n    default:\n      return null\n  }\n}\n\n/** Commits once when focus leaves a control that the keyboard changed. */\nfunction useKeyboardCommit() {\n  const { color, commit } = useColorPicker()\n  const changed = React.useRef(false)\n  return {\n    mark: () => {\n      changed.current = true\n    },\n    onBlur: () => {\n      if (!changed.current) return\n      changed.current = false\n      commit(color)\n    },\n  }\n}\n\nfunction ColorPickerArea({ className, style, ...props }: React.ComponentProps<\"div\">) {\n  const { color, setColor, commit } = useColorPicker()\n  const latest = React.useRef(color)\n  const keys = useKeyboardCommit()\n  const drag = useDrag(\n    (x, y) => {\n      latest.current = { ...color, s: x * 100, v: (1 - y) * 100 }\n      setColor(latest.current)\n    },\n    () => commit(latest.current),\n  )\n  const s = Math.round(color.s)\n  const v = Math.round(color.v)\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const d = stepFromKey(e)\n    if (!d) return\n    e.preventDefault()\n    const ns = d.jump ? (d.jump === \"min\" ? 0 : 100) : clamp(s + d.x, 0, 100)\n    setColor({ ...color, s: ns, v: clamp(v + d.y, 0, 100) })\n    keys.mark()\n  }\n  return (\n    <div\n      data-slot=\"color-picker-area\"\n      className={cn(\"relative h-40 w-full shrink-0 cursor-crosshair touch-none rounded-lg select-none\", className)}\n      style={{\n        background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${color.h} 100% 50%))`,\n        ...style,\n      }}\n      {...drag}\n      {...props}\n    >\n      <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 rounded-[inherit] ring-1 ring-foreground/10 ring-inset\" />\n      <div\n        role=\"slider\"\n        tabIndex={0}\n        aria-label=\"Saturation and brightness\"\n        aria-roledescription=\"2D slider\"\n        aria-valuemin={0}\n        aria-valuemax={100}\n        aria-valuenow={s}\n        aria-valuetext={`Saturation ${s}%, brightness ${v}%`}\n        data-slot=\"color-picker-area-thumb\"\n        className={thumbClass}\n        style={{ left: `${color.s}%`, top: `${100 - color.v}%`, background: formatColor({ ...color, a: 1 }) }}\n        onKeyDown={onKeyDown}\n        onBlur={keys.onBlur}\n      />\n    </div>\n  )\n}\n\ntype SliderProps = Omit<React.ComponentProps<\"div\">, \"onChange\"> & {\n  label: string\n  value: number\n  max: number\n  valueText: string\n  track: React.CSSProperties\n  thumb: string\n  /** The picker color for a slider value. */\n  toColor: (value: number) => Hsva\n}\n\nfunction ColorSlider({ label, value, max, valueText, track, thumb, toColor, className, ...props }: SliderProps) {\n  const { color, setColor, commit } = useColorPicker()\n  const keys = useKeyboardCommit()\n  const latest = React.useRef(color)\n  const drag = useDrag(\n    (x) => {\n      latest.current = toColor(round(x * max))\n      setColor(latest.current)\n    },\n    () => commit(latest.current),\n  )\n  const onKeyDown = (e: React.KeyboardEvent) => {\n    const d = stepFromKey(e)\n    if (!d) return\n    e.preventDefault()\n    setColor(toColor(d.jump ? (d.jump === \"min\" ? 0 : max) : clamp(Math.round(value) + d.x + d.y, 0, max)))\n    keys.mark()\n  }\n  return (\n    <div\n      className={cn(\"relative h-3 w-full min-w-0 cursor-pointer touch-none rounded-full select-none\", className)}\n      style={track}\n      {...drag}\n      {...props}\n    >\n      <div aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 rounded-[inherit] ring-1 ring-foreground/10 ring-inset\" />\n      <div\n        role=\"slider\"\n        tabIndex={0}\n        aria-label={label}\n        aria-orientation=\"horizontal\"\n        aria-valuemin={0}\n        aria-valuemax={max}\n        aria-valuenow={Math.round(value)}\n        aria-valuetext={valueText}\n        className={cn(thumbClass, \"top-1/2\")}\n        style={{ left: `${(value / max) * 100}%`, background: thumb }}\n        onKeyDown={onKeyDown}\n        onBlur={keys.onBlur}\n      />\n    </div>\n  )\n}\n\nconst HUE_GRADIENT = \"linear-gradient(to right, #f00 0%, #ff0 16.67%, #0f0 33.33%, #0ff 50%, #00f 66.67%, #f0f 83.33%, #f00 100%)\"\n\nfunction ColorPickerHue({ className, ...props }: React.ComponentProps<\"div\">) {\n  const { color } = useColorPicker()\n  const h = Math.round(color.h)\n  return (\n    <ColorSlider\n      data-slot=\"color-picker-hue\"\n      label=\"Hue\"\n      value={color.h}\n      max={360}\n      valueText={`${h} degrees, ${hueName(h)}`}\n      track={{ background: HUE_GRADIENT }}\n      thumb={`hsl(${color.h} 100% 50%)`}\n      toColor={(h) => ({ ...color, h })}\n      className={className}\n      {...props}\n    />\n  )\n}\n\n/** Renders only when the ColorPicker has `alpha`. */\nfunction ColorPickerAlpha({ className, ...props }: React.ComponentProps<\"div\">) {\n  const { color, alpha } = useColorPicker()\n  if (!alpha) return null\n  const { r, g, b } = hsvaToRgba(color)\n  const pct = Math.round(color.a * 100)\n  return (\n    <ColorSlider\n      data-slot=\"color-picker-alpha\"\n      label=\"Opacity\"\n      value={pct}\n      max={100}\n      valueText={`${pct}%`}\n      track={{\n        backgroundImage: `linear-gradient(to right, rgb(${r} ${g} ${b} / 0), rgb(${r} ${g} ${b})), ${CHECKER}`,\n        backgroundSize: \"100% 100%, 8px 8px\",\n      }}\n      thumb={`rgb(${r} ${g} ${b} / ${color.a})`}\n      toColor={(p) => ({ ...color, a: p / 100 })}\n      className={className}\n      {...props}\n    />\n  )\n}\n\n// ---------------------------------------------------------------------------------------------\n// Eyedropper\n\ntype EyeDropperCtor = new () => { open: () => Promise<{ sRGBHex: string }> }\nconst noSubscribe = () => () => {}\n\n/** A button that samples a color from anywhere on screen. Renders nothing where the browser has no EyeDropper. */\nfunction ColorPickerEyeDropper({ className, ...props }: React.ComponentProps<typeof Button>) {\n  const { color, setColor, commit } = useColorPicker()\n  const supported = React.useSyncExternalStore(\n    noSubscribe,\n    () => \"EyeDropper\" in window,\n    () => false,\n  )\n  if (!supported) return null\n  const pick = async () => {\n    try {\n      const Dropper = (window as unknown as { EyeDropper: EyeDropperCtor }).EyeDropper\n      const { sRGBHex } = await new Dropper().open()\n      const picked = parseColor(sRGBHex)\n      if (!picked) return\n      const next = { ...picked, a: color.a }\n      setColor(next)\n      commit(next)\n    } catch {\n      // Cancelled with Escape.\n    }\n  }\n  return (\n    <Button\n      type=\"button\"\n      variant=\"outline\"\n      size=\"icon\"\n      aria-label=\"Pick a color from the screen\"\n      title=\"Pick a color from the screen\"\n      data-slot=\"color-picker-eyedropper\"\n      className={className}\n      onClick={pick}\n      {...props}\n    >\n      <PipetteIcon />\n    </Button>\n  )\n}\n\n// ---------------------------------------------------------------------------------------------\n// Inputs\n\nconst FORMATS = [\n  { value: \"hex\", label: \"Hex\" },\n  { value: \"rgb\", label: \"RGB\" },\n  { value: \"hsl\", label: \"HSL\" },\n]\n\n/** Switches ColorPickerInput between hex, RGB and HSL. */\nfunction ColorPickerFormatSelect({ className }: { className?: string }) {\n  const { format, setFormat } = useColorPicker()\n  return (\n    <Select items={FORMATS} value={format} onValueChange={(v) => v && setFormat(v as ColorFormat)}>\n      <SelectTrigger size=\"sm\" aria-label=\"Color format\" data-slot=\"color-picker-format\" className={cn(\"h-8 w-[4.75rem] shrink-0\", className)}>\n        <SelectValue />\n      </SelectTrigger>\n      <SelectContent>\n        {FORMATS.map((f) => (\n          <SelectItem key={f.value} value={f.value}>\n            {f.label}\n          </SelectItem>\n        ))}\n      </SelectContent>\n    </Select>\n  )\n}\n\nfunction Field({ short, className, children }: { short: string; className?: string; children: React.ReactNode }) {\n  return (\n    <label className={cn(\"flex min-w-0 flex-1 flex-col items-center gap-1\", className)}>\n      {children}\n      <span aria-hidden=\"true\" className=\"text-xs leading-none text-muted-foreground\">\n        {short}\n      </span>\n    </label>\n  )\n}\n\n/** A whole-number field: type a value, or Arrow Up/Down (Shift for 10). Out of range values clamp on blur. */\nfunction NumberField({ label, short, value, max, toColor }: { label: string; short: string; value: number; max: number; toColor: (n: number) => Hsva }) {\n  const { color, alpha, setColor, commit } = useColorPicker()\n  const shown = String(Math.round(value))\n  const [draft, setDraft] = React.useState<{ text: string; for: string } | null>(null)\n  const start = React.useRef<string | null>(null)\n  const text = draft && draft.for === shown ? draft.text : shown\n  /** Applies what was typed (clamped) and returns the color the field settled on. */\n  const finish = () => {\n    let next = color\n    if (draft && draft.for === shown) {\n      const n = parseFloat(draft.text)\n      if (Number.isFinite(n)) {\n        next = toColor(clamp(Math.round(n), 0, max))\n        setColor(next)\n      }\n    }\n    setDraft(null)\n    return next\n  }\n  const commitIfChanged = (next: Hsva) => {\n    if (start.current !== null && start.current !== toValue(next, alpha)) commit(next)\n  }\n  return (\n    <Field short={short}>\n      <Input\n        inputMode=\"numeric\"\n        aria-label={label}\n        value={text}\n        className=\"h-8 px-1 text-center tabular-nums\"\n        onFocus={(e) => {\n          start.current = toValue(color, alpha)\n          e.currentTarget.select()\n        }}\n        onChange={(e) => {\n          const t = e.target.value.replace(/[^\\d.]/g, \"\").slice(0, 3)\n          const n = parseFloat(t)\n          if (Number.isFinite(n) && n >= 0 && n <= max) {\n            setColor(toColor(n))\n            setDraft({ text: t, for: String(Math.round(n)) })\n          } else setDraft({ text: t, for: shown })\n        }}\n        onKeyDown={(e) => {\n          if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n            e.preventDefault()\n            const step = (e.shiftKey ? 10 : 1) * (e.key === \"ArrowUp\" ? 1 : -1)\n            setColor(toColor(clamp(Math.round(value) + step, 0, max)))\n            setDraft(null)\n          } else if (e.key === \"Enter\") {\n            const next = finish()\n            commitIfChanged(next)\n            start.current = toValue(next, alpha)\n          }\n        }}\n        onBlur={() => {\n          commitIfChanged(finish())\n          start.current = null\n        }}\n      />\n    </Field>\n  )\n}\n\n/** What is typed, the color it was typed over, and whether typing already changed the color. */\ntype HexDraft = { text: string; for: string; invalid?: boolean; applied?: boolean } | null\n\n/** Hex digits apply as you type once there are six or eight; three, four or a pasted rgb()/hsl() wait for Enter or blur. */\nfunction HexField({ draft, setDraft, errorId }: { draft: HexDraft; setDraft: (d: HexDraft) => void; errorId: string }) {\n  const { color, alpha, setColor, commit } = useColorPicker()\n  const shown = formatColor(color, \"hex\")\n  const active = draft && draft.for === shown ? draft : null\n\n  const read = (text: string) => {\n    const rgba = parseHex(text)\n    if (rgba) {\n      const digits = text.trim().replace(\"#\", \"\").length\n      return keepHue({ ...rgbaToHsva(rgba), a: alpha && (digits === 4 || digits === 8) ? rgba.a : color.a }, color)\n    }\n    const parsed = parseColor(text)\n    return parsed ? keepHue(alpha ? parsed : { ...parsed, a: color.a }, color) : null\n  }\n  const apply = () => {\n    if (!active) return\n    if (active.text.trim().replace(\"#\", \"\").toLowerCase() === shown.slice(1)) {\n      setDraft(null)\n      if (active.applied) commit(color)\n      return\n    }\n    const next = read(active.text)\n    if (!next) return setDraft({ ...active, invalid: true })\n    setDraft(null)\n    setColor(next)\n    commit(next)\n  }\n\n  return (\n    <Field short=\"Hex\" className=\"flex-[2.4]\">\n      <Input\n        aria-label=\"Hex color\"\n        spellCheck={false}\n        autoComplete=\"off\"\n        value={active ? active.text : shown}\n        aria-invalid={active?.invalid || undefined}\n        aria-describedby={active?.invalid ? errorId : undefined}\n        className=\"h-8 px-2 tabular-nums\"\n        onFocus={(e) => e.currentTarget.select()}\n        onChange={(e) => {\n          const text = e.target.value\n          const next = /^#?([0-9a-f]{6}|[0-9a-f]{8})$/i.test(text.trim()) ? read(text) : null\n          if (next) {\n            setColor(next)\n            setDraft({ text, for: formatColor(next, \"hex\"), applied: true })\n          } else setDraft({ text, for: shown, applied: active?.applied })\n        }}\n        onKeyDown={(e) => {\n          if (e.key === \"Enter\") apply()\n          if (e.key === \"Escape\" && active) {\n            // Undo the typing instead of closing a surrounding popover.\n            e.stopPropagation()\n            setDraft(null)\n          }\n        }}\n        onBlur={apply}\n      />\n    </Field>\n  )\n}\n\n/** The fields for the current format (hex, RGB or HSL), plus opacity when the picker has alpha. */\nfunction ColorPickerInput({ className, ...props }: React.ComponentProps<\"div\">) {\n  const { color, alpha, format, id } = useColorPicker()\n  const [hexDraft, setHexDraft] = React.useState<HexDraft>(null)\n  const rgba = hsvaToRgba(color)\n  const hsla = hsvaToHsla(color)\n  const fromRgb = (patch: Partial<Rgba>) => keepHue(rgbaToHsva({ ...rgba, ...patch }), color)\n  const fromHsl = (patch: Partial<Hsla>) => hslaToHsva({ ...hsla, ...patch })\n  const errorId = `${id}-hex-error`\n  const hexInvalid = format === \"hex\" && !!hexDraft?.invalid && hexDraft.for === formatColor(color, \"hex\")\n  return (\n    <div data-slot=\"color-picker-input\" className={cn(\"flex min-w-0 flex-1 flex-col gap-1.5\", className)} {...props}>\n      <div className=\"flex min-w-0 gap-1.5\">\n        {format === \"hex\" ? <HexField draft={hexDraft} setDraft={setHexDraft} errorId={errorId} /> : null}\n        {format === \"rgb\" ? (\n          <>\n            <NumberField label=\"Red\" short=\"R\" value={rgba.r} max={255} toColor={(r) => fromRgb({ r })} />\n            <NumberField label=\"Green\" short=\"G\" value={rgba.g} max={255} toColor={(g) => fromRgb({ g })} />\n            <NumberField label=\"Blue\" short=\"B\" value={rgba.b} max={255} toColor={(b) => fromRgb({ b })} />\n          </>\n        ) : null}\n        {format === \"hsl\" ? (\n          <>\n            <NumberField label=\"Hue, degrees\" short=\"H\" value={hsla.h} max={360} toColor={(h) => fromHsl({ h })} />\n            <NumberField label=\"Saturation, percent\" short=\"S\" value={hsla.s} max={100} toColor={(s) => fromHsl({ s })} />\n            <NumberField label=\"Lightness, percent\" short=\"L\" value={hsla.l} max={100} toColor={(l) => fromHsl({ l })} />\n          </>\n        ) : null}\n        {alpha ? (\n          <NumberField label=\"Opacity, percent\" short=\"A\" value={color.a * 100} max={100} toColor={(n) => ({ ...color, a: n / 100 })} />\n        ) : null}\n      </div>\n      {hexInvalid ? (\n        <p id={errorId} role=\"alert\" data-slot=\"color-picker-input-error\" className=\"text-xs text-destructive\">\n          Use 3, 6 or 8 hex digits, like #3b82f6.\n        </p>\n      ) : null}\n    </div>\n  )\n}\n\n// ---------------------------------------------------------------------------------------------\n// Swatches\n\ntype SwatchColor = string | { value: string; label?: string }\n\n/** A color chip with a checkerboard behind it, for triggers and readouts. Shows the picker's color by default. */\nfunction ColorPickerSwatch({ color, className, ...props }: React.ComponentProps<\"span\"> & { color?: string }) {\n  const ctx = React.useContext(ColorPickerContext)\n  const c = color ?? ctx?.value ?? \"transparent\"\n  return (\n    <span\n      data-slot=\"color-picker-swatch\"\n      aria-hidden=\"true\"\n      className={cn(\"relative inline-block size-5 shrink-0 overflow-hidden rounded-md\", className)}\n      style={{ backgroundImage: CHECKER, backgroundSize: \"8px 8px\" }}\n      {...props}\n    >\n      <span className=\"absolute inset-0\" style={{ background: c }} />\n      <span className=\"absolute inset-0 rounded-[inherit] ring-1 ring-foreground/15 ring-inset\" />\n    </span>\n  )\n}\n\ntype SwatchGridProps = React.ComponentProps<\"div\"> & {\n  colors: SwatchColor[]\n  /** A visible heading for the row; without one, pass aria-label or aria-labelledby (they go on the swatch group). */\n  label?: string\n  /** Shown in place of the swatches when there are none. */\n  emptyText?: string\n  /** Lay the swatches out in this many equal columns that fill the width, instead of a wrapping row. */\n  columns?: number\n}\n\n/** Swatch buttons in a wrapping row. Arrow keys move between them; Enter or Space picks one. `children` go at the end of the row. */\nfunction SwatchGrid({ colors, label, emptyText, columns, recent, className, children, \"aria-label\": ariaLabel, \"aria-labelledby\": ariaLabelledBy, ...props }: SwatchGridProps & { recent?: boolean }) {\n  const { color, value, alpha, setColor, commit } = useColorPicker()\n  const labelId = React.useId()\n  const refs = React.useRef<(HTMLButtonElement | null)[]>([])\n  const [focusIndex, setFocusIndex] = React.useState<number | null>(null)\n  const items = colors\n    .map((c) => (typeof c === \"string\" ? { value: c } : c))\n    .map((c) => ({ ...c, color: parseColor(c.value) }))\n    .filter((c): c is { value: string; label?: string; color: Hsva } => !!c.color)\n  const selected = items.findIndex((c) => toValue(alpha ? c.color : { ...c.color, a: 1 }, alpha) === value)\n  const tabbable = focusIndex !== null && focusIndex < items.length ? focusIndex : Math.max(selected, 0)\n\n  const onKeyDown = (e: React.KeyboardEvent, i: number) => {\n    const buttons = refs.current.slice(0, items.length).filter(Boolean) as HTMLButtonElement[]\n    const top = buttons[0]?.offsetTop\n    const cols = Math.max(1, buttons.filter((b) => b.offsetTop === top).length)\n    const keys: Record<string, number> = { ArrowRight: i + 1, ArrowLeft: i - 1, ArrowDown: i + cols, ArrowUp: i - cols, Home: 0, End: items.length - 1 }\n    const next = keys[e.key]\n    if (next === undefined) return\n    e.preventDefault()\n    const n = clamp(next, 0, items.length - 1)\n    refs.current[n]?.focus()\n    setFocusIndex(n)\n  }\n\n  return (\n    <div data-slot={recent ? \"color-picker-recent\" : \"color-picker-swatches\"} className={cn(\"flex flex-col gap-2\", className)} {...props}>\n      {label ? (\n        <p id={labelId} className=\"text-xs font-medium text-muted-foreground\">\n          {label}\n        </p>\n      ) : null}\n      <div\n        role=\"group\"\n        aria-labelledby={label ? labelId : ariaLabelledBy} aria-label={label ? undefined : ariaLabel}\n        className={columns ? \"grid gap-1.5\" : \"flex flex-wrap items-center gap-1.5\"}\n        style={columns ? { gridTemplateColumns: `repeat(${columns}, minmax(0, 1fr))` } : undefined}\n      >\n        {!items.length && emptyText ? <p className=\"col-span-full mr-1 text-xs text-muted-foreground\">{emptyText}</p> : null}\n        {items.map((c, i) => {\n          const on = i === selected\n          const opaque = formatColor({ ...c.color, a: 1 })\n          return (\n            <button\n              key={`${c.value}-${i}`}\n              ref={(el) => {\n                refs.current[i] = el\n              }}\n              type=\"button\"\n              aria-label={c.label ? `${c.label}, ${c.value}` : c.value}\n              aria-pressed={on}\n              title={c.label ?? c.value}\n              tabIndex={i === tabbable ? 0 : -1}\n              data-slot=\"color-picker-swatch-button\"\n              className={cn(\n                \"relative flex shrink-0 cursor-pointer\",\n                columns ? \"aspect-square w-full\" : \"size-[var(--swatch-size,1.5rem)]\",\n                \"items-center justify-center overflow-hidden rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/60 aria-pressed:ring-2 aria-pressed:ring-ring aria-pressed:ring-offset-2 aria-pressed:ring-offset-background\",\n              )}\n              style={{ backgroundImage: CHECKER, backgroundSize: \"8px 8px\" }}\n              onFocus={() => setFocusIndex(i)}\n              onKeyDown={(e) => onKeyDown(e, i)}\n              onClick={() => {\n                const next = keepHue(alpha ? c.color : { ...c.color, a: 1 }, color)\n                setColor(next)\n                commit(next, { recent: false })\n              }}\n            >\n              <span className=\"absolute inset-0\" style={{ background: c.value }} />\n              <span className=\"absolute inset-0 rounded-[inherit] ring-1 ring-foreground/15 ring-inset\" />\n              {on ? <CheckIcon className=\"relative size-3.5\" strokeWidth={3} style={{ color: getReadableTextColor(opaque) }} /> : null}\n            </button>\n          )\n        })}\n        {children}\n      </div>\n    </div>\n  )\n}\n\n/** Preset colors. Picking one sets the color without adding it to the recent list. */\nfunction ColorPickerSwatches(props: SwatchGridProps) {\n  return <SwatchGrid {...props} />\n}\n\n/** Colors the person settled on, newest first (see onValueCommit). Shows `emptyText` until there are some. */\nfunction ColorPickerRecent({ label = \"Recent\", emptyText = \"Colors you pick show up here.\", ...props }: Omit<SwatchGridProps, \"colors\">) {\n  const { recent } = useColorPicker()\n  return <SwatchGrid colors={recent} label={label} emptyText={emptyText} recent {...props} />\n}\n\nexport {\n  ColorPicker,\n  ColorPickerAlpha,\n  ColorPickerArea,\n  ColorPickerEyeDropper,\n  ColorPickerFormatSelect,\n  ColorPickerHue,\n  ColorPickerInput,\n  ColorPickerRecent,\n  ColorPickerSwatch,\n  ColorPickerSwatches,\n  formatColor,\n  getColorDetails,\n  getContrastRatio,\n  getReadableTextColor,\n  parseColor,\n  useColorPicker,\n}\nexport type { ColorDetails, ColorFormat, Hsla, Hsva, Rgba, SwatchColor }\n"
    }
  ],
  "docs": "Color picker is in components/ui. Examples: https://dresscodeui.com/components/color-picker"
}
