{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"color-picker","type":"registry:ui","title":"Color Picker","description":"A hex field with a swatch that opens saturation, brightness and hue, presets and a pick from the screen.","dependencies":["lucide-react"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/lib-locale.json","https://dashral.com/r/field.json","https://dashral.com/r/input.json","https://dashral.com/r/popover.json"],"files":[{"path":"registry/dashral/color-picker.tsx","type":"registry:file","target":"components/dashral/color-picker.tsx","content":"\"use client\"\n\nimport * as React from \"react\"\nimport { CheckIcon, PipetteIcon } from \"lucide-react\"\n\nimport { useLocale } from \"./lib/locale\"\nimport { cn } from \"./lib/utils\"\nimport { type FieldClassNames, type FieldOwnProps } from \"./field\"\nimport { Input } from \"./input\"\nimport { PopoverContent, PopoverRoot, PopoverTrigger } from \"./popover\"\n\ntype Hsv = { h: number; s: number; v: number }\n\n/** \"#abc\" or \"#aabbcc\" (any case, # optional) as \"#aabbcc\"; null when it isn't a color. */\nfunction normalizeHex(text: string): string | null {\n  const raw = text.trim().replace(/^#/, \"\").toLowerCase()\n  if (/^[0-9a-f]{3}$/.test(raw)) return `#${[...raw].map((c) => c + c).join(\"\")}`\n  if (/^[0-9a-f]{6}$/.test(raw)) return `#${raw}`\n  return null\n}\n\nfunction hexToHsv(hex: string): Hsv {\n  const n = parseInt(hex.slice(1), 16)\n  const [r, g, b] = [(n >> 16) & 255, (n >> 8) & 255, n & 255].map((c) => c / 255) as [number, number, number]\n  const max = Math.max(r, g, b)\n  const d = max - Math.min(r, g, b)\n  let h = 0\n  if (d) h = max === r ? ((g - b) / d) % 6 : max === g ? (b - r) / d + 2 : (r - g) / d + 4\n  // Not rounded: hsvToHex(hexToHsv(hex)) has to give the same hex back, or the picker would keep resyncing.\n  return { h: (h * 60 + 360) % 360, s: max ? (d / max) * 100 : 0, v: max * 100 }\n}\n\nfunction hsvToHex({ h, s, v }: Hsv): string {\n  const f = (k: number) => {\n    const n = (k + h / 60) % 6\n    const value = (v / 100) * (1 - (s / 100) * Math.max(0, Math.min(n, 4 - n, 1)))\n    return Math.round(value * 255).toString(16).padStart(2, \"0\")\n  }\n  return `#${f(5)}${f(3)}${f(1)}`\n}\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\n\ntype ColorPickerProps = FieldOwnProps & {\n  /** The color as hex, controlled: \"#2563eb\". */\n  value?: string\n  defaultValue?: string\n  /** Called with the new color as lowercase \"#rrggbb\", as it's dragged, picked or typed. */\n  onValueChange?: (value: string) => void\n  /** Colors to pick in one click under the picker: your brand's, or recent ones. */\n  swatches?: string[]\n  /** A button that picks a color from anywhere on the screen, where the browser can (Chrome, Edge). On by default. */\n  eyeDropper?: boolean\n  /** The form field's name: the color is sent as \"#rrggbb\". */\n  name?: string\n  id?: string\n  disabled?: boolean\n  required?: boolean\n  placeholder?: string\n  \"aria-label\"?: string\n  \"aria-invalid\"?: React.AriaAttributes[\"aria-invalid\"]\n  /** The field's classes. */\n  className?: string\n  classNames?: FieldClassNames & { content?: string }\n}\n\ntype EyeDropperConstructor = new () => { open: () => Promise<{ sRGBHex: string }> }\n\n/**\n * A color field, in one tag: `<ColorPicker label=\"Brand color\" value={color} onValueChange={setColor} />`. Type a hex\n * value, or open the swatch to drag through saturation, brightness and hue (the arrow keys work too, Shift for big\n * steps), pick a preset, or take one from the screen.\n */\nfunction ColorPicker({\n  value,\n  defaultValue = \"#2563eb\",\n  onValueChange,\n  swatches,\n  eyeDropper = true,\n  disabled,\n  className,\n  classNames,\n  ...props\n}: ColorPickerProps) {\n  const { t } = useLocale()\n  const [internal, setInternal] = React.useState(() => normalizeHex(defaultValue) ?? \"#000000\")\n  const color = normalizeHex(value ?? internal) ?? \"#000000\"\n  // Hue and saturation are kept apart from the hex: at black or grey they can't be read back, and the hue slider\n  // would jump to red.\n  const [hsv, setHsv] = React.useState(() => hexToHsv(color))\n  if (hsvToHex(hsv) !== color) {\n    // The color changed from outside (typed, a swatch, the parent): follow it, keeping the hue where it can't be read.\n    const next = hexToHsv(color)\n    setHsv(next.s === 0 || next.v === 0 ? { ...next, h: hsv.h } : next)\n  }\n  const [text, setText] = React.useState(color)\n  const [editing, setEditing] = React.useState(false)\n  const [canDrop, setCanDrop] = React.useState(false)\n  React.useEffect(() => setCanDrop(eyeDropper && \"EyeDropper\" in window), [eyeDropper])\n\n  function commit(next: string, nextHsv?: Hsv) {\n    if (nextHsv) setHsv(nextHsv)\n    if (value === undefined) setInternal(next)\n    if (next !== color) onValueChange?.(next)\n  }\n  const fromHsv = (next: Hsv) => commit(hsvToHex(next), next)\n\n  async function drop() {\n    const EyeDropper = (window as unknown as { EyeDropper?: EyeDropperConstructor }).EyeDropper\n    if (!EyeDropper) return\n    try {\n      const { sRGBHex } = await new EyeDropper().open()\n      const hex = normalizeHex(sRGBHex)\n      if (hex) commit(hex)\n    } catch {\n      // Cancelled with Escape: nothing to do.\n    }\n  }\n\n  const swatch = (\n    <PopoverRoot>\n      <PopoverTrigger\n        type=\"button\"\n        disabled={disabled}\n        aria-label={t(\"pickColor\")}\n        className=\"-ms-1 size-6 shrink-0 rounded-sm border border-black/10 shadow-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/50 disabled:pointer-events-none dark:border-white/15\"\n        style={{ backgroundColor: color }}\n      />\n      <PopoverContent align=\"start\" sideOffset={8} className={cn(\"grid w-64 gap-3 p-3\", classNames?.content)}>\n        <SaturationArea hsv={hsv} onChange={fromHsv} />\n        <div className=\"flex items-center gap-2\">\n          <HueSlider hsv={hsv} onChange={fromHsv} />\n          {canDrop && (\n            <button\n              type=\"button\"\n              onClick={drop}\n              aria-label={t(\"pickFromScreen\")}\n              className=\"grid size-7 shrink-0 place-items-center rounded-md text-muted-foreground outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/50 [&_svg]:size-4\"\n            >\n              <PipetteIcon aria-hidden />\n            </button>\n          )}\n        </div>\n        {swatches && swatches.length > 0 && (\n          <div role=\"group\" aria-label={t(\"swatches\")} className=\"grid grid-cols-8 gap-1.5 border-t pt-3\">\n            {swatches.map((entry) => {\n              const hex = normalizeHex(entry)\n              if (!hex) return null\n              const picked = hex === color\n              return (\n                <button\n                  key={hex}\n                  type=\"button\"\n                  aria-label={hex}\n                  aria-pressed={picked}\n                  onClick={() => commit(hex)}\n                  className=\"grid aspect-square place-items-center rounded-sm border border-black/10 outline-none transition-transform focus-visible:ring-2 focus-visible:ring-ring/50 motion-safe:hover:scale-110 dark:border-white/15\"\n                  style={{ backgroundColor: hex }}\n                >\n                  {picked && <CheckIcon aria-hidden className={cn(\"size-3.5\", hexToHsv(hex).v > 60 && hexToHsv(hex).s < 50 ? \"text-black\" : \"text-white\")} />}\n                </button>\n              )\n            })}\n          </div>\n        )}\n      </PopoverContent>\n    </PopoverRoot>\n  )\n\n  return (\n    <Input\n      {...props}\n      disabled={disabled}\n      prefix={swatch}\n      value={editing ? text : color}\n      spellCheck={false}\n      autoComplete=\"off\"\n      maxLength={7}\n      className={cn(\"font-mono uppercase\", className)}\n      classNames={classNames}\n      onFocus={() => {\n        setText(color)\n        setEditing(true)\n      }}\n      onChange={(event) => {\n        setText(event.target.value)\n        const hex = normalizeHex(event.target.value)\n        if (hex) commit(hex)\n      }}\n      // What was typed but isn't a color goes back to the color on leaving.\n      onBlur={() => setEditing(false)}\n    />\n  )\n}\n\n/** Steps for the arrow keys: 1, or 10 with Shift; Page Up and Down take 10 too. */\nconst keyStep = (event: React.KeyboardEvent) => (event.shiftKey || event.key.startsWith(\"Page\") ? 10 : 1)\n\n/** Follows a pointer from press to release, from wherever it was pressed, with the position as 0–1 across and down. */\nfunction useDrag(onMove: (x: number, y: number) => void) {\n  return {\n    onPointerDown(event: React.PointerEvent<HTMLElement>) {\n      if (event.button !== 0) return\n      const el = event.currentTarget\n      el.setPointerCapture(event.pointerId)\n      el.focus()\n      const move = (e: { clientX: number; clientY: number }) => {\n        const rect = el.getBoundingClientRect()\n        onMove(clamp((e.clientX - rect.left) / rect.width, 0, 1), clamp((e.clientY - rect.top) / rect.height, 0, 1))\n      }\n      move(event)\n      const up = () => {\n        el.removeEventListener(\"pointermove\", move)\n        el.removeEventListener(\"pointerup\", up)\n        el.removeEventListener(\"pointercancel\", up)\n      }\n      el.addEventListener(\"pointermove\", move)\n      el.addEventListener(\"pointerup\", up)\n      el.addEventListener(\"pointercancel\", up)\n    },\n  }\n}\n\nconst thumbClass = \"pointer-events-none absolute size-4 -translate-x-1/2 -translate-y-1/2 rounded-full border-2 border-white shadow-[0_0_0_1px_rgb(0_0_0/0.25),0_1px_3px_rgb(0_0_0/0.3)]\"\n\n/** Saturation across, brightness up: a square of the hue's shades. Colors don't turn around in Arabic, so it's ltr. */\nfunction SaturationArea({ hsv, onChange }: { hsv: Hsv; onChange: (next: Hsv) => void }) {\n  const { t } = useLocale()\n  const drag = useDrag((x, y) => onChange({ ...hsv, s: x * 100, v: (1 - y) * 100 }))\n  const s = Math.round(hsv.s)\n  const v = Math.round(hsv.v)\n  return (\n    <div\n      dir=\"ltr\"\n      role=\"slider\"\n      tabIndex={0}\n      aria-label={t(\"colorArea\")}\n      aria-valuemin={0}\n      aria-valuemax={100}\n      aria-valuenow={s}\n      aria-valuetext={t(\"colorAreaValue\", { saturation: s, brightness: v })}\n      {...drag}\n      onKeyDown={(event) => {\n        const step = keyStep(event)\n        const moves: Record<string, Partial<Hsv>> = {\n          ArrowRight: { s: hsv.s + step },\n          ArrowLeft: { s: hsv.s - step },\n          ArrowUp: { v: hsv.v + step },\n          ArrowDown: { v: hsv.v - step },\n          PageUp: { v: hsv.v + step },\n          PageDown: { v: hsv.v - step },\n        }\n        const move = moves[event.key]\n        if (!move) return\n        event.preventDefault()\n        onChange({ h: hsv.h, s: clamp(move.s ?? hsv.s, 0, 100), v: clamp(move.v ?? hsv.v, 0, 100) })\n      }}\n      className=\"relative h-36 touch-none rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-popover\"\n      style={{ background: `linear-gradient(to top, #000, transparent), linear-gradient(to right, #fff, hsl(${hsv.h} 100% 50%))` }}\n    >\n      <span className={thumbClass} style={{ left: `${hsv.s}%`, top: `${100 - hsv.v}%`, backgroundColor: hsvToHex(hsv) }} />\n    </div>\n  )\n}\n\nfunction HueSlider({ hsv, onChange }: { hsv: Hsv; onChange: (next: Hsv) => void }) {\n  const { t } = useLocale()\n  const drag = useDrag((x) => onChange({ ...hsv, h: Math.round(x * 360) }))\n  const h = Math.round(hsv.h)\n  return (\n    <div\n      dir=\"ltr\"\n      role=\"slider\"\n      tabIndex={0}\n      aria-label={t(\"hue\")}\n      aria-orientation=\"horizontal\"\n      aria-valuemin={0}\n      aria-valuemax={360}\n      aria-valuenow={h}\n      {...drag}\n      onKeyDown={(event) => {\n        const step = keyStep(event)\n        const next =\n          event.key === \"ArrowRight\" || event.key === \"ArrowUp\" || event.key === \"PageUp\"\n            ? hsv.h + step\n            : event.key === \"ArrowLeft\" || event.key === \"ArrowDown\" || event.key === \"PageDown\"\n              ? hsv.h - step\n              : event.key === \"Home\"\n                ? 0\n                : event.key === \"End\"\n                  ? 360\n                  : null\n        if (next === null) return\n        event.preventDefault()\n        onChange({ ...hsv, h: clamp(next, 0, 360) })\n      }}\n      className=\"relative h-3 flex-1 touch-none rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-popover\"\n      style={{ background: \"linear-gradient(to right, #f00, #ff0, #0f0, #0ff, #00f, #f0f, #f00)\" }}\n    >\n      <span className={cn(thumbClass, \"top-1/2\")} style={{ left: `${(hsv.h / 360) * 100}%`, backgroundColor: `hsl(${hsv.h} 100% 50%)` }} />\n    </div>\n  )\n}\n\nexport { ColorPicker, type ColorPickerProps }\n"}]}