{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "color-swatch",
  "title": "Color Swatch",
  "description": "Shows a colour with its name and value, alone or as a palette, with a label that stays readable on any fill and a checker under transparency.",
  "dependencies": [
    "lucide-react"
  ],
  "registryDependencies": [
    "utils"
  ],
  "files": [
    {
      "path": "registry/miseui/ui/color-swatch.tsx",
      "content": "import type * as React from \"react\"\r\nimport { Children, createContext, useContext, useEffect, useMemo, useRef, useState } from \"react\"\r\nimport { Check } from \"lucide-react\"\r\nimport { CHECKER_BACKGROUND, parseColor, readableInk, type Rgba } from \"@/registry/miseui/ui/color-swatch-math\"\r\nimport { cn } from \"@/registry/miseui/lib/utils\"\r\n\r\ntype ColorSwatchVariant = \"circle\" | \"square\" | \"chip\" | \"tile\"\r\ntype ColorSwatchEffect = \"lift\"\r\n\r\nconst ROOT_CLASS: Record<ColorSwatchVariant, string> = {\r\n  circle: \"inline-grid w-16 justify-items-center gap-2 rounded-md text-center\",\r\n  square: \"flex w-full min-w-0 items-center gap-3 rounded-md text-left\",\r\n  chip: \"inline-flex h-8 max-w-full items-center gap-2 rounded-full border pr-3 pl-1 text-left pointer-coarse:h-10\",\r\n  tile: \"relative isolate flex min-h-24 w-full min-w-0 flex-col justify-end gap-1 rounded-lg p-3 text-left\",\r\n}\r\n\r\n/** A hairline on every fill: white on a white page and near-black on a dark page would otherwise vanish. */\r\nconst FILL_CLASS: Record<ColorSwatchVariant, string> = {\r\n  circle: \"relative size-10 rounded-full\",\r\n  square: \"relative size-10 rounded-md\",\r\n  chip: \"relative size-5 rounded-full\",\r\n  tile: \"absolute inset-0 -z-10 rounded-[inherit] items-start justify-end p-3\",\r\n}\r\n\r\nconst GROUP_CLASS: Record<ColorSwatchVariant, string> = {\r\n  circle: \"flex flex-wrap gap-x-2 gap-y-4\",\r\n  square: \"grid grid-cols-[repeat(auto-fill,minmax(min(100%,9rem),1fr))] gap-3\",\r\n  chip: \"flex flex-wrap gap-2\",\r\n  tile: \"grid grid-cols-[repeat(auto-fit,minmax(6.5rem,1fr))] gap-2\",\r\n}\r\n\r\nconst CLICKABLE_CLASS =\r\n  \"cursor-pointer outline-none focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:pointer-events-none disabled:opacity-50\"\r\nconst LIFT_CLASS =\r\n  \"transition-[translate,box-shadow] duration-(--duration-fast) ease-(--ease-mise) motion-safe:hover:-translate-y-0.5\"\r\n/** Black, not foreground: a foreground shadow would turn into a glow in dark mode. */\r\nconst TILE_LIFT_CLASS = \"hover:shadow-md hover:shadow-black/20 dark:hover:shadow-black/50\"\r\n\r\nconst GroupContext = createContext<{ variant: ColorSwatchVariant; effect?: ColorSwatchEffect } | null>(null)\r\n\r\n/** The parser cannot read var(--mise) or a named colour, so those are resolved by asking the browser what it painted. */\r\nfunction useResolvedColor(color: string) {\r\n  const ref = useRef<HTMLSpanElement>(null)\r\n  const parsed = parseColor(color)\r\n  const [probed, setProbed] = useState<{ source: string; rgba: Rgba | null } | null>(null)\r\n  useEffect(() => {\r\n    const node = ref.current\r\n    if (parseColor(color) || !node) return\r\n    const frame = requestAnimationFrame(() =>\r\n      setProbed({ source: color, rgba: parseColor(getComputedStyle(node).backgroundColor) }),\r\n    )\r\n    return () => cancelAnimationFrame(frame)\r\n  }, [color])\r\n  return { ref, rgba: parsed ?? (probed?.source === color ? probed.rgba : null) }\r\n}\r\n\r\nfunction paint(color: string, rgba: Rgba | null): React.CSSProperties {\r\n  if (!rgba || rgba.a >= 1) return { backgroundColor: color }\r\n  return { background: `linear-gradient(${color}, ${color}), ${CHECKER_BACKGROUND}` }\r\n}\r\n\r\ninterface ColorFillProps {\r\n  look: ColorSwatchVariant\r\n  color: string\r\n  rgba: Rgba | null\r\n  fillRef: React.Ref<HTMLSpanElement>\r\n  selected: boolean\r\n}\r\n\r\nfunction ColorFill({ look, color, rgba, fillRef, selected }: ColorFillProps) {\r\n  return (\r\n    <span\r\n      ref={fillRef}\r\n      aria-hidden=\"true\"\r\n      data-slot=\"color-swatch-fill\"\r\n      style={paint(color, rgba)}\r\n      className={cn(\r\n        \"flex shrink-0 items-center justify-center inset-ring inset-ring-black/10 dark:inset-ring-white/15\",\r\n        FILL_CLASS[look],\r\n        selected && \"ring-2 ring-foreground ring-offset-2 ring-offset-background\",\r\n      )}\r\n    >\r\n      {selected ? (\r\n        <Check aria-hidden=\"true\" className=\"size-4\" style={{ color: rgba ? readableInk(rgba) : undefined }} />\r\n      ) : null}\r\n    </span>\r\n  )\r\n}\r\n\r\nfunction SwatchText({ look, name, value }: { look: ColorSwatchVariant; name?: React.ReactNode; value: React.ReactNode }) {\r\n  const body = (\r\n    <>\r\n      {name ? (\r\n        <span className={cn(\"block min-w-0 truncate font-medium\", look === \"tile\" ? \"text-sm\" : \"text-[13px]\")}>{name}</span>\r\n      ) : null}\r\n      <span className={cn(\"block min-w-0 truncate font-mono text-xs\", look === \"tile\" ? \"opacity-80\" : \"text-muted-foreground\")}>\r\n        {value}\r\n      </span>\r\n    </>\r\n  )\r\n  if (look === \"tile\") return body\r\n  if (look === \"chip\") return <span className=\"flex min-w-0 items-baseline gap-2\">{body}</span>\r\n  return <span className=\"grid w-full min-w-0 gap-1\">{body}</span>\r\n}\r\n\r\ntype ColorSwatchProps = Omit<React.ComponentProps<\"div\">, \"color\" | \"onSelect\"> & {\r\n  /** Any CSS colour, including var(--mise). Transparent colours sit on a checker. */\r\n  color: string\r\n  name?: React.ReactNode\r\n  /** The text under the name; defaults to the colour itself. */\r\n  value?: React.ReactNode\r\n  /** `circle` a dot over its name, `square` a row with name and value, `chip` an inline pill, `tile` the label on the colour. Inherited from a group. */\r\n  variant?: ColorSwatchVariant\r\n  /** `lift` raises a clickable swatch on hover. Static swatches stay put, since movement would promise a click. */\r\n  effect?: ColorSwatchEffect\r\n  selected?: boolean\r\n  /** Makes the swatch a button. */\r\n  onSelect?: () => void\r\n  disabled?: boolean\r\n}\r\n\r\nfunction ColorSwatch({ color, name, value, variant, effect, selected = false, onSelect, disabled, className, style, ...props }: ColorSwatchProps) {\r\n  const group = useContext(GroupContext)\r\n  const look = variant ?? group?.variant ?? \"square\"\r\n  const resolvedEffect = effect ?? group?.effect\r\n  const { ref, rgba } = useResolvedColor(color)\r\n  const clickable = onSelect !== undefined\r\n  const lift = clickable && resolvedEffect === \"lift\"\r\n  const Root = (clickable ? \"button\" : \"div\") as React.ElementType\r\n  const buttonProps = clickable ? { type: \"button\", \"aria-pressed\": selected, disabled, onClick: onSelect } : {}\r\n  return (\r\n    <Root\r\n      data-slot=\"color-swatch\"\r\n      data-variant={look}\r\n      data-effect={resolvedEffect}\r\n      data-transparent={rgba && rgba.a < 1 ? \"true\" : undefined}\r\n      className={cn(\r\n        ROOT_CLASS[look],\r\n        clickable && CLICKABLE_CLASS,\r\n        lift && LIFT_CLASS,\r\n        lift && look === \"tile\" && TILE_LIFT_CLASS,\r\n        className,\r\n      )}\r\n      style={look === \"tile\" && rgba ? { color: readableInk(rgba), ...style } : style}\r\n      {...props}\r\n      {...buttonProps}\r\n    >\r\n      <ColorFill {...{ look, color, rgba, selected }} fillRef={ref} />\r\n      <SwatchText look={look} name={name} value={value ?? color} />\r\n    </Root>\r\n  )\r\n}\r\n\r\ntype ColorSwatchGroupProps = React.ComponentProps<\"div\"> & {\r\n  variant?: ColorSwatchVariant\r\n  effect?: ColorSwatchEffect\r\n}\r\n\r\n/** A palette: one look for all its swatches, laid out for that look. Name it with aria-label. */\r\nfunction ColorSwatchGroup({ variant = \"square\", effect, className, children, ...props }: ColorSwatchGroupProps) {\r\n  const context = useMemo(() => ({ variant, effect }), [variant, effect])\r\n  return (\r\n    <GroupContext.Provider value={context}>\r\n      <div\r\n        role=\"list\"\r\n        data-slot=\"color-swatch-group\"\r\n        data-variant={variant}\r\n        className={cn(GROUP_CLASS[variant], className)}\r\n        {...props}\r\n      >\r\n        {Children.map(children, (child) => (\r\n          <div role=\"listitem\" className=\"min-w-0\">\r\n            {child}\r\n          </div>\r\n        ))}\r\n      </div>\r\n    </GroupContext.Provider>\r\n  )\r\n}\r\n\r\nexport { ColorSwatch, ColorSwatchGroup, type ColorSwatchProps, type ColorSwatchGroupProps, type ColorSwatchVariant, type ColorSwatchEffect }\r\n",
      "type": "registry:ui"
    },
    {
      "path": "registry/miseui/ui/color-swatch-math.ts",
      "content": "interface Rgba {\n  /** 0 to 255 */\n  r: number\n  g: number\n  b: number\n  /** 0 to 1 */\n  a: number\n}\n\nconst INK_DARK = \"#0a0a0a\"\nconst INK_LIGHT = \"#ffffff\"\n/** What a transparent colour sits on: the average of the two checker squares. */\nconst CHECKER_LIGHT = \"#ffffff\"\nconst CHECKER_DARK = \"#d4d4d8\"\nconst CHECKER_AVERAGE: Rgba = { r: 234, g: 234, b: 236, a: 1 }\n\nconst clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))\n\nfunction parseHex(color: string): Rgba | null {\n  const match = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(color)\n  if (!match) return null\n  const raw = match[1]\n  const full = raw.length <= 4 ? [...raw].map((digit) => digit + digit).join(\"\") : raw\n  const channel = (start: number) => Number.parseInt(full.slice(start, start + 2), 16)\n  return { r: channel(0), g: channel(2), b: channel(4), a: full.length === 8 ? channel(6) / 255 : 1 }\n}\n\n/** Both the comma and the space syntax, with or without a slash before alpha. */\nfunction functionArguments(color: string, names: string) {\n  const match = new RegExp(`^(?:${names})\\\\((.+)\\\\)$`, \"i\").exec(color)\n  return match ? match[1].trim().split(/[\\s,/]+/) : null\n}\n\nconst toNumber = (token: string, percentScale: number) =>\n  token.endsWith(\"%\") ? (Number.parseFloat(token) / 100) * percentScale : Number.parseFloat(token)\n\nconst toAlpha = (token: string | undefined) => (token === undefined ? 1 : clamp(toNumber(token, 1), 0, 1))\n\nfunction parseRgb(color: string): Rgba | null {\n  const parts = functionArguments(color, \"rgba?\")\n  if (!parts || parts.length < 3) return null\n  const [r, g, b] = parts.slice(0, 3).map((token) => clamp(toNumber(token, 255), 0, 255))\n  return { r, g, b, a: toAlpha(parts[3]) }\n}\n\nfunction parseHsl(color: string): Rgba | null {\n  const parts = functionArguments(color, \"hsla?\")\n  if (!parts || parts.length < 3) return null\n  const hue = ((Number.parseFloat(parts[0]) % 360) + 360) % 360\n  const saturation = clamp(toNumber(parts[1], 1), 0, 1)\n  const lightness = clamp(toNumber(parts[2], 1), 0, 1)\n  const chroma = saturation * Math.min(lightness, 1 - lightness)\n  const channel = (offset: number) => {\n    const turn = (offset + hue / 30) % 12\n    return 255 * (lightness - chroma * Math.max(-1, Math.min(turn - 3, 9 - turn, 1)))\n  }\n  return { r: channel(0), g: channel(8), b: channel(4), a: toAlpha(parts[3]) }\n}\n\nconst gammaEncode = (linear: number) =>\n  255 * clamp(linear <= 0.0031308 ? 12.92 * linear : 1.055 * linear ** (1 / 2.4) - 0.055, 0, 1)\n\n/** Björn Ottosson's matrices; the theme colours of this kit are written in oklch. */\nfunction parseOklch(color: string): Rgba | null {\n  const parts = functionArguments(color, \"oklch\")\n  if (!parts || parts.length < 3) return null\n  const lightness = toNumber(parts[0], 1)\n  const chroma = toNumber(parts[1], 0.4)\n  const hue = (Number.parseFloat(parts[2]) * Math.PI) / 180\n  const a = chroma * Math.cos(hue)\n  const b = chroma * Math.sin(hue)\n  const l = (lightness + 0.3963377774 * a + 0.2158037573 * b) ** 3\n  const m = (lightness - 0.1055613458 * a - 0.0638541728 * b) ** 3\n  const s = (lightness - 0.0894841775 * a - 1.291485548 * b) ** 3\n  return {\n    r: gammaEncode(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s),\n    g: gammaEncode(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s),\n    b: gammaEncode(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s),\n    a: toAlpha(parts[3]),\n  }\n}\n\nfunction parseColor(color: string): Rgba | null {\n  const text = color.trim()\n  if (text.toLowerCase() === \"transparent\") return { r: 0, g: 0, b: 0, a: 0 }\n  const parsed = parseHex(text) ?? parseRgb(text) ?? parseHsl(text) ?? parseOklch(text)\n  if (!parsed) return null\n  return [parsed.r, parsed.g, parsed.b, parsed.a].some(Number.isNaN) ? null : parsed\n}\n\n/** WCAG relative luminance, 0 for black and 1 for white. */\nfunction relativeLuminance({ r, g, b }: Rgba) {\n  const linear = (channel: number) => {\n    const unit = channel / 255\n    return unit <= 0.04045 ? unit / 12.92 : ((unit + 0.055) / 1.055) ** 2.4\n  }\n  return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)\n}\n\nfunction contrastRatio(first: Rgba, second: Rgba) {\n  const a = relativeLuminance(first)\n  const b = relativeLuminance(second)\n  return (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)\n}\n\nfunction compositeOverChecker(color: Rgba): Rgba {\n  const mix = (top: number, bottom: number) => top * color.a + bottom * (1 - color.a)\n  return {\n    r: mix(color.r, CHECKER_AVERAGE.r),\n    g: mix(color.g, CHECKER_AVERAGE.g),\n    b: mix(color.b, CHECKER_AVERAGE.b),\n    a: 1,\n  }\n}\n\n/** The ink that reads best on this colour as it actually appears, transparency included. */\nfunction readableInk(color: Rgba) {\n  const surface = compositeOverChecker(color)\n  const onDark = contrastRatio(surface, parseHex(INK_LIGHT) as Rgba)\n  const onLight = contrastRatio(surface, parseHex(INK_DARK) as Rgba)\n  return onDark > onLight ? INK_LIGHT : INK_DARK\n}\n\n/** Conic stops rather than a tiled image: no asset to ship, and it stays sharp at any pixel density. */\nconst CHECKER_BACKGROUND = `repeating-conic-gradient(${CHECKER_DARK} 0% 25%, ${CHECKER_LIGHT} 0% 50%) 50% / 12px 12px`\n\nexport {\n  CHECKER_BACKGROUND,\n  INK_DARK,\n  INK_LIGHT,\n  compositeOverChecker,\n  contrastRatio,\n  parseColor,\n  readableInk,\n  relativeLuminance,\n  type Rgba,\n}\n",
      "type": "registry:ui"
    }
  ],
  "categories": [
    "display"
  ],
  "type": "registry:ui"
}