{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"convert","type":"registry:block","title":"Convert","description":"A two-sided exchange block joined by a live rate hairline that shortens from both ends as the quote ages, re-quotes in place with delta and snaps taut on lock.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency","https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/convert.tsx","type":"registry:component","content":"// Hairline UI · convert · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport {\n  AlertCircle,\n  ArrowUpDown,\n  Check,\n  Loader2,\n  Lock,\n  RefreshCw,\n} from \"lucide-react\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  createSpring,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { NumberRoll } from \"./number-roll\";\nimport { PillSelect, type PillOption } from \"./pill-select\";\nimport { TextMorph } from \"./text-morph\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * CONVERT: two-sided exchange card with a live rate clock\n *\n *   clock     the hairline between the two panes IS the quote's\n *             clock: two symmetrical hairline wings shorten from\n *             both outer edges inward toward the centre rate pill\n *             as `expiresAt` approaches (direct GPU scaleX writes,\n *             zero per-frame React renders)\n *\n *   requote   when the quote expires it re-quotes in place without\n *             blanking the card — the wings refill outward, the\n *             received amount rolls smoothly to the new figure and\n *             the percentage change appears beside the rate\n *\n *   lock      clicking Review locks the quote: both hairline wings\n *             snap taut to 100% on a spring, the rate pill gains a\n *             lock mark and the fee/net breakdown opens in place\n * ───────────────────────────────────────────────────────── */\n\nexport interface ConvertAsset {\n  /** Ticker or ISO code (e.g. \"USD\", \"EUR\", \"USDC\", \"ETH\", \"CREDITS\"). */\n  code: string;\n  /** Human-readable asset name (e.g. \"US Dollar\"). */\n  name: string;\n  /** Optional prefix/short symbol (e.g. \"$\", \"€\", \"£\"). Falls back to `code`. */\n  symbol?: string;\n  /** Decimal precision for formatting and input (default 2). */\n  decimals?: number;\n  /** Optional available balance in major units; enables Max & overdraft guard. */\n  balance?: number;\n  /** Optional secondary tag shown in the asset menu (e.g. \"Fiat\", \"ERC-20\"). */\n  badge?: string;\n}\n\nexport interface ConvertQuote {\n  /** Optional quote identifier returned by your backend. */\n  id?: string;\n  from: string;\n  to: string;\n  fromAmount: number;\n  /** Net amount received in `to` units after fee/spread. */\n  toAmount: number;\n  /** Exchange rate: 1 `from` = `rate` `to`. */\n  rate: number;\n  /** Optional fee expressed in `from` units. */\n  fee?: number;\n  /** Optional human-readable fee note (e.g. \"0.25% FX fee\", \"Zero fee\"). */\n  feeLabel?: string;\n  /** Epoch milliseconds when this quote expires. */\n  expiresAt: number;\n  /** Optional percentage change vs previous quote; calculated automatically when omitted. */\n  deltaPct?: number;\n}\n\nexport interface ConvertProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  /** Available assets users can convert between (minimum 2). */\n  assets: ConvertAsset[];\n  /** Initial source asset code (defaults to `assets[0].code`). */\n  defaultFrom?: string;\n  /** Initial target asset code (defaults to `assets[1].code`). */\n  defaultTo?: string;\n  /** Initial source amount (default 250). */\n  defaultAmount?: number | null;\n  /** Pricing contract: return a live quote (sync or async) for (from, to, amount). */\n  getQuote: (from: string, to: string, amount: number) => Promise<ConvertQuote> | ConvertQuote;\n  /** Settlement contract: execute the locked quote; throw an Error to show its message inline. */\n  onConvert: (quote: ConvertQuote) => Promise<unknown> | unknown;\n  /** Optional quick amount chips shown under the source figure (e.g. [100, 500, 1000]). */\n  presets?: number[];\n  /** BCP 47 locale for number formatting (default \"en-US\"). */\n  locale?: string;\n  /** Optional card header title (default \"Convert\"). */\n  title?: string;\n  /** Opt-in Web Audio cues (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\nconst BAYER8: Float32Array = (() => {\n  const m = [\n    [0, 32, 8, 40, 2, 34, 10, 42],\n    [48, 16, 56, 24, 50, 18, 58, 26],\n    [12, 44, 4, 36, 14, 46, 6, 38],\n    [60, 28, 52, 20, 62, 30, 54, 22],\n    [3, 35, 11, 43, 1, 33, 9, 41],\n    [51, 19, 59, 27, 49, 17, 57, 25],\n    [15, 47, 7, 39, 13, 45, 5, 37],\n    [63, 31, 55, 23, 61, 29, 53, 21],\n  ];\n  const out = new Float32Array(64);\n  for (let y = 0; y < 8; y++) {\n    for (let x = 0; x < 8; x++) out[(y << 3) | x] = (m[y][x] + 0.5) / 64;\n  }\n  return out;\n})();\n\nconst IS_LE = (() => {\n  const b = new ArrayBuffer(4);\n  new Uint32Array(b)[0] = 0x0a0b0c0d;\n  return new Uint8Array(b)[0] === 0x0d;\n})();\n\nfunction packRgba(r: number, g: number, b: number, a: number): number {\n  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;\n  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;\n  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;\n  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;\n  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\nfunction formatAssetAmount(value: number, asset: ConvertAsset, locale: string, compact = false): string {\n  const decimals = asset.decimals ?? 2;\n  const safe = Number.isFinite(value) ? value : 0;\n  const dropDecimals = compact && Number.isInteger(safe);\n  const nf = new Intl.NumberFormat(locale, {\n    minimumFractionDigits: dropDecimals ? 0 : Math.min(decimals, 2),\n    maximumFractionDigits: decimals,\n  });\n  const formatted = nf.format(safe);\n  if (asset.symbol && asset.symbol.length <= 2) {\n    return `${asset.symbol}${formatted}`;\n  }\n  return `${formatted} ${asset.symbol ?? asset.code}`;\n}\n\nfunction formatRateNumber(rate: number, locale: string): string {\n  const maxFrac = rate >= 100 ? 2 : rate >= 1 ? 4 : 6;\n  return new Intl.NumberFormat(locale, {\n    minimumFractionDigits: Math.min(2, maxFrac),\n    maximumFractionDigits: maxFrac,\n  }).format(rate);\n}\n\nfunction sanitizeDraft(raw: string, decimals: number): string {\n  let out = \"\";\n  let seenDot = false;\n  let fracCount = 0;\n  for (let i = 0; i < raw.length; i++) {\n    const ch = raw[i];\n    if (ch >= \"0\" && ch <= \"9\") {\n      if (seenDot) {\n        if (fracCount >= decimals) continue;\n        fracCount++;\n      }\n      out += ch;\n    } else if ((ch === \".\" || ch === \",\") && decimals > 0 && !seenDot) {\n      seenDot = true;\n      out += out.length === 0 ? \"0.\" : \".\";\n    }\n  }\n  // Prevent runaway integer digits\n  const [intPart, fracPart] = out.split(\".\");\n  const trimmedInt = intPart.length > 10 ? intPart.slice(0, 10) : intPart;\n  return fracPart !== undefined ? `${trimmedInt}.${fracPart}` : trimmedInt;\n}\n\n/** 1.5px Bayer settlement pulse on the bottom edge of the card when conversion completes. */\nfunction SettlementFloorPulse({\n  trigger,\n  tone,\n  active,\n  reduced,\n}: {\n  trigger: number;\n  tone: \"emerald\" | \"rose\";\n  active: boolean;\n  reduced: boolean;\n}) {\n  const canvasRef = React.useRef<HTMLCanvasElement | null>(null);\n  const lastRef = React.useRef(trigger);\n\n  React.useEffect(() => {\n    if (trigger === lastRef.current) return;\n    lastRef.current = trigger;\n    if (reduced || !active) return;\n\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    const rect = canvas.getBoundingClientRect();\n    const cssW = Math.max(120, Math.round(rect.width));\n    const cssH = Math.max(20, Math.round(rect.height));\n    const cell = 1.5;\n    const w = Math.max(48, Math.round(cssW / cell));\n    const h = Math.max(12, Math.round(cssH / cell));\n    canvas.width = w;\n    canvas.height = h;\n    const img = ctx.createImageData(w, h);\n    const u32 = new Uint32Array(img.data.buffer);\n\n    const rgb: [number, number, number] = tone === \"emerald\" ? [16, 185, 129] : [239, 68, 68];\n    const duration = 640;\n    const start = performance.now();\n    let raf = 0;\n\n    const frame = (now: number) => {\n      const p = clamp((now - start) / duration, 0, 1);\n      const env = Math.sin(p * Math.PI);\n      const sweepX = p * 1.35 - 0.17;\n      u32.fill(0);\n      for (let y = 0; y < h; y++) {\n        const yFall = Math.pow(y / Math.max(1, h - 1), 1.45);\n        for (let x = 0; x < w; x++) {\n          const nx = x / Math.max(1, w - 1);\n          const wave = Math.exp(-Math.pow((nx - sweepX) / 0.24, 2));\n          const density = yFall * env * (0.25 + 0.75 * wave) * 0.72;\n          const thr = BAYER8[((y & 7) << 3) | (x & 7)];\n          if (density > thr) {\n            u32[y * w + x] = packRgba(rgb[0], rgb[1], rgb[2], Math.round(180 * env));\n          }\n        }\n      }\n      ctx.putImageData(img, 0, 0);\n      if (p < 1) {\n        raf = window.requestAnimationFrame(frame);\n      } else {\n        ctx.clearRect(0, 0, w, h);\n      }\n    };\n\n    raf = window.requestAnimationFrame(frame);\n    return () => {\n      window.cancelAnimationFrame(raf);\n      ctx.clearRect(0, 0, w, h);\n    };\n  }, [trigger, tone, active, reduced]);\n\n  return (\n    <canvas\n      ref={canvasRef}\n      aria-hidden=\"true\"\n      className=\"pointer-events-none absolute inset-x-0 bottom-0 h-7 w-full [image-rendering:pixelated]\"\n    />\n  );\n}\n\n/** Hairline asset selector powered by PillSelect (pill morphs smoothly into its portaled listbox). */\nfunction AssetPill({\n  asset,\n  assets,\n  disabled,\n  locale,\n  ariaLabel,\n  onSelect,\n}: {\n  asset: ConvertAsset;\n  assets: ConvertAsset[];\n  disabled?: boolean;\n  locale: string;\n  ariaLabel: string;\n  onSelect: (code: string) => void;\n}) {\n  const options = React.useMemo<PillOption[]>(\n    () =>\n      assets.map((item) => ({\n        value: item.code,\n        label: item.code,\n        description:\n          item.balance !== undefined\n            ? `${item.name} · ${formatAssetAmount(item.balance, item, locale, true)}`\n            : item.name,\n      })),\n    [assets, locale],\n  );\n\n  return (\n    <PillSelect\n      options={options}\n      value={asset.code}\n      onValueChange={onSelect}\n      label={ariaLabel}\n      disabled={disabled}\n      mono\n      size=\"sm\"\n      width={228}\n      className=\"h-8! pl-1.5! pr-2.5!\"\n      renderValue={() => (\n        <span className=\"inline-flex items-center gap-1.5\">\n          <span className=\"inline-flex size-5 items-center justify-center rounded-full border border-border/80 bg-muted/60 font-mono text-[10.5px] font-semibold text-foreground\">\n            {asset.symbol && asset.symbol.length <= 2 ? asset.symbol : asset.code.slice(0, 2)}\n          </span>\n          <span className=\"font-mono text-[12.5px] font-semibold tracking-[0.01em] text-foreground\">\n            <TextMorph>{asset.code}</TextMorph>\n          </span>\n        </span>\n      )}\n    />\n  );\n}\n\n/** Smooth height fold that keeps its last content while folding shut. */\nfunction Fold({ open, reduced, children }: { open: boolean; reduced: boolean; children: React.ReactNode }) {\n  return (\n    <div\n      className={`grid ${!open ? \"pointer-events-none\" : \"\"}`}\n      inert={!open}\n      style={{\n        gridTemplateRows: open ? \"1fr\" : \"0fr\",\n        opacity: open ? 1 : 0,\n        transition: reduced ? \"none\" : `grid-template-rows 380ms ${EASE_OUT}, opacity 240ms ${EASE_OUT}`,\n      }}\n    >\n      <div className=\"min-h-0 overflow-clip\">{children}</div>\n    </div>\n  );\n}\n\ntype ConvertStage = \"edit\" | \"review\" | \"converting\" | \"converted\";\n\nexport function Convert({\n  assets,\n  defaultFrom,\n  defaultTo,\n  defaultAmount = 250,\n  getQuote,\n  onConvert,\n  presets,\n  locale = \"en-US\",\n  title = \"Convert\",\n  sound = false,\n  className = \"\",\n  ...props\n}: ConvertProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();\n\n  const initialFrom = defaultFrom && assets.some((a) => a.code === defaultFrom) ? defaultFrom : assets[0]?.code ?? \"USD\";\n  const initialTo =\n    defaultTo && defaultTo !== initialFrom && assets.some((a) => a.code === defaultTo)\n      ? defaultTo\n      : assets.find((a) => a.code !== initialFrom)?.code ?? initialFrom;\n\n  const [fromCode, setFromCode] = React.useState(initialFrom);\n  const [toCode, setToCode] = React.useState(initialTo);\n  const [draft, setDraft] = React.useState(() => (defaultAmount != null && defaultAmount > 0 ? String(defaultAmount) : \"\"));\n  const [stage, setStage] = React.useState<ConvertStage>(\"edit\");\n  const [quote, setQuote] = React.useState<ConvertQuote | null>(null);\n  const [quoteIssuedAt, setQuoteIssuedAt] = React.useState<number>(0);\n  const [quoting, setQuoting] = React.useState(false);\n  const [rateDeltaPct, setRateDeltaPct] = React.useState<number | null>(null);\n  const [secondsLeft, setSecondsLeft] = React.useState<number | null>(null);\n  const [errorMsg, setErrorMsg] = React.useState<string | null>(null);\n  const [settledQuote, setSettledQuote] = React.useState<ConvertQuote | null>(null);\n  const [pulseSeq, setPulseSeq] = React.useState(0);\n  const [pulseTone, setPulseTone] = React.useState<\"emerald\" | \"rose\">(\"emerald\");\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n\n  const fromAsset = React.useMemo(() => assets.find((a) => a.code === fromCode) ?? assets[0], [assets, fromCode]);\n  const toAsset = React.useMemo(() => assets.find((a) => a.code === toCode) ?? assets[1] ?? assets[0], [assets, toCode]);\n\n  const parsedAmount = React.useMemo(() => {\n    const n = Number.parseFloat(draft);\n    return Number.isFinite(n) && n > 0 ? n : 0;\n  }, [draft]);\n\n  const overBalance = fromAsset?.balance !== undefined && parsedAmount > fromAsset.balance + 1e-9;\n  const shortfall = overBalance && fromAsset?.balance !== undefined ? parsedAmount - fromAsset.balance : 0;\n\n  // Refs for zero-re-render GPU animations\n  const leftWingRef = React.useRef<HTMLDivElement | null>(null);\n  const rightWingRef = React.useRef<HTMLDivElement | null>(null);\n  const swapIconRef = React.useRef<HTMLSpanElement | null>(null);\n  const cardShakeRef = React.useRef<HTMLDivElement | null>(null);\n\n  const wingSpringRef = React.useRef<Spring | null>(null);\n  const swapSpringRef = React.useRef<Spring | null>(null);\n  const swapRotTargetRef = React.useRef(0);\n  const wingValueRef = React.useRef(1);\n  const lastPairRateRef = React.useRef<{ pair: string; rate: number } | null>(null);\n  const reqSeqRef = React.useRef(0);\n  const getQuoteRef = React.useRef(getQuote);\n  React.useEffect(() => {\n    getQuoteRef.current = getQuote;\n  }, [getQuote]);\n\n  // Write wing scale directly to DOM\n  const applyWings = React.useCallback((ratio: number, urgent: boolean, mode: \"live\" | \"locked\" | \"settled\" = \"live\") => {\n    const r = clamp(ratio, 0, 1);\n    wingValueRef.current = r;\n    const left = leftWingRef.current;\n    const right = rightWingRef.current;\n    const color =\n      mode === \"settled\"\n        ? \"rgb(16 185 129)\"\n        : mode === \"locked\"\n          ? \"var(--primary)\"\n          : urgent\n            ? \"rgb(245 158 11)\"\n            : \"color-mix(in oklab, var(--foreground) 48%, transparent)\";\n    if (left) {\n      left.style.transform = `scaleX(${r})`;\n      left.style.backgroundColor = color;\n    }\n    if (right) {\n      right.style.transform = `scaleX(${r})`;\n      right.style.backgroundColor = color;\n    }\n  }, []);\n\n  // Quote fetcher (debounced lightly for typing, immediate for pair switches & expiry refreshes)\n  const requestQuote = React.useCallback(\n    async (fCode: string, tCode: string, amount: number, isRequote = false) => {\n      if (amount <= 0) {\n        setQuote(null);\n        setQuoting(false);\n        setRateDeltaPct(null);\n        setSecondsLeft(null);\n        return;\n      }\n      const seq = ++reqSeqRef.current;\n      setQuoting(true);\n      try {\n        const res = await getQuoteRef.current(fCode, tCode, amount);\n        if (seq !== reqSeqRef.current) return;\n\n        const pairKey = `${fCode}->${tCode}`;\n        let delta: number | null = null;\n        if (typeof res.deltaPct === \"number\" && Number.isFinite(res.deltaPct)) {\n          delta = res.deltaPct;\n        } else if (isRequote && lastPairRateRef.current && lastPairRateRef.current.pair === pairKey && lastPairRateRef.current.rate > 0) {\n          const pct = ((res.rate - lastPairRateRef.current.rate) / lastPairRateRef.current.rate) * 100;\n          if (Math.abs(pct) >= 0.005) delta = pct;\n        }\n        lastPairRateRef.current = { pair: pairKey, rate: res.rate };\n\n        const now = Date.now();\n        setQuote(res);\n        setQuoteIssuedAt(now);\n        setRateDeltaPct(delta);\n        setSecondsLeft(Math.max(0, Math.ceil((res.expiresAt - now) / 1000)));\n        setQuoting(false);\n\n        if (isRequote) {\n          setLiveStatus(`Rate updated: 1 ${fCode} equals ${formatRateNumber(res.rate, locale)} ${tCode}`);\n          if (sound) playSound(\"tick\", 0.24);\n        }\n      } catch {\n        if (seq !== reqSeqRef.current) return;\n        setQuoting(false);\n      }\n    },\n    [locale, sound],\n  );\n\n  // Trigger quote whenever inputs change while editing\n  React.useEffect(() => {\n    if (stage !== \"edit\") return;\n    if (parsedAmount <= 0) {\n      const raf = window.requestAnimationFrame(() => {\n        setQuote(null);\n        setQuoting(false);\n        setRateDeltaPct(null);\n        setSecondsLeft(null);\n      });\n      return () => window.cancelAnimationFrame(raf);\n    }\n    const timer = window.setTimeout(() => {\n      void requestQuote(fromCode, toCode, parsedAmount, false);\n    }, 110);\n    return () => window.clearTimeout(timer);\n  }, [fromCode, toCode, parsedAmount, stage, requestQuote]);\n\n  // SIGNATURE MOMENT: Live shrinking hairline clock + auto re-quote on expiry + spring snap taut on lock\n  React.useEffect(() => {\n    wingSpringRef.current?.stop();\n\n    if (stage === \"review\" || stage === \"converting\" || stage === \"converted\") {\n      const wingMode = stage === \"converted\" ? \"settled\" : \"locked\";\n      // Snap wings taut to 100% on lock!\n      if (reduced) {\n        applyWings(1, false, wingMode);\n        return;\n      }\n      const sp = createSpring(\n        wingValueRef.current,\n        { stiffness: 420, damping: 28 },\n        () => applyWings(sp.get(), false, wingMode),\n        0.002,\n      );\n      sp.set(1);\n      wingSpringRef.current = sp;\n      return () => sp.stop();\n    }\n\n    if (!quote || !onScreen) {\n      applyWings(quote ? 1 : 0.22, false, \"live\");\n      return;\n    }\n\n    const totalMs = Math.max(1000, quote.expiresAt - quoteIssuedAt);\n    let raf = 0;\n    let lastSec = -1;\n    let requoted = false;\n\n    const tick = () => {\n      const now = Date.now();\n      const remMs = quote.expiresAt - now;\n      const ratio = clamp(remMs / totalMs, 0, 1);\n      const sec = Math.max(0, Math.ceil(remMs / 1000));\n      if (sec !== lastSec) {\n        lastSec = sec;\n        setSecondsLeft(sec);\n      }\n      applyWings(reduced ? (ratio > 0 ? 1 : 0) : ratio, remMs <= 3000 && remMs > 0, \"live\");\n\n      if (remMs <= 0 && !requoted) {\n        requoted = true;\n        void requestQuote(fromCode, toCode, parsedAmount, true);\n        return;\n      }\n      raf = window.requestAnimationFrame(tick);\n    };\n\n    raf = window.requestAnimationFrame(tick);\n    return () => window.cancelAnimationFrame(raf);\n  }, [quote, quoteIssuedAt, stage, onScreen, reduced, applyWings, requestQuote, fromCode, toCode, parsedAmount]);\n\n  // Damped horizontal recoil helper for errors\n  const recoilCard = React.useCallback(() => {\n    if (reduced || !cardShakeRef.current) return;\n    const el = cardShakeRef.current;\n    const start = performance.now();\n    const duration = 360;\n    const step = (now: number) => {\n      const t = clamp((now - start) / duration, 0, 1);\n      const x = Math.sin(t * Math.PI * 5) * (1 - t) * 5.5;\n      el.style.transform = `translate3d(${x.toFixed(2)}px, 0, 0)`;\n      if (t < 1) window.requestAnimationFrame(step);\n      else el.style.transform = \"\";\n    };\n    window.requestAnimationFrame(step);\n  }, [reduced]);\n\n  const handleSwapDirection = () => {\n    if (stage !== \"edit\") return;\n    setFromCode(toCode);\n    setToCode(fromCode);\n    setErrorMsg(null);\n    setRateDeltaPct(null);\n    if (sound) playSound(\"pop\", 0.3);\n\n    swapRotTargetRef.current += 180;\n    if (!reduced && swapIconRef.current) {\n      swapSpringRef.current?.stop();\n      const iconEl = swapIconRef.current;\n      const sp = createSpring(\n        swapRotTargetRef.current - 180,\n        { stiffness: 340, damping: 22 },\n        () => {\n          iconEl.style.transform = `rotate(${sp.get().toFixed(1)}deg)`;\n        },\n        0.2,\n      );\n      sp.set(swapRotTargetRef.current);\n      swapSpringRef.current = sp;\n    }\n  };\n\n  const handleSelectFrom = (code: string) => {\n    if (code === toCode) {\n      handleSwapDirection();\n      return;\n    }\n    setFromCode(code);\n    setErrorMsg(null);\n    setRateDeltaPct(null);\n  };\n\n  const handleSelectTo = (code: string) => {\n    if (code === fromCode) {\n      handleSwapDirection();\n      return;\n    }\n    setToCode(code);\n    setErrorMsg(null);\n    setRateDeltaPct(null);\n  };\n\n  const handleEnterReview = () => {\n    if (!quote || parsedAmount <= 0 || overBalance) return;\n    setErrorMsg(null);\n    setStage(\"review\");\n    setLiveStatus(\"Quote locked for review\");\n    if (sound) playSound(\"drop\", 0.34);\n  };\n\n  const handleConfirmConvert = async () => {\n    if (!quote) return;\n    setStage(\"converting\");\n    setErrorMsg(null);\n    try {\n      await onConvert(quote);\n      setSettledQuote(quote);\n      setStage(\"converted\");\n      setPulseTone(\"emerald\");\n      setPulseSeq((n) => n + 1);\n      setLiveStatus(\n        `Converted ${formatAssetAmount(quote.fromAmount, fromAsset, locale)} to ${formatAssetAmount(quote.toAmount, toAsset, locale)}`,\n      );\n      if (sound) playSound(\"success\", 0.42);\n    } catch (err) {\n      const msg = err instanceof Error && err.message ? err.message : \"Conversion could not be completed. Try again.\";\n      setErrorMsg(msg);\n      setStage(\"review\");\n      setPulseTone(\"rose\");\n      setPulseSeq((n) => n + 1);\n      recoilCard();\n      setLiveStatus(msg);\n      if (sound) playSound(\"error\", 0.38);\n    }\n  };\n\n  const handleResetAfterConvert = () => {\n    setSettledQuote(null);\n    setErrorMsg(null);\n    setStage(\"edit\");\n    if (parsedAmount > 0) {\n      void requestQuote(fromCode, toCode, parsedAmount, false);\n    }\n  };\n\n  // Auto-scale typography class so large numbers never wrap or clip\n  const figureSizeClass =\n    draft.length > 10\n      ? \"text-[21px]\"\n      : draft.length > 7\n        ? \"text-[26px]\"\n        : \"text-[32px]\";\n\n  const locked = stage === \"review\" || stage === \"converting\" || stage === \"converted\";\n  const canReview = stage === \"edit\" && Boolean(quote) && parsedAmount > 0 && !overBalance && !quoting;\n\n  const toDecimals = toAsset?.decimals ?? 2;\n  const toPrefix = toAsset?.symbol && toAsset.symbol.length <= 2 ? toAsset.symbol : \"\";\n  const rateMaxFrac = quote ? (quote.rate >= 100 ? 2 : quote.rate >= 1 ? 4 : 6) : 4;\n  const feeText = quote\n    ? quote.feeLabel\n      ? quote.feeLabel\n      : quote.fee && quote.fee > 0 && fromAsset\n        ? `Fee ${formatAssetAmount(quote.fee, fromAsset, locale)}`\n        : \"Zero fee\"\n    : \"\";\n\n  const ctaLabel =\n    stage === \"converted\"\n      ? \"New conversion\"\n      : stage === \"converting\"\n        ? \"Converting…\"\n        : stage === \"review\" && quote && toAsset\n          ? `Convert to ${formatAssetAmount(quote.toAmount, toAsset, locale)}`\n          : overBalance\n            ? `Insufficient ${fromCode} balance`\n            : parsedAmount <= 0\n              ? \"Enter an amount\"\n              : quoting && !quote\n                ? \"Getting live quote…\"\n                : \"Review conversion\";\n\n  const [lastError, setLastError] = React.useState(\"\");\n  if (errorMsg && errorMsg !== lastError) setLastError(errorMsg);\n  const [lastShortfall, setLastShortfall] = React.useState(\"\");\n  if (overBalance && fromAsset) {\n    const s = `Exceeds balance by ${formatAssetAmount(shortfall, fromAsset, locale)}`;\n    if (s !== lastShortfall) setLastShortfall(s);\n  }\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"region\"\n      aria-label={title}\n      data-stage={stage}\n      data-locked={locked ? \"true\" : \"false\"}\n      className={`relative w-full max-w-[430px] rounded-[18px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${className}`}\n      {...props}\n    >\n      <div aria-hidden=\"true\" data-natural-width className=\"grid h-0\" style={{ gridTemplateColumns: \"minmax(0, 430px)\" }} />\n      <div className=\"pointer-events-none absolute inset-0 overflow-hidden rounded-[17px]\">\n        <SettlementFloorPulse trigger={pulseSeq} tone={pulseTone} active={onScreen} reduced={reduced} />\n      </div>\n\n      <div ref={cardShakeRef} className=\"@container relative z-10 flex w-full flex-col\">\n        {/* Header bar */}\n        <div className=\"flex items-center justify-between border-b border-border/80 px-4 py-3\">\n          <span className=\"text-[13px] font-medium tracking-[-0.01em] text-foreground\">{title}</span>\n          <div className=\"flex items-center gap-2 text-[11.5px] text-muted-foreground\">\n            {stage === \"edit\" && secondsLeft !== null && quote && (\n              <span className=\"inline-flex items-center gap-1 font-mono tabular-nums\" data-quote-countdown={secondsLeft}>\n                <span\n                  className={`size-1.5 rounded-full transition-colors ${\n                    secondsLeft <= 3 ? \"bg-amber-500\" : \"bg-emerald-500\"\n                  }`}\n                />\n                <NumberRoll value={secondsLeft} direction=\"down\" suffix=\"s\" duration={480} />\n              </span>\n            )}\n            {stage === \"edit\" && quote && (\n              <button\n                type=\"button\"\n                aria-label=\"Refresh quote\"\n                title=\"Refresh quote now\"\n                onClick={() => void requestQuote(fromCode, toCode, parsedAmount, true)}\n                className={`inline-flex size-6 cursor-pointer items-center justify-center rounded-[7px] text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <RefreshCw className={`size-3.5 ${quoting ? \"animate-spin\" : \"\"}`} strokeWidth={2} />\n              </button>\n            )}\n            {locked && (\n              <span\n                className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10.5px] font-medium transition-colors duration-200 ${\n                  stage === \"converted\"\n                    ? \"border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-300\"\n                    : \"border-foreground/20 bg-accent text-foreground\"\n                }`}\n              >\n                {stage === \"converted\" ? (\n                  <Check className=\"size-3\" strokeWidth={2.4} />\n                ) : (\n                  <Lock className=\"size-2.5\" strokeWidth={2.2} />\n                )}\n                <TextMorph>{stage === \"converted\" ? \"Settled\" : stage === \"converting\" ? \"Settling…\" : \"Quote locked\"}</TextMorph>\n              </span>\n            )}\n          </div>\n        </div>\n\n        {/* TOP PANE: You pay */}\n        <div className=\"flex flex-col px-4 pb-4 pt-4\">\n          <div className=\"mb-2.5 flex items-center justify-between gap-2 text-[11.5px]\">\n            <span className=\"text-muted-foreground\">You pay</span>\n            {fromAsset?.balance !== undefined && (\n              <div className=\"flex items-center gap-1.5\">\n                <span className={`font-mono tabular-nums transition-colors ${overBalance ? \"text-red-600 dark:text-red-400\" : \"text-muted-foreground\"}`}>\n                  Available <TextMorph>{formatAssetAmount(fromAsset.balance, fromAsset, locale)}</TextMorph>\n                </span>\n                {stage === \"edit\" && (\n                  <button\n                    type=\"button\"\n                    onClick={() => {\n                      const maxStr = String(fromAsset.balance);\n                      setDraft(maxStr);\n                      setErrorMsg(null);\n                      if (sound) playSound(\"tick\", 0.28);\n                    }}\n                    className={`cursor-pointer rounded-[6px] border border-border bg-background px-1.5 py-0.5 text-[10.5px] font-medium text-foreground hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    Max\n                  </button>\n                )}\n              </div>\n            )}\n          </div>\n\n          <div className=\"flex items-center justify-between gap-3\">\n            {fromAsset && (\n              <AssetPill\n                asset={fromAsset}\n                assets={assets}\n                disabled={stage !== \"edit\"}\n                locale={locale}\n                ariaLabel=\"Source currency\"\n                onSelect={handleSelectFrom}\n              />\n            )}\n\n            <label className=\"flex min-w-0 flex-1 cursor-text items-baseline justify-end\">\n              {fromAsset?.symbol && fromAsset.symbol.length <= 2 && (\n                <span\n                  aria-hidden=\"true\"\n                  className={`mr-0.5 select-none font-mono font-semibold leading-none tracking-[-0.03em] transition-colors ${figureSizeClass} ${\n                    overBalance ? \"text-red-500\" : draft ? \"text-foreground\" : \"text-muted-foreground/40\"\n                  }`}\n                >\n                  <TextMorph>{fromAsset.symbol}</TextMorph>\n                </span>\n              )}\n              <span className=\"inline-grid max-w-full items-baseline\">\n                <span\n                  aria-hidden=\"true\"\n                  className={`invisible col-start-1 row-start-1 whitespace-pre font-mono font-semibold leading-none tracking-[-0.03em] tabular-nums ${figureSizeClass}`}\n                >\n                  {draft || \"0.00\"}\n                </span>\n                <input\n                  type=\"text\"\n                  size={1}\n                  inputMode=\"decimal\"\n                  aria-label=\"Amount to convert\"\n                  aria-invalid={overBalance || undefined}\n                  disabled={stage !== \"edit\"}\n                  placeholder=\"0.00\"\n                  value={draft}\n                  onChange={(e) => {\n                    const next = sanitizeDraft(e.currentTarget.value, fromAsset?.decimals ?? 2);\n                    setDraft(next);\n                    setErrorMsg(null);\n                  }}\n                  className={`col-start-1 row-start-1 w-0 min-w-full bg-transparent text-right font-mono font-semibold leading-none tracking-[-0.03em] tabular-nums transition-[font-size,color] duration-150 placeholder:text-muted-foreground/35 focus:outline-none disabled:opacity-90 ${figureSizeClass} ${\n                    overBalance ? \"text-red-600 dark:text-red-400\" : \"text-foreground\"\n                  }`}\n                />\n              </span>\n            </label>\n          </div>\n\n          <Fold open={Boolean(overBalance && fromAsset)} reduced={reduced}>\n            <p role=\"alert\" className=\"pt-2 text-right text-[11.5px] font-medium text-red-600 dark:text-red-400\">\n              <TextMorph animateWidth={false}>{lastShortfall}</TextMorph>\n            </p>\n          </Fold>\n\n          <Fold open={Boolean(presets && presets.length > 0 && stage === \"edit\")} reduced={reduced}>\n            {presets && presets.length > 0 && (\n              <div className=\"flex flex-wrap items-center justify-end gap-1 pt-2.5\">\n                {presets.map((amt) => {\n                  const active = Math.abs(parsedAmount - amt) < 1e-9;\n                  return (\n                    <button\n                      key={amt}\n                      type=\"button\"\n                      onClick={() => {\n                        setDraft(String(amt));\n                        setErrorMsg(null);\n                        if (sound) playSound(\"tick\", 0.25);\n                      }}\n                      className={`cursor-pointer rounded-[7px] border px-2 py-0.5 font-mono text-[11px] tabular-nums transition-colors ${\n                        active\n                          ? \"border-foreground/25 bg-accent text-foreground\"\n                          : \"border-border/75 bg-background text-muted-foreground hover:text-foreground\"\n                      } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                    >\n                      <TextMorph>{fromAsset ? formatAssetAmount(amt, fromAsset, locale, true) : String(amt)}</TextMorph>\n                    </button>\n                  );\n                })}\n              </div>\n            )}\n          </Fold>\n        </div>\n\n        {/* SIGNATURE MOMENT: The Rate Hairline Clock (shortens symmetrically inward toward the centre rate pill, snaps taut on lock) */}\n        <div className=\"relative flex h-8 items-center px-4\" data-rate-clock=\"true\">\n          {/* Passive hairline track */}\n          <div aria-hidden=\"true\" className=\"absolute inset-x-0 top-1/2 h-px -translate-y-1/2 bg-border/75\" />\n\n          {/* Left live wing: shrinks from left outer edge inward toward centre (origin-right) */}\n          <div className=\"relative mr-2 h-[2px] flex-1 overflow-hidden\">\n            <div\n              ref={leftWingRef}\n              aria-hidden=\"true\"\n              className=\"h-full w-full origin-right will-change-transform\"\n              style={{ transform: \"scaleX(1)\", backgroundColor: \"color-mix(in oklab, var(--foreground) 48%, transparent)\" }}\n            />\n          </div>\n\n          {/* Centre opaque rate pill + swap trigger */}\n          <div className=\"relative z-10 flex shrink-0 items-center gap-1 rounded-full border border-border bg-card px-1.5 py-0.5 shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)]\">\n            <button\n              type=\"button\"\n              disabled={stage !== \"edit\"}\n              aria-label=\"Swap currencies\"\n              title=\"Swap currencies\"\n              onClick={handleSwapDirection}\n              className={`inline-flex size-5 cursor-pointer items-center justify-center rounded-full text-muted-foreground hover:bg-accent hover:text-foreground disabled:cursor-default disabled:opacity-45 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n            >\n              <span ref={swapIconRef} className=\"inline-flex\">\n                <ArrowUpDown className=\"size-3\" strokeWidth={2.1} />\n              </span>\n            </button>\n\n            <span className=\"pr-1.5 font-mono text-[11px] font-medium tabular-nums text-foreground\" data-rate-pill=\"true\">\n              {quote ? (\n                <span className=\"inline-flex items-center gap-1.5\">\n                  {locked && <Lock className=\"size-2.5 text-muted-foreground\" strokeWidth={2.2} />}\n                  <span className=\"inline-flex items-center gap-1\">\n                    <span>1</span>\n                    <TextMorph>{fromCode}</TextMorph>\n                    <span>=</span>\n                    <NumberRoll\n                      value={quote.rate}\n                      locales={locale}\n                      format={{ minimumFractionDigits: Math.min(2, rateMaxFrac), maximumFractionDigits: rateMaxFrac }}\n                      duration={520}\n                    />\n                    <TextMorph>{toCode}</TextMorph>\n                  </span>\n                  {rateDeltaPct !== null && Math.abs(rateDeltaPct) >= 0.005 && (\n                    <span\n                      data-rate-delta={rateDeltaPct > 0 ? \"up\" : \"down\"}\n                      className={`rounded-full px-1.5 py-0 text-[10px] font-semibold ${\n                        rateDeltaPct > 0\n                          ? \"bg-emerald-500/15 text-emerald-700 dark:text-emerald-300\"\n                          : \"bg-red-500/15 text-red-700 dark:text-red-300\"\n                      }`}\n                    >\n                      <NumberRoll\n                        value={Math.abs(rateDeltaPct)}\n                        prefix={rateDeltaPct > 0 ? \"+\" : \"-\"}\n                        suffix=\"%\"\n                        format={{ minimumFractionDigits: 2, maximumFractionDigits: 2 }}\n                        duration={440}\n                      />\n                    </span>\n                  )}\n                </span>\n              ) : (\n                <span className=\"text-muted-foreground\">\n                  <TextMorph>{quoting ? \"Fetching rate…\" : \"Enter amount\"}</TextMorph>\n                </span>\n              )}\n            </span>\n          </div>\n\n          {/* Right live wing: shrinks from right outer edge inward toward centre (origin-left) */}\n          <div className=\"relative ml-2 h-[2px] flex-1 overflow-hidden\">\n            <div\n              ref={rightWingRef}\n              aria-hidden=\"true\"\n              className=\"h-full w-full origin-left will-change-transform\"\n              style={{ transform: \"scaleX(1)\", backgroundColor: \"color-mix(in oklab, var(--foreground) 48%, transparent)\" }}\n            />\n          </div>\n        </div>\n\n        {/* BOTTOM PANE: You receive */}\n        <div className=\"flex flex-col gap-2 bg-muted/15 px-4 pb-4 pt-4\">\n          <div className=\"flex items-center justify-between gap-2 text-[11.5px]\">\n            <span className=\"text-muted-foreground\">You receive</span>\n            <span className=\"font-mono text-[11px] tabular-nums text-muted-foreground\">\n              <TextMorph>{feeText}</TextMorph>\n            </span>\n          </div>\n\n          <div className=\"flex items-center justify-between gap-3\">\n            {toAsset && (\n              <AssetPill\n                asset={toAsset}\n                assets={assets}\n                disabled={stage !== \"edit\"}\n                locale={locale}\n                ariaLabel=\"Target currency\"\n                onSelect={handleSelectTo}\n              />\n            )}\n\n            <div className=\"min-w-0 flex-1 text-right\">\n              {quote && toAsset ? (\n                <NumberRoll\n                  value={quote.toAmount}\n                  locales={locale}\n                  prefix={toPrefix}\n                  format={{ minimumFractionDigits: Math.min(toDecimals, 2), maximumFractionDigits: toDecimals }}\n                  duration={580}\n                  className={`font-mono font-semibold leading-none tracking-[-0.03em] text-foreground transition-opacity ${\n                    String(Math.round(quote.toAmount)).length > 7 ? \"text-[25px]\" : \"text-[30px]\"\n                  } ${quoting ? \"opacity-55\" : \"opacity-100\"}`}\n                />\n              ) : (\n                <span className=\"font-mono text-[30px] font-semibold leading-none tracking-[-0.03em] tabular-nums text-muted-foreground/35\">\n                  {toPrefix ? `${toPrefix}0.00` : \"0.00\"}\n                </span>\n              )}\n            </div>\n          </div>\n        </div>\n\n        {/* LOCKED REVIEW BREAKDOWN (smooth grid-template-rows fold) */}\n        <Fold open={Boolean((stage === \"review\" || stage === \"converting\") && quote && fromAsset && toAsset)} reduced={reduced}>\n          {quote && fromAsset && toAsset && (\n            <div className=\"border-t border-border/80 bg-background/60 px-4 py-3 text-[12px]\">\n              <div className=\"flex flex-col gap-1.5\">\n                <div className=\"flex items-center justify-between\">\n                  <span className=\"text-muted-foreground\">Locked rate</span>\n                  <span className=\"font-mono tabular-nums text-foreground\">\n                    1 {fromCode} = {formatRateNumber(quote.rate, locale)} {toCode}\n                  </span>\n                </div>\n                <div className=\"flex items-center justify-between\">\n                  <span className=\"text-muted-foreground\">Conversion fee</span>\n                  <span className=\"font-mono tabular-nums text-foreground\">\n                    {quote.fee && quote.fee > 0 ? formatAssetAmount(quote.fee, fromAsset, locale) : \"Included\"}\n                  </span>\n                </div>\n                <div className=\"mt-1 flex items-center justify-between border-t border-border/70 pt-1.5 font-medium\">\n                  <span className=\"text-foreground\">Guaranteed payout</span>\n                  <span className=\"font-mono tabular-nums text-foreground\">\n                    {formatAssetAmount(quote.toAmount, toAsset, locale)}\n                  </span>\n                </div>\n              </div>\n            </div>\n          )}\n        </Fold>\n\n        {/* SETTLED RECEIPT (smooth grid-template-rows fold) */}\n        <Fold open={Boolean(stage === \"converted\" && settledQuote && fromAsset && toAsset)} reduced={reduced}>\n          {settledQuote && fromAsset && toAsset && (\n            <div className=\"border-t border-emerald-500/25 bg-emerald-500/[0.06] px-4 py-3 text-[12px]\">\n              <div className=\"flex items-center justify-between gap-2\">\n                <span className=\"font-medium text-emerald-700 dark:text-emerald-300\">\n                  {formatAssetAmount(settledQuote.fromAmount, fromAsset, locale)} →{\" \"}\n                  {formatAssetAmount(settledQuote.toAmount, toAsset, locale)}\n                </span>\n                <span className=\"font-mono text-[11px] tabular-nums text-muted-foreground\">\n                  @ {formatRateNumber(settledQuote.rate, locale)}\n                </span>\n              </div>\n            </div>\n          )}\n        </Fold>\n\n        {/* INLINE ERROR (smooth grid-template-rows fold) */}\n        <Fold open={Boolean(errorMsg)} reduced={reduced}>\n          <div role=\"alert\" className=\"flex items-center gap-2 border-t border-red-500/25 bg-red-500/[0.07] px-4 py-2.5 text-[12px] text-red-700 dark:text-red-300\">\n            <AlertCircle className=\"size-3.5 shrink-0\" strokeWidth={2} />\n            <TextMorph animateWidth={false}>{errorMsg ?? lastError}</TextMorph>\n          </div>\n        </Fold>\n\n        {/* ACTION FOOTER: one continuous CTA bar with smooth Edit reveal & TextMorph labels */}\n        <div className=\"border-t border-border/80 px-4 py-3\">\n          <div className=\"flex items-center\">\n            <div\n              className=\"grid shrink-0\"\n              inert={stage !== \"review\" && stage !== \"converting\"}\n              style={{\n                gridTemplateColumns: stage === \"review\" || stage === \"converting\" ? \"1fr\" : \"0fr\",\n                opacity: stage === \"review\" || stage === \"converting\" ? 1 : 0,\n                transition: reduced ? \"none\" : `grid-template-columns 360ms ${EASE_OUT}, opacity 200ms ${EASE_OUT}`,\n              }}\n            >\n              <div className=\"min-w-0 overflow-hidden\">\n                <div className=\"pr-2\">\n                  <button\n                    type=\"button\"\n                    disabled={stage === \"converting\"}\n                    onClick={() => {\n                      setStage(\"edit\");\n                      setErrorMsg(null);\n                      if (sound) playSound(\"fold\", 0.25);\n                    }}\n                    className={`flex h-10 cursor-pointer items-center justify-center rounded-[11px] border border-border bg-background px-3.5 text-[12.5px] font-medium text-foreground hover:bg-accent disabled:opacity-40 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    Edit\n                  </button>\n                </div>\n              </div>\n            </div>\n\n            <button\n              type=\"button\"\n              disabled={(stage === \"edit\" && !canReview) || stage === \"converting\"}\n              onClick={() => {\n                if (stage === \"edit\") handleEnterReview();\n                else if (stage === \"review\") void handleConfirmConvert();\n                else if (stage === \"converted\") handleResetAfterConvert();\n              }}\n              className={`flex h-10 flex-1 cursor-pointer items-center justify-center gap-2 rounded-[11px] px-4 text-[13px] font-medium transition-[background-color,color,border-color,opacity,scale] duration-200 disabled:cursor-not-allowed disabled:opacity-35 ${\n                stage === \"converted\"\n                  ? \"border border-border bg-background text-foreground hover:bg-accent\"\n                  : \"bg-primary text-primary-foreground hover:opacity-90\"\n              } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n            >\n              {stage === \"converting\" && <Loader2 className=\"size-4 shrink-0 animate-spin\" strokeWidth={2.2} />}\n              <TextMorph>{ctaLabel}</TextMorph>\n            </button>\n          </div>\n        </div>\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {liveStatus}\n      </span>\n    </div>\n  );\n}\n\nexport default Convert;\n"},{"path":"registry/pill-select.tsx","type":"registry:component","content":"// Hairline UI · convert · 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 { TextMorph } from \"./text-morph\";\n\n/* ─────────────────────────────────────────────────────────\n * PILL SELECT: a select that's the same surface as its pill\n *\n *   open      the pill grows into its list (size and corners\n *             ease) from the edge it's lined up with, while its\n *             label fades into the options; it opens upward when\n *             there's no room below, and long lists scroll\n *   pick      the list folds back into the pill and the label\n *             morphs to the new choice; the current option\n *             carries a drawn check\n *   keys      arrows move a highlight that glides between rows,\n *             Home and End jump, typing a few letters finds an\n *             option, Enter picks, Escape folds it back\n *\n * The list lives in a portal on the page's body, placed over\n * the pill, so a clipping toolbar, fold or scroller never cuts\n * it off; it carries the theme's colours with it. Scrolling\n * the page closes it.\n *\n * Used wherever a component needs a choice from a list; never\n * the browser's own dropdown, which can't follow the theme.\n * ───────────────────────────────────────────────────────── */\n\nexport interface PillOption {\n  value: string;\n  label: string;\n  /** A second line in the list, e.g. a sample value. */\n  description?: string;\n}\n\nexport interface PillSelectProps {\n  options: PillOption[];\n  value: string | null | undefined;\n  onValueChange: (value: string) => void;\n  /** Accessible name, e.g. \"Column for Email\". */\n  label: string;\n  /** Shown while nothing is chosen. */\n  placeholder?: string;\n  /** What the pill shows for a choice; the option's label by default. */\n  display?: (option: PillOption | undefined) => string;\n  /** The pill's contents, when it needs more than text (an icon that turns). */\n  renderValue?: (option: PillOption | undefined, open: boolean) => React.ReactNode;\n  /** Monospace labels, for code-like values (event names, column headers). */\n  mono?: boolean;\n  /** Which edge of the pill the list lines up with. */\n  align?: \"start\" | \"end\";\n  /** The list's width; never narrower than the pill. */\n  width?: number;\n  /** Fill the width it's given. */\n  block?: boolean;\n  /** Dims the pill's text, e.g. for \"Don't import\". */\n  muted?: boolean;\n  disabled?: boolean;\n  /** \"sm\" is the 28px pill for toolbars; \"md\" is 36px, the height of the other form fields. */\n  size?: \"sm\" | \"md\";\n  className?: string;\n}\n\ntype Phase = \"closed\" | \"opening\" | \"open\" | \"closing\";\n\nconst EASE = \"cubic-bezier(0.16,1,0.3,1)\";\nconst DURATION = 420;\nconst MAX_LIST = 280;\nconst PILL_SIZE = { sm: \"h-7 px-2.5 text-[12px]\", md: \"h-9 pl-4 pr-3.5 text-[13.5px]\" };\n// The theme travels with the list, so it matches the pill wherever the pill's colours were set.\nconst TOKENS = [\"--background\", \"--foreground\", \"--popover\", \"--popover-foreground\", \"--border\", \"--accent\", \"--accent-foreground\", \"--primary\", \"--primary-foreground\", \"--muted\", \"--muted-foreground\", \"--ring\"];\nconst FOCUS = \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/40\";\n\nconst reducedQuery = \"(prefers-reduced-motion: reduce)\";\nconst subscribeReduced = (onChange: () => void) => {\n  const query = window.matchMedia(reducedQuery);\n  query.addEventListener(\"change\", onChange);\n  return () => query.removeEventListener(\"change\", onChange);\n};\nconst useReducedMotion = () =>\n  React.useSyncExternalStore(subscribeReduced, () => window.matchMedia(reducedQuery).matches, () => false);\n\nfunction Chevron({ up, reduced }: { up: boolean; reduced: boolean }) {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"size-3 shrink-0 text-muted-foreground\" style={{ transform: up ? \"rotate(180deg)\" : \"none\", transition: reduced ? \"none\" : `transform 320ms ${EASE}` }}>\n      <path d=\"M4.5 6.25 8 9.75l3.5-3.5\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" strokeLinejoin=\"round\" />\n    </svg>\n  );\n}\n\nexport function PillSelect({\n  options,\n  value,\n  onValueChange,\n  label,\n  placeholder = \"Choose\",\n  display,\n  renderValue,\n  mono = false,\n  align = \"start\",\n  width = 240,\n  block = false,\n  muted = false,\n  disabled = false,\n  size = \"sm\",\n  className = \"\",\n}: PillSelectProps) {\n  const id = React.useId();\n  const reduced = useReducedMotion();\n  const [phase, setPhase] = React.useState<Phase>(\"closed\");\n  const [active, setActive] = React.useState(0);\n  const [pill, setPill] = React.useState({ width: 0, height: 28 });\n  const [panelHeight, setPanelHeight] = React.useState(0);\n  const [fit, setFit] = React.useState({ up: false, width, shift: 0, x: 0, y: 0, theme: {} as Record<string, string> });\n  const [highlight, setHighlight] = React.useState({ top: 0, height: 0, ready: false });\n  const [quiet, setQuiet] = React.useState(false);\n  const wrapRef = React.useRef<HTMLDivElement>(null);\n  const triggerRef = React.useRef<HTMLButtonElement>(null);\n  const panelRef = React.useRef<HTMLDivElement>(null);\n  const surfaceRef = React.useRef<HTMLDivElement>(null);\n  const listRef = React.useRef<HTMLDivElement>(null);\n  const rowRefs = React.useRef<(HTMLDivElement | null)[]>([]);\n  const timer = React.useRef(0);\n  const typed = React.useRef({ text: \"\", at: 0 });\n  const selected = options.find((o) => o.value === value);\n  const expanded = phase === \"open\";\n  const mounted = phase !== \"closed\";\n  const [prevPhase, setPrevPhase] = React.useState(phase);\n  if (phase !== prevPhase) {\n    setPrevPhase(phase);\n    if (phase === \"closed\") {\n      setHighlight({ top: 0, height: 0, ready: false });\n    }\n  }\n  const text = display ? display(selected) : (selected?.label ?? placeholder);\n\n  const measureFit = () => {\n    const wrap = wrapRef.current;\n    if (!wrap) return;\n    const rect = wrap.getBoundingClientRect();\n    const vw = document.documentElement.clientWidth;\n    const w = Math.min(Math.max(width, rect.width), vw - 24);\n    // Lined up with the pill's edge, nudged back on screen.\n    const shift = align === \"start\" ? Math.min(0, vw - 12 - (rect.left + w)) : Math.max(0, 12 - (rect.right - w));\n    const estimate = Math.min(MAX_LIST, options.length * (options.some((o) => o.description) ? 46 : 32)) + 12;\n    const vh = window.innerHeight;\n    const below = vh - 8 - rect.top;\n    const above = rect.bottom - 8;\n    const up = below < estimate + 8 && above > below;\n    // Fixed coordinates of the pill's corner the list grows from.\n    const x = align === \"start\" ? rect.left : vw - rect.right;\n    const y = up ? vh - rect.bottom : rect.top;\n    const cs = getComputedStyle(wrap);\n    const theme: Record<string, string> = { colorScheme: cs.colorScheme, fontFamily: cs.fontFamily };\n    for (const t of TOKENS) {\n      const v = cs.getPropertyValue(t);\n      if (v) theme[t] = v;\n    }\n    setFit({ up, width: w, shift, x, y, theme });\n  };\n\n  const open = () => {\n    if (disabled || phase === \"open\" || phase === \"opening\") return;\n    window.clearTimeout(timer.current);\n    measureFit();\n    setActive(Math.max(0, options.findIndex((o) => o.value === value)));\n    setPhase(reduced ? \"open\" : \"opening\");\n  };\n\n  const close = React.useCallback(\n    (refocus = true) => {\n      window.clearTimeout(timer.current);\n      if (refocus) triggerRef.current?.focus({ preventScroll: true });\n      if (reduced) return setPhase(\"closed\");\n      setPhase(\"closing\");\n      timer.current = window.setTimeout(() => setPhase(\"closed\"), DURATION);\n    },\n    [reduced],\n  );\n\n  React.useEffect(() => {\n    if (phase !== \"opening\") return;\n    let inner = 0;\n    const outer = requestAnimationFrame(() => (inner = requestAnimationFrame(() => setPhase(\"open\"))));\n    return () => {\n      cancelAnimationFrame(outer);\n      cancelAnimationFrame(inner);\n    };\n  }, [phase]);\n  React.useEffect(() => () => window.clearTimeout(timer.current), []);\n\n  React.useLayoutEffect(() => {\n    const trigger = triggerRef.current;\n    if (!trigger) return;\n    const measure = () => setPill((p) => (p.width === trigger.offsetWidth && p.height === trigger.offsetHeight ? p : { width: trigger.offsetWidth, height: trigger.offsetHeight }));\n    measure();\n    const observer = new ResizeObserver(measure);\n    observer.observe(trigger);\n    return () => observer.disconnect();\n  }, []);\n\n  React.useLayoutEffect(() => {\n    const panel = panelRef.current;\n    if (panel) setPanelHeight(panel.offsetHeight);\n  }, [mounted, options]);\n\n  // The highlight glides to the active row, and the list scrolls to keep it in view.\n  React.useLayoutEffect(() => {\n    const row = rowRefs.current[active];\n    const list = listRef.current;\n    if (!row || !list) return;\n    setHighlight((h) => (h.top === row.offsetTop && h.height === row.offsetHeight && h.ready === (h.ready || expanded) ? h : { top: row.offsetTop, height: row.offsetHeight, ready: h.ready || expanded }));\n    const scroller = list.parentElement;\n    if (scroller && scroller.scrollHeight > scroller.clientHeight) {\n      if (row.offsetTop < scroller.scrollTop) scroller.scrollTop = row.offsetTop - 4;\n      else if (row.offsetTop + row.offsetHeight > scroller.scrollTop + scroller.clientHeight) scroller.scrollTop = row.offsetTop + row.offsetHeight - scroller.clientHeight + 4;\n    }\n  }, [active, expanded, mounted]);\n\n  React.useEffect(() => {\n    if (expanded) listRef.current?.focus({ preventScroll: true });\n  }, [expanded]);\n\n  React.useEffect(() => {\n    if (!expanded) return;\n    const inside = (n: Node) => Boolean(wrapRef.current?.contains(n) || surfaceRef.current?.contains(n));\n    const onDown = (e: PointerEvent) => {\n      if (!inside(e.target as Node)) close(false);\n    };\n    // The list sits where the pill was; if the page moves under it, it goes at once rather than fold in the wrong place.\n    const gone = () => {\n      window.clearTimeout(timer.current);\n      setPhase(\"closed\");\n    };\n    const onScroll = (e: Event) => {\n      if (!surfaceRef.current?.contains(e.target as Node)) gone();\n    };\n    const onResize = gone;\n    document.addEventListener(\"pointerdown\", onDown);\n    window.addEventListener(\"scroll\", onScroll, true);\n    window.addEventListener(\"resize\", onResize);\n    return () => {\n      document.removeEventListener(\"pointerdown\", onDown);\n      window.removeEventListener(\"scroll\", onScroll, true);\n      window.removeEventListener(\"resize\", onResize);\n    };\n  }, [expanded, close]);\n\n  const choose = (o: PillOption) => {\n    close();\n    if (o.value !== value) onValueChange(o.value);\n  };\n\n  const onListKey = (e: React.KeyboardEvent) => {\n    const last = options.length - 1;\n    const move = (to: number) => {\n      e.preventDefault();\n      setActive(Math.max(0, Math.min(last, to)));\n    };\n    if (e.key === \"ArrowDown\") move(active === last ? 0 : active + 1);\n    else if (e.key === \"ArrowUp\") move(active === 0 ? last : active - 1);\n    else if (e.key === \"Home\") move(0);\n    else if (e.key === \"End\") move(last);\n    else if (e.key === \"PageDown\") move(active + 6);\n    else if (e.key === \"PageUp\") move(active - 6);\n    else if (e.key === \"Enter\" || e.key === \" \") {\n      e.preventDefault();\n      if (options[active]) choose(options[active]);\n    } else if (e.key === \"Tab\") close(false);\n    else if (e.key.length === 1 && /\\S/.test(e.key)) {\n      // A few letters typed quickly find the option that starts with them.\n      const now = performance.now();\n      typed.current = { text: (now - typed.current.at < 700 ? typed.current.text : \"\") + e.key.toLowerCase(), at: now };\n      const hit = options.findIndex((o) => o.label.toLowerCase().startsWith(typed.current.text));\n      if (hit !== -1) setActive(hit);\n    }\n  };\n\n  const w = expanded ? fit.width : pill.width;\n  const h = expanded ? panelHeight : pill.height;\n  const listId = `${id}-list`;\n  const pillText = renderValue ? null : (\n    <>\n      <span className={`min-w-0 flex-1 truncate text-left ${mono ? \"font-mono text-[11.5px]\" : \"\"} ${muted || !selected ? \"text-muted-foreground\" : \"text-foreground\"}`}>\n        {block ? text : <TextMorph>{text}</TextMorph>}\n      </span>\n      <Chevron up={expanded} reduced={reduced} />\n    </>\n  );\n\n  return (\n    <div\n      ref={wrapRef}\n      className={`relative ${block ? \"flex w-full min-w-0\" : \"inline-flex\"} ${className}`}\n      onKeyDown={(e) => {\n        setQuiet(false);\n        if (e.key === \"Escape\" && expanded) {\n          e.preventDefault();\n          e.stopPropagation();\n          close();\n        }\n      }}\n      onBlur={(e) => {\n        const to = e.relatedTarget as Node | null;\n        if (expanded && document.hasFocus() && !(to && (wrapRef.current?.contains(to) || surfaceRef.current?.contains(to)))) close(false);\n      }}\n    >\n      <button\n        ref={triggerRef}\n        type=\"button\"\n        aria-haspopup=\"listbox\"\n        aria-expanded={expanded}\n        aria-controls={mounted ? listId : undefined}\n        aria-label={`${label}: ${selected?.label ?? placeholder}`}\n        disabled={disabled}\n        onClick={() => (expanded ? close() : open())}\n        onKeyDown={(e) => {\n          if (e.key === \"ArrowDown\" || e.key === \"ArrowUp\") {\n            e.preventDefault();\n            open();\n          }\n        }}\n        onPointerDown={() => setQuiet(true)}\n        className={`inline-flex ${PILL_SIZE[size]} min-w-0 cursor-pointer items-center gap-1.5 rounded-full font-medium whitespace-nowrap shadow-[inset_0_0_0_1px_var(--border)] transition-colors duration-150 hover:bg-accent disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent ${block ? \"w-full\" : \"\"} ${quiet ? \"outline-none\" : FOCUS}`}\n      >\n        {renderValue ? renderValue(selected, expanded) : pillText}\n      </button>\n\n      {mounted &&\n        createPortal(\n        <div\n          ref={surfaceRef}\n          onKeyDown={(e) => {\n            if (e.key === \"Escape\") {\n              e.preventDefault();\n              e.stopPropagation();\n              close();\n            }\n          }}\n          onPointerDown={(e) => {\n            if (!(e.target as HTMLElement).closest(\"[data-scroll]\")) e.preventDefault();\n            setQuiet(true);\n          }}\n          className=\"fixed z-[60] overflow-hidden bg-popover text-popover-foreground\"\n          style={{\n            ...fit.theme,\n            [fit.up ? \"bottom\" : \"top\"]: fit.y,\n            [align === \"start\" ? \"left\" : \"right\"]: fit.x + (expanded ? (align === \"start\" ? fit.shift : -fit.shift) : 0),\n            width: w,\n            height: h,\n            borderRadius: expanded ? 16 : pill.height / 2,\n            // The pill's own hairline, the whole way: it is the same surface.\n            boxShadow: \"inset 0 0 0 1px var(--border)\",\n            transition: reduced ? \"none\" : `width ${DURATION}ms ${EASE}, height ${DURATION}ms ${EASE}, left ${DURATION}ms ${EASE}, right ${DURATION}ms ${EASE}, border-radius ${DURATION}ms ${EASE}`,\n          }}\n        >\n          {/* The pill's label, fading out as the surface grows and back in as it folds. */}\n          <span\n            aria-hidden=\"true\"\n            className={`pointer-events-none absolute inline-flex ${PILL_SIZE[size]} items-center gap-1.5 font-medium whitespace-nowrap ${fit.up ? \"bottom-0\" : \"top-0\"} ${align === \"start\" ? \"left-0\" : \"right-0\"}`}\n            style={{ width: pill.width, opacity: expanded ? 0 : 1, transition: reduced ? \"none\" : `opacity ${expanded ? 120 : 260}ms ${EASE} ${expanded ? 0 : 120}ms` }}\n          >\n            {renderValue ? renderValue(selected, expanded) : pillText}\n          </span>\n          <div\n            ref={panelRef}\n            className={`absolute p-1 ${fit.up ? \"bottom-0\" : \"top-0\"} ${align === \"start\" ? \"left-0\" : \"right-0\"}`}\n            style={{ width: fit.width, opacity: expanded ? 1 : 0, transition: reduced ? \"none\" : `opacity ${expanded ? 260 : 120}ms ${EASE} ${expanded ? 90 : 0}ms` }}\n          >\n            <div data-scroll=\"\" className=\"overflow-y-auto overscroll-contain\" style={{ maxHeight: MAX_LIST }}>\n              <div\n                ref={listRef}\n                id={listId}\n                role=\"listbox\"\n                tabIndex={-1}\n                aria-label={label}\n                aria-activedescendant={`${id}-o${active}`}\n                onKeyDown={onListKey}\n                className=\"relative outline-none\"\n              >\n                <span\n                  aria-hidden=\"true\"\n                  className=\"pointer-events-none absolute inset-x-0 top-0 rounded-[12px] bg-accent\"\n                  style={{\n                    height: highlight.height,\n                    transform: `translateY(${highlight.top}px)`,\n                    opacity: highlight.ready ? 1 : 0,\n                    transition: highlight.ready && !reduced ? `transform 260ms ${EASE}, height 260ms ${EASE}, opacity 200ms` : \"none\",\n                  }}\n                />\n                {options.map((o, i) => {\n                  const on = o.value === value;\n                  return (\n                    <div\n                      key={o.value}\n                      ref={(el) => {\n                        rowRefs.current[i] = el;\n                      }}\n                      id={`${id}-o${i}`}\n                      role=\"option\"\n                      aria-selected={on}\n                      onPointerMove={() => setActive(i)}\n                      onClick={() => choose(o)}\n                      className=\"relative flex cursor-pointer items-start gap-2 rounded-[12px] px-2.5 py-1.5\"\n                    >\n                      <span className=\"min-w-0 flex-1\">\n                        <span className={`block truncate ${mono ? \"font-mono text-[12px]\" : \"text-[12.5px] font-medium\"}`}>{o.label}</span>\n                        {o.description && <span className=\"mt-0.5 block truncate text-[11.5px] text-muted-foreground\">{o.description}</span>}\n                      </span>\n                      <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"mt-0.5 size-3.5 shrink-0\">\n                        <path\n                          d=\"M3.5 8.5 6.5 11.5 12.5 4.5\"\n                          stroke=\"currentColor\"\n                          strokeWidth=\"1.8\"\n                          strokeLinecap=\"round\"\n                          strokeLinejoin=\"round\"\n                          pathLength={1}\n                          strokeDasharray={1}\n                          style={{ strokeDashoffset: on && expanded ? 0 : 1, transition: reduced ? \"none\" : `stroke-dashoffset 380ms ${EASE} 160ms` }}\n                        />\n                      </svg>\n                    </div>\n                  );\n                })}\n              </div>\n            </div>\n          </div>\n        </div>,\n          document.body,\n        )}\n    </div>\n  );\n}\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · convert · 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"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · convert · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n/* ─────────────────────────────────────────────────────────\n * UI SOUNDS: small interface sounds, made in code\n *\n * No files and nothing to license: every sound is built from a\n * tone or a burst of noise with the Web Audio API the moment it\n * plays. They're short and quiet, made to sit under an interface,\n * and components only play them when you pass `sound`.\n *\n *   fold     paper creasing: two short crisp bursts\n *   unfold   paper opening: a soft rising sweep\n *   drop     something small landing: a low, soft knock\n *   tick     a light click\n *   pop      a quick bright blip\n *   success  two soft rising notes\n *   error    two low falling notes\n *\n * Browsers only start audio after the visitor has pressed\n * something on the page, so a sound before that stays silent.\n * ───────────────────────────────────────────────────────── */\n\nexport type UiSound = \"fold\" | \"unfold\" | \"drop\" | \"tick\" | \"pop\" | \"success\" | \"error\";\n\nlet context: AudioContext | null = null;\nlet noise: AudioBuffer | null = null;\n\nfunction audio() {\n  if (typeof window === \"undefined\") return null;\n  if (!context) {\n    const Ctx = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;\n    if (!Ctx) return null;\n    context = new Ctx();\n  }\n  if (context.state === \"suspended\") void context.resume().catch(() => {});\n  return context;\n}\n\nfunction noiseBuffer(ctx: AudioContext) {\n  if (noise && noise.sampleRate === ctx.sampleRate) return noise;\n  noise = ctx.createBuffer(1, Math.floor(ctx.sampleRate * 0.5), ctx.sampleRate);\n  const data = noise.getChannelData(0);\n  for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n  return noise;\n}\n\n/** A burst of filtered noise. */\nfunction burst(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"bandpass\", from = 2000, to = from, q = 0.9, level = 0.5 }: { type?: BiquadFilterType; from?: number; to?: number; q?: number; level?: number }) {\n  const src = ctx.createBufferSource();\n  src.buffer = noiseBuffer(ctx);\n  const filter = ctx.createBiquadFilter();\n  filter.type = type;\n  filter.Q.value = q;\n  filter.frequency.setValueAtTime(from, at);\n  filter.frequency.exponentialRampToValueAtTime(Math.max(40, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + Math.min(0.012, length / 3));\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  src.connect(filter).connect(gain).connect(out);\n  src.start(at, Math.random() * 0.3, length + 0.02);\n}\n\n/** A tone that glides from one pitch to another. */\nfunction tone(ctx: AudioContext, out: AudioNode, at: number, length: number, { type = \"sine\", from, to = from, level = 0.4 }: { type?: OscillatorType; from: number; to?: number; level?: number }) {\n  const osc = ctx.createOscillator();\n  osc.type = type;\n  osc.frequency.setValueAtTime(from, at);\n  osc.frequency.exponentialRampToValueAtTime(Math.max(20, to), at + length);\n  const gain = ctx.createGain();\n  gain.gain.setValueAtTime(0.0001, at);\n  gain.gain.exponentialRampToValueAtTime(level, at + 0.006);\n  gain.gain.exponentialRampToValueAtTime(0.0001, at + length);\n  osc.connect(gain).connect(out);\n  osc.start(at);\n  osc.stop(at + length + 0.02);\n}\n\n/** Plays one sound. `volume` is 0 to 1; the default sits quietly under an interface. */\nexport function playSound(name: UiSound, volume = 0.5) {\n  const ctx = audio();\n  if (!ctx) return;\n  const out = ctx.createGain();\n  out.gain.value = Math.max(0, Math.min(1, volume)) * 0.5;\n  out.connect(ctx.destination);\n  const t = ctx.currentTime + 0.005;\n  switch (name) {\n    case \"fold\":\n      burst(ctx, out, t, 0.05, { type: \"highpass\", from: 2600, q: 0.7, level: 0.45 });\n      burst(ctx, out, t + 0.07, 0.07, { type: \"bandpass\", from: 3200, to: 1800, q: 1.2, level: 0.35 });\n      break;\n    case \"unfold\":\n      burst(ctx, out, t, 0.16, { type: \"bandpass\", from: 900, to: 2800, q: 0.8, level: 0.3 });\n      break;\n    case \"drop\":\n      tone(ctx, out, t, 0.12, { from: 180, to: 70, level: 0.55 });\n      burst(ctx, out, t, 0.03, { type: \"lowpass\", from: 1200, q: 0.5, level: 0.2 });\n      break;\n    case \"tick\":\n      tone(ctx, out, t, 0.025, { type: \"triangle\", from: 1900, to: 1500, level: 0.25 });\n      break;\n    case \"pop\":\n      tone(ctx, out, t, 0.06, { from: 620, to: 980, level: 0.3 });\n      break;\n    case \"success\":\n      tone(ctx, out, t, 0.11, { from: 660, level: 0.22 });\n      tone(ctx, out, t + 0.09, 0.16, { from: 990, level: 0.22 });\n      break;\n    case \"error\":\n      tone(ctx, out, t, 0.12, { type: \"triangle\", from: 330, level: 0.25 });\n      tone(ctx, out, t + 0.1, 0.18, { type: \"triangle\", from: 247, level: 0.25 });\n      break;\n  }\n  window.setTimeout(() => out.disconnect(), 600);\n}\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/convert. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}