{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-picker",
  "title": "Color Picker",
  "description": "Swatch palette for choosing a colour, with a standalone swatch part.",
  "dependencies": [
    "class-variance-authority@^0.7.1",
    "lucide-react@^1.27.0"
  ],
  "registryDependencies": [
    "@pestoui/input",
    "@pestoui/style",
    "@pestoui/utils"
  ],
  "files": [
    {
      "path": "pestoui/ui/color-picker.tsx",
      "content": "\"use client\"\n\nimport * as React from \"react\"\nimport { cva, type VariantProps } from \"class-variance-authority\"\n\nimport { cn } from \"@/lib/utils\"\nimport { Input } from \"@/components/ui/input\"\nimport { CheckIcon, PlusIcon } from \"lucide-react\"\n\n/* The palette is *content*, not theme. These literals are the values the picker\n   offers; they only ever reach the DOM through `style`, never as a class. Every\n   piece of chrome around them stays on the token utilities. */\nconst DEFAULT_COLORS = [\n  \"#1c1917\",\n  \"#78716c\",\n  \"#d6d3d1\",\n  \"#ffffff\",\n  \"#dc2626\",\n  \"#f97316\",\n  \"#f59e0b\",\n  \"#16a34a\",\n  \"#14b8a6\",\n  \"#3b82f6\",\n  \"#8b5cf6\",\n  \"#ec4899\",\n]\n\nconst HEX_PATTERN = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i\n\n/* Returns the six-digit form of a hex string, or null when the string is not a\n   hex colour at all. Every parse in this file funnels through here so a\n   half-typed value can be ignored instead of thrown. */\nfunction toHex6(value: string) {\n  const hex = value.trim().toLowerCase()\n  if (!HEX_PATTERN.test(hex)) return null\n  if (hex.length === 7) return hex\n  return `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`\n}\n\nfunction sameColor(a: string, b: string) {\n  return (\n    (toHex6(a) ?? a.trim().toLowerCase()) ===\n    (toHex6(b) ?? b.trim().toLowerCase())\n  )\n}\n\n/* How many chips sit in the first row — measured off the DOM so the roving grid\n   follows however the swatches actually wrapped at this width. */\nfunction columnsOf(items: HTMLElement[]) {\n  if (items.length === 0) return 1\n  const top = items[0].offsetTop\n  let columns = 1\n  while (columns < items.length && items[columns].offsetTop === top) {\n    columns += 1\n  }\n  return columns\n}\n\nconst colorSwatchVariants = cva(\n  \"group/color-swatch relative inline-flex shrink-0 items-center justify-center bg-clip-padding align-middle transition-all duration-spring-press ease-spring-press outline-none select-none focus-visible:ring-3 focus-visible:ring-ring/50 active:translate-y-px disabled:pointer-events-none disabled:opacity-50\",\n  {\n    variants: {\n      /* Explicit radii — a token radius on a box this small exceeds half the\n         width and collapses the squircle into a circle. */\n      size: {\n        sm: \"size-7 rounded-[9px]\",\n        default: \"size-9 rounded-[11px]\",\n        lg: \"size-11 rounded-[14px]\",\n      },\n    },\n    defaultVariants: {\n      size: \"default\",\n    },\n  }\n)\n\n/* Selection ring — drawn outside the chip so it survives on any fill, and left\n   to the selected accent alone: it is the one accent that means \"selected\". It\n   takes --selected rather than --primary, because a two-pixel ring is a\n   thin graphic and has to clear the indicator contrast bar against both the\n   card behind it and the chip it wraps. Radii are the chip radius plus the\n   offset so the squircle stays a squircle.\n\n   It grows the last few percent into place on the press spring and leaves on the\n   short tween. The unselected state is the ring's own from- *and* to-value, so\n   the travel cannot differ between the two directions the way a keyframe pair's\n   can; the asymmetry is carried by the duration and the curve instead. Both\n   resting states are pixel-identical to before — the resting ring is at scale 1,\n   and the one that is scaled down is at zero opacity. */\nfunction SwatchRing() {\n  return (\n    <span\n      aria-hidden=\"true\"\n      data-slot=\"color-swatch-ring\"\n      className=\"pointer-events-none absolute inset-[-3px] scale-95 rounded-[14px] opacity-0 ring-2 ring-selected transition-[opacity,scale] duration-exit ease-out-expo group-data-[size=lg]/color-swatch:rounded-[17px] group-data-[size=sm]/color-swatch:inset-[-2px] group-data-[size=sm]/color-swatch:rounded-[11px] group-data-[selected=true]/color-swatch:scale-100 group-data-[selected=true]/color-swatch:opacity-100 group-data-[selected=true]/color-swatch:duration-spring-press group-data-[selected=true]/color-swatch:ease-spring-press\"\n    />\n  )\n}\n\n/* The check rides on an accent disc rather than sitting bare on the fill: a\n   plain glyph disappears on white in one direction and on black in the other,\n   and no token pair flips independently of the theme. The disc stays on the\n   --selected fill with --selected-foreground on the glyph — a genuine filled\n   area, which is the pairing that keeps the mark legible on every swatch.\n\n   The disc materialises rather than switching on: it resolves out of a blur as\n   it lands, which is what makes a small mark read as arriving on top of the fill\n   instead of being revealed by it. Blur is enter-only and always resolves to 0 —\n   the selected state is the same pixels it was before. */\nfunction SwatchCheck() {\n  return (\n    <span\n      aria-hidden=\"true\"\n      data-slot=\"color-swatch-check\"\n      className=\"pointer-events-none relative flex size-5 scale-50 items-center justify-center rounded-full bg-selected text-selected-foreground opacity-0 blur-xs shadow-tile transition-[opacity,scale,filter] duration-exit ease-out-expo group-data-[size=lg]/color-swatch:size-6 group-data-[size=sm]/color-swatch:size-4 group-data-[selected=true]/color-swatch:scale-100 group-data-[selected=true]/color-swatch:opacity-100 group-data-[selected=true]/color-swatch:blur-none group-data-[selected=true]/color-swatch:duration-spring-press group-data-[selected=true]/color-swatch:ease-spring-press\"\n    >\n      <CheckIcon\n        strokeWidth={3}\n        className=\"size-3 group-data-[size=lg]/color-swatch:size-3.5 group-data-[size=sm]/color-swatch:size-2.5\"\n      />\n    </span>\n  )\n}\n\ntype ColorSwatchProps = Omit<\n  React.ComponentProps<\"button\">,\n  \"color\" | \"onSelect\"\n> &\n  VariantProps<typeof colorSwatchVariants> & {\n    color: string\n    selected?: boolean\n    onSelect?: (color: string) => void\n    label?: string\n  }\n\nfunction ColorSwatch({\n  className,\n  color,\n  selected = false,\n  onSelect,\n  onClick,\n  size = \"default\",\n  label,\n  style,\n  ...props\n}: ColorSwatchProps) {\n  const resolvedSize = size ?? \"default\"\n\n  return (\n    <button\n      type=\"button\"\n      data-slot=\"color-swatch\"\n      data-size={resolvedSize}\n      data-selected={selected}\n      aria-pressed={selected}\n      aria-label={label ?? color}\n      title={label ?? color}\n      style={{ backgroundColor: color, ...style }}\n      onClick={(event) => {\n        onClick?.(event)\n        if (!event.defaultPrevented) onSelect?.(color)\n      }}\n      className={cn(\n        colorSwatchVariants({ size: resolvedSize }),\n        /* Hairline sits *inside* the chip so white and pale fills keep an edge\n           on the light card. --foreground flips with the theme, so the same\n           pair reads on the dark card too. */\n        \"inset-ring-1 inset-ring-foreground/15 dark:inset-ring-foreground/25\",\n        className\n      )}\n      {...props}\n    >\n      <SwatchRing />\n      <SwatchCheck />\n    </button>\n  )\n}\n\ntype ColorPickerProps = Omit<\n  React.ComponentProps<\"div\">,\n  \"color\" | \"defaultValue\" | \"onChange\"\n> & {\n  value?: string\n  defaultValue?: string\n  onValueChange?: (hex: string) => void\n  colors?: string[]\n  showCustom?: boolean\n  showInput?: boolean\n  size?: VariantProps<typeof colorSwatchVariants>[\"size\"]\n}\n\nfunction ColorPicker({\n  className,\n  value,\n  defaultValue,\n  onValueChange,\n  colors = DEFAULT_COLORS,\n  showCustom = true,\n  showInput = false,\n  size = \"default\",\n  ...props\n}: ColorPickerProps) {\n  /* cva reads an explicit `null` as \"no variant\" and would emit a tile with no\n     dimensions at all, so the size is normalised once and reused everywhere. */\n  const resolvedSize = size ?? \"default\"\n\n  const [internalValue, setInternalValue] = React.useState(\n    () => defaultValue ?? colors[0] ?? \"#000000\"\n  )\n  const [focusedIndex, setFocusedIndex] = React.useState<number | null>(null)\n  const [editing, setEditing] = React.useState(false)\n\n  const current = value ?? internalValue\n\n  const [draft, setDraft] = React.useState(current)\n\n  /* The field only re-syncs while it is *not* being typed into, so committing a\n     shorthand hex never yanks the caret mid-edit. Blur reconciles it. */\n  React.useEffect(() => {\n    if (!editing) setDraft(current)\n  }, [current, editing])\n\n  const commit = React.useCallback(\n    (next: string) => {\n      if (value === undefined) setInternalValue(next)\n      onValueChange?.(next)\n    },\n    [value, onValueChange]\n  )\n\n  const selectedIndex = colors.findIndex((entry) => sameColor(entry, current))\n  const customSelected = showCustom && selectedIndex === -1\n  const rovingIndex = Math.min(\n    focusedIndex ?? Math.max(selectedIndex, 0),\n    Math.max(colors.length - 1, 0)\n  )\n\n  function handleKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {\n    const items = Array.from(\n      event.currentTarget.querySelectorAll<HTMLButtonElement>(\n        '[data-slot=\"color-swatch\"]:not(:disabled)'\n      )\n    )\n    const from = items.findIndex((item) => item === document.activeElement)\n    if (from === -1) return\n\n    const last = items.length - 1\n    const columns = columnsOf(items)\n    let next = from\n\n    switch (event.key) {\n      case \"ArrowRight\":\n        next = Math.min(from + 1, last)\n        break\n      case \"ArrowLeft\":\n        next = Math.max(from - 1, 0)\n        break\n      case \"ArrowDown\":\n        next = Math.min(from + columns, last)\n        break\n      case \"ArrowUp\":\n        next = Math.max(from - columns, 0)\n        break\n      case \"Home\":\n        next = 0\n        break\n      case \"End\":\n        next = last\n        break\n      default:\n        return\n    }\n\n    /* Focus moves, selection does not — activation stays on Enter/Space so a\n       keyboard user can survey the palette without committing to it. */\n    event.preventDefault()\n    items[next].focus()\n  }\n\n  function handleDraftChange(event: React.ChangeEvent<HTMLInputElement>) {\n    const next = event.target.value\n    setDraft(next)\n    const hex = toHex6(next)\n    if (hex) commit(hex)\n  }\n\n  return (\n    <div\n      role=\"group\"\n      aria-label=\"Color picker\"\n      data-slot=\"color-picker\"\n      className={cn(\"flex w-full flex-col gap-3\", className)}\n      {...props}\n    >\n      <div\n        data-slot=\"color-picker-grid\"\n        className=\"flex flex-wrap items-center gap-2\"\n        onKeyDown={handleKeyDown}\n      >\n        {colors.map((entry, index) => (\n          <ColorSwatch\n            key={`${entry}-${index}`}\n            color={entry}\n            label={entry}\n            size={resolvedSize}\n            selected={index === selectedIndex}\n            onSelect={commit}\n            tabIndex={index === rovingIndex ? 0 : -1}\n            onFocus={() => setFocusedIndex(index)}\n          />\n        ))}\n\n        {showCustom ? (\n          /* Escape hatch. The native control is stretched over the tile at zero\n             opacity so it keeps its own focus and OS picker while the tile keeps\n             the house squircle. */\n          <div\n            data-slot=\"color-picker-custom\"\n            data-size={resolvedSize}\n            data-selected={customSelected}\n            style={customSelected ? { backgroundColor: current } : undefined}\n            className={cn(\n              colorSwatchVariants({ size: resolvedSize }),\n              \"text-muted-foreground has-[:focus-visible]:ring-3 has-[:focus-visible]:ring-ring/50\",\n              /* Once a colour is showing, the tile carries no border at all:\n                 the base sets bg-clip-padding, so even a transparent border\n                 would clip the fill and leave a hairline of card showing\n                 through. Selected state falls back to the same inside hairline\n                 the palette chips use. */\n              customSelected\n                ? \"inset-ring-1 inset-ring-foreground/15 dark:inset-ring-foreground/25\"\n                : \"border border-dashed border-input bg-card has-[:focus-visible]:border-ring dark:bg-input/30\"\n            )}\n          >\n            <input\n              type=\"color\"\n              data-slot=\"color-picker-custom-input\"\n              aria-label=\"Custom color\"\n              value={toHex6(current) ?? \"#000000\"}\n              onChange={(event) => commit(event.target.value)}\n              className=\"absolute inset-0 size-full cursor-pointer opacity-0\"\n            />\n            {customSelected ? (\n              <>\n                <SwatchRing />\n                <SwatchCheck />\n              </>\n            ) : (\n              <PlusIcon\n                aria-hidden=\"true\"\n                className=\"pointer-events-none size-4 group-data-[size=lg]/color-swatch:size-5 group-data-[size=sm]/color-swatch:size-3.5\"\n              />\n            )}\n          </div>\n        ) : null}\n      </div>\n\n      {showInput ? (\n        <div data-slot=\"color-picker-field\" className=\"flex items-center gap-2\">\n          {/* The preview crossfades to the committed value instead of cutting\n              to it — the fade is what ties the field to the tile while a hex is\n              being typed a character at a time. */}\n          <span\n            aria-hidden=\"true\"\n            data-slot=\"color-picker-preview\"\n            style={{ backgroundColor: current }}\n            className=\"size-11 shrink-0 rounded-[14px] shadow-soft inset-ring-1 inset-ring-foreground/15 transition-colors duration-base ease-out-expo dark:inset-ring-foreground/25\"\n          />\n          <Input\n            value={draft}\n            onChange={handleDraftChange}\n            onFocus={() => setEditing(true)}\n            onBlur={() => setEditing(false)}\n            aria-label=\"Hex color\"\n            aria-invalid={draft.trim().length > 0 && toHex6(draft) === null}\n            autoComplete=\"off\"\n            spellCheck={false}\n            maxLength={7}\n            placeholder=\"#rrggbb\"\n            className=\"font-mono text-body lowercase\"\n          />\n        </div>\n      ) : null}\n    </div>\n  )\n}\n\nexport { ColorPicker, ColorSwatch, colorSwatchVariants }\n",
      "type": "registry:ui"
    }
  ],
  "type": "registry:ui"
}