{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"color-picker","type":"registry:component","title":"Color picker","description":"Drag a color out of the square, then fine-tune hue and opacity.","author":"Yash Bavadiya <https://xevrion.dev>","dependencies":["motion"],"registryDependencies":["utils"],"files":[{"path":"components/color-picker.tsx","type":"registry:component","content":"\"use client\";\n\nimport { useId, useRef, useState } from \"react\";\nimport {\n  AnimatePresence,\n  motion,\n  useMotionValue,\n  useMotionValueEvent,\n  useTransform,\n  type MotionValue,\n} from \"motion/react\";\nimport { useReducedMotion } from \"@/hooks/use-reduced-motion\";\nimport { cn } from \"@/lib/utils\";\n\ntype Hsva = { h: number; s: number; v: number; a: number };\n\n// Wide enough for a useful history, narrow enough to stay one row at 320px.\nconst MAX_RECENT = 8;\nconst DEFAULT_RECENT = [\"#E5484D\", \"#F5A524\", \"#30A46C\", \"#0090FF\", \"#8E4EC6\"];\nconst SWATCH = { type: \"spring\", duration: 0.3, bounce: 0 } as const;\nconst SWATCH_EXIT = { duration: 0.15, ease: [0.23, 1, 0.32, 1] } as const;\nconst HUE_GRADIENT =\n  \"linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)\";\n// Tokens, not raw greys, so transparency reads correctly in both themes.\nconst CHECKER = {\n  backgroundImage:\n    \"repeating-conic-gradient(var(--border) 0 25%, var(--background) 0 50%)\",\n  backgroundSize: \"8px 8px\",\n};\n// Half the 20px thumb: the rail stops here so the thumb never overhangs.\nconst THUMB_RADIUS = 10;\nconst HAIRLINE =\n  \"shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_10%,transparent)]\";\n\nconst clamp = (n: number) => Math.min(Math.max(n, 0), 1);\n\nfunction hsvToRgb(h: number, s: number, v: number) {\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 [f(5), f(3), f(1)] as const;\n}\n\n// Grey has no hue and black no saturation, so both keep what the user had\n// instead of snapping to 0. That is what stops the hue thumb jumping home\n// when a hex like #808080 or #000 comes in.\nfunction rgbToHsv(r: number, g: number, b: number, prev: Hsva) {\n  const [R, G, B] = [r / 255, g / 255, b / 255];\n  const max = Math.max(R, G, B);\n  const d = max - Math.min(R, G, B);\n  let h = prev.h;\n  if (d !== 0) {\n    const sector =\n      max === R\n        ? ((G - B) / d) % 6\n        : max === G\n          ? (B - R) / d + 2\n          : (R - G) / d + 4;\n    h = (sector * 60 + 360) % 360;\n  }\n  return { h, s: max === 0 ? prev.s : d / max, v: max };\n}\n\nfunction parseHex(input: string) {\n  const hex = input.trim().replace(/^#/, \"\");\n  if (!/^([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;\n  const full = hex.length <= 4 ? [...hex].map((c) => c + c).join(\"\") : hex;\n  const byte = (i: number) => parseInt(full.slice(i, i + 2), 16);\n  return {\n    r: byte(0),\n    g: byte(2),\n    b: byte(4),\n    a: full.length === 8 ? byte(6) / 255 : 1,\n  };\n}\n\nfunction toHex({ h, s, v, a }: Hsva) {\n  const pair = (n: number) => n.toString(16).padStart(2, \"0\");\n  const alpha = Math.round(a * 255);\n  return (\n    \"#\" +\n    hsvToRgb(h, s, v).map(pair).join(\"\") +\n    (alpha < 255 ? pair(alpha) : \"\")\n  ).toUpperCase();\n}\n\nfunction fromHex(hex: string, prev: Hsva): Hsva | null {\n  const rgba = parseHex(hex);\n  if (!rgba) return null;\n  return { ...rgbToHsv(rgba.r, rgba.g, rgba.b, prev), a: rgba.a };\n}\n\n// Pointer capture keeps the drag alive outside the element, and only the\n// first pointer counts, so a second finger can't make the handle jump.\nfunction useDrag({\n  onPoint,\n  onEnd,\n  inset = 0,\n}: {\n  onPoint: (x: number, y: number) => void;\n  onEnd: () => void;\n  inset?: number;\n}) {\n  const pointer = useRef<number | null>(null);\n  const rect = useRef<DOMRect | null>(null);\n  const point = (e: React.PointerEvent) => {\n    const r = rect.current;\n    if (!r) return;\n    onPoint(\n      clamp((e.clientX - r.left - inset) / (r.width - inset * 2)),\n      clamp((e.clientY - r.top) / r.height),\n    );\n  };\n  const end = (e: React.PointerEvent) => {\n    if (e.pointerId !== pointer.current) return;\n    pointer.current = null;\n    onEnd();\n  };\n  return {\n    onPointerDown: (e: React.PointerEvent<HTMLElement>) => {\n      if (pointer.current !== null) return;\n      if (e.pointerType === \"mouse\" && e.button !== 0) return;\n      pointer.current = e.pointerId;\n      e.currentTarget.setPointerCapture(e.pointerId);\n      // Read once per drag rather than on every move.\n      rect.current = e.currentTarget.getBoundingClientRect();\n      point(e);\n    },\n    onPointerMove: (e: React.PointerEvent) => {\n      if (e.pointerId === pointer.current) point(e);\n    },\n    onPointerUp: end,\n    onPointerCancel: end,\n  };\n}\n\n// Arrows move one step, Shift or the Page keys ten, Home and End jump to\n// the ends.\nfunction keyStep(e: React.KeyboardEvent, step: number) {\n  const big = step * 10;\n  const unit = e.shiftKey ? big : step;\n  switch (e.key) {\n    case \"ArrowRight\":\n    case \"ArrowUp\":\n      return unit;\n    case \"ArrowLeft\":\n    case \"ArrowDown\":\n      return -unit;\n    case \"PageUp\":\n      return big;\n    case \"PageDown\":\n      return -big;\n    case \"Home\":\n      return -Infinity;\n    case \"End\":\n      return Infinity;\n  }\n  return null;\n}\n\nexport function ColorPicker({\n  defaultValue = \"#5B8DEF\",\n  recent: initialRecent = DEFAULT_RECENT,\n  onChange,\n  className,\n}: {\n  defaultValue?: string;\n  recent?: string[];\n  onChange?: (hex: string) => void;\n  className?: string;\n}) {\n  const reduceMotion = useReducedMotion();\n  const id = useId();\n  const [initial] = useState<Hsva>(\n    () =>\n      fromHex(defaultValue, { h: 0, s: 0, v: 0, a: 1 }) ?? {\n        h: 220,\n        s: 0.6,\n        v: 0.9,\n        a: 1,\n      },\n  );\n  // The color lives in motion values, not React state, so a drag repaints\n  // only the few styles that depend on it and never re-renders the tree.\n  const h = useMotionValue(initial.h);\n  const s = useMotionValue(initial.s);\n  const v = useMotionValue(initial.v);\n  const a = useMotionValue(initial.a);\n  const read = (): Hsva => ({ h: h.get(), s: s.get(), v: v.get(), a: a.get() });\n\n  const [recent, setRecent] = useState(() =>\n    initialRecent.map((c) => c.toUpperCase()),\n  );\n  const [active, setActive] = useState<string | null>(null);\n  const [invalid, setInvalid] = useState(false);\n  const hexRef = useRef<HTMLInputElement>(null);\n\n  const rgbOf = () => hsvToRgb(h.get(), s.get(), v.get()).join(\" \");\n  const rgb = useTransform(() => `rgb(${rgbOf()})`);\n  const rgba = useTransform(() => `rgb(${rgbOf()} / ${a.get()})`);\n  const alphaTrack = useTransform(\n    () => `linear-gradient(to right, rgb(${rgbOf()} / 0), rgb(${rgbOf()}))`,\n  );\n  const hueColor = useTransform(h, (x) => `hsl(${x} 100% 50%)`);\n  const hueFraction = useTransform(h, (x) => x / 360);\n  const alphaLabel = useTransform(a, (x) => `${Math.round(x * 100)}%`);\n\n  // The field is uncontrolled so a drag never re-renders it. It follows the\n  // color except while you're typing in it.\n  const syncHex = () => {\n    const input = hexRef.current;\n    if (input && document.activeElement !== input)\n      input.value = toHex(read()).slice(1);\n  };\n  useMotionValueEvent(h, \"change\", syncHex);\n  useMotionValueEvent(s, \"change\", syncHex);\n  useMotionValueEvent(v, \"change\", syncHex);\n  useMotionValueEvent(a, \"change\", syncHex);\n\n  const update = (patch: Partial<Hsva>) => {\n    if (patch.h !== undefined) h.set(patch.h);\n    if (patch.s !== undefined) s.set(patch.s);\n    if (patch.v !== undefined) v.set(patch.v);\n    if (patch.a !== undefined) a.set(patch.a);\n    const hex = toHex(read());\n    // Once it is null this bails out without rendering.\n    setActive((current) => (current === hex ? current : null));\n    onChange?.(hex);\n  };\n\n  // Recents update when a change settles, so a drag adds one swatch rather\n  // than one per frame.\n  const commit = () => {\n    const hex = toHex(read());\n    setRecent((list) =>\n      list[0] === hex\n        ? list\n        : [hex, ...list.filter((c) => c !== hex)].slice(0, MAX_RECENT),\n    );\n    setActive(hex);\n  };\n\n  const applyHex = (leaving: boolean) => {\n    const input = hexRef.current;\n    if (!input) return;\n    const next = fromHex(input.value, read());\n    if (!next) {\n      // Enter keeps the text so it can be fixed. Leaving the field puts the\n      // real value back rather than stranding a broken one.\n      if (leaving) input.value = toHex(read()).slice(1);\n      setInvalid(!leaving);\n      return;\n    }\n    setInvalid(false);\n    const changed = toHex(next) !== toHex(read());\n    update(next);\n    input.value = toHex(next).slice(1);\n    if (changed) commit();\n  };\n\n  return (\n    // 20px outer radius around 8px controls with 12px padding: concentric.\n    <div\n      className={cn(\n        \"flex w-[min(320px,100%)] flex-col gap-3 rounded-[20px] bg-background p-3 shadow-raised\",\n        className,\n      )}\n    >\n      <Pad\n        s={s}\n        v={v}\n        hueColor={hueColor}\n        rgb={rgb}\n        onChange={update}\n        onCommit={commit}\n      />\n\n      <div className=\"flex items-center gap-3\">\n        <div className=\"flex flex-1 flex-col gap-1\">\n          <Channel\n            label=\"Hue\"\n            max={360}\n            fraction={hueFraction}\n            track={HUE_GRADIENT}\n            thumb={hueColor}\n            valueText={(f) => `${Math.round(f * 360)} degrees`}\n            onChange={(f) => update({ h: f * 360 })}\n            onCommit={commit}\n            step={1 / 360}\n          />\n          <Channel\n            label=\"Opacity\"\n            max={100}\n            fraction={a}\n            track={alphaTrack}\n            thumb={rgba}\n            checker\n            valueText={(f) => `${Math.round(f * 100)}%`}\n            onChange={(f) => update({ a: f })}\n            onCommit={commit}\n            step={0.01}\n          />\n        </div>\n        <span\n          aria-hidden\n          className=\"relative size-11 shrink-0 overflow-hidden rounded-lg\"\n          style={CHECKER}\n        >\n          <motion.span\n            className={cn(\"absolute inset-0 rounded-lg\", HAIRLINE)}\n            style={{ backgroundColor: rgba }}\n          />\n        </span>\n      </div>\n\n      <div className=\"flex gap-2\">\n        <label\n          htmlFor={`${id}-hex`}\n          className={cn(\n            \"flex h-9 flex-1 cursor-text items-center rounded-lg border bg-background px-2.5 font-mono text-sm text-foreground transition-[border-color] duration-150 ease-out focus-within:outline-2 focus-within:outline-solid focus-within:-outline-offset-1\",\n            invalid\n              ? \"border-destructive focus-within:outline-destructive\"\n              : \"border-border focus-within:outline-foreground\",\n          )}\n        >\n          <span\n            className={cn(\n              \"transition-[color] duration-150 ease-out select-none\",\n              invalid ? \"text-destructive\" : \"text-muted-foreground\",\n            )}\n          >\n            #\n          </span>\n          <input\n            ref={hexRef}\n            id={`${id}-hex`}\n            aria-label=\"Hex color\"\n            aria-invalid={invalid}\n            defaultValue={toHex(initial).slice(1)}\n            maxLength={9}\n            spellCheck={false}\n            autoComplete=\"off\"\n            autoCapitalize=\"characters\"\n            className=\"min-w-0 flex-1 bg-transparent pl-0.5 uppercase outline-hidden\"\n            onFocus={(e) => e.currentTarget.select()}\n            onChange={() => {\n              if (invalid) setInvalid(false);\n            }}\n            onKeyDown={(e) => {\n              if (e.key === \"Enter\") applyHex(false);\n              if (e.key === \"Escape\") {\n                e.currentTarget.value = toHex(read()).slice(1);\n                setInvalid(false);\n              }\n            }}\n            onBlur={() => applyHex(true)}\n          />\n        </label>\n        <motion.span\n          aria-hidden\n          className=\"flex h-9 w-14 items-center justify-center rounded-lg border border-border font-mono text-sm text-muted-foreground tabular-nums select-none\"\n        >\n          {alphaLabel}\n        </motion.span>\n        <span className=\"sr-only\" aria-live=\"polite\">\n          {invalid ? \"Not a valid hex color\" : \"\"}\n        </span>\n      </div>\n\n      <div className=\"border-t border-border pt-3\">\n        <p\n          id={`${id}-recent`}\n          className=\"mb-2 text-xs text-muted-foreground select-none\"\n        >\n          Recent\n        </p>\n        <div\n          role=\"group\"\n          aria-labelledby={`${id}-recent`}\n          className=\"relative flex h-7 gap-2\"\n        >\n          <AnimatePresence initial={false} mode=\"popLayout\">\n            {recent.map((hex) => (\n              <motion.button\n                key={hex}\n                type=\"button\"\n                layout={reduceMotion ? false : \"position\"}\n                aria-label={`Use ${hex}`}\n                aria-pressed={active === hex}\n                initial={\n                  reduceMotion\n                    ? { opacity: 0 }\n                    : { opacity: 0, scale: 0.6, filter: \"blur(4px)\" }\n                }\n                animate={{ opacity: 1, scale: 1, filter: \"blur(0px)\" }}\n                exit={{\n                  opacity: 0,\n                  ...(reduceMotion ? {} : { scale: 0.6, filter: \"blur(4px)\" }),\n                  transition: SWATCH_EXIT,\n                }}\n                transition={SWATCH}\n                onClick={() => {\n                  const next = fromHex(hex, read());\n                  if (!next) return;\n                  // Applies without reordering, so the swatch under the\n                  // cursor stays exactly where it is.\n                  update(next);\n                  setActive(hex);\n                  setInvalid(false);\n                }}\n                className={cn(\n                  \"relative size-7 shrink-0 touch-manipulation rounded-full ring-offset-2 ring-offset-background outline-hidden transition-[scale,box-shadow] duration-150 ease-out select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-4 focus-visible:outline-foreground active:scale-[0.96] motion-reduce:transition-[box-shadow]\",\n                  // A 36px hit area; with the 8px gap neighbours meet but\n                  // never overlap.\n                  \"after:absolute after:-inset-1 after:rounded-full\",\n                  active === hex ? \"ring-2 ring-foreground\" : \"ring-0\",\n                )}\n                style={CHECKER}\n              >\n                <span\n                  className={cn(\"absolute inset-0 rounded-full\", HAIRLINE)}\n                  style={{ backgroundColor: hex }}\n                />\n              </motion.button>\n            ))}\n          </AnimatePresence>\n        </div>\n      </div>\n    </div>\n  );\n}\n\nfunction Pad({\n  s,\n  v,\n  hueColor,\n  rgb,\n  onChange,\n  onCommit,\n}: {\n  s: MotionValue<number>;\n  v: MotionValue<number>;\n  hueColor: MotionValue<string>;\n  rgb: MotionValue<string>;\n  onChange: (patch: Partial<Hsva>) => void;\n  onCommit: () => void;\n}) {\n  const ref = useRef<HTMLDivElement>(null);\n  const dirty = useRef(false);\n  const drag = useDrag({\n    onPoint: (x, y) => onChange({ s: x, v: 1 - y }),\n    onEnd: onCommit,\n  });\n  // left/top on one small absolute element rather than a translated\n  // full-size layer, which would overhang the pad and widen the page.\n  const left = useTransform(s, (x) => `${x * 100}%`);\n  const top = useTransform(v, (x) => `${(1 - x) * 100}%`);\n\n  const text = () =>\n    `Saturation ${Math.round(s.get() * 100)}%, brightness ${Math.round(v.get() * 100)}%`;\n  const syncAria = () => {\n    ref.current?.setAttribute(\n      \"aria-valuenow\",\n      String(Math.round(s.get() * 100)),\n    );\n    ref.current?.setAttribute(\"aria-valuetext\", text());\n  };\n  useMotionValueEvent(s, \"change\", syncAria);\n  useMotionValueEvent(v, \"change\", syncAria);\n\n  return (\n    <motion.div\n      ref={ref}\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(s.get() * 100)}\n      aria-valuetext={text()}\n      {...drag}\n      onKeyDown={(e) => {\n        const delta = keyStep(e, 0.01);\n        if (delta === null) return;\n        e.preventDefault();\n        dirty.current = true;\n        // Left and right move saturation, the rest brightness, matching the\n        // axes on screen.\n        if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\")\n          onChange({ s: clamp(s.get() + delta) });\n        else onChange({ v: clamp(v.get() + delta) });\n      }}\n      onBlur={() => {\n        if (dirty.current) onCommit();\n        dirty.current = false;\n      }}\n      className=\"group relative h-44 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-foreground\"\n      style={{\n        backgroundColor: hueColor,\n        backgroundImage:\n          \"linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, transparent)\",\n      }}\n    >\n      <span\n        className={cn(\n          \"pointer-events-none absolute inset-0 rounded-lg\",\n          HAIRLINE,\n        )}\n      />\n      <Thumb left={left} top={top} fill={rgb} />\n    </motion.div>\n  );\n}\n\nfunction Channel({\n  label,\n  max,\n  fraction,\n  track,\n  thumb,\n  checker,\n  valueText,\n  onChange,\n  onCommit,\n  step,\n}: {\n  label: string;\n  max: number;\n  fraction: MotionValue<number>;\n  track: string | MotionValue<string>;\n  thumb: MotionValue<string>;\n  checker?: boolean;\n  valueText: (fraction: number) => string;\n  onChange: (fraction: number) => void;\n  onCommit: () => void;\n  step: number;\n}) {\n  const ref = useRef<HTMLDivElement>(null);\n  const dirty = useRef(false);\n  const drag = useDrag({\n    onPoint: (x) => onChange(x),\n    onEnd: onCommit,\n    inset: THUMB_RADIUS,\n  });\n  const left = useTransform(fraction, (f) => `${f * 100}%`);\n\n  useMotionValueEvent(fraction, \"change\", (f) => {\n    ref.current?.setAttribute(\"aria-valuenow\", String(Math.round(f * max)));\n    ref.current?.setAttribute(\"aria-valuetext\", valueText(f));\n  });\n\n  return (\n    <div\n      ref={ref}\n      role=\"slider\"\n      tabIndex={0}\n      aria-label={label}\n      aria-valuemin={0}\n      aria-valuemax={max}\n      aria-valuenow={Math.round(fraction.get() * max)}\n      aria-valuetext={valueText(fraction.get())}\n      {...drag}\n      onKeyDown={(e) => {\n        const delta = keyStep(e, step);\n        if (delta === null) return;\n        e.preventDefault();\n        dirty.current = true;\n        onChange(clamp(fraction.get() + delta));\n      }}\n      onBlur={() => {\n        if (dirty.current) onCommit();\n        dirty.current = false;\n      }}\n      className=\"group relative h-7 cursor-pointer touch-none rounded-full outline-hidden select-none focus-visible:outline-2 focus-visible:outline-solid focus-visible:outline-offset-1 focus-visible:outline-foreground\"\n    >\n      <span\n        className=\"absolute inset-x-0 top-1/2 h-3 -translate-y-1/2 overflow-hidden rounded-full\"\n        style={checker ? CHECKER : undefined}\n      >\n        <motion.span\n          className={cn(\"absolute inset-0 rounded-full\", HAIRLINE)}\n          style={{ backgroundImage: track }}\n        />\n      </span>\n      <span\n        className=\"pointer-events-none absolute inset-y-0\"\n        style={{ left: THUMB_RADIUS, right: THUMB_RADIUS }}\n      >\n        <Thumb left={left} top=\"50%\" fill={thumb} checker={checker} />\n      </span>\n    </div>\n  );\n}\n\nfunction Thumb({\n  left,\n  top,\n  fill,\n  checker,\n}: {\n  left: MotionValue<string>;\n  top: MotionValue<string> | string;\n  fill: MotionValue<string>;\n  checker?: boolean;\n}) {\n  return (\n    <motion.span\n      // Raw black and white on purpose: the thumb sits on arbitrary colors,\n      // so it needs a ring that contrasts with all of them, not a theme.\n      // It grows a touch while held so you can tell you've got hold of it.\n      className=\"pointer-events-none absolute size-5 -translate-1/2 overflow-hidden rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.12),0_1px_3px_rgb(0_0_0/0.3)] transition-[scale] duration-150 ease-out group-active:scale-110 motion-reduce:transition-none\"\n      style={{ left, top, ...(checker ? CHECKER : {}) }}\n    >\n      <motion.span className=\"absolute inset-0\" style={{ backgroundColor: fill }} />\n    </motion.span>\n  );\n}\n\nexport default function ColorPickerDemo() {\n  return <ColorPicker />;\n}\n"},{"path":"hooks/use-reduced-motion.ts","type":"registry:hook","target":"hooks/use-reduced-motion.ts","content":"\"use client\";\n\nimport { useSyncExternalStore } from \"react\";\n\n// Motion's useReducedMotion reads the media query on the very first client\n// render, but the server can't know it, so every component that renders\n// differently under reduced motion broke hydration for those users. This\n// reports false during hydration, matching the server HTML, then the real\n// preference straight after, and follows it if it changes.\nconst query = \"(prefers-reduced-motion: reduce)\";\n\nfunction subscribe(onChange: () => void) {\n  const media = window.matchMedia(query);\n  media.addEventListener(\"change\", onChange);\n  return () => media.removeEventListener(\"change\", onChange);\n}\n\nexport function useReducedMotion() {\n  return useSyncExternalStore(\n    subscribe,\n    () => window.matchMedia(query).matches,\n    () => false,\n  );\n}\n"}],"cssVars":{"light":{"shadow-raised":"0 0 0 1px oklch(0 0 0 / 0.06), 0 1px 2px oklch(0 0 0 / 0.06), 0 6px 16px -6px oklch(0 0 0 / 0.12)"},"dark":{"shadow-raised":"0 0 0 1px oklch(1 0 0 / 0.08), 0 1px 2px oklch(0 0 0 / 0.4), 0 6px 16px -6px oklch(0 0 0 / 0.6)"},"theme":{"shadow-raised":"var(--shadow-raised)"}},"categories":["inputs"],"docs":"From ui lab: https://lab.xevrion.dev/lab/color-picker"}