{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"color-picker","type":"registry:component","title":"Color picker","description":"A colour field with a real saturation surface, kinetic hue and opacity rails, typed hex, RGB or HSL, and swatches that stay in sync.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/color-picker.tsx","type":"registry:component","content":"// Hairline UI · color-picker · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { createPortal } from \"react-dom\";\nimport { Field, fieldSurface, useFieldIds, useShake } from \"./field\";\nimport { enterStyle, themeVars, useDismiss, useFloating, usePresence } from \"./floating\";\nimport { TextMorph } from \"./text-morph\";\nimport { EASE_OUT, EASE_THROW, INTERACTION_FOCUS, INTERACTION_PRESS, interactionIcon, useInteractionReducedMotion } from \"./ui-interaction-motion\";\nimport { colorCss, formatColor, parseColor, sameColor, type ColorFormat, type Hsla } from \"./color-picker-color\";\n\nexport type { ColorFormat } from \"./color-picker-color\";\n\nexport interface ColorPickerProps {\n  value?: string | null;\n  defaultValue?: string | null;\n  onValueChange?: (value: string | null) => void;\n  onValueCommit?: (value: string | null) => void;\n  format?: ColorFormat;\n  alpha?: boolean;\n  swatches?: readonly string[];\n  label?: React.ReactNode;\n  hint?: React.ReactNode;\n  error?: React.ReactNode;\n  disabled?: boolean;\n  name?: string;\n  id?: string;\n  className?: string;\n}\n\nconst FALLBACK: Hsla = { h: 224, s: 72, l: 53, a: 1 };\nconst FORMATS: ColorFormat[] = [\"hex\", \"rgb\", \"hsl\"];\nconst DEFAULT_SWATCHES = [\"#305DDE\", \"#7C3AED\", \"#DB2777\", \"#EA580C\", \"#059669\", \"#0891B2\"];\nconst clamp = (n: number, min: number, max: number) => Math.min(max, Math.max(min, n));\nconst areaTransform = (color: Hsla, size: { w: number; h: number }) => `translate3d(${(color.s / 100) * size.w}px, ${(1 - color.l / 100) * size.h}px, 0) translate(-50%, -50%)`;\nconst railTransform = (value: number, width: number) => `translate3d(${value * width}px, -50%, 0) translateX(-50%)`;\n/** Drawn under anything that can be see-through, so opacity reads as opacity. Theme tokens only. */\nconst CHECKER: React.CSSProperties = {\n  backgroundImage: \"repeating-conic-gradient(color-mix(in oklab, var(--foreground) 14%, transparent) 0 25%, transparent 0 50%)\",\n  backgroundSize: \"8px 8px\",\n  backgroundColor: \"var(--background)\",\n};\n\nfunction ClockwiseIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"size-3.5\">\n      <path d=\"m4.5 6 3.5 3 3.5-3\" stroke=\"currentColor\" strokeWidth=\"1.5\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nfunction CopyIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"size-3.5\">\n      <rect x=\"5.5\" y=\"5.5\" width=\"7\" height=\"7\" rx=\"1.5\" stroke=\"currentColor\" strokeWidth=\"1.35\" />\n      <path d=\"M10.5 3.5h-6a1 1 0 0 0-1 1v6\" stroke=\"currentColor\" strokeWidth=\"1.35\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nexport function ColorPicker({\n  value,\n  defaultValue = \"#305DDE\",\n  onValueChange,\n  onValueCommit,\n  format = \"hex\",\n  alpha = false,\n  swatches = DEFAULT_SWATCHES,\n  label,\n  hint,\n  error,\n  disabled,\n  name,\n  id,\n  className = \"\",\n}: ColorPickerProps) {\n  const reduced = useInteractionReducedMotion();\n  const ids = useFieldIds(id);\n  const [own, setOwn] = React.useState<string | null>(defaultValue);\n  const current = value !== undefined ? value : own;\n  const parsed = current ? parseColor(current) : null;\n  const [lastColor, setLastColor] = React.useState<Hsla>(() => parsed ?? FALLBACK);\n  const color = parsed ?? lastColor;\n  const [outputFormat, setOutputFormat] = React.useState<ColorFormat>(format);\n  const [seenFormat, setSeenFormat] = React.useState(format);\n  if (format !== seenFormat) {\n    setSeenFormat(format);\n    setOutputFormat(format);\n  }\n  const [open, setOpen] = React.useState(false);\n  const [draft, setDraft] = React.useState<string | null>(null);\n  const [badInput, setBadInput] = React.useState(false);\n  const [copyState, setCopyState] = React.useState<\"idle\" | \"copied\" | \"failed\">(\"idle\");\n  const [areaSize, setAreaSize] = React.useState({ w: 256, h: 144 });\n  const [railWidth, setRailWidth] = React.useState(224);\n  const anchor = React.useRef<HTMLDivElement>(null);\n  const surface = React.useRef<HTMLDivElement>(null);\n  const trigger = React.useRef<HTMLButtonElement>(null);\n  const area = React.useRef<HTMLDivElement>(null);\n  const areaThumb = React.useRef<HTMLSpanElement>(null);\n  const hueTrack = React.useRef<HTMLDivElement>(null);\n  const hueThumb = React.useRef<HTMLSpanElement>(null);\n  const alphaTrack = React.useRef<HTMLDivElement>(null);\n  const alphaThumb = React.useRef<HTMLSpanElement>(null);\n  const alphaFill = React.useRef<HTMLDivElement>(null);\n  const input = React.useRef<HTMLInputElement>(null);\n  const triggerSwatch = React.useRef<HTMLSpanElement>(null);\n  const previewSwatch = React.useRef<HTMLSpanElement>(null);\n  const gesture = React.useRef<\"area\" | \"hue\" | \"alpha\" | null>(null);\n  const latest = React.useRef(color);\n  const copyTimer = React.useRef(0);\n  // Thumbs glide to a colour picked from a swatch, the field or the keys, but follow a drag exactly; nothing glides\n  // until the panel's first frames are placed.\n  const settled = React.useRef(false);\n  const shakeRef = useShake<HTMLDivElement>(badInput);\n  const { mounted, shown } = usePresence(open, 180);\n  const place = useFloating({ open: mounted, anchor, floating: surface, side: \"bottom\", align: \"start\", offset: 6 });\n  const [vars, setVars] = React.useState<React.CSSProperties>({});\n\n  const text = current ? formatColor(color, outputFormat) : \"\";\n\n  const paint = React.useCallback(\n    (next: Hsla) => {\n      const glide = settled.current && !gesture.current && !reduced;\n      const move = `${glide ? `transform 420ms ${EASE_OUT}, ` : \"\"}scale 220ms ${EASE_THROW}`;\n      for (const thumb of [areaThumb.current, hueThumb.current, alphaThumb.current]) thumb?.style.setProperty(\"transition\", reduced ? \"none\" : move);\n      areaThumb.current?.style.setProperty(\"transform\", areaTransform(next, areaSize));\n      hueThumb.current?.style.setProperty(\"transform\", railTransform(next.h / 360, railWidth));\n      alphaThumb.current?.style.setProperty(\"transform\", railTransform(next.a, railWidth));\n      if (area.current) {\n        area.current.style.transition = glide ? `background-color 420ms ${EASE_OUT}` : \"none\";\n        area.current.style.backgroundColor = `hsl(${next.h} 100% 50%)`;\n      }\n      if (alphaFill.current) alphaFill.current.style.background = `linear-gradient(to right, transparent, hsl(${next.h} ${next.s}% ${next.l}%))`;\n      if (triggerSwatch.current) triggerSwatch.current.style.backgroundColor = colorCss(next);\n      if (previewSwatch.current) previewSwatch.current.style.backgroundColor = colorCss(next);\n      if (input.current && document.activeElement !== input.current) input.current.value = formatColor(next, outputFormat);\n    },\n    [areaSize, railWidth, outputFormat, reduced],\n  );\n\n  React.useLayoutEffect(() => {\n    latest.current = color;\n    if (mounted) paint(color);\n  }, [color, mounted, paint]);\n\n  React.useLayoutEffect(() => {\n    if (!mounted) return;\n    setVars(themeVars(anchor.current));\n    const measure = () => {\n      const box = area.current?.getBoundingClientRect();\n      if (box) setAreaSize((old) => (old.w === box.width && old.h === box.height ? old : { w: box.width, h: box.height }));\n      const width = hueTrack.current?.getBoundingClientRect().width;\n      if (width) setRailWidth((old) => (old === width ? old : width));\n    };\n    measure();\n    settled.current = false;\n    let frame = requestAnimationFrame(() => {\n      frame = requestAnimationFrame(() => {\n        settled.current = true;\n      });\n    });\n    const observer = new ResizeObserver(measure);\n    if (area.current) observer.observe(area.current);\n    if (hueTrack.current) observer.observe(hueTrack.current);\n    return () => {\n      cancelAnimationFrame(frame);\n      observer.disconnect();\n    };\n  }, [mounted, alpha]);\n\n  React.useEffect(() => () => window.clearTimeout(copyTimer.current), []);\n\n  const close = (refocus: boolean) => {\n    setOpen(false);\n    setDraft(null);\n    setBadInput(false);\n    if (refocus) trigger.current?.focus({ preventScroll: true });\n  };\n  useDismiss(open, (reason) => close(reason === \"escape\"), [anchor, surface]);\n\n  const emit = (next: Hsla | null) => {\n    const formatted = next ? formatColor(next, outputFormat) : null;\n    if (value === undefined) setOwn(formatted);\n    onValueChange?.(formatted);\n    return formatted;\n  };\n\n  const commit = (next: Hsla, notify = true) => {\n    const normalised = { ...next, a: alpha ? next.a : 1 };\n    latest.current = normalised;\n    setLastColor(normalised);\n    setCopyState(\"idle\");\n    const formatted = formatColor(normalised, outputFormat);\n    if (value === undefined) setOwn(formatted);\n    if (notify) onValueChange?.(formatted);\n    return formatted;\n  };\n\n  const changeFromPointer = (kind: \"area\" | \"hue\" | \"alpha\", e: React.PointerEvent<HTMLDivElement>) => {\n    const target = kind === \"area\" ? area.current : kind === \"hue\" ? hueTrack.current : alphaTrack.current;\n    if (!target) return;\n    const rect = target.getBoundingClientRect();\n    const old = latest.current;\n    let next: Hsla;\n    if (kind === \"area\") {\n      next = { ...old, s: clamp(((e.clientX - rect.left) / rect.width) * 100, 0, 100), l: clamp(100 - ((e.clientY - rect.top) / rect.height) * 100, 0, 100), a: alpha ? old.a : 1 };\n    } else if (kind === \"hue\") {\n      next = { ...old, h: clamp(((e.clientX - rect.left) / rect.width) * 360, 0, 359.999), a: alpha ? old.a : 1 };\n    } else {\n      next = { ...old, a: clamp((e.clientX - rect.left) / rect.width, 0, 1) };\n    }\n    latest.current = next;\n    paint(next);\n    onValueChange?.(formatColor(next, outputFormat));\n  };\n\n  const begin = (kind: \"area\" | \"hue\" | \"alpha\", e: React.PointerEvent<HTMLDivElement>) => {\n    if (disabled || e.button !== 0) return;\n    gesture.current = kind;\n    const held = kind === \"area\" ? areaThumb.current : kind === \"hue\" ? hueThumb.current : alphaThumb.current;\n    held?.style.setProperty(\"scale\", \"1.25\");\n    e.currentTarget.setPointerCapture(e.pointerId);\n    changeFromPointer(kind, e);\n  };\n\n  const end = () => {\n    if (!gesture.current) return;\n    for (const thumb of [areaThumb.current, hueThumb.current, alphaThumb.current]) thumb?.style.setProperty(\"scale\", \"1\");\n    gesture.current = null;\n    const formatted = commit(latest.current, false);\n    onValueCommit?.(formatted);\n  };\n\n  const keyAdjust = (kind: \"area\" | \"hue\" | \"alpha\", e: React.KeyboardEvent<HTMLDivElement>) => {\n    const old = latest.current;\n    let next = { ...old };\n    const direction = e.key === \"ArrowRight\" || e.key === \"ArrowUp\" ? 1 : e.key === \"ArrowLeft\" || e.key === \"ArrowDown\" ? -1 : 0;\n    if (kind === \"area\") {\n      if (e.key === \"ArrowLeft\" || e.key === \"ArrowRight\") next.s = clamp(old.s + direction * 2, 0, 100);\n      else if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") next.l = clamp(old.l + direction * 2, 0, 100);\n      else if (e.key === \"PageUp\" || e.key === \"PageDown\") next.l = clamp(old.l + (e.key === \"PageUp\" ? 10 : -10), 0, 100);\n      else if (e.key === \"Home\") next = { ...old, s: 0, l: 100 };\n      else if (e.key === \"End\") next = { ...old, s: 100, l: 0 };\n      else return;\n    } else if (kind === \"hue\") {\n      if (direction) next.h = (old.h + direction * (e.shiftKey ? 15 : 2) + 360) % 360;\n      else if (e.key === \"Home\") next.h = 0;\n      else if (e.key === \"End\") next.h = 359;\n      else return;\n    } else {\n      if (direction) next.a = clamp(old.a + direction * (e.shiftKey ? 0.1 : 0.02), 0, 1);\n      else if (e.key === \"Home\") next.a = 0;\n      else if (e.key === \"End\") next.a = 1;\n      else return;\n    }\n    e.preventDefault();\n    const formatted = commit(next);\n    onValueCommit?.(formatted);\n  };\n\n  const settle = () => {\n    if (draft === null) return;\n    const next = parseColor(draft);\n    if (!next) {\n      setBadInput(true);\n      return;\n    }\n    setBadInput(false);\n    setDraft(null);\n    const formatted = commit(next);\n    onValueCommit?.(formatted);\n  };\n\n  const cycleFormat = () => {\n    const next = FORMATS[(FORMATS.indexOf(outputFormat) + 1) % FORMATS.length];\n    setOutputFormat(next);\n    if (current) {\n      const formatted = formatColor(color, next);\n      if (value === undefined) setOwn(formatted);\n      onValueChange?.(formatted);\n    }\n  };\n\n  const copy = async () => {\n    if (!text) return;\n    window.clearTimeout(copyTimer.current);\n    try {\n      await navigator.clipboard.writeText(text);\n      setCopyState(\"copied\");\n    } catch {\n      setCopyState(\"failed\");\n    }\n    copyTimer.current = window.setTimeout(() => setCopyState(\"idle\"), 1600);\n  };\n\n  const describedBy = [hint && !error ? ids.hint : null, error ? ids.error : null].filter(Boolean).join(\" \") || undefined;\n  const copyLabel = copyState === \"copied\" ? \"Copied\" : copyState === \"failed\" ? \"Failed\" : \"Copy\";\n\n  return (\n    <Field id={ids.id} label={label} hint={hint} error={error} className={className}>\n      <div ref={anchor}>\n        <button\n          ref={trigger}\n          id={ids.id}\n          type=\"button\"\n          disabled={disabled}\n          aria-haspopup=\"dialog\"\n          aria-expanded={open}\n          aria-describedby={describedBy}\n          onClick={() => (open ? close(false) : setOpen(true))}\n          className={`${fieldSurface({ invalid: !!error, disabled })} h-9 cursor-pointer gap-2.5 px-3 text-left text-[16px] sm:text-[13.5px] ${INTERACTION_FOCUS}`}\n        >\n          <span className=\"relative flex size-5 shrink-0 overflow-hidden rounded-full\" style={CHECKER}>\n            <span ref={triggerSwatch} className=\"size-full transition-[background-color] duration-300\" style={{ backgroundColor: current ? colorCss(color) : \"transparent\" }} />\n            <span aria-hidden=\"true\" className=\"absolute inset-0 rounded-full shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_12%,transparent)]\" />\n          </span>\n          <span className=\"min-w-0 flex-1 truncate font-mono text-[12.5px]\">\n            <TextMorph animateWidth={false}>{text || \"Choose a colour\"}</TextMorph>\n          </span>\n          <span className=\"text-muted-foreground transition-transform duration-300\" style={{ transform: open ? \"rotate(180deg)\" : \"none\" }}>\n            <ClockwiseIcon />\n          </span>\n        </button>\n      </div>\n      {name && <input type=\"hidden\" name={name} value={current ?? \"\"} />}\n      {mounted &&\n        createPortal(\n          <div\n            ref={surface}\n            role=\"dialog\"\n            aria-label=\"Choose a colour\"\n            className=\"fixed left-0 top-0 z-[55] w-[280px] max-w-[calc(100vw-16px)] rounded-[18px] bg-popover p-3 text-popover-foreground shadow-[0_0_0_1px_var(--border)]\"\n            style={{ ...vars, left: place.x, top: place.y, transformOrigin: place.origin, ...enterStyle(shown, place.side, reduced) }}\n          >\n            <div\n              ref={area}\n              role=\"slider\"\n              tabIndex={0}\n              aria-label=\"Saturation and lightness\"\n              aria-valuemin={0}\n              aria-valuemax={100}\n              aria-valuenow={Math.round(color.l)}\n              aria-valuetext={`${Math.round(color.s)}% saturation, ${Math.round(color.l)}% lightness`}\n              onPointerDown={(e) => begin(\"area\", e)}\n              onPointerMove={(e) => gesture.current === \"area\" && changeFromPointer(\"area\", e)}\n              onPointerUp={end}\n              onPointerCancel={end}\n              onLostPointerCapture={end}\n              onKeyDown={(e) => keyAdjust(\"area\", e)}\n              className=\"relative h-36 w-full cursor-crosshair touch-none rounded-[12px] bg-[linear-gradient(to_top,#000,transparent),linear-gradient(to_right,#fff,transparent)] shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_10%,transparent)] outline-none focus-visible:shadow-[inset_0_0_0_2px_var(--ring)]\"\n              style={{ backgroundColor: `hsl(${color.h} 100% 50%)` }}\n            >\n              <span\n                ref={areaThumb}\n                aria-hidden=\"true\"\n                className=\"pointer-events-none absolute left-0 top-0 size-4 rounded-full border border-white shadow-[0_0_0_1px_rgb(0_0_0/0.35)]\"\n                style={{ transform: areaTransform(color, areaSize) }}\n              />\n            </div>\n\n            <div className=\"mt-3 flex items-center gap-3\">\n              <span className=\"relative flex size-9 shrink-0 overflow-hidden rounded-full\" style={CHECKER}>\n                <span ref={previewSwatch} className=\"size-full\" style={{ backgroundColor: colorCss(color) }} />\n                <span aria-hidden=\"true\" className=\"absolute inset-0 rounded-full shadow-[inset_0_0_0_1px_var(--border)]\" />\n              </span>\n              <div className=\"min-w-0 flex-1\">\n                <div\n                  ref={hueTrack}\n                  role=\"slider\"\n                  tabIndex={0}\n                  aria-label=\"Hue\"\n                  aria-valuemin={0}\n                  aria-valuemax={359}\n                  aria-valuenow={Math.round(color.h)}\n                  onPointerDown={(e) => begin(\"hue\", e)}\n                  onPointerMove={(e) => gesture.current === \"hue\" && changeFromPointer(\"hue\", e)}\n                  onPointerUp={end}\n                  onPointerCancel={end}\n                  onLostPointerCapture={end}\n                  onKeyDown={(e) => keyAdjust(\"hue\", e)}\n                  className={`relative h-4 cursor-ew-resize touch-pan-y rounded-full outline-none ${INTERACTION_FOCUS}`}\n                >\n                  <div aria-hidden=\"true\" className=\"absolute inset-x-0 top-1/2 h-2 -translate-y-1/2 rounded-full bg-[linear-gradient(to_right,#f00,#ff0,#0f0,#0ff,#00f,#f0f,#f00)]\" />\n                  <span ref={hueThumb} aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-1/2 size-4 rounded-full bg-background shadow-[0_0_0_1px_color-mix(in_oklab,var(--foreground)_35%,var(--border))]\" style={{ transform: railTransform(color.h / 360, railWidth) }} />\n                </div>\n                {alpha && (\n                  <div\n                    ref={alphaTrack}\n                    role=\"slider\"\n                    tabIndex={0}\n                    aria-label=\"Opacity\"\n                    aria-valuemin={0}\n                    aria-valuemax={100}\n                    aria-valuenow={Math.round(color.a * 100)}\n                    onPointerDown={(e) => begin(\"alpha\", e)}\n                    onPointerMove={(e) => gesture.current === \"alpha\" && changeFromPointer(\"alpha\", e)}\n                    onPointerUp={end}\n                    onPointerCancel={end}\n                    onLostPointerCapture={end}\n                    onKeyDown={(e) => keyAdjust(\"alpha\", e)}\n                    className={`relative mt-2 h-4 cursor-ew-resize touch-pan-y rounded-full outline-none ${INTERACTION_FOCUS}`}\n                  >\n                    <div aria-hidden=\"true\" className=\"absolute inset-x-0 top-1/2 h-2 -translate-y-1/2 overflow-hidden rounded-full\" style={CHECKER}>\n                      <div ref={alphaFill} className=\"size-full\" style={{ background: `linear-gradient(to right, transparent, hsl(${color.h} ${color.s}% ${color.l}%))` }} />\n                      <div className=\"absolute inset-0 rounded-full shadow-[inset_0_0_0_1px_var(--border)]\" />\n                    </div>\n                    <span ref={alphaThumb} aria-hidden=\"true\" className=\"pointer-events-none absolute left-0 top-1/2 size-4 rounded-full bg-background shadow-[0_0_0_1px_color-mix(in_oklab,var(--foreground)_35%,var(--border))]\" style={{ transform: railTransform(color.a, railWidth) }} />\n                  </div>\n                )}\n              </div>\n            </div>\n\n            <div ref={shakeRef} className=\"mt-3 flex h-8 items-center rounded-full bg-background shadow-[inset_0_0_0_1px_var(--border)] focus-within:shadow-[inset_0_0_0_1px_var(--ring),0_0_0_3px_color-mix(in_oklab,var(--ring)_16%,transparent)]\">\n              <input\n                ref={input}\n                value={draft ?? text}\n                placeholder=\"#305DDE\"\n                aria-label=\"Colour value\"\n                aria-invalid={badInput || undefined}\n                onChange={(e) => {\n                  setDraft(e.target.value);\n                  setBadInput(false);\n                }}\n                onBlur={settle}\n                onKeyDown={(e) => {\n                  if (e.key === \"Enter\") {\n                    e.preventDefault();\n                    settle();\n                  }\n                }}\n                className=\"h-full min-w-0 flex-1 bg-transparent pl-3 font-mono text-[12px] uppercase outline-none placeholder:text-muted-foreground/60\"\n              />\n              <button type=\"button\" onClick={cycleFormat} className={`h-6 shrink-0 rounded-full px-2 font-mono text-[10.5px] uppercase text-muted-foreground cursor-pointer hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}>\n                {outputFormat}\n              </button>\n              <button type=\"button\" onClick={copy} disabled={!text} aria-label={copyLabel} className={`mr-1 flex h-6 min-w-6 shrink-0 items-center justify-center gap-1 rounded-full px-1.5 text-[11px] text-muted-foreground cursor-pointer hover:bg-accent hover:text-foreground disabled:cursor-default disabled:opacity-40 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}>\n                <span aria-hidden=\"true\" className=\"relative flex size-3.5 items-center justify-center\">\n                  <span className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(copyState !== \"copied\", reduced)}>\n                    <CopyIcon />\n                  </span>\n                  <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"absolute size-3.5\">\n                    <path\n                      d=\"m3.75 8.25 2.75 2.75 5.75-6\"\n                      stroke=\"currentColor\"\n                      strokeWidth=\"1.6\"\n                      strokeLinecap=\"round\"\n                      strokeLinejoin=\"round\"\n                      pathLength={1}\n                      strokeDasharray={1}\n                      style={{ strokeDashoffset: copyState === \"copied\" ? 0 : 1, transition: reduced ? \"none\" : `stroke-dashoffset ${copyState === \"copied\" ? 360 : 120}ms ${EASE_OUT}` }}\n                    />\n                  </svg>\n                </span>\n                <TextMorph>{copyLabel}</TextMorph>\n              </button>\n            </div>\n            <div className=\"grid\" style={{ gridTemplateRows: badInput ? \"1fr\" : \"0fr\", transition: reduced ? \"none\" : `grid-template-rows 280ms ${EASE_OUT}` }}>\n              <p className=\"min-h-0 overflow-hidden pt-1.5 text-[11.5px] text-red-600 dark:text-red-400\">Use hex, RGB or HSL, for example #305DDE.</p>\n            </div>\n\n            {swatches.length > 0 && (\n              <div className=\"mt-3 flex flex-wrap gap-2 border-t border-border pt-3\">\n                {swatches.map((swatch) => {\n                  const parsedSwatch = parseColor(swatch);\n                  if (!parsedSwatch) return null;\n                  const active = sameColor(parsedSwatch, color);\n                  return (\n                    <button\n                      key={swatch}\n                      type=\"button\"\n                      aria-label={`Use ${swatch}`}\n                      aria-pressed={active}\n                      onClick={() => {\n                        const formatted = commit(parsedSwatch);\n                        onValueCommit?.(formatted);\n                      }}\n                      className={`relative flex size-6 cursor-pointer items-center justify-center rounded-full bg-muted ${INTERACTION_FOCUS}`}\n                      style={{ transition: reduced ? \"none\" : `transform 300ms ${EASE_THROW}`, transform: active ? \"scale(1.12)\" : \"scale(1)\" }}\n                    >\n                      <span className=\"size-5 rounded-full shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_12%,transparent)]\" style={{ backgroundColor: swatch }} />\n                      <span\n                        className=\"absolute size-7 rounded-full shadow-[0_0_0_1px_var(--ring)]\"\n                        aria-hidden=\"true\"\n                        style={{ opacity: active ? 1 : 0, scale: active ? \"1\" : \"0.7\", transition: reduced ? \"none\" : `opacity 220ms ${EASE_OUT}, scale 320ms ${EASE_THROW}` }}\n                      />\n                    </button>\n                  );\n                })}\n                {current && (\n                  <button\n                    type=\"button\"\n                    onClick={() => {\n                      emit(null);\n                      onValueCommit?.(null);\n                      setDraft(null);\n                    }}\n                    className={`ml-auto h-7 rounded-full px-2 text-[11.5px] text-muted-foreground cursor-pointer hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    Clear\n                  </button>\n                )}\n              </div>\n            )}\n          </div>,\n          document.body,\n        )}\n    </Field>\n  );\n}\n\nexport { parseColor } from \"./color-picker-color\";\nexport default ColorPicker;\n"},{"path":"registry/color-picker-color.ts","type":"registry:component","content":"// Hairline UI · color-picker · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\nexport type ColorFormat = \"hex\" | \"rgb\" | \"hsl\";\n\nexport interface Hsla {\n  h: number;\n  s: number;\n  l: number;\n  a: number;\n}\n\nconst clamp = (n: number, min = 0, max = 1) => Math.min(max, Math.max(min, n));\nconst hue = (n: number) => ((n % 360) + 360) % 360;\nconst byte = (n: number) => Math.round(clamp(n, 0, 255)).toString(16).padStart(2, \"0\");\n\nexport function hslaToRgba({ h, s, l, a }: Hsla) {\n  const sat = clamp(s, 0, 100) / 100;\n  const light = clamp(l, 0, 100) / 100;\n  const chroma = (1 - Math.abs(2 * light - 1)) * sat;\n  const part = chroma * (1 - Math.abs(((hue(h) / 60) % 2) - 1));\n  const match = light - chroma / 2;\n  const sector = Math.floor(hue(h) / 60) % 6;\n  const rgb = [\n    [chroma, part, 0],\n    [part, chroma, 0],\n    [0, chroma, part],\n    [0, part, chroma],\n    [part, 0, chroma],\n    [chroma, 0, part],\n  ][sector];\n  return { r: Math.round((rgb[0] + match) * 255), g: Math.round((rgb[1] + match) * 255), b: Math.round((rgb[2] + match) * 255), a: clamp(a) };\n}\n\nexport function rgbaToHsla(r: number, g: number, b: number, a = 1): Hsla {\n  const red = clamp(r, 0, 255) / 255;\n  const green = clamp(g, 0, 255) / 255;\n  const blue = clamp(b, 0, 255) / 255;\n  const max = Math.max(red, green, blue);\n  const min = Math.min(red, green, blue);\n  const delta = max - min;\n  let h = 0;\n  if (delta) {\n    if (max === red) h = 60 * (((green - blue) / delta) % 6);\n    else if (max === green) h = 60 * ((blue - red) / delta + 2);\n    else h = 60 * ((red - green) / delta + 4);\n  }\n  const l = (max + min) / 2;\n  const s = delta ? delta / (1 - Math.abs(2 * l - 1)) : 0;\n  return { h: hue(h), s: s * 100, l: l * 100, a: clamp(a) };\n}\n\nfunction alpha(input: string | undefined) {\n  if (input === undefined) return 1;\n  return input.endsWith(\"%\") ? clamp(Number.parseFloat(input) / 100) : clamp(Number.parseFloat(input));\n}\n\nfunction channel(input: string) {\n  const n = input.endsWith(\"%\") ? (Number.parseFloat(input) / 100) * 255 : Number.parseFloat(input);\n  return Number.isFinite(n) ? clamp(n, 0, 255) : null;\n}\n\n/** Reads hex, rgb/rgba and hsl/hsla, including modern space-separated syntax. */\nexport function parseColor(input: string): Hsla | null {\n  const text = input.trim().toLowerCase();\n  const hex = text.match(/^#?([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i);\n  if (hex) {\n    let value = hex[1];\n    if (value.length < 6) value = [...value].map((c) => c + c).join(\"\");\n    const a = value.length === 8 ? Number.parseInt(value.slice(6), 16) / 255 : 1;\n    return rgbaToHsla(Number.parseInt(value.slice(0, 2), 16), Number.parseInt(value.slice(2, 4), 16), Number.parseInt(value.slice(4, 6), 16), a);\n  }\n\n  const functional = text.match(/^(rgba?|hsla?)\\(\\s*([^)]+)\\s*\\)$/);\n  if (!functional) return null;\n  const body = functional[2].replace(/\\s*[,/]\\s*/g, \" \").trim();\n  const parts = body.split(/\\s+/);\n  if (parts.length < 3 || parts.length > 4 || parts.some((p) => p === \"\")) return null;\n  const a = alpha(parts[3]);\n  if (!Number.isFinite(a)) return null;\n\n  if (functional[1].startsWith(\"rgb\")) {\n    const channels = parts.slice(0, 3).map(channel);\n    if (channels.some((n) => n === null)) return null;\n    return rgbaToHsla(channels[0]!, channels[1]!, channels[2]!, a);\n  }\n\n  const h = Number.parseFloat(parts[0]);\n  const s = Number.parseFloat(parts[1]);\n  const l = Number.parseFloat(parts[2]);\n  if (!Number.isFinite(h) || !parts[1].endsWith(\"%\") || !parts[2].endsWith(\"%\") || !Number.isFinite(s) || !Number.isFinite(l)) return null;\n  return { h: hue(h), s: clamp(s, 0, 100), l: clamp(l, 0, 100), a };\n}\n\nexport function formatColor(color: Hsla, format: ColorFormat): string {\n  const { r, g, b, a } = hslaToRgba(color);\n  if (format === \"rgb\") return `rgb(${r} ${g} ${b}${a < 0.999 ? ` / ${Math.round(a * 100)}%` : \"\"})`;\n  if (format === \"hsl\") {\n    const h = Math.round(color.h);\n    const s = Math.round(color.s);\n    const l = Math.round(color.l);\n    return `hsl(${h} ${s}% ${l}%${a < 0.999 ? ` / ${Math.round(a * 100)}%` : \"\"})`;\n  }\n  return `#${byte(r)}${byte(g)}${byte(b)}${a < 0.999 ? byte(a * 255) : \"\"}`.toUpperCase();\n}\n\nexport function colorCss(color: Hsla) {\n  return `hsl(${color.h.toFixed(2)} ${color.s.toFixed(2)}% ${color.l.toFixed(2)}% / ${color.a.toFixed(3)})`;\n}\n\nexport function sameColor(a: Hsla, b: Hsla) {\n  const left = hslaToRgba(a);\n  const right = hslaToRgba(b);\n  return left.r === right.r && left.g === right.g && left.b === right.b && Math.abs(left.a - right.a) < 0.004;\n}\n"},{"path":"registry/field.tsx","type":"registry:component","content":"// Hairline UI · color-picker · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { EASE_OUT, useInteractionReducedMotion } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * FIELD: the column every text control sits in\n *\n *   label    above, with an optional aside on the right (a count)\n *   hint     under the control while all is well\n *   error    takes the hint's place: the hint folds away, the\n *            error rises in out of a blur, the control shakes once\n *\n * Shared by input, textarea, password, search and select so the\n * whole family has one surface, one focus ring and one error.\n * ───────────────────────────────────────────────────────── */\n\nexport interface FieldProps {\n  id: string;\n  label?: React.ReactNode;\n  /** Right side of the label row, e.g. a character count. */\n  aside?: React.ReactNode;\n  hint?: React.ReactNode;\n  error?: React.ReactNode;\n  required?: boolean;\n  className?: string;\n  children: React.ReactNode;\n}\n\nexport type FieldSize = \"sm\" | \"md\";\n\n/** The surface of a text control: a hairline that darkens on hover and turns to the ring on focus. */\nexport function fieldSurface({ invalid, disabled, round = true }: { invalid?: boolean; disabled?: boolean; round?: boolean }) {\n  const ring = invalid\n    ? \"shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-red-500)_55%,transparent)] focus-within:shadow-[inset_0_0_0_1px_var(--color-red-500),0_0_0_3px_color-mix(in_oklab,var(--color-red-500)_14%,transparent)]\"\n    : \"shadow-[inset_0_0_0_1px_var(--border)] [&:not(:focus-within)]:hover:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_24%,var(--border))] focus-within:shadow-[inset_0_0_0_1px_var(--ring),0_0_0_3px_color-mix(in_oklab,var(--ring)_16%,transparent)]\";\n  return `relative flex w-full items-center bg-background text-foreground transition-[box-shadow,background-color,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] ${round ? \"rounded-full\" : \"rounded-[14px]\"} ${ring} ${\n    disabled ? \"pointer-events-none opacity-50\" : \"\"\n  }`;\n}\n\n/** ids for the control's label, hint and error. */\nexport function useFieldIds(id?: string) {\n  const auto = React.useId();\n  const base = id ?? auto;\n  return { id: base, hint: `${base}-hint`, error: `${base}-error` };\n}\n\n/** One short shake whenever `on` turns true (an error arrives). */\nexport function useShake<T extends HTMLElement>(on: boolean) {\n  const ref = React.useRef<T>(null);\n  const reduced = useInteractionReducedMotion();\n  React.useEffect(() => {\n    if (!on || reduced) return;\n    ref.current?.animate(\n      [{ transform: \"none\" }, { transform: \"translateX(-4px)\" }, { transform: \"translateX(4px)\" }, { transform: \"translateX(-2px)\" }, { transform: \"none\" }],\n      { duration: 380, easing: \"ease-out\" },\n    );\n  }, [on, reduced]);\n  return ref;\n}\n\n/** Sets a native input's value so React's onChange still fires (clear buttons, pickers). */\nexport function setNativeValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {\n  const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;\n  Object.getOwnPropertyDescriptor(proto, \"value\")?.set?.call(el, value);\n  el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n}\n\n/** A line under the control that folds open and closed; keeps its last words while closing. */\nfunction Line({ show, children, id, tone, reduced }: { show: boolean; children: React.ReactNode; id: string; tone: string; reduced: boolean }) {\n  const [kept, setKept] = React.useState(children);\n  if (show && children !== kept) setKept(children);\n  return (\n    <div\n      className=\"grid\"\n      style={{ gridTemplateRows: show ? \"1fr\" : \"0fr\", transition: reduced ? \"none\" : `grid-template-rows 320ms ${EASE_OUT}` }}\n    >\n      <div className=\"min-h-0 overflow-hidden\">\n        <p\n          id={id}\n          className={`pt-1.5 pl-3 text-[12.5px] leading-snug ${tone}`}\n          style={{\n            opacity: show ? 1 : 0,\n            filter: show ? \"blur(0px)\" : \"blur(4px)\",\n            transform: show ? \"none\" : \"translateY(-4px)\",\n            transition: reduced ? \"none\" : show ? `opacity 280ms ${EASE_OUT} 60ms, filter 280ms ${EASE_OUT} 60ms, transform 380ms ${EASE_OUT}` : `opacity 140ms ${EASE_OUT}, filter 140ms ${EASE_OUT}, transform 200ms ${EASE_OUT}`,\n          }}\n        >\n          {show ? children : kept}\n        </p>\n      </div>\n    </div>\n  );\n}\n\nexport function Field({ id, label, aside, hint, error, required, className = \"\", children }: FieldProps) {\n  const reduced = useInteractionReducedMotion();\n  const ids = { hint: `${id}-hint`, error: `${id}-error` };\n  return (\n    <div className={`flex w-full flex-col ${className}`}>\n      {(label || aside) && (\n        <div className=\"flex items-baseline justify-between gap-3 px-3 pb-1.5\">\n          {label && (\n            <label htmlFor={id} className=\"text-[13px] font-medium text-foreground\">\n              {label}\n              {required && (\n                <span aria-hidden=\"true\" className=\"ml-0.5 text-muted-foreground\">\n                  *\n                </span>\n              )}\n            </label>\n          )}\n          {aside && <span className=\"text-[12px] tabular-nums text-muted-foreground\">{aside}</span>}\n        </div>\n      )}\n      {children}\n      <Line show={!error && !!hint} id={ids.hint} tone=\"text-muted-foreground\" reduced={reduced}>\n        {hint}\n      </Line>\n      <Line show={!!error} id={ids.error} tone=\"text-red-600 dark:text-red-400\" reduced={reduced}>\n        {error}\n      </Line>\n    </div>\n  );\n}\n\nexport default Field;\n"},{"path":"registry/floating.ts","type":"registry:component","content":"// Hairline UI · color-picker · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\n\n/* ─────────────────────────────────────────────────────────\n * FLOATING: what every popover, menu and tooltip shares\n *\n *   place     beside an anchor on a side, lined up start, centre\n *             or end; flips to the other side when it doesn't fit\n *             and shifts to stay `padding` inside the viewport;\n *             follows scroll and resize\n *   presence  mounts on open, shows a frame later (so the entry\n *             transitions run), hides, then unmounts after `exit`\n *   dismiss   Escape and a press outside both close it\n *   theme     the portal carries the anchor's theme tokens, so a\n *             light specimen on a dark page stays light\n * ───────────────────────────────────────────────────────── */\n\nexport type Side = \"top\" | \"bottom\" | \"left\" | \"right\";\nexport type Align = \"start\" | \"center\" | \"end\";\n\nconst TOKENS = [\"--background\", \"--foreground\", \"--popover\", \"--popover-foreground\", \"--border\", \"--accent\", \"--accent-foreground\", \"--primary\", \"--primary-foreground\", \"--muted\", \"--muted-foreground\", \"--ring\", \"--card\"];\n\n/** The anchor's theme tokens as inline styles for something portalled out of its tree. */\nexport function themeVars(anchor: Element | null): React.CSSProperties {\n  if (!anchor) return {};\n  const style = getComputedStyle(anchor);\n  const vars: Record<string, string> = {};\n  for (const t of TOKENS) {\n    const v = style.getPropertyValue(t);\n    if (v) vars[t] = v;\n  }\n  return vars as React.CSSProperties;\n}\n\nconst OPPOSITE: Record<Side, Side> = { top: \"bottom\", bottom: \"top\", left: \"right\", right: \"left\" };\n\nexport interface Placement {\n  x: number;\n  y: number;\n  side: Side;\n  /** Where the surface grows from, for transform-origin. */\n  origin: string;\n  ready: boolean;\n}\n\n/** Positions `floating` (position: fixed) next to `anchor` while `open`. Pass a point instead of an anchor for context menus. */\nexport function useFloating({\n  open,\n  anchor,\n  point,\n  floating,\n  side = \"bottom\",\n  align = \"center\",\n  offset = 8,\n  padding = 8,\n}: {\n  open: boolean;\n  anchor?: React.RefObject<Element | null>;\n  point?: { x: number; y: number } | null;\n  floating: React.RefObject<HTMLElement | null>;\n  side?: Side;\n  align?: Align;\n  offset?: number;\n  padding?: number;\n}): Placement {\n  const [place, setPlace] = React.useState<Placement>({ x: -9999, y: -9999, side, origin: \"center\", ready: false });\n\n  React.useLayoutEffect(() => {\n    if (!open) return;\n    let frame = 0;\n    const measure = () => {\n      const el = floating.current;\n      if (!el) return;\n      const a = point\n        ? { left: point.x, right: point.x, top: point.y, bottom: point.y, width: 0, height: 0 }\n        : anchor?.current?.getBoundingClientRect();\n      if (!a) return;\n      const w = el.offsetWidth;\n      const h = el.offsetHeight;\n      const vw = window.innerWidth;\n      const vh = window.innerHeight;\n      const room: Record<Side, number> = { top: a.top - padding, bottom: vh - a.bottom - padding, left: a.left - padding, right: vw - a.right - padding };\n      const need = side === \"top\" || side === \"bottom\" ? h + offset : w + offset;\n      const s = room[side] < need && room[OPPOSITE[side]] > room[side] ? OPPOSITE[side] : side;\n      let x: number;\n      let y: number;\n      if (s === \"top\" || s === \"bottom\") {\n        y = s === \"bottom\" ? a.bottom + offset : a.top - offset - h;\n        x = align === \"start\" ? a.left : align === \"end\" ? a.right - w : a.left + a.width / 2 - w / 2;\n        if (point) x = a.left;\n      } else {\n        x = s === \"right\" ? a.right + offset : a.left - offset - w;\n        y = align === \"start\" ? a.top : align === \"end\" ? a.bottom - h : a.top + a.height / 2 - h / 2;\n      }\n      x = Math.max(padding, Math.min(vw - padding - w, x));\n      y = Math.max(padding, Math.min(vh - padding - h, y));\n      // Grow from the point on the anchor's edge nearest the surface.\n      const ox = s === \"left\" ? \"100%\" : s === \"right\" ? \"0%\" : `${Math.max(0, Math.min(w, a.left + a.width / 2 - x))}px`;\n      const oy = s === \"top\" ? \"100%\" : s === \"bottom\" ? \"0%\" : `${Math.max(0, Math.min(h, a.top + a.height / 2 - y))}px`;\n      const next = { x: Math.round(x), y: Math.round(y), side: s, origin: `${ox} ${oy}`, ready: true };\n      setPlace((p) => (p.x === next.x && p.y === next.y && p.side === next.side && p.origin === next.origin && p.ready ? p : next));\n    };\n    const schedule = () => {\n      cancelAnimationFrame(frame);\n      frame = requestAnimationFrame(measure);\n    };\n    measure();\n    const ro = new ResizeObserver(schedule);\n    if (floating.current) ro.observe(floating.current);\n    window.addEventListener(\"scroll\", schedule, { capture: true, passive: true });\n    window.addEventListener(\"resize\", schedule);\n    return () => {\n      cancelAnimationFrame(frame);\n      ro.disconnect();\n      window.removeEventListener(\"scroll\", schedule, { capture: true });\n      window.removeEventListener(\"resize\", schedule);\n    };\n  }, [open, anchor, point, floating, side, align, offset, padding]);\n\n  return open ? place : { ...place, ready: false };\n}\n\n/** Mount → show next frame → hide → unmount after `exit` ms. */\nexport function usePresence(open: boolean, exit = 160) {\n  const [mounted, setMounted] = React.useState(open);\n  const [shown, setShown] = React.useState(false);\n  if (open && !mounted) setMounted(true);\n  React.useEffect(() => {\n    if (open) {\n      let inner = 0;\n      const outer = requestAnimationFrame(() => {\n        inner = requestAnimationFrame(() => setShown(true));\n      });\n      return () => {\n        cancelAnimationFrame(outer);\n        cancelAnimationFrame(inner);\n      };\n    }\n    const timer = window.setTimeout(() => {\n      setMounted(false);\n      setShown(false);\n    }, exit);\n    return () => window.clearTimeout(timer);\n  }, [open, exit]);\n  return { mounted: mounted || open, shown: open && shown };\n}\n\n/** Escape and presses outside `refs` call onDismiss while `open`. */\nexport function useDismiss(open: boolean, onDismiss: (reason: \"escape\" | \"outside\") => void, refs: React.RefObject<Element | null>[]) {\n  const latest = React.useRef({ onDismiss, refs });\n  React.useEffect(() => {\n    latest.current = { onDismiss, refs };\n  });\n  React.useEffect(() => {\n    if (!open) return;\n    const onKey = (e: KeyboardEvent) => {\n      if (e.key !== \"Escape\") return;\n      e.stopPropagation();\n      latest.current.onDismiss(\"escape\");\n    };\n    const onDown = (e: PointerEvent) => {\n      const target = e.target as Node;\n      if (latest.current.refs.some((r) => r.current?.contains(target))) return;\n      latest.current.onDismiss(\"outside\");\n    };\n    document.addEventListener(\"keydown\", onKey);\n    document.addEventListener(\"pointerdown\", onDown, true);\n    return () => {\n      document.removeEventListener(\"keydown\", onKey);\n      document.removeEventListener(\"pointerdown\", onDown, true);\n    };\n  }, [open]);\n}\n\n/** The entry pose for a surface on `side`: it comes 6px from the anchor, 0.96 and blurred. */\nexport function enterStyle(shown: boolean, side: Side, reduced: boolean, ease = \"cubic-bezier(0.16,1,0.3,1)\"): React.CSSProperties {\n  const d = 6;\n  const shift = side === \"top\" ? `0 ${d}px` : side === \"bottom\" ? `0 -${d}px` : side === \"left\" ? `${d}px 0` : `-${d}px 0`;\n  return {\n    opacity: shown ? 1 : 0,\n    translate: shown || reduced ? \"0 0\" : shift,\n    scale: shown || reduced ? \"1\" : \"0.96\",\n    filter: shown || reduced ? \"blur(0px)\" : \"blur(4px)\",\n    transition: reduced\n      ? \"opacity 120ms ease-out\"\n      : shown\n        ? `opacity 220ms ${ease}, translate 320ms ${ease}, scale 320ms ${ease}, filter 220ms ${ease}`\n        : `opacity 140ms ${ease}, translate 180ms ${ease}, scale 180ms ${ease}, filter 140ms ${ease}`,\n  };\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · color-picker · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/color-picker. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}