{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-picker",
  "title": "Color Picker",
  "description": "Color field with saturation area, hue and opacity sliders, formats, eyedropper and saved swatches.",
  "dependencies": [
    "lucide-react",
    "motion",
    "radix-ui"
  ],
  "registryDependencies": [
    "@ikas/animated-check",
    "@ikas/badge",
    "@ikas/button",
    "@ikas/input-group",
    "@ikas/motion",
    "@ikas/theme",
    "@ikas/utils"
  ],
  "files": [
    {
      "path": "registry/ikas/color-picker.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { AnimatePresence, Reorder, animate, motion, useMotionValue, usePresence, useTransform } from \"motion/react\"\nimport { CheckIcon, PipetteIcon, PlusIcon } from \"lucide-react\"\nimport { Popover as PopoverPrimitive } from \"radix-ui\"\n\nimport { cn } from \"@/lib/utils\"\nimport { EASE_IN_OUT, EASE_OUT, FADE_OUT, INSTANT, SPRING, usePrefersReducedMotion } from \"@/lib/motion\"\nimport { Badge } from \"@/components/ui/badge\"\nimport { Button } from \"@/components/ui/button\"\nimport { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput } from \"@/components/ui/input-group\"\nimport { CopyIconButton } from \"@/components/ikas/animated-check\"\n\ntype ColorFormat = \"hex\" | \"rgb\" | \"hsl\" | \"oklch\"\n\ntype ColorPickerProps = {\n  /** Selected color. Reads hex, rgb(), hsl() and oklch(); leave undefined with defaultValue for an uncontrolled picker. */\n  value?: string\n  /** Initial color when uncontrolled. */\n  defaultValue?: string\n  /** Called with the color as #RRGGBB, or #RRGGBBAA when it is not opaque. */\n  onValueChange?: (hex: string) => void\n  /** Format the text field opens in; the format button cycles through the rest. */\n  defaultFormat?: ColorFormat\n  /** Shows the opacity slider. Without it every color stays opaque. */\n  alpha?: boolean\n  /** Background the color will sit on. Shows the WCAG contrast readout when set. */\n  contrastWith?: string\n  /** Saved colors, newest first. Leave undefined with defaultSwatches to let the picker keep them. */\n  swatches?: string[]\n  /** Initial saved colors when uncontrolled. */\n  defaultSwatches?: string[]\n  /** Called when a color is saved, removed or moved; once per drag, when the swatch is dropped. */\n  onSwatchesChange?: (swatches: string[]) => void\n  /** Most saved colors. Saving past it drops the oldest. */\n  maxSwatches?: number\n  /** Name of the color, for the panel heading and accessible names. */\n  label?: string\n  /** Blocks the trigger. */\n  disabled?: boolean\n  /** Id of the trigger, for a FieldLabel htmlFor. */\n  id?: string\n  /** Marks the trigger invalid, for form errors. */\n  \"aria-invalid\"?: boolean\n  /** Panel alignment against the trigger. */\n  align?: \"start\" | \"center\" | \"end\"\n  /** Classes for the trigger. */\n  className?: string\n}\n\n/* ---------- Color math: sRGB channels and alpha run 0 to 1, hue in degrees. ---------- */\n\ntype Hsv = { h: number; s: number; v: number; a: number }\ntype Rgb = { r: number; g: number; b: number; a: number }\n\nconst unit = (n: number) => Math.min(1, Math.max(0, n))\nconst fixed = (n: number, digits: number) => Number(n.toFixed(digits))\n\n/** Picks the RGB triple for a hue sector, given chroma and the second-largest component. */\nfunction sector(h: number, c: number, x: number): [number, number, number] {\n  const i = Math.floor((((h % 360) + 360) % 360) / 60)\n  return ([[c, x, 0], [x, c, 0], [0, c, x], [0, x, c], [x, 0, c], [c, 0, x]] as const)[i] as [number, number, number]\n}\n\nfunction fromHsv({ h, s, v, a }: Hsv): Rgb {\n  const c = v * s\n  const x = c * (1 - Math.abs(((h / 60) % 2) - 1))\n  const [r, g, b] = sector(h, c, x)\n  const m = v - c\n  return { r: r + m, g: g + m, b: b + m, a }\n}\n\n/** Hue of an RGB color, or `fallback` for greys, where hue is undefined. */\nfunction hueOf({ r, g, b }: Rgb, fallback: number) {\n  const max = Math.max(r, g, b)\n  const delta = max - Math.min(r, g, b)\n  if (delta < 1e-6) return fallback\n  const h = max === r ? ((g - b) / delta) % 6 : max === g ? (b - r) / delta + 2 : (r - g) / delta + 4\n  return (h * 60 + 360) % 360\n}\n\nfunction toHsv(rgb: Rgb, fallbackHue: number): Hsv {\n  const max = Math.max(rgb.r, rgb.g, rgb.b)\n  const delta = max - Math.min(rgb.r, rgb.g, rgb.b)\n  return { h: hueOf(rgb, fallbackHue), s: max === 0 ? 0 : delta / max, v: max, a: rgb.a }\n}\n\nfunction fromHsl(h: number, s: number, l: number, a: number): Rgb {\n  const c = (1 - Math.abs(2 * l - 1)) * s\n  const x = c * (1 - Math.abs(((h / 60) % 2) - 1))\n  const [r, g, b] = sector(h, c, x)\n  const m = l - c / 2\n  return { r: r + m, g: g + m, b: b + m, a }\n}\n\nfunction toHsl(rgb: Rgb, fallbackHue: number) {\n  const max = Math.max(rgb.r, rgb.g, rgb.b)\n  const min = Math.min(rgb.r, rgb.g, rgb.b)\n  const l = (max + min) / 2\n  const delta = max - min\n  return { h: hueOf(rgb, fallbackHue), s: delta < 1e-6 ? 0 : delta / (1 - Math.abs(2 * l - 1)), l }\n}\n\n/** sRGB transfer curve. */\nconst linear = (c: number) => (c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4)\nconst gamma = (c: number) => (c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055)\n\n/** OKLab matrices from Björn Ottosson's reference implementation. */\nfunction toOklch(rgb: Rgb, fallbackHue: number) {\n  const [r, g, b] = [linear(rgb.r), linear(rgb.g), linear(rgb.b)]\n  const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)\n  const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)\n  const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)\n  const L = 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s\n  const A = 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s\n  const B = 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s\n  const C = Math.hypot(A, B)\n  return { l: L, c: C, h: C < 0.0005 ? fallbackHue : ((Math.atan2(B, A) * 180) / Math.PI + 360) % 360 }\n}\n\nfunction fromOklch(L: number, C: number, H: number, alpha: number): Rgb {\n  const rad = (H * Math.PI) / 180\n  const A = C * Math.cos(rad)\n  const B = C * Math.sin(rad)\n  const l = (L + 0.3963377774 * A + 0.2158037573 * B) ** 3\n  const m = (L - 0.1055613458 * A - 0.0638541728 * B) ** 3\n  const s = (L - 0.0894841775 * A - 1.291485548 * B) ** 3\n  return {\n    r: unit(gamma(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s)),\n    g: unit(gamma(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s)),\n    b: unit(gamma(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s)),\n    a: alpha,\n  }\n}\n\nconst to255 = (c: number) => Math.round(unit(c) * 255)\nconst hexPair = (c: number) => to255(c).toString(16).padStart(2, \"0\").toUpperCase()\nconst opaque = (a: number) => a > 0.999\n\nfunction toHex(hsv: Hsv) {\n  const { r, g, b, a } = fromHsv(hsv)\n  return `#${hexPair(r)}${hexPair(g)}${hexPair(b)}${opaque(a) ? \"\" : hexPair(a)}`\n}\n\nfunction formatAs(hsv: Hsv, format: ColorFormat) {\n  if (format === \"hex\") return toHex(hsv)\n  const rgb = fromHsv(hsv)\n  const alpha = opaque(hsv.a) ? \"\" : ` / ${Math.round(hsv.a * 100)}%`\n  if (format === \"rgb\") return `rgb(${to255(rgb.r)} ${to255(rgb.g)} ${to255(rgb.b)}${alpha})`\n  if (format === \"hsl\") {\n    const { h, s, l } = toHsl(rgb, hsv.h)\n    return `hsl(${Math.round(h) % 360} ${Math.round(s * 100)}% ${Math.round(l * 100)}%${alpha})`\n  }\n  const { l, c, h } = toOklch(rgb, hsv.h)\n  return `oklch(${fixed(l * 100, 1)}% ${fixed(c, 3)} ${fixed(h, 1) % 360}${alpha})`\n}\n\n/** One CSS number: `50%` becomes `percentOf / 2`, a bare number stays as is. */\nfunction amount(token: string | undefined, percentOf: number) {\n  if (token === undefined) return NaN\n  const n = parseFloat(token)\n  return token.endsWith(\"%\") ? (n / 100) * percentOf : n\n}\n\n/** Reads #rgb, #rgba, #rrggbb, #rrggbbaa and rgb(), hsl(), oklch() in space or comma syntax. Null when unreadable. */\nfunction parse(input: string, fallbackHue = 0): Hsv | null {\n  const text = input.trim().toLowerCase()\n  const hex = /^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/.exec(text)?.[1]\n  if (hex) {\n    const full = hex.length <= 4 ? [...hex].map((d) => d + d).join(\"\") : hex\n    const pair = (i: number) => parseInt(full.slice(i * 2, i * 2 + 2), 16) / 255\n    return toHsv({ r: pair(0), g: pair(1), b: pair(2), a: full.length === 8 ? pair(3) : 1 }, fallbackHue)\n  }\n  const call = /^(rgba?|hsla?|oklch)\\((.+)\\)$/.exec(text)\n  if (!call) return null\n  const parts = call[2].replace(/deg/g, \"\").split(/[\\s,/]+/).filter(Boolean)\n  if (parts.length < 3 || parts.length > 4) return null\n  const alpha = parts[3] === undefined ? 1 : unit(amount(parts[3], 1))\n  let rgb: Rgb\n  let hue = fallbackHue\n  if (call[1].startsWith(\"rgb\")) {\n    rgb = { r: unit(amount(parts[0], 255) / 255), g: unit(amount(parts[1], 255) / 255), b: unit(amount(parts[2], 255) / 255), a: alpha }\n  } else if (call[1].startsWith(\"hsl\")) {\n    hue = ((parseFloat(parts[0]) % 360) + 360) % 360\n    const pct = (t: string) => unit(parseFloat(t) / 100)\n    rgb = fromHsl(hue, pct(parts[1]), pct(parts[2]), alpha)\n  } else {\n    const L = parts[0].endsWith(\"%\") ? parseFloat(parts[0]) / 100 : parseFloat(parts[0])\n    // CSS Color 4: 100% chroma is 0.4.\n    rgb = fromOklch(unit(L), amount(parts[1], 0.4), parseFloat(parts[2]), alpha)\n  }\n  if ([rgb.r, rgb.g, rgb.b, rgb.a].some(Number.isNaN)) return null\n  const hsv = toHsv(rgb, hue)\n  return call[1].startsWith(\"hsl\") ? { ...hsv, h: hue } : hsv\n}\n\n/** WCAG 2 contrast of the color, laid over the background, against that background. */\nfunction contrastRatio(color: Hsv, background: Hsv) {\n  const fg = fromHsv(color)\n  const bg = fromHsv({ ...background, a: 1 })\n  const over = (c: number, base: number) => c * fg.a + base * (1 - fg.a)\n  const luminance = (r: number, g: number, b: number) => 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)\n  const top = luminance(over(fg.r, bg.r), over(fg.g, bg.g), over(fg.b, bg.b))\n  const base = luminance(bg.r, bg.g, bg.b)\n  return (Math.max(top, base) + 0.05) / (Math.min(top, base) + 0.05)\n}\n\nfunction grade(ratio: number) {\n  if (ratio >= 7) return { label: \"AAA\", status: \"success\", spoken: \"AAA seviyesini geçiyor\" } as const\n  if (ratio >= 4.5) return { label: \"AA\", status: \"success\", spoken: \"AA seviyesini geçiyor\" } as const\n  if (ratio >= 3) return { label: \"AA büyük\", status: \"warning\", spoken: \"yalnızca büyük metin için AA\" } as const\n  return { label: \"Yetersiz\", status: \"danger\", spoken: \"kontrast yetersiz\" } as const\n}\n\n/* ---------- Interaction helpers ---------- */\n\nconst FORMATS: ColorFormat[] = [\"hex\", \"rgb\", \"hsl\", \"oklch\"]\nconst FORMAT_NAMES: Record<ColorFormat, string> = { hex: \"HEX\", rgb: \"RGB\", hsl: \"HSL\", oklch: \"OKLCH\" }\nconst FALLBACK: Hsv = { h: 220, s: 0.8, v: 0.95, a: 1 }\n/** Thumb radius in px. Track gradients start and end this far in, so the color under a thumb is the value it reports. */\nconst THUMB = 8\nconst CHECKER = \"repeating-conic-gradient(var(--muted) 0 25%, var(--card) 0 50%) 0 0 / 8px 8px\"\ntype EyeDropperApi = new () => { open: () => Promise<{ sRGBHex: string }> }\nconst noSubscribe = () => () => {}\n/** True where the browser can pick a color from the screen. False during SSR and the first render. */\nfunction useEyeDropper() {\n  return React.useSyncExternalStore(noSubscribe, () => \"EyeDropper\" in window, () => false)\n}\n\n/**\n * Pointer tracking over a box. `pressed` is true while the button is down and\n * `dragging` once the pointer has moved: a click glides the thumb on the spring,\n * a drag keeps it under the pointer.\n */\nfunction usePointerBox(box: React.RefObject<HTMLElement | null>, onPoint: (x: number, y: number) => void) {\n  const [pressed, setPressed] = React.useState(false)\n  const [dragging, setDragging] = React.useState(false)\n  const pointer = React.useRef<number | null>(null)\n\n  function read(event: React.PointerEvent) {\n    const rect = (box.current ?? (event.currentTarget as HTMLElement)).getBoundingClientRect()\n    onPoint(unit((event.clientX - rect.left) / rect.width), unit((event.clientY - rect.top) / rect.height))\n  }\n  function release(event: React.PointerEvent) {\n    if (event.pointerId !== pointer.current) return\n    pointer.current = null\n    setPressed(false)\n    setDragging(false)\n  }\n\n  return {\n    pressed,\n    dragging,\n    handlers: {\n      onPointerDown(event: React.PointerEvent<HTMLElement>) {\n        if (event.button !== 0 || pointer.current !== null) return\n        pointer.current = event.pointerId\n        try {\n          event.currentTarget.setPointerCapture(event.pointerId)\n        } catch {}\n        setPressed(true)\n        read(event)\n      },\n      onPointerMove(event: React.PointerEvent<HTMLElement>) {\n        if (event.pointerId !== pointer.current) return\n        setDragging(true)\n        read(event)\n      },\n      onPointerUp: release,\n      onPointerCancel: release,\n    },\n  }\n}\n\n/** A motion value that glides to `target` on SPRING, or jumps while glued to the pointer or under reduced motion. */\nfunction useGlide(target: number, glued: boolean, reduce: boolean) {\n  const value = useMotionValue(target)\n  React.useEffect(() => {\n    if (glued || reduce) {\n      value.jump(target)\n      return\n    }\n    const controls = animate(value, target, SPRING)\n    return () => controls.stop()\n  }, [glued, reduce, target, value])\n  return value\n}\n\nconst percent = (n: number) => `${n * 100}%`\n\n/** Arrow keys step 1, Shift or Page keys step 10. Returns [dx, dy] with up as +y, or null for other keys. */\nfunction arrowStep(event: React.KeyboardEvent): [number, number] | null {\n  const n = event.shiftKey || event.key.startsWith(\"Page\") ? 10 : 1\n  switch (event.key) {\n    case \"ArrowRight\":\n      return [n, 0]\n    case \"ArrowLeft\":\n      return [-n, 0]\n    case \"ArrowUp\":\n    case \"PageUp\":\n      return [0, n]\n    case \"ArrowDown\":\n    case \"PageDown\":\n      return [0, -n]\n  }\n  return null\n}\n\n/** A rounded chip over a checkerboard, so opacity reads as opacity. */\nfunction Chip({ color, className }: { color: string; className?: string }) {\n  return (\n    <span aria-hidden=\"true\" className={cn(\"relative block shrink-0 overflow-hidden\", className)} style={{ background: CHECKER }}>\n      <span className=\"absolute inset-0 rounded-[inherit] shadow-[inset_0_0_0_1px_var(--shade-border)]\" style={{ background: color }} />\n    </span>\n  )\n}\n\n/** Text that slides up when it changes, the way AnimatedNumber rolls. */\nfunction Slide({ children, reduce, className }: { children: string; reduce: boolean; className?: string }) {\n  return (\n    <span className={cn(\"relative inline-flex overflow-hidden\", className)}>\n      <AnimatePresence mode=\"popLayout\" initial={false}>\n        <motion.span\n          key={children}\n          initial={reduce ? { opacity: 0 } : { y: 10, opacity: 0 }}\n          animate={{ y: 0, opacity: 1 }}\n          exit={reduce ? { opacity: 0, transition: INSTANT } : { y: -10, opacity: 0, transition: FADE_OUT }}\n          transition={reduce ? INSTANT : SPRING}\n          className=\"inline-block whitespace-nowrap\"\n        >\n          {children}\n        </motion.span>\n      </AnimatePresence>\n    </span>\n  )\n}\n\ntype TrackProps = {\n  label: string\n  value: number\n  max: number\n  valueText: string\n  background: string\n  thumbColor: string\n  reduce: boolean\n  onChange: (value: number) => void\n}\n\n/** Horizontal slider for hue and opacity. */\nfunction Track({ label, value, max, valueText, background, thumbColor, reduce, onChange }: TrackProps) {\n  const rail = React.useRef<HTMLDivElement>(null)\n  const { pressed, dragging, handlers } = usePointerBox(rail, (x) => onChange(x * max))\n  const x = useGlide(value / max, dragging, reduce)\n  const left = useTransform(x, percent)\n\n  return (\n    <div\n      data-slot=\"color-picker-track\"\n      className=\"relative h-3 cursor-pointer touch-none rounded-full shadow-[inset_0_0_0_1px_var(--shade-border)]\"\n      style={{ background }}\n      {...handlers}\n    >\n      <div ref={rail} className=\"absolute inset-y-0\" style={{ insetInline: THUMB }}>\n        <motion.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={valueText}\n          animate={{ scale: pressed ? 1.15 : 1 }}\n          transition={reduce ? INSTANT : SPRING}\n          className=\"absolute top-1/2 size-4 -translate-1/2 cursor-grab rounded-full shadow-thumb ring-2 ring-white outline-none focus-visible:outline-3 focus-visible:outline-offset-1 focus-visible:outline-ring/50 active:cursor-grabbing\"\n          style={{ left, background: `linear-gradient(${thumbColor}, ${thumbColor}), ${CHECKER}` }}\n          onKeyDown={(event) => {\n            if (event.key === \"Home\" || event.key === \"End\") {\n              event.preventDefault()\n              onChange(event.key === \"Home\" ? 0 : max)\n              return\n            }\n            const step = arrowStep(event)\n            if (!step) return\n            event.preventDefault()\n            onChange(Math.min(max, Math.max(0, value + (step[0] || step[1]))))\n          }}\n        />\n      </div>\n    </div>\n  )\n}\n\ntype GrowPanelProps = React.ComponentProps<\"div\"> & {\n  /** Box and corner radius of the trigger the panel grows out of. */\n  from: { width: number; height: number; radius: number }\n  reduce: boolean\n  /** Called once the fold back into the trigger has finished, right before unmount. */\n  onFolded: () => void\n}\n\n/**\n * The panel opens over its trigger and grows out of the trigger's box on SPRING,\n * from whichever corner it is anchored to; on close it folds back on EASE_OUT and\n * only then unmounts. At rest size it is an exact copy of the trigger (box and\n * corner radius), so the two hand off without a seam. Its drop shadow follows the\n * clipped shape.\n */\nfunction GrowPanel({ from, reduce, onFolded, children, className, style, ref, ...props }: GrowPanelProps) {\n  const [isPresent, safeToRemove] = usePresence()\n  const node = React.useRef<HTMLDivElement | null>(null)\n  const box = React.useRef({ width: from.width, height: from.height })\n  const progress = useMotionValue(reduce ? 1 : 0)\n\n  React.useLayoutEffect(() => {\n    const el = node.current\n    if (!el) return\n    const measure = () => (box.current = { width: el.offsetWidth, height: el.offsetHeight })\n    measure()\n    const observer = new ResizeObserver(measure)\n    observer.observe(el)\n    return () => observer.disconnect()\n  }, [])\n\n  React.useEffect(() => {\n    if (isPresent) {\n      if (reduce) return progress.jump(1)\n      const controls = animate(progress, 1, SPRING)\n      return () => controls.stop()\n    }\n    const done = () => {\n      onFolded()\n      safeToRemove()\n    }\n    if (reduce) return done()\n    const controls = animate(progress, 0, { duration: 0.18, ease: EASE_OUT })\n    controls.then(done)\n    return () => controls.stop()\n  }, [isPresent, onFolded, progress, reduce, safeToRemove])\n\n  const clipPath = useTransform(() => {\n    const q = progress.get()\n    const dx = Math.max(0, box.current.width - from.width) * (1 - q)\n    const dy = Math.max(0, box.current.height - from.height) * (1 - q)\n    // Radix writes the side and alignment it settled on, so the fold always starts at the trigger's corner.\n    const top = node.current?.dataset.side === \"top\"\n    const end = node.current?.dataset.align === \"end\"\n    // Corners grow with the box, from the trigger's rounded-lg to the panel's rounded-xl (1.4×, as in the theme).\n    return `inset(${top ? dy : 0}px ${end ? 0 : dx}px ${top ? 0 : dy}px ${end ? dx : 0}px round ${from.radius * (1 + 0.4 * q)}px)`\n  })\n\n  return (\n    <motion.div\n      ref={(el: HTMLDivElement | null) => {\n        node.current = el\n        if (typeof ref === \"function\") ref(el)\n        else if (ref) ref.current = el\n      }}\n      data-closing={!isPresent || undefined}\n      className=\"z-50 outline-hidden data-closing:pointer-events-none\"\n      style={{ ...style, width: Math.max(288, from.width), filter: \"drop-shadow(0 12px 24px var(--shade-3)) drop-shadow(0 2px 6px var(--shade-2))\" }}\n      {...(props as React.ComponentProps<typeof motion.div>)}\n    >\n      <motion.div\n        className={cn(\"rounded-xl bg-popover text-sm text-popover-foreground shadow-[inset_0_0_0_1px_var(--shade-border)]\", className)}\n        style={{ clipPath }}\n      >\n        {children}\n      </motion.div>\n    </motion.div>\n  )\n}\n\n/* ---------- ColorPicker ---------- */\n\n/** A color field that opens a picker: saturation and brightness area, hue and opacity, four text formats, eyedropper, contrast and saved colors. */\nfunction ColorPicker({\n  value,\n  defaultValue = \"#3B6FE0\",\n  onValueChange,\n  defaultFormat = \"hex\",\n  alpha = true,\n  contrastWith,\n  swatches: swatchesProp,\n  defaultSwatches = [],\n  onSwatchesChange,\n  maxSwatches = 7,\n  label = \"Renk\",\n  disabled = false,\n  id,\n  \"aria-invalid\": ariaInvalid,\n  align = \"start\",\n  className,\n}: ColorPickerProps) {\n  const uid = React.useId()\n  const reduce = usePrefersReducedMotion()\n  const canPick = useEyeDropper()\n\n  const [hsv, setHsv] = React.useState<Hsv>(() => parse(value ?? defaultValue) ?? FALLBACK)\n  // A controlled value is the truth: follow it whenever the shown color differs, which also undoes a change\n  // the parent didn't take. Hue (and saturation on black) stay local, since a grey hex can't carry them.\n  if (value !== undefined) {\n    const next = parse(value, hsv.h)\n    if (next && toHex(next) !== toHex(hsv)) setHsv(next)\n  }\n  const [ownSwatches, setOwnSwatches] = React.useState(defaultSwatches)\n  const savedSwatches = swatchesProp ?? ownSwatches\n  // The order while a swatch is dragged; saved once when it is dropped.\n  const [swatchOrder, setSwatchOrder] = React.useState<string[] | null>(null)\n  const swatches = swatchOrder ?? savedSwatches\n\n  const [open, setOpen] = React.useState(false)\n  const [triggerBox, setTriggerBox] = React.useState({ width: 192, height: 36, radius: 10 })\n  // True from the moment the panel opens over the trigger until it has folded back into it; the trigger hides meanwhile.\n  const [covered, setCovered] = React.useState(false)\n  const onFolded = React.useCallback(() => setCovered(false), [])\n  const triggerRef = React.useRef<HTMLButtonElement>(null)\n  const [format, setFormat] = React.useState(defaultFormat)\n  const [draft, setDraft] = React.useState<string | null>(null)\n  const [invalid, setInvalid] = React.useState(false)\n  const [rovingSwatch, setRovingSwatch] = React.useState<string | null>(null)\n\n  const areaRef = React.useRef<HTMLDivElement>(null)\n  const areaThumb = React.useRef<HTMLDivElement>(null)\n  const addRef = React.useRef<HTMLButtonElement>(null)\n  const swatchRefs = React.useRef(new Map<string, HTMLButtonElement>())\n  const draggedSwatch = React.useRef(false)\n  const shake = useMotionValue(0)\n  // Each focus of the text field sends one highlight around its border.\n  const [lap, setLap] = React.useState(0)\n\n  const hex = toHex(hsv)\n  const rgb = fromHsv(hsv)\n  const solid = `rgb(${to255(rgb.r)} ${to255(rgb.g)} ${to255(rgb.b)})`\n  const css = `rgb(${to255(rgb.r)} ${to255(rgb.g)} ${to255(rgb.b)} / ${fixed(hsv.a, 3)})`\n  const pureHue = `hsl(${fixed(hsv.h, 1)} 100% 50%)`\n  const text = formatAs(hsv, format)\n  const backdrop = contrastWith ? parse(contrastWith) : null\n  const ratio = backdrop ? contrastRatio(hsv, backdrop) : 0\n  const level = grade(ratio)\n\n  function commit(next: Hsv) {\n    const color = alpha ? next : { ...next, a: 1 }\n    setHsv(color)\n    if (toHex(color) !== hex) onValueChange?.(toHex(color))\n  }\n  function setSwatches(next: string[]) {\n    if (swatchesProp === undefined) setOwnSwatches(next)\n    onSwatchesChange?.(next)\n  }\n  function dropSwatch() {\n    if (!swatchOrder) return\n    setSwatchOrder(null)\n    const next = swatchOrder.filter((c) => savedSwatches.includes(c))\n    if (next.length === savedSwatches.length && next.some((c, i) => c !== savedSwatches[i])) setSwatches(next)\n  }\n\n  const area = usePointerBox(areaRef, (x, y) => commit({ ...hsv, s: x, v: 1 - y }))\n  const areaX = useGlide(hsv.s, area.dragging, reduce)\n  const areaY = useGlide(1 - hsv.v, area.dragging, reduce)\n  const areaLeft = useTransform(areaX, percent)\n  const areaTop = useTransform(areaY, percent)\n\n  function cycleFormat() {\n    setFormat(FORMATS[(FORMATS.indexOf(format) + 1) % FORMATS.length])\n    setDraft(null)\n    setInvalid(false)\n  }\n\n  /** Applies the typed text. False when it cannot be read. */\n  function applyDraft() {\n    if (draft === null) return true\n    const next = parse(draft, hsv.h)\n    if (!next) {\n      setInvalid(true)\n      if (!reduce) animate(shake, [0, -6, 5, -3, 0], { duration: 0.3, ease: EASE_OUT })\n      return false\n    }\n    commit(next)\n    setDraft(null)\n    setInvalid(false)\n    return true\n  }\n\n  function pickFromScreen() {\n    const Api = (window as unknown as { EyeDropper?: EyeDropperApi }).EyeDropper\n    if (!Api) return\n    new Api()\n      .open()\n      .then(({ sRGBHex }) => {\n        const next = parse(sRGBHex, hsv.h)\n        if (next) commit({ ...next, a: hsv.a })\n      })\n      .catch(() => {})\n  }\n\n  function saveColor() {\n    // Saving a color already in the list moves it to the front instead of adding a copy.\n    setSwatches([hex, ...swatches.filter((c) => c !== hex)].slice(0, maxSwatches))\n    setRovingSwatch(hex)\n  }\n\n  function focusSwatch(color: string | undefined) {\n    requestAnimationFrame(() => (color ? swatchRefs.current.get(color)?.focus({ preventScroll: true }) : addRef.current?.focus({ preventScroll: true })))\n  }\n\n  function onSwatchKey(event: React.KeyboardEvent<HTMLButtonElement>, index: number) {\n    const color = swatches[index]\n    if (event.key === \"Delete\" || event.key === \"Backspace\") {\n      event.preventDefault()\n      const next = swatches.filter((c) => c !== color)\n      const neighbor = next[Math.min(index, next.length - 1)]\n      setSwatches(next)\n      setRovingSwatch(neighbor ?? null)\n      focusSwatch(neighbor)\n      return\n    }\n    const dir = event.key === \"ArrowRight\" ? 1 : event.key === \"ArrowLeft\" ? -1 : 0\n    if (dir && event.altKey) {\n      event.preventDefault()\n      const to = index + dir\n      if (to < 0 || to >= swatches.length) return\n      const next = [...swatches]\n      next.splice(index, 1)\n      next.splice(to, 0, color)\n      setSwatches(next)\n      focusSwatch(color)\n      return\n    }\n    if (!dir && event.key !== \"Home\" && event.key !== \"End\") return\n    event.preventDefault()\n    const target = event.key === \"Home\" ? 0 : event.key === \"End\" ? swatches.length - 1 : (index + dir + swatches.length) % swatches.length\n    setRovingSwatch(swatches[target])\n    swatchRefs.current.get(swatches[target])?.focus({ preventScroll: true })\n  }\n\n  const tabSwatch = rovingSwatch && swatches.includes(rovingSwatch) ? rovingSwatch : swatches[0]\n  const hueTrack = `linear-gradient(to right, ${[0, 60, 120, 180, 240, 300, 360].map((h) => `hsl(${h} 100% 50%) calc(${THUMB}px + (100% - ${THUMB * 2}px) * ${h / 360})`).join(\", \")})`\n  const alphaTrack = `linear-gradient(to right, transparent ${THUMB}px, ${solid} calc(100% - ${THUMB}px)), ${CHECKER}`\n\n  const header = (\n    <div className=\"flex h-9 items-center gap-2 pr-1.5 pl-3.5\">\n      <Chip color={css} className=\"size-5 rounded-md\" />\n      <span className=\"min-w-0 truncate font-mono text-[13px] tabular-nums\">{hex}</span>\n      <CopyIconButton value={hex} label=\"Hex kodunu kopyala\" size=\"icon-xs\" className=\"mr-auto\" />\n      {canPick && (\n        <Button variant=\"ghost\" size=\"icon-xs\" aria-label=\"Ekrandan renk seç\" onClick={pickFromScreen}>\n          <PipetteIcon data-anim=\"pop\" />\n        </Button>\n      )}\n      <PopoverPrimitive.Close asChild>\n        <Button variant=\"ghost\" size=\"icon-xs\" aria-label=\"Bitti\">\n          <CheckIcon data-anim=\"pop\" />\n        </Button>\n      </PopoverPrimitive.Close>\n    </div>\n  )\n  // Body sections enter one after another on the theme's panel-enter (--stagger), right behind the growing edge.\n\n  return (\n    <PopoverPrimitive.Root\n      open={open}\n      onOpenChange={(next) => {\n        const el = triggerRef.current\n        if (next && el) {\n          setTriggerBox({ width: el.offsetWidth, height: el.offsetHeight, radius: parseFloat(getComputedStyle(el).borderTopLeftRadius) || 0 })\n          setCovered(true)\n        }\n        setOpen(next)\n        if (!next) {\n          setDraft(null)\n          setInvalid(false)\n        }\n      }}\n    >\n      <PopoverPrimitive.Trigger asChild>\n        <Button\n          ref={triggerRef}\n          id={id}\n          variant=\"outline\"\n          disabled={disabled}\n          aria-invalid={ariaInvalid}\n          data-slot=\"color-picker-trigger\"\n          data-covered={covered || undefined}\n          className={cn(\"w-full justify-start font-normal aria-invalid:ring-3 aria-invalid:ring-destructive/20 data-covered:opacity-0 sm:w-48\", className)}\n        >\n          <Chip color={css} className=\"size-5 rounded-md\" />\n          <span className=\"truncate font-mono text-[13px] tabular-nums\">{hex}</span>\n        </Button>\n      </PopoverPrimitive.Trigger>\n      <AnimatePresence>\n        {open && (\n          <PopoverPrimitive.Portal key=\"panel\" forceMount>\n            <PopoverPrimitive.Content\n              forceMount\n              asChild\n              side=\"bottom\"\n              align={align}\n              sideOffset={-triggerBox.height}\n              collisionPadding={8}\n              aria-label={label}\n              onOpenAutoFocus={(event) => {\n                event.preventDefault()\n                areaThumb.current?.focus({ preventScroll: true })\n              }}\n              onEscapeKeyDown={(event) => {\n                // Escape first drops a typed draft; the next one closes the panel.\n                if (draft === null) return\n                event.preventDefault()\n                setDraft(null)\n                setInvalid(false)\n              }}\n            >\n              <GrowPanel data-slot=\"color-picker\" from={triggerBox} reduce={reduce} onFolded={onFolded}>\n                {header}\n                <div className=\"grid gap-3 px-3 pt-1 pb-3\">\n                <div\n                  ref={areaRef}\n                  data-slot=\"color-picker-area\"\n                  className=\"relative h-36 animate-panel-enter cursor-crosshair touch-none rounded-lg shadow-[inset_0_0_0_1px_var(--shade-border)] [--stagger:0.6]\"\n                  style={{ background: `linear-gradient(to top, black, transparent), linear-gradient(to right, white, transparent), ${pureHue}` }}\n                  {...area.handlers}\n                >\n                  <motion.div\n                    ref={areaThumb}\n                    role=\"slider\"\n                    tabIndex={0}\n                    aria-roledescription=\"2 boyutlu kaydırıcı\"\n                    aria-label=\"Doygunluk ve parlaklık\"\n                    aria-valuemin={0}\n                    aria-valuemax={100}\n                    aria-valuenow={Math.round(hsv.s * 100)}\n                    aria-valuetext={`Doygunluk %${Math.round(hsv.s * 100)}, parlaklık %${Math.round(hsv.v * 100)}`}\n                    animate={{ scale: area.pressed ? 1.15 : 1 }}\n                    transition={reduce ? INSTANT : SPRING}\n                    className=\"absolute size-4 -translate-1/2 cursor-grab rounded-full shadow-thumb ring-2 ring-white outline-none focus-visible:outline-3 focus-visible:outline-offset-1 focus-visible:outline-ring/50 active:cursor-grabbing\"\n                    style={{ left: areaLeft, top: areaTop, background: solid }}\n                    onKeyDown={(event) => {\n                      const step = arrowStep(event)\n                      if (!step) return\n                      event.preventDefault()\n                      commit({ ...hsv, s: unit(hsv.s + step[0] / 100), v: unit(hsv.v + step[1] / 100) })\n                    }}\n                  />\n                </div>\n\n                <div className=\"grid animate-panel-enter gap-2.5 [--stagger:1.2]\">\n                  <Track\n                    label=\"Ton\"\n                    value={hsv.h}\n                    max={360}\n                    valueText={`${Math.round(hsv.h)} derece`}\n                    background={hueTrack}\n                    thumbColor={pureHue}\n                    reduce={reduce}\n                    onChange={(h) => commit({ ...hsv, h: Math.min(h, 359.9) })}\n                  />\n                  {alpha && (\n                    <Track\n                      label=\"Opaklık\"\n                      value={hsv.a * 100}\n                      max={100}\n                      valueText={`%${Math.round(hsv.a * 100)}`}\n                      background={alphaTrack}\n                      thumbColor={css}\n                      reduce={reduce}\n                      onChange={(a) => commit({ ...hsv, a: unit(a / 100) })}\n                    />\n                  )}\n                </div>\n\n                <div className=\"grid animate-panel-enter gap-1 [--stagger:1.8]\">\n                  <motion.div\n                    style={{\n                      x: shake,\n                      // The field wears the picked color; a little foreground keeps near-white colors visible on the panel.\n                      \"--field-edge\": `color-mix(in oklab, ${solid} 82%, var(--foreground))`,\n                      \"--field-ring\": `color-mix(in oklab, ${solid} 24%, transparent)`,\n                    } as React.ComponentProps<typeof motion.div>[\"style\"]}\n                    className=\"relative\"\n                  >\n                    <InputGroup className=\"border-(--field-edge) transition-[border-color,box-shadow] duration-200 ease-out hover:border-(--field-edge) has-[[data-slot=input-group-control]:focus-visible]:border-(--field-edge) has-[[data-slot=input-group-control]:focus-visible]:ring-(--field-ring)\">\n                      <InputGroupAddon className=\"ml-0 self-stretch border-r border-(--field-edge) py-0 pl-0 has-[>button]:ml-0\">\n                        <InputGroupButton\n                          onClick={cycleFormat}\n                          aria-label={`Biçim: ${FORMAT_NAMES[format]}. Değiştir`}\n                          className=\"h-full w-16 justify-center rounded-none rounded-l-[calc(var(--radius-lg)-1px)] font-mono text-[11px] text-foreground\"\n                        >\n                          <Slide reduce={reduce}>{FORMAT_NAMES[format]}</Slide>\n                        </InputGroupButton>\n                      </InputGroupAddon>\n                      <div className=\"relative flex h-full min-w-0 flex-1 overflow-hidden\">\n                        <AnimatePresence mode=\"popLayout\" initial={false}>\n                          <motion.div\n                            key={format}\n                            initial={reduce ? { opacity: 0 } : { y: 12, opacity: 0 }}\n                            animate={{ y: 0, opacity: 1 }}\n                            exit={reduce ? { opacity: 0, transition: INSTANT } : { y: -12, opacity: 0, transition: FADE_OUT }}\n                            // A beat behind the format label, so the two read as one motion.\n                            transition={reduce ? INSTANT : { ...SPRING, delay: 0.04 }}\n                            className=\"flex min-w-0 flex-1\"\n                          >\n                            <InputGroupInput\n                              value={draft ?? text}\n                              spellCheck={false}\n                              autoComplete=\"off\"\n                              aria-label={`${label}, ${FORMAT_NAMES[format]}`}\n                              aria-invalid={invalid || undefined}\n                              aria-describedby={invalid ? `${uid}-error` : undefined}\n                              className=\"h-full pl-2.5 font-mono text-[13px] tabular-nums md:text-[13px]\"\n                              onChange={(event) => {\n                                setDraft(event.target.value)\n                                setInvalid(false)\n                              }}\n                              onKeyDown={(event) => {\n                                if (event.key !== \"Enter\") return\n                                event.preventDefault()\n                                if (applyDraft()) event.currentTarget.select()\n                              }}\n                              onFocus={() => {\n                                if (!reduce) setLap((n) => n + 1)\n                              }}\n                              onBlur={() => {\n                                if (!applyDraft()) {\n                                  setDraft(null)\n                                  setInvalid(false)\n                                }\n                              }}\n                            />\n                          </motion.div>\n                        </AnimatePresence>\n                      </div>\n                      </InputGroup>\n                      {/* One lap of light around the border: a conic wedge spins inside a 2.5px ring mask laid over the border, then fades as it comes home. */}\n                      <span\n                        aria-hidden=\"true\"\n                        className=\"pointer-events-none absolute -inset-px overflow-hidden rounded-[calc(var(--radius-lg)+1px)] p-[2.5px]\"\n                        style={{ mask: \"linear-gradient(black 0 0) content-box exclude, linear-gradient(black 0 0)\", WebkitMask: \"linear-gradient(black 0 0) content-box xor, linear-gradient(black 0 0)\" }}\n                      >\n                        <AnimatePresence>\n                          {lap > 0 && (\n                            <motion.span\n                              key={lap}\n                              className=\"absolute top-1/2 left-1/2 aspect-square w-[150%] -translate-1/2\"\n                              style={{ background: `conic-gradient(from 200deg, transparent 0 50%, ${solid} 72%, color-mix(in oklab, ${solid}, white 65%) 86%, transparent 95%)` }}\n                              initial={{ rotate: 0, opacity: 1 }}\n                              animate={{ rotate: 360, opacity: [1, 1, 0] }}\n                              // On-screen travel takes ease-in-out, so the light moves evenly around the field instead of zipping and stalling.\n                            transition={{ duration: 0.75, ease: EASE_IN_OUT, opacity: { duration: 0.75, times: [0, 0.7, 1] } }}\n                              onAnimationComplete={() => setLap(0)}\n                            />\n                          )}\n                        </AnimatePresence>\n                      </span>\n                    </motion.div>\n                  <p id={`${uid}-error`} aria-live=\"polite\" className=\"text-xs text-destructive empty:hidden\">\n                    {invalid ? \"HEX, RGB, HSL veya OKLCH bir renk girin.\" : \"\"}\n                  </p>\n                </div>\n\n                {backdrop && (\n                  <div data-slot=\"color-picker-contrast\" className=\"flex animate-panel-enter items-center gap-2.5 [--stagger:2.4]\">\n                    <span\n                      aria-hidden=\"true\"\n                      className=\"grid h-7 w-9 shrink-0 place-items-center rounded-md text-sm font-semibold shadow-[inset_0_0_0_1px_var(--shade-border)]\"\n                      style={{ background: contrastWith, color: css }}\n                    >\n                      Aa\n                    </span>\n                    <span className=\"text-sm font-medium tabular-nums\">{ratio.toFixed(2)}:1</span>\n                    <span className=\"min-w-0 flex-1 truncate text-xs text-muted-foreground\">arka plana karşı</span>\n                    <AnimatePresence mode=\"popLayout\" initial={false}>\n                      <motion.span\n                        key={level.label}\n                        initial={reduce ? { opacity: 0 } : { opacity: 0, y: 4, filter: \"blur(2px)\" }}\n                        animate={{ opacity: 1, y: 0, filter: \"blur(0px)\" }}\n                        exit={{ opacity: 0, transition: INSTANT }}\n                        transition={reduce ? INSTANT : SPRING}\n                      >\n                        <Badge status={level.status}>{level.label}</Badge>\n                      </motion.span>\n                    </AnimatePresence>\n                    <span className=\"sr-only\">{`Kontrast ${ratio.toFixed(2)}'e 1, ${level.spoken}`}</span>\n                  </div>\n                )}\n\n                <div data-slot=\"color-picker-swatches\" className=\"flex animate-panel-enter items-center gap-1.5 [--stagger:3]\">\n                  <Button ref={addRef} variant=\"ghost\" size=\"icon-xs\" aria-label={`${hex} rengini kaydet`} onClick={saveColor}>\n                    <PlusIcon data-anim=\"spin\" />\n                  </Button>\n                  <Reorder.Group\n                    as=\"div\"\n                    axis=\"x\"\n                    values={swatches}\n                    onReorder={setSwatchOrder}\n                    role=\"listbox\"\n                    aria-label=\"Kaydedilen renkler\"\n                    aria-orientation=\"horizontal\"\n                    className={cn(\"flex min-w-0 gap-1.5\", swatches.length > 0 && \"flex-1\")}\n                  >\n                    <AnimatePresence initial={false}>\n                      {swatches.map((color, index) => (\n                        <Reorder.Item\n                          key={color}\n                          value={color}\n                          as=\"button\"\n                          ref={(node: HTMLButtonElement | null) => {\n                            if (node) swatchRefs.current.set(color, node)\n                            else swatchRefs.current.delete(color)\n                          }}\n                          type=\"button\"\n                          role=\"option\"\n                          aria-selected={color === hex}\n                          aria-label={`${color}. Taşımak için Alt ve ok tuşları, silmek için Delete`}\n                          tabIndex={color === tabSwatch ? 0 : -1}\n                          data-current={color === hex || undefined}\n                          initial={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.6, x: -14 }}\n                          animate={{ opacity: 1, scale: 1, x: 0 }}\n                          exit={reduce ? { opacity: 0, transition: INSTANT } : { opacity: 0, scale: 0.6, transition: FADE_OUT }}\n                          transition={reduce ? INSTANT : SPRING}\n                          whileDrag={reduce ? undefined : { scale: 1.12, zIndex: 1 }}\n                          whileTap={reduce ? undefined : { scale: 0.9 }}\n                          dragElastic={0.1}\n                          className=\"relative size-6 shrink-0 cursor-pointer touch-pan-y rounded-md outline-none focus-visible:ring-3 focus-visible:ring-ring/30 data-current:ring-2 data-current:ring-ring data-current:ring-offset-2 data-current:ring-offset-popover\"\n                          onFocus={() => setRovingSwatch(color)}\n                          onKeyDown={(event: React.KeyboardEvent<HTMLButtonElement>) => onSwatchKey(event, index)}\n                          onDragStart={() => {\n                            draggedSwatch.current = true\n                          }}\n                          onDragEnd={() => {\n                            dropSwatch()\n                            requestAnimationFrame(() => (draggedSwatch.current = false))\n                          }}\n                          onClick={() => {\n                            if (draggedSwatch.current) return\n                            const next = parse(color, hsv.h)\n                            if (next) commit(next)\n                          }}\n                        >\n                          <Chip color={color} className=\"size-full rounded-md\" />\n                        </Reorder.Item>\n                      ))}\n                    </AnimatePresence>\n                  </Reorder.Group>\n                  {swatches.length === 0 && <span className=\"text-xs text-muted-foreground\">Kayıtlı renk yok</span>}\n                </div>\n                </div>\n              </GrowPanel>\n            </PopoverPrimitive.Content>\n          </PopoverPrimitive.Portal>\n        )}\n      </AnimatePresence>\n    </PopoverPrimitive.Root>\n  )\n}\n\nexport { ColorPicker, type ColorPickerProps, type ColorFormat }\n",
      "type": "registry:component",
      "target": "@components/ikas/color-picker.tsx"
    }
  ],
  "docs": "https://builders.ikas.com/tr/docs/app-development/ui-kit/components/color-picker",
  "categories": [
    "forms"
  ],
  "type": "registry:component"
}