{
  "schemaVersion": 1,
  "target": "react",
  "name": "color-picker",
  "version": "0.1.1",
  "category": "forms",
  "title": "Color Picker",
  "description": "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.",
  "tags": [
    "color",
    "picker",
    "hex",
    "rgb",
    "hsl",
    "eyedropper",
    "swatches",
    "form",
    "popover"
  ],
  "requires": {
    "projectTypes": [
      "next",
      "vite-react"
    ],
    "styling": "tailwind-v4"
  },
  "npmDependencies": {},
  "registryDependencies": [
    {
      "name": "popover",
      "version": "0.2.2"
    }
  ],
  "docsPath": "/components/color-picker",
  "props": [
    {
      "name": "value / defaultValue / onValueChange",
      "type": "string",
      "default": "\"#3b82f6\"",
      "description": "The color. Accepts hex, rgb() and hsl(); emits \"#rrggbb\", or \"#rrggbbaa\" when alpha is on and the color is translucent."
    },
    {
      "name": "alpha",
      "type": "boolean",
      "default": "false",
      "description": "Adds the opacity slider and channel."
    },
    {
      "name": "presets",
      "type": "string[]",
      "default": "defaultColorPresets",
      "description": "Swatches under the controls, nine to a row. Pass [] to hide them."
    },
    {
      "name": "eyeDropper",
      "type": "boolean",
      "default": "true",
      "description": "Shows the eyedropper button where the browser has the EyeDropper API."
    },
    {
      "name": "defaultRecent / recentLimit / onRecentChange",
      "type": "string[] / number / (recent) => void",
      "default": "[] / 8",
      "description": "ColorPicker: the recent row. Closing the popover with a new color adds it."
    },
    {
      "name": "disabled / name / id / aria-label / className",
      "type": "boolean / string",
      "description": "ColorPicker: trigger state, a hidden input for forms, attributes, and trigger classes."
    },
    {
      "name": "side / align",
      "type": "\"top\" | \"bottom\" | \"left\" | \"right\" / \"start\" | \"center\" | \"end\"",
      "default": "\"bottom\" / \"start\"",
      "description": "ColorPicker: popover placement."
    },
    {
      "name": "ColorPanel",
      "type": "component",
      "description": "The surface on its own for inline use; also takes recent and previous (the color the preview compares against)."
    },
    {
      "name": "parseColor / toHex / hsvToRgb / rgbToHsv / hsvToHsl / hslToHsv",
      "type": "functions",
      "description": "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."
  ],
  "states": [
    "closed",
    "open",
    "dragging",
    "with alpha",
    "recent colors"
  ],
  "files": [
    {
      "path": "ui/color-picker.tsx",
      "content": "\"use client\";\n\nimport { type KeyboardEvent, type PointerEvent, type ReactNode, useEffect, useMemo, useRef, useState } from \"react\";\nimport { Popover, PopoverContent, PopoverTrigger } from \"./popover\";\n\nfunction cx(...classes: (string | false | null | undefined)[]) {\n  return classes.filter(Boolean).join(\" \");\n}\n\n// Color math. Everything is plain sRGB; channels are 0-255, hue 0-360, the rest 0-1.\n\nexport type Rgba = { r: number; g: number; b: number; a: number };\nexport type Hsva = { h: number; s: number; v: number; a: number };\nexport type Hsla = { h: number; s: number; l: number; a: number };\n\nconst clamp = (value: number, min = 0, max = 1) => Math.min(max, Math.max(min, value));\n\nexport function hsvToRgb({ h, s, v, a }: Hsva): Rgba {\n  const f = (n: number) => {\n    const k = (n + h / 60) % 6;\n    return v - v * s * Math.max(0, Math.min(k, 4 - k, 1));\n  };\n  return { r: Math.round(f(5) * 255), g: Math.round(f(3) * 255), b: Math.round(f(1) * 255), a };\n}\n\nexport function rgbToHsv({ r, g, b, a }: Rgba, hueFallback = 0): Hsva {\n  const [rn, gn, bn] = [r / 255, g / 255, b / 255];\n  const max = Math.max(rn, gn, bn);\n  const delta = max - Math.min(rn, gn, bn);\n  let h = hueFallback;\n  if (delta > 0) {\n    if (max === rn) h = 60 * (((gn - bn) / delta) % 6);\n    else if (max === gn) h = 60 * ((bn - rn) / delta + 2);\n    else h = 60 * ((rn - gn) / delta + 4);\n  }\n  return { h: (h + 360) % 360, s: max === 0 ? 0 : delta / max, v: max, a };\n}\n\nexport function hsvToHsl({ h, s, v, a }: Hsva): Hsla {\n  const l = v * (1 - s / 2);\n  return { h, s: l === 0 || l === 1 ? 0 : (v - l) / Math.min(l, 1 - l), l, a };\n}\n\nexport function hslToHsv({ h, s, l, a }: Hsla): Hsva {\n  const v = l + s * Math.min(l, 1 - l);\n  return { h, s: v === 0 ? 0 : 2 * (1 - l / v), v, a };\n}\n\nconst hex2 = (value: number) => Math.round(value).toString(16).padStart(2, \"0\");\n\n/** \"#rrggbb\", or \"#rrggbbaa\" when `withAlpha` and the color is not opaque. */\nexport function toHex({ r, g, b, a }: Rgba, withAlpha = false) {\n  return `#${hex2(r)}${hex2(g)}${hex2(b)}${withAlpha && a < 1 ? hex2(a * 255) : \"\"}`;\n}\n\n/** Reads #rgb, #rgba, #rrggbb, #rrggbbaa, rgb()/rgba(), and hsl()/hsla(). Returns null for anything else. */\nexport function parseColor(input: string | null | undefined): Rgba | null {\n  if (!input) return null;\n  const value = input.trim().toLowerCase();\n  const hex = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(value);\n  if (hex) {\n    let digits = hex[1]!;\n    if (digits.length <= 4) digits = [...digits].map((char) => char + char).join(\"\");\n    const n = (index: number) => parseInt(digits.slice(index, index + 2), 16);\n    return { r: n(0), g: n(2), b: n(4), a: digits.length === 8 ? Math.round((n(6) / 255) * 100) / 100 : 1 };\n  }\n  const fn = /^(rgba?|hsla?)\\(([^)]+)\\)$/.exec(value);\n  if (!fn) return null;\n  const parts = fn[2]!.split(/[\\s,/]+/).filter(Boolean);\n  if (parts.length < 3) return null;\n  const num = (part: string, scale: number) => (part.endsWith(\"%\") ? (parseFloat(part) / 100) * scale : parseFloat(part));\n  const alpha = parts[3] !== undefined ? clamp(num(parts[3], 1)) : 1;\n  if (fn[1]!.startsWith(\"rgb\")) {\n    const [r, g, b] = parts.slice(0, 3).map((part) => clamp(num(part, 255), 0, 255));\n    if ([r, g, b].some((n) => Number.isNaN(n))) return null;\n    return { r: Math.round(r!), g: Math.round(g!), b: Math.round(b!), a: alpha };\n  }\n  const h = parseFloat(parts[0]!);\n  const s = clamp(parseFloat(parts[1]!) / 100);\n  const l = clamp(parseFloat(parts[2]!) / 100);\n  if ([h, s, l].some((n) => Number.isNaN(n))) return null;\n  return hsvToRgb(hslToHsv({ h: ((h % 360) + 360) % 360, s, l, a: alpha }));\n}\n\nfunction sameColor(a: string | null | undefined, b: string | null | undefined) {\n  const x = parseColor(a);\n  const y = parseColor(b);\n  return !!x && !!y && toHex(x, true) === toHex(y, true);\n}\n\n/** Nine swatches, one row: two neutrals and seven hues. */\nexport const defaultColorPresets = [\"#09090b\", \"#a1a1aa\", \"#ef4444\", \"#f59e0b\", \"#10b981\", \"#06b6d4\", \"#3b82f6\", \"#8b5cf6\", \"#ec4899\"];\n\ntype Format = \"hex\" | \"rgb\" | \"hsl\";\n\n// Two rows of light and dark squares, drawn under anything with transparency.\nconst checker = \"repeating-conic-gradient(rgb(0 0 0 / 0.09) 0% 25%, transparent 0% 50%) 50% / 8px 8px\";\n\nfunction useDrag(onMove: (x: number, y: number) => void, onEnd?: () => void) {\n  const [dragging, setDragging] = useState(false);\n  function move(event: PointerEvent<HTMLElement>) {\n    const rect = event.currentTarget.getBoundingClientRect();\n    onMove(clamp((event.clientX - rect.left) / rect.width), clamp((event.clientY - rect.top) / rect.height));\n  }\n  return {\n    dragging,\n    handlers: {\n      onPointerDown(event: PointerEvent<HTMLElement>) {\n        if (event.button !== 0) return;\n        event.preventDefault();\n        event.currentTarget.setPointerCapture(event.pointerId);\n        event.currentTarget.focus({ preventScroll: true });\n        setDragging(true);\n        move(event);\n      },\n      onPointerMove(event: PointerEvent<HTMLElement>) {\n        if (event.currentTarget.hasPointerCapture(event.pointerId)) move(event);\n      },\n      onPointerUp(event: PointerEvent<HTMLElement>) {\n        if (!event.currentTarget.hasPointerCapture(event.pointerId)) return;\n        event.currentTarget.releasePointerCapture(event.pointerId);\n        setDragging(false);\n        onEnd?.();\n      },\n      onPointerCancel() {\n        setDragging(false);\n      },\n    },\n  };\n}\n\nexport interface ColorPanelProps {\n  /** The color as hex. Accepts any CSS color `parseColor` reads. */\n  value?: string;\n  defaultValue?: string;\n  /** Called with \"#rrggbb\", or \"#rrggbbaa\" when alpha is on and the color is translucent. */\n  onValueChange?: (value: string) => void;\n  /** Adds an opacity slider and channel. */\n  alpha?: boolean;\n  /** Swatches under the controls. Pass `[]` to hide them. */\n  presets?: string[];\n  /** Recently used colors, newest first. */\n  recent?: string[];\n  /** Shows the eyedropper button in browsers that have the EyeDropper API. */\n  eyeDropper?: boolean;\n  /** The color the preview compares against; clicking its half restores it. Defaults to the first value. */\n  previous?: string;\n  className?: string;\n}\n\n/**\n * The picker surface on its own: a saturation and brightness area, a hue slider, an optional\n * alpha slider, hex, RGB and HSL fields, an eyedropper, and swatches. Every control works from\n * the keyboard; arrow keys move the area's thumb (Shift for bigger steps).\n */\nexport function ColorPanel({\n  value: valueProp,\n  defaultValue = \"#3b82f6\",\n  onValueChange,\n  alpha = false,\n  presets = defaultColorPresets,\n  recent = [],\n  eyeDropper = true,\n  previous: previousProp,\n  className,\n}: ColorPanelProps) {\n  const [hsva, setHsva] = useState<Hsva>(() => rgbToHsv(parseColor(valueProp ?? defaultValue) ?? { r: 59, g: 130, b: 246, a: 1 }));\n  const lastEmitted = useRef<string | null>(null);\n  const [initial] = useState(() => valueProp ?? defaultValue);\n  const previous = previousProp ?? initial;\n\n  // An outside change replaces the color; hue survives grays so the area does not jump to red.\n  useEffect(() => {\n    if (valueProp === undefined || sameColor(valueProp, lastEmitted.current)) return;\n    const rgba = parseColor(valueProp);\n    if (rgba) setHsva((current) => rgbToHsv(rgba, current.h));\n  }, [valueProp]);\n\n  const rgba = hsvToRgb(hsva);\n  const hex = toHex(rgba, alpha);\n\n  function update(next: Hsva) {\n    const normalized = { ...next, a: alpha ? next.a : 1 };\n    setHsva(normalized);\n    const out = toHex(hsvToRgb(normalized), alpha);\n    if (out === lastEmitted.current) return;\n    lastEmitted.current = out;\n    onValueChange?.(out);\n  }\n\n  function apply(color: string) {\n    const parsed = parseColor(color);\n    if (parsed) update(rgbToHsv(parsed, hsva.h));\n  }\n\n  const [canDrop, setCanDrop] = useState(false);\n  useEffect(() => setCanDrop(typeof window !== \"undefined\" && \"EyeDropper\" in window), []);\n\n  async function pickFromScreen() {\n    try {\n      const Dropper = (window as unknown as { EyeDropper: new () => { open: () => Promise<{ sRGBHex: string }> } }).EyeDropper;\n      const result = await new Dropper().open();\n      const parsed = parseColor(result.sRGBHex);\n      if (parsed) update(rgbToHsv({ ...parsed, a: hsva.a }, hsva.h));\n    } catch {\n      // Escape closes the dropper without a color.\n    }\n  }\n\n  return (\n    <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)}>\n      <SaturationArea hsva={hsva} onChange={update} />\n      <div className=\"flex items-center gap-3\">\n        <PreviewSwatch previous={previous} current={hex} onRevert={() => apply(previous)} />\n        <div className=\"grid flex-1 gap-2.5\">\n          <ChannelSlider\n            label=\"Hue\"\n            value={hsva.h}\n            max={360}\n            unit=\"°\"\n            track=\"linear-gradient(to right, #f00 0%, #ff0 17%, #0f0 33%, #0ff 50%, #00f 67%, #f0f 83%, #f00 100%)\"\n            thumbColor={`hsl(${hsva.h} 100% 50%)`}\n            onChange={(h) => update({ ...hsva, h })}\n          />\n          {alpha ? (\n            <ChannelSlider\n              label=\"Opacity\"\n              value={Math.round(hsva.a * 100)}\n              max={100}\n              unit=\"%\"\n              checkered\n              track={`linear-gradient(to right, rgb(${rgba.r} ${rgba.g} ${rgba.b} / 0), rgb(${rgba.r} ${rgba.g} ${rgba.b}))`}\n              thumbColor={`rgb(${rgba.r} ${rgba.g} ${rgba.b} / ${hsva.a})`}\n              onChange={(a) => update({ ...hsva, a: a / 100 })}\n            />\n          ) : null}\n        </div>\n      </div>\n      <ColorFields hsva={hsva} alpha={alpha} onChange={update}>\n        {eyeDropper && canDrop ? (\n          <button\n            type=\"button\"\n            aria-label=\"Pick a color from the screen\"\n            onClick={pickFromScreen}\n            className={cx(\n              \"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\",\n              \"transition-[background-color,border-color,color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.94] motion-reduce:transition-none\",\n              \"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\",\n              \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n            )}\n          >\n            <svg aria-hidden=\"true\" viewBox=\"0 0 16 16\" fill=\"none\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" className=\"size-4\">\n              <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\" />\n              <path d=\"m11 2.75 2.25 2.25\" />\n            </svg>\n          </button>\n        ) : null}\n      </ColorFields>\n      {presets.length > 0 ? <SwatchRow label=\"Presets\" colors={presets} current={hex} onPick={apply} /> : null}\n      {recent.length > 0 ? <SwatchRow label=\"Recent\" colors={recent} current={hex} onPick={apply} /> : null}\n    </div>\n  );\n}\n\nfunction SaturationArea({ hsva, onChange }: { hsva: Hsva; onChange: (next: Hsva) => void }) {\n  const [keyboard, setKeyboard] = useState(false);\n  const { dragging, handlers } = useDrag((x, y) => onChange({ ...hsva, s: x, v: 1 - y }));\n  const { r, g, b } = hsvToRgb({ ...hsva, a: 1 });\n  const active = dragging || keyboard;\n\n  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    const delta = event.shiftKey ? 0.1 : 0.01;\n    const moves: Record<string, Partial<Hsva>> = {\n      ArrowLeft: { s: clamp(hsva.s - delta) },\n      ArrowRight: { s: clamp(hsva.s + delta) },\n      ArrowUp: { v: clamp(hsva.v + delta) },\n      ArrowDown: { v: clamp(hsva.v - delta) },\n      Home: { s: 0 },\n      End: { s: 1 },\n      PageUp: { v: 1 },\n      PageDown: { v: 0 },\n    };\n    const move = moves[event.key];\n    if (!move) return;\n    event.preventDefault();\n    setKeyboard(true);\n    onChange({ ...hsva, ...move });\n  }\n\n  return (\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={Math.round(hsva.s * 100)}\n      aria-valuetext={`Saturation ${Math.round(hsva.s * 100)}%, brightness ${Math.round(hsva.v * 100)}%`}\n      onKeyDown={onKeyDown}\n      onBlur={() => setKeyboard(false)}\n      onPointerDown={(event) => {\n        setKeyboard(false);\n        handlers.onPointerDown(event);\n      }}\n      onPointerMove={handlers.onPointerMove}\n      onPointerUp={handlers.onPointerUp}\n      onPointerCancel={handlers.onPointerCancel}\n      className={cx(\n        \"group relative h-36 cursor-crosshair touch-none rounded-lg outline-hidden select-none\",\n        \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n      )}\n      style={{ background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${hsva.h} 100% 50%))` }}\n    >\n      <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)]\" />\n      {/* Hairline guides through the thumb, shown while dragging or stepping with keys. */}\n      <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 overflow-hidden rounded-lg mix-blend-difference\">\n        <span\n          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\")}\n          style={{ top: `${(1 - hsva.v) * 100}%` }}\n        />\n        <span\n          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\")}\n          style={{ left: `${hsva.s * 100}%` }}\n        />\n      </span>\n      <span\n        aria-hidden=\"true\"\n        className=\"pointer-events-none absolute size-0\"\n        style={{ left: `${hsva.s * 100}%`, top: `${(1 - hsva.v) * 100}%` }}\n      >\n        <Thumb color={`rgb(${r} ${g} ${b})`} active={dragging} />\n      </span>\n    </div>\n  );\n}\n\n/** A white ring with a dark hairline outside, so it reads on any color; it lifts slightly while held. */\nfunction Thumb({ color, active, checkered }: { color: string; active: boolean; checkered?: boolean }) {\n  return (\n    <span\n      className={cx(\n        \"absolute top-0 left-0 block size-4 -translate-x-1/2 -translate-y-1/2 rounded-full\",\n        \"border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.22),0_1px_3px_rgb(0_0_0/0.25)]\",\n        \"transition-[scale,box-shadow] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n        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)]\",\n      )}\n      style={{ background: checkered ? `linear-gradient(${color}, ${color}), ${checker}, #fff` : color }}\n    />\n  );\n}\n\nfunction ChannelSlider({\n  label,\n  value,\n  max,\n  unit,\n  track,\n  thumbColor,\n  checkered,\n  onChange,\n}: {\n  label: string;\n  value: number;\n  max: number;\n  unit: string;\n  track: string;\n  thumbColor: string;\n  checkered?: boolean;\n  onChange: (value: number) => void;\n}) {\n  const { dragging, handlers } = useDrag((x) => onChange(Math.round(x * max)));\n\n  function onKeyDown(event: KeyboardEvent<HTMLDivElement>) {\n    const delta = event.shiftKey ? 10 : 1;\n    const moves: Record<string, number> = {\n      ArrowLeft: value - delta,\n      ArrowDown: value - delta,\n      ArrowRight: value + delta,\n      ArrowUp: value + delta,\n      PageDown: value - 10,\n      PageUp: value + 10,\n      Home: 0,\n      End: max,\n    };\n    const next = moves[event.key];\n    if (next === undefined) return;\n    event.preventDefault();\n    onChange(Math.min(max, Math.max(0, next)));\n  }\n\n  return (\n    <div\n      role=\"slider\"\n      tabIndex={0}\n      aria-label={label}\n      aria-valuemin={0}\n      aria-valuemax={max}\n      aria-valuenow={Math.round(value)}\n      aria-valuetext={`${Math.round(value)}${unit}`}\n      onKeyDown={onKeyDown}\n      {...handlers}\n      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\"\n      style={{ background: checkered ? `${track}, ${checker}, #fff` : track }}\n    >\n      <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)]\" />\n      {/* The thumb's center travels from 6px in at each end, so it never hangs past the track. */}\n      <span aria-hidden=\"true\" className=\"pointer-events-none absolute inset-y-0 right-1.5 left-1.5\">\n        <span className=\"absolute top-1/2 size-0\" style={{ left: `${(value / max) * 100}%` }}>\n          <Thumb color={thumbColor} active={dragging} checkered={checkered} />\n        </span>\n      </span>\n    </div>\n  );\n}\n\nfunction PreviewSwatch({ previous, current, onRevert }: { previous: string; current: string; onRevert: () => void }) {\n  const changed = !sameColor(previous, current);\n  return (\n    <div className=\"relative grid size-10 shrink-0 grid-cols-2 overflow-hidden rounded-lg\" style={{ background: `${checker}, #fff` }}>\n      <button\n        type=\"button\"\n        aria-label={`Restore previous color ${previous}`}\n        disabled={!changed}\n        onClick={onRevert}\n        className=\"outline-hidden focus-visible:outline-2 focus-visible:outline-solid focus-visible:-outline-offset-2 focus-visible:outline-sky-500 disabled:cursor-default\"\n        style={{ background: previous }}\n      />\n      <span aria-hidden=\"true\" className=\"transition-[background-color] duration-150 ease-out motion-reduce:transition-none\" style={{ background: current }} />\n      <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)]\" />\n    </div>\n  );\n}\n\nfunction ColorFields({ hsva, alpha, onChange, children }: { hsva: Hsva; alpha: boolean; onChange: (next: Hsva) => void; children?: ReactNode }) {\n  const [format, setFormat] = useState<Format>(\"hex\");\n  const rgba = hsvToRgb(hsva);\n  const hsla = hsvToHsl(hsva);\n  const percent = (value: number) => Math.round(value * 100);\n\n  const channels: { label: string; value: number; max: number; set: (n: number) => Hsva }[] =\n    format === \"rgb\"\n      ? [\n          { label: \"Red\", value: rgba.r, max: 255, set: (r) => rgbToHsv({ ...rgba, r }, hsva.h) },\n          { label: \"Green\", value: rgba.g, max: 255, set: (g) => rgbToHsv({ ...rgba, g }, hsva.h) },\n          { label: \"Blue\", value: rgba.b, max: 255, set: (b) => rgbToHsv({ ...rgba, b }, hsva.h) },\n        ]\n      : [\n          { label: \"Hue\", value: Math.round(hsla.h), max: 360, set: (h) => hslToHsv({ ...hsla, h }) },\n          { label: \"Saturation\", value: percent(hsla.s), max: 100, set: (s) => hslToHsv({ ...hsla, s: s / 100 }) },\n          { label: \"Lightness\", value: percent(hsla.l), max: 100, set: (l) => hslToHsv({ ...hsla, l: l / 100 }) },\n        ];\n  if (alpha) channels.push({ label: \"Opacity\", value: percent(hsva.a), max: 100, set: (a) => ({ ...hsva, a: a / 100 }) });\n\n  return (\n    <div className=\"flex items-center gap-1.5\">\n      <div className=\"relative shrink-0\">\n        <select\n          aria-label=\"Color format\"\n          value={format}\n          onChange={(event) => setFormat(event.target.value as Format)}\n          className={cx(\n            \"h-8 appearance-none rounded-lg border border-zinc-950/12 bg-white ps-2 pe-6 text-xs font-medium text-zinc-700\",\n            \"dark:border-white/15 dark:bg-black dark:text-zinc-300\",\n            \"transition-[border-color] duration-150 ease-out hover:border-zinc-950/20 dark:hover:border-white/25 motion-reduce:transition-none\",\n            \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n          )}\n        >\n          <option value=\"hex\">Hex</option>\n          <option value=\"rgb\">RGB</option>\n          <option value=\"hsl\">HSL</option>\n        </select>\n        <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\">\n          <path d=\"m5 6.5 3-3 3 3M5 9.5l3 3 3-3\" />\n        </svg>\n      </div>\n      {format === \"hex\" ? (\n        <TextChannel\n          label=\"Hex color\"\n          value={toHex(rgba, alpha).slice(1).toUpperCase()}\n          prefix=\"#\"\n          onCommit={(text) => {\n            const parsed = parseColor(`#${text.replace(/^#/, \"\")}`);\n            if (parsed) onChange(rgbToHsv(alpha ? parsed : { ...parsed, a: 1 }, hsva.h));\n          }}\n        />\n      ) : (\n        channels.map((channel) => (\n          <TextChannel\n            key={channel.label}\n            label={channel.label}\n            value={String(channel.value)}\n            numeric={channel.max}\n            onCommit={(text) => {\n              const n = Number(text);\n              if (text.trim() !== \"\" && Number.isFinite(n)) onChange(channel.set(Math.min(channel.max, Math.max(0, Math.round(n)))));\n            }}\n          />\n        ))\n      )}\n      {children}\n    </div>\n  );\n}\n\n/** A small text field that keeps what you type until Enter or blur, then commits or snaps back. */\nfunction TextChannel({\n  label,\n  value,\n  prefix,\n  numeric,\n  onCommit,\n}: {\n  label: string;\n  value: string;\n  prefix?: string;\n  numeric?: number;\n  onCommit: (text: string) => void;\n}) {\n  const [draft, setDraft] = useState<string | null>(null);\n\n  function onKeyDown(event: KeyboardEvent<HTMLInputElement>) {\n    if (event.key === \"Enter\") {\n      onCommit(event.currentTarget.value);\n      setDraft(null);\n    } else if (event.key === \"Escape\" && draft !== null) {\n      event.stopPropagation();\n      setDraft(null);\n    } else if (numeric !== undefined && (event.key === \"ArrowUp\" || event.key === \"ArrowDown\")) {\n      event.preventDefault();\n      const step = (event.shiftKey ? 10 : 1) * (event.key === \"ArrowUp\" ? 1 : -1);\n      onCommit(String(Math.min(numeric, Math.max(0, Number(value) + step))));\n      setDraft(null);\n    }\n  }\n\n  return (\n    <label\n      className={cx(\n        \"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\",\n        \"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\",\n        \"has-[:focus-visible]:outline-2 has-[:focus-visible]:outline-solid has-[:focus-visible]:outline-offset-2 has-[:focus-visible]:outline-sky-500\",\n      )}\n    >\n      {prefix ? <span className=\"text-xs text-zinc-500\">{prefix}</span> : null}\n      <input\n        aria-label={label}\n        title={label}\n        value={draft ?? value}\n        inputMode={numeric !== undefined ? \"numeric\" : \"text\"}\n        spellCheck={false}\n        autoComplete=\"off\"\n        maxLength={numeric !== undefined ? 3 : 9}\n        onChange={(event) => setDraft(event.target.value)}\n        onFocus={(event) => event.currentTarget.select()}\n        onBlur={(event) => {\n          if (draft !== null) onCommit(event.currentTarget.value);\n          setDraft(null);\n        }}\n        onKeyDown={onKeyDown}\n        className=\"w-full min-w-0 bg-transparent font-mono text-xs text-zinc-950 tabular-nums outline-hidden dark:text-white\"\n      />\n    </label>\n  );\n}\n\nfunction SwatchRow({ label, colors, current, onPick }: { label: string; colors: string[]; current: string; onPick: (color: string) => void }) {\n  return (\n    <div role=\"group\" aria-label={label} className=\"grid gap-1.5\">\n      <span aria-hidden=\"true\" className=\"text-xs font-medium text-zinc-500\">\n        {label}\n      </span>\n      <div className=\"grid grid-cols-9 gap-1.5\">\n        {colors.map((color) => {\n          const selected = sameColor(color, current);\n          return (\n            <button\n              key={color}\n              type=\"button\"\n              aria-label={color}\n              aria-pressed={selected}\n              title={color}\n              onClick={() => onPick(color)}\n              className={cx(\n                \"relative size-[22px] rounded-md\",\n                \"transition-[scale] duration-150 ease-out motion-safe:hover:scale-110 motion-safe:active:scale-95 motion-reduce:transition-none\",\n                \"focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-2 focus-visible:outline-sky-500\",\n              )}\n              style={{ background: `linear-gradient(${color}, ${color}), ${checker}, #fff` }}\n            >\n              <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)]\" />\n              {/* The current swatch gets a ring in the page color, set off by a hairline. */}\n              <span\n                aria-hidden=\"true\"\n                className={cx(\n                  \"absolute -inset-[3px] rounded-[9px] shadow-[0_0_0_1.5px_rgb(9_9_11)] dark:shadow-[0_0_0_1.5px_white]\",\n                  \"transition-[opacity,scale] duration-200 ease-[cubic-bezier(0.23,1,0.32,1)] motion-reduce:transition-none\",\n                  selected ? \"scale-100 opacity-100\" : \"scale-90 opacity-0\",\n                )}\n              />\n            </button>\n          );\n        })}\n      </div>\n    </div>\n  );\n}\n\nexport interface ColorPickerProps extends Omit<ColorPanelProps, \"recent\" | \"previous\" | \"className\"> {\n  /** Colors already in the recent row, newest first. */\n  defaultRecent?: string[];\n  /** How many recent colors to keep. */\n  recentLimit?: number;\n  /** Called when the recent list changes, for example to persist it. */\n  onRecentChange?: (recent: string[]) => void;\n  /** Turns the trigger off. */\n  disabled?: boolean;\n  /** Submits the value under this name with a hidden input. */\n  name?: string;\n  /** Accessible name for the trigger; its text already includes the color. */\n  \"aria-label\"?: string;\n  id?: string;\n  /** Classes for the trigger. */\n  className?: string;\n  side?: \"top\" | \"bottom\" | \"left\" | \"right\";\n  align?: \"start\" | \"center\" | \"end\";\n}\n\n/**\n * A swatch button that opens the `ColorPanel` in a popover. The color changes live while you\n * pick; closing the popover with a new color adds it to the recent row.\n */\nexport function ColorPicker({\n  value: valueProp,\n  defaultValue = \"#3b82f6\",\n  onValueChange,\n  defaultRecent = [],\n  recentLimit = 8,\n  onRecentChange,\n  disabled,\n  name,\n  id,\n  className,\n  side = \"bottom\",\n  align = \"start\",\n  alpha,\n  \"aria-label\": ariaLabel,\n  ...panel\n}: ColorPickerProps) {\n  const [inner, setInner] = useState(defaultValue);\n  const value = valueProp ?? inner;\n  const [open, setOpen] = useState(false);\n  const [recent, setRecent] = useState(defaultRecent);\n  const [openedWith, setOpenedWith] = useState(value);\n  const rgba = useMemo(() => parseColor(value), [value]);\n\n  function onChange(next: string) {\n    if (valueProp === undefined) setInner(next);\n    onValueChange?.(next);\n  }\n\n  function onOpenChange(next: boolean) {\n    if (next) setOpenedWith(value);\n    else if (!sameColor(value, openedWith)) {\n      const list = [value, ...recent.filter((color) => !sameColor(color, value))].slice(0, recentLimit);\n      setRecent(list);\n      onRecentChange?.(list);\n    }\n    setOpen(next);\n  }\n\n  const label = rgba ? toHex(rgba, alpha).toUpperCase() : value;\n\n  return (\n    <Popover open={open} onOpenChange={onOpenChange}>\n      <PopoverTrigger\n        id={id}\n        disabled={disabled}\n        aria-label={ariaLabel ? `${ariaLabel}, ${label}` : undefined}\n        className={cx(\n          \"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)]\",\n          \"dark:border-white/15 dark:bg-black dark:text-white dark:shadow-none\",\n          \"transition-[background-color,border-color,scale] duration-150 ease-out active:duration-100 motion-safe:active:scale-[0.97] motion-reduce:transition-none\",\n          \"hover:border-zinc-950/20 hover:bg-zinc-950/[0.03] dark:hover:border-white/25 dark:hover:bg-white/[0.06]\",\n          \"data-[popup-open]:border-zinc-950/20 dark:data-[popup-open]:border-white/25\",\n          \"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\",\n          className,\n        )}\n      >\n        <span aria-hidden=\"true\" className=\"relative size-6 overflow-hidden rounded-md\" style={{ background: `linear-gradient(${value}, ${value}), ${checker}, #fff` }}>\n          <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)]\" />\n        </span>\n        <span className=\"font-mono text-xs tabular-nums\">{label}</span>\n      </PopoverTrigger>\n      <PopoverContent side={side} align={align} className=\"w-auto p-3\">\n        <ColorPanel {...panel} alpha={alpha} value={value} onValueChange={onChange} recent={recent} previous={openedWith} />\n      </PopoverContent>\n      {name ? <input type=\"hidden\" name={name} value={value} /> : null}\n    </Popover>\n  );\n}\n"
    }
  ],
  "example": {
    "content": "\"use client\";\n\nimport { useState } from \"react\";\nimport { ColorPicker } from \"@/components/shaken/ui/color-picker\";\n\nconst labelColors = [\"#ef4444\", \"#f59e0b\", \"#10b981\", \"#06b6d4\", \"#6366f1\", \"#a855f7\", \"#ec4899\", \"#71717a\"];\n\nexport default function ColorPickerExample() {\n  const [accent, setAccent] = useState(\"#6366f1\");\n\n  return (\n    <div className=\"flex flex-wrap items-start justify-center gap-6\">\n      <div className=\"grid gap-1.5\">\n        <label htmlFor=\"brand-accent\" className=\"text-sm font-medium text-zinc-950 dark:text-white\">\n          Brand accent\n        </label>\n        <ColorPicker id=\"brand-accent\" value={accent} onValueChange={setAccent} alpha defaultRecent={[\"#0ea5e9\", \"#f43f5e\"]} />\n        <p className=\"max-w-64 text-xs text-zinc-500\">\n          Used for links and the primary button in the{\" \"}\n          <span className=\"font-medium\" style={{ color: accent }}>\n            customer portal\n          </span>\n        </p>\n      </div>\n      <div className=\"grid gap-1.5\">\n        <label htmlFor=\"label-color\" className=\"text-sm font-medium text-zinc-950 dark:text-white\">\n          Label color\n        </label>\n        <ColorPicker id=\"label-color\" defaultValue=\"#10b981\" presets={labelColors} />\n      </div>\n    </div>\n  );\n}\n"
  }
}
