{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-picker",
  "type": "registry:ui",
  "title": "Color Picker",
  "description": "A colour chosen in OKLCH (lightness, chroma, hue: even steps the eye sees as even): a field of lightness and chroma to point at, a slider for each of the three that the keys drive, swatches of the project's colours, and the value as text that can be typed, in OKLCH or hex.",
  "categories": [
    "ui"
  ],
  "dependencies": [
    "radix-ui"
  ],
  "registryDependencies": [
    "@rivier-ui/theme",
    "@rivier-ui/cn",
    "@rivier-ui/input",
    "@rivier-ui/use-controllable-state"
  ],
  "files": [
    {
      "path": "registry/ui/color-picker.tsx",
      "type": "registry:ui",
      "target": "components/ui/color-picker.tsx",
      "content": "\"use client\";\n/**\n * @name color-picker\n * @category ui\n * @description A colour chosen in OKLCH (lightness, chroma, hue: even steps the eye sees as even): a field of lightness and chroma to point at, a slider for each of the three that the keys drive, swatches of the project's colours, and the value as text that can be typed, in OKLCH or hex.\n * @when Choosing a brand colour, a highlight, a label colour. To choose among a few fixed colours use toggle-group or radio-group with swatches; for the theme's highlight use theme-provider (its accent hue and chroma are this picker's).\n * @example\n * <ColorPicker aria-label=\"Label colour\" defaultValue=\"oklch(0.62 0.17 250)\" swatches={[\"oklch(0.62 0.17 250)\", \"oklch(0.7 0.15 150)\", \"#d95926\"]} />\n */\nimport { Slider } from \"radix-ui\";\nimport { useEffect, useId, useRef, useState, type ComponentProps, type PointerEvent } from \"react\";\nimport { cn } from \"@/lib/cn\";\nimport { useControllableState } from \"@/lib/use-controllable-state\";\nimport { inputVariants } from \"@/components/ui/input\";\n\nexport type Oklch = { l: number; c: number; h: number };\n\nconst MAX_CHROMA = 0.37;\n\n/** OKLCH to sRGB, each 0 to 1 (outside means out of the sRGB gamut). Björn Ottosson's matrices. */\nexport function oklchToRgb({ l, c, h }: Oklch): [number, number, number] {\n  const a = c * Math.cos((h * Math.PI) / 180);\n  const b = c * Math.sin((h * Math.PI) / 180);\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  const linear = [4.0767416621 * l_ - 3.3077115913 * m_ + 0.2309699292 * s_, -1.2684380046 * l_ + 2.6097574011 * m_ - 0.3413193965 * s_, -0.0041960863 * l_ - 0.7034186147 * m_ + 1.707614701 * s_];\n  const gamma = (x: number): number => (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.sign(x) * Math.abs(x) ** (1 / 2.4) - 0.055);\n  return [gamma(linear[0] ?? 0), gamma(linear[1] ?? 0), gamma(linear[2] ?? 0)];\n}\n\n/** sRGB (0 to 1 each) to OKLCH. */\nexport function rgbToOklch([r, g, b]: [number, number, number]): Oklch {\n  const lin = (x: number): number => (x <= 0.04045 ? x / 12.92 : ((x + 0.055) / 1.055) ** 2.4);\n  const [R, G, B] = [lin(r), lin(g), lin(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 Bb = 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_;\n  const h = (Math.atan2(Bb, A) * 180) / Math.PI;\n  return { l: L, c: Math.hypot(A, Bb), h: h < 0 ? h + 360 : h };\n}\n\nconst inGamut = (rgb: readonly number[]): boolean => rgb.every((x) => x >= -0.0005 && x <= 1.0005);\n\n/** Reads \"oklch(L C H)\" (L as 0–1 or a percentage) or \"#rgb\" / \"#rrggbb\". */\nexport function parseColor(text: string): Oklch | null {\n  const t = text.trim().toLowerCase();\n  const ok = /^oklch\\(\\s*([\\d.]+)(%?)\\s+([\\d.]+)\\s+([\\d.]+)(?:deg)?\\s*(?:\\/\\s*[\\d.%]+\\s*)?\\)$/.exec(t);\n  if (ok) return { l: Number(ok[1]) / (ok[2] ? 100 : 1), c: Number(ok[3]), h: Number(ok[4]) % 360 };\n  const hex = /^#([\\da-f]{3}|[\\da-f]{6})$/.exec(t);\n  if (hex) {\n    const digits = (hex[1] ?? \"\").length === 3 ? [...(hex[1] ?? \"\")].map((d) => d + d).join(\"\") : (hex[1] ?? \"\");\n    return rgbToOklch([parseInt(digits.slice(0, 2), 16) / 255, parseInt(digits.slice(2, 4), 16) / 255, parseInt(digits.slice(4, 6), 16) / 255]);\n  }\n  return null;\n}\n\nexport function formatColor(color: Oklch, format: \"oklch\" | \"hex\"): string {\n  if (format === \"hex\") {\n    const to = (x: number): string =>\n      Math.round(Math.max(0, Math.min(1, x)) * 255)\n        .toString(16)\n        .padStart(2, \"0\");\n    const [r, g, b] = oklchToRgb(color);\n    return `#${to(r)}${to(g)}${to(b)}`;\n  }\n  return `oklch(${color.l.toFixed(3)} ${color.c.toFixed(3)} ${color.h.toFixed(1)})`;\n}\n\nexport type ColorPickerLabels = { lightness: string; chroma: string; hue: string; value: string; swatches: string; outOfGamut: string; field: string };\n\nconst LABELS: ColorPickerLabels = {\n  lightness: \"Lightness\",\n  chroma: \"Colourfulness\",\n  hue: \"Hue\",\n  value: \"Colour value\",\n  swatches: \"Colours\",\n  outOfGamut: \"Outside what most screens show: it will be shown a little less colourful\",\n  field: \"Lightness and colourfulness\",\n};\n\nexport type ColorPickerProps = Omit<ComponentProps<\"div\">, \"defaultValue\" | \"onChange\"> & {\n  /** A CSS colour as \"oklch(…)\" or \"#rrggbb\". */\n  value?: string;\n  defaultValue?: string;\n  onValueChange?: (value: string) => void;\n  /** How the value is written. Default \"oklch\". */\n  format?: \"oklch\" | \"hex\";\n  swatches?: readonly string[];\n  labels?: Partial<ColorPickerLabels>;\n  name?: string;\n};\n\nexport function ColorPicker({ value, defaultValue = \"oklch(0.62 0.17 250)\", onValueChange, format = \"oklch\", swatches = [], labels: given, name, className, ...props }: ColorPickerProps) {\n  const labels = { ...LABELS, ...given };\n  const [text, setText] = useControllableState<string>({ value, defaultValue, onChange: onValueChange });\n  const color = parseColor(text) ?? { l: 0.62, c: 0.17, h: 250 };\n  const [draft, setDraft] = useState<string | null>(null);\n  const canvas = useRef<HTMLCanvasElement>(null);\n  const textId = useId();\n  const set = (next: Oklch): void => setText(formatColor({ l: Math.max(0, Math.min(1, next.l)), c: Math.max(0, Math.min(MAX_CHROMA, next.c)), h: ((next.h % 360) + 360) % 360 }, format));\n  const gamut = inGamut(oklchToRgb(color));\n\n  // The field is drawn pixel by pixel from the maths: lightness up, chroma across, at the current hue.\n  useEffect(() => {\n    const node = canvas.current;\n    const context = node?.getContext(\"2d\");\n    if (!node || !context) return;\n    const w = 96;\n    const h = 64;\n    node.width = w;\n    node.height = h;\n    const image = context.createImageData(w, h);\n    for (let y = 0; y < h; y++) {\n      for (let x = 0; x < w; x++) {\n        const rgb = oklchToRgb({ l: 1 - y / (h - 1), c: (x / (w - 1)) * MAX_CHROMA, h: color.h });\n        const i = (y * w + x) * 4;\n        const outside = !inGamut(rgb);\n        image.data[i] = Math.round(Math.max(0, Math.min(1, rgb[0])) * 255);\n        image.data[i + 1] = Math.round(Math.max(0, Math.min(1, rgb[1])) * 255);\n        image.data[i + 2] = Math.round(Math.max(0, Math.min(1, rgb[2])) * 255);\n        // Colours a screen cannot show are faded, so the edge of the gamut is visible.\n        image.data[i + 3] = outside ? 70 : 255;\n      }\n    }\n    context.putImageData(image, 0, 0);\n  }, [color.h]);\n\n  const pointAt = (event: PointerEvent<HTMLDivElement>): void => {\n    const box = event.currentTarget.getBoundingClientRect();\n    const fx = Math.max(0, Math.min(1, (event.clientX - box.left) / box.width));\n    const fy = Math.max(0, Math.min(1, (event.clientY - box.top) / box.height));\n    // The field is not mirrored in a right-to-left page: chroma grows to the right like the hue bar.\n    set({ l: 1 - fy, c: fx * MAX_CHROMA, h: color.h });\n  };\n  const slider = (label: string, valueOf: number, max: number, stepOf: number, onSet: (v: number) => void, text: string, track: string) => (\n    <div className=\"flex flex-col gap-1\">\n      <div className=\"flex justify-between text-xs text-muted-foreground\">\n        <span>{label}</span>\n        <span className=\"tabular-nums\">{text}</span>\n      </div>\n      <Slider.Root value={[valueOf]} max={max} step={stepOf} onValueChange={(v) => onSet(v[0] ?? 0)} dir=\"ltr\" className=\"relative flex h-6 touch-none select-none items-center\">\n        <Slider.Track className=\"relative h-2 grow overflow-hidden rounded-full\" style={{ background: track }}>\n          <Slider.Range className=\"absolute h-full\" />\n        </Slider.Track>\n        <Slider.Thumb aria-label={label} aria-valuetext={text} className=\"block size-5 rounded-full border-2 border-background bg-foreground outline-offset-2 pointer-coarse:size-7\" />\n      </Slider.Root>\n    </div>\n  );\n  const stops = (fn: (t: number) => Oklch): string => `linear-gradient(to right, ${Array.from({ length: 9 }, (_, i) => formatColor(fn(i / 8), \"hex\")).join(\", \")})`;\n  const css = formatColor(color, \"oklch\");\n\n  return (\n    <div data-slot=\"color-picker\" role=\"group\" className={cn(\"flex w-full max-w-80 min-w-0 flex-col gap-3\", className)} {...props}>\n      <div\n        data-slot=\"color-picker-field\"\n        aria-hidden=\"true\"\n        className=\"relative aspect-[3/2] w-full cursor-crosshair touch-none overflow-hidden rounded-surface border\"\n        onPointerDown={(event) => {\n          event.currentTarget.setPointerCapture(event.pointerId);\n          pointAt(event);\n        }}\n        onPointerMove={(event) => {\n          if (event.currentTarget.hasPointerCapture(event.pointerId)) pointAt(event);\n        }}\n      >\n        <canvas ref={canvas} className=\"size-full\" style={{ imageRendering: \"auto\" }} />\n        <span\n          className=\"absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-background outline-2 outline-foreground\"\n          style={{ left: `${(color.c / MAX_CHROMA) * 100}%`, top: `${(1 - color.l) * 100}%`, background: css }}\n        />\n      </div>\n      <span className=\"sr-only\">{labels.field}</span>\n      {slider(\n        labels.lightness,\n        Math.round(color.l * 1000),\n        1000,\n        5,\n        (v) => set({ ...color, l: v / 1000 }),\n        `${Math.round(color.l * 100)}%`,\n        stops((t) => ({ l: t, c: Math.min(color.c, 0.12), h: color.h })),\n      )}\n      {slider(\n        labels.chroma,\n        Math.round(color.c * 1000),\n        Math.round(MAX_CHROMA * 1000),\n        5,\n        (v) => set({ ...color, c: v / 1000 }),\n        color.c.toFixed(3),\n        stops((t) => ({ l: color.l, c: t * MAX_CHROMA, h: color.h })),\n      )}\n      {slider(\n        labels.hue,\n        Math.round(color.h),\n        359,\n        1,\n        (v) => set({ ...color, h: v }),\n        `${Math.round(color.h)}°`,\n        stops((t) => ({ l: 0.7, c: 0.13, h: t * 359 })),\n      )}\n      <div className=\"flex items-center gap-2\">\n        <span aria-hidden=\"true\" className=\"size-(--control-h) shrink-0 rounded-control border\" style={{ background: css }} />\n        <input\n          id={textId}\n          aria-label={labels.value}\n          value={draft ?? text}\n          spellCheck={false}\n          onChange={(event) => setDraft(event.target.value)}\n          onBlur={() => {\n            if (draft !== null) {\n              const parsed = parseColor(draft);\n              if (parsed) set(parsed);\n              setDraft(null);\n            }\n          }}\n          onKeyDown={(event) => {\n            if (event.key === \"Enter\" && draft !== null) {\n              const parsed = parseColor(draft);\n              if (parsed) set(parsed);\n              setDraft(null);\n            }\n          }}\n          aria-invalid={draft !== null && parseColor(draft) === null ? true : undefined}\n          className={cn(inputVariants(), \"font-mono text-xs\")}\n        />\n      </div>\n      {!gamut ? (\n        <p data-slot=\"color-picker-gamut\" className=\"text-xs text-muted-foreground\">\n          {labels.outOfGamut}\n        </p>\n      ) : null}\n      {swatches.length > 0 ? (\n        <div role=\"group\" aria-label={labels.swatches} className=\"flex flex-wrap gap-2\">\n          {swatches.map((swatch) => {\n            const parsed = parseColor(swatch);\n            const chosen = parsed !== null && formatColor(parsed, \"hex\") === formatColor(color, \"hex\");\n            return (\n              <button\n                key={swatch}\n                type=\"button\"\n                aria-pressed={chosen}\n                aria-label={swatch}\n                onClick={() => parsed && set(parsed)}\n                className={cn(\"size-8 rounded-control border pointer-coarse:size-10\", chosen && \"outline-2 outline-offset-2 outline-foreground\")}\n                style={{ background: parsed ? formatColor(parsed, \"oklch\") : swatch }}\n              />\n            );\n          })}\n        </div>\n      ) : null}\n      {name ? <input type=\"hidden\" name={name} value={text} /> : null}\n    </div>\n  );\n}\n"
    }
  ],
  "meta": {
    "category": "ui",
    "when": "Choosing a brand colour, a highlight, a label colour. To choose among a few fixed colours use toggle-group or radio-group with swatches; for the theme's highlight use theme-provider (its accent hue and chroma are this picker's).",
    "example": "<ColorPicker aria-label=\"Label colour\" defaultValue=\"oklch(0.62 0.17 250)\" swatches={[\"oklch(0.62 0.17 250)\", \"oklch(0.7 0.15 150)\", \"#d95926\"]} />",
    "client": true
  }
}
