{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"amount-field","type":"registry:component","title":"Amount field","description":"A hero auto-scaling money and credits input with spring typography scaling, a gliding velocity-stretch caret, smooth Max roll-up and live overdraft feedback.","author":"Hairline UI","dependencies":[],"files":[{"path":"registry/amount-field.tsx","type":"registry:component","content":"// Hairline UI · amount-field · 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  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  createSpring,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * AMOUNT FIELD: hero auto-scale money & credits composer\n *\n *   scale     the figure is the hero: as digits arrive, a spring\n *             measures real text width and scales typography down\n *             smoothly (56px -> 24px) so large amounts never wrap\n *             or clip, then breathes back up as you delete\n *\n *   motion    thousands separators open smoothly between digits\n *             by place-value key; the hairline caret glides on a\n *             spring with subtle velocity stretch and blinks only\n *             at rest; clicking Max or a preset smoothly rolls the\n *             figure from its current value\n *\n *   balance   crossing `balance` triggers a damped recoil + rose\n *             8×8 Bayer floor pulse, tints the figure crimson and\n *             names the exact shortfall with a one-tap Set to max\n * ───────────────────────────────────────────────────────── */\n\nexport interface AmountConversion {\n  /** Multiplier applied to the entered numeric amount (e.g. 0.9214 for USD -> EUR, or 1000 for $ -> credits). */\n  rate: number;\n  /** Target ISO 4217 currency code (e.g. \"EUR\", \"GBP\"). */\n  currency?: string;\n  /** Target non-currency unit label (e.g. \"credits\", \"ETH\", \"pts\"). */\n  unit?: string;\n  /** Fraction digits for the converted output (defaults to 2 for currency, 0 for unit). */\n  decimals?: number;\n  /** Optional rate note displayed beside the output (e.g. \"1 USD = 0.9214 EUR\"). */\n  rateLabel?: string;\n}\n\nexport interface AmountFieldProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"defaultValue\" | \"onChange\"> {\n  /** Controlled numeric value, or null when empty. */\n  value?: number | null;\n  /** Initial uncontrolled value (default null). */\n  defaultValue?: number | null;\n  /** Called with the parsed number or null whenever the value changes. */\n  onChange?: (value: number | null) => void;\n  /** ISO 4217 currency code (default \"USD\"). */\n  currency?: string;\n  /** Explicit symbol or token label overriding Intl's currency symbol (e.g. \"USDC\"). */\n  symbol?: string;\n  /** Where the symbol renders relative to the figure (default \"prefix\"). */\n  symbolPosition?: \"prefix\" | \"suffix\";\n  /** BCP 47 locale for grouping and decimal marks (default \"en-US\"). */\n  locale?: string;\n  /** Max fractional digits allowed (defaults to currency's standard fraction digits). */\n  decimals?: number;\n  /** Available balance or spending cap: enables Max roll-up and overdraft shortfall readout. */\n  balance?: number;\n  /** Optional quick-pick preset amounts (e.g. [50, 250, 1000]). */\n  presets?: number[];\n  /** Optional live FX or credits conversion readout underneath the figure. */\n  conversion?: AmountConversion;\n  /** Accessible name for the numeric input (default \"Amount\"). */\n  label?: string;\n  /** Disabled state. */\n  disabled?: boolean;\n  /** Opt-in quiet Web Audio ticks on typing, preset roll and overdraft (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\ninterface GlyphToken {\n  key: string;\n  ch: string;\n  kind: \"digit\" | \"sep\" | \"dot\" | \"frac\";\n  /** Character index inside raw `draft` immediately AFTER this glyph. */\n  rawAfter: number;\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++) {\n      out[(y << 3) | x] = (m[y][x] + 0.5) / 64;\n    }\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\nconst clamp = (v: number, lo: number, hi: number) => (v < lo ? lo : v > hi ? hi : v);\nconst clamp01 = (v: number) => (Number.isFinite(v) ? clamp(v, 0, 1) : 0);\n\nfunction getLocaleMeta(locale: string, currency: string) {\n  let group = \",\";\n  let decimal = \".\";\n  let curSymbol = \"$\";\n  let defaultDecimals = 2;\n  try {\n    const nf = new Intl.NumberFormat(locale, { style: \"currency\", currency });\n    const opts = nf.resolvedOptions();\n    defaultDecimals = opts.maximumFractionDigits ?? 2;\n    const parts = nf.formatToParts(12345.67);\n    for (const p of parts) {\n      if (p.type === \"group\") group = p.value;\n      else if (p.type === \"decimal\") decimal = p.value;\n      else if (p.type === \"currency\") curSymbol = p.value;\n    }\n  } catch {\n    // Fallback to USD/en-US defaults\n  }\n  return { group, decimal, curSymbol, defaultDecimals };\n}\n\nfunction numberToDraft(n: number | null | undefined, maxDecimals: number): string {\n  if (n === null || n === undefined || !Number.isFinite(n)) return \"\";\n  const abs = Math.max(0, n);\n  if (maxDecimals <= 0) return String(Math.round(abs));\n  const fixed = abs.toFixed(maxDecimals);\n  // Trim unnecessary trailing zeroes while preserving clean decimals\n  return fixed.replace(/\\.?0+$/, \"\") || \"0\";\n}\n\nfunction sanitizeDraft(raw: string, maxDecimals: number, localeDecimal: string): string {\n  let s = raw.replace(/\\s+/g, \"\");\n  // Normalize pasted European decimal comma when unambiguous\n  if (localeDecimal === \",\") {\n    s = s.replace(/\\./g, \"\").replace(/,/g, \".\");\n  } else {\n    s = s.replace(/,/g, \"\");\n  }\n  let out = \"\";\n  let seenDot = false;\n  let intCount = 0;\n  let fracCount = 0;\n\n  for (let i = 0; i < s.length; i++) {\n    const ch = s[i];\n    if (ch >= \"0\" && ch <= \"9\") {\n      if (seenDot) {\n        if (fracCount < maxDecimals) {\n          out += ch;\n          fracCount++;\n        }\n      } else {\n        if (intCount < 11) {\n          out += ch;\n          intCount++;\n        }\n      }\n    } else if (ch === \".\" && maxDecimals > 0 && !seenDot) {\n      if (out.length === 0) {\n        out = \"0.\";\n        intCount = 1;\n      } else {\n        out += \".\";\n      }\n      seenDot = true;\n    }\n  }\n\n  // Strip redundant leading zeros like \"005\" -> \"5\", keeping \"0\" and \"0.xxx\"\n  if (!seenDot && out.length > 1 && out.startsWith(\"0\")) {\n    out = out.replace(/^0+/, \"\") || \"0\";\n  } else if (seenDot && out.startsWith(\"00\")) {\n    const [ip, fp] = out.split(\".\");\n    out = `${ip.replace(/^0+/, \"\") || \"0\"}.${fp ?? \"\"}`;\n  }\n  return out;\n}\n\nfunction parseDraft(draft: string): number | null {\n  if (!draft) return null;\n  const n = Number(draft);\n  return Number.isFinite(n) ? n : null;\n}\n\nfunction formatMoney(n: number, locale: string, currency: string, symbolOverride?: string, symbolPosition: \"prefix\" | \"suffix\" = \"prefix\", decimals?: number): string {\n  if (symbolOverride) {\n    const formatted = new Intl.NumberFormat(locale, {\n      minimumFractionDigits: decimals ?? 0,\n      maximumFractionDigits: decimals ?? 2,\n    }).format(n);\n    return symbolPosition === \"suffix\" ? `${formatted} ${symbolOverride}` : `${symbolOverride}${formatted}`;\n  }\n  try {\n    return new Intl.NumberFormat(locale, {\n      style: \"currency\",\n      currency,\n      ...(decimals !== undefined ? { minimumFractionDigits: decimals, maximumFractionDigits: decimals } : {}),\n    }).format(n);\n  } catch {\n    return `$${n.toLocaleString(locale)}`;\n  }\n}\n\nfunction buildTokens(draft: string, groupSep: string, decimalSep: string): GlyphToken[] {\n  if (!draft) return [];\n  const dotIdx = draft.indexOf(\".\");\n  const intPart = dotIdx === -1 ? draft : draft.slice(0, dotIdx);\n  const fracPart = dotIdx === -1 ? \"\" : draft.slice(dotIdx + 1);\n\n  const tokens: GlyphToken[] = [];\n  const len = intPart.length;\n\n  for (let i = 0; i < len; i++) {\n    const placeFromRight = len - 1 - i;\n    tokens.push({\n      key: `int-${placeFromRight}`,\n      ch: intPart[i],\n      kind: \"digit\",\n      rawAfter: i + 1,\n    });\n    if (placeFromRight > 0 && placeFromRight % 3 === 0) {\n      tokens.push({\n        key: `sep-${placeFromRight / 3}`,\n        ch: groupSep,\n        kind: \"sep\",\n        rawAfter: i + 1,\n      });\n    }\n  }\n\n  if (dotIdx !== -1) {\n    tokens.push({\n      key: \"dot\",\n      ch: decimalSep,\n      kind: \"dot\",\n      rawAfter: dotIdx + 1,\n    });\n    for (let j = 0; j < fracPart.length; j++) {\n      tokens.push({\n        key: `frac-${j}`,\n        ch: fracPart[j],\n        kind: \"frac\",\n        rawAfter: dotIdx + 2 + j,\n      });\n    }\n  }\n\n  return tokens;\n}\n\nexport function AmountField({\n  value: controlledValue,\n  defaultValue = null,\n  onChange,\n  currency = \"USD\",\n  symbol,\n  symbolPosition = \"prefix\",\n  locale = \"en-US\",\n  decimals: decimalsProp,\n  balance,\n  presets,\n  conversion,\n  label = \"Amount\",\n  disabled = false,\n  sound = false,\n  className = \"\",\n  ...props\n}: AmountFieldProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();\n\n  const meta = React.useMemo(() => getLocaleMeta(locale, currency), [locale, currency]);\n  const maxDecimals = decimalsProp ?? meta.defaultDecimals;\n  const displaySymbol = symbol ?? meta.curSymbol;\n\n  const [draft, setDraft] = React.useState<string>(() =>\n    numberToDraft(controlledValue !== undefined ? controlledValue : defaultValue, maxDecimals),\n  );\n  const [rollingDraft, setRollingDraft] = React.useState<string | null>(null);\n  const [focused, setFocused] = React.useState(false);\n  const [caretRawIdx, setCaretRawIdx] = React.useState<number>(() => draft.length);\n  const [caretIdle, setCaretIdle] = React.useState(true);\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n\n  // Sync controlled value changes when they differ from current parsed draft (preserves typing \"12.\" cleanly)\n  const draftNum = parseDraft(draft);\n  const effectiveNum = controlledValue !== undefined ? controlledValue : draftNum;\n  const shownDraft =\n    rollingDraft !== null\n      ? rollingDraft\n      : controlledValue !== undefined && controlledValue !== draftNum\n        ? numberToDraft(controlledValue, maxDecimals)\n        : draft;\n\n  const isOverBalance = balance !== undefined && effectiveNum !== null && effectiveNum > balance;\n  const shortfall = isOverBalance && balance !== undefined && effectiveNum !== null ? effectiveNum - balance : 0;\n\n  const tokens = React.useMemo(\n    () => buildTokens(shownDraft, meta.group, meta.decimal),\n    [shownDraft, meta.group, meta.decimal],\n  );\n\n  const stageRef = React.useRef<HTMLDivElement>(null);\n  const scalerRef = React.useRef<HTMLDivElement>(null);\n  const measureRef = React.useRef<HTMLSpanElement>(null);\n  const digitsRef = React.useRef<HTMLSpanElement>(null);\n  const caretElRef = React.useRef<HTMLSpanElement>(null);\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const floorCanvasRef = React.useRef<HTMLCanvasElement>(null);\n\n  const scaleSpringRef = React.useRef<Spring | null>(null);\n  const caretSpringRef = React.useRef<Spring | null>(null);\n  const recoilSpringRef = React.useRef<Spring | null>(null);\n  const rollRafRef = React.useRef(0);\n  const idleTimerRef = React.useRef(0);\n  const prevOverRef = React.useRef(false);\n  const flashTriggerRef = React.useRef<((kind: \"over\" | \"roll\") => void) | null>(null);\n\n  // Measure unscaled natural figure width vs available stage width (with generous side breathing room) -> drive fluid scaleSpring!\n  const updateScale = React.useCallback(\n    (jumpNow = false) => {\n      const stage = stageRef.current;\n      const measure = measureRef.current;\n      const sp = scaleSpringRef.current;\n      if (!stage || !measure || !sp) return;\n      const avail = Math.max(120, stage.clientWidth - 64);\n      const natural = Math.max(1, measure.offsetWidth);\n      const target = clamp(avail / natural, 0.42, 1);\n      if (jumpNow || reduced) sp.jump(target);\n      else sp.set(target);\n    },\n    [reduced],\n  );\n\n  // Measure exact caret X inside `digitsRef` for current `caretRawIdx` -> drive spring-gliding caret!\n  const updateCaretPos = React.useCallback(\n    (rawIdx: number, jumpNow = false) => {\n      const digitsEl = digitsRef.current;\n      const sp = caretSpringRef.current;\n      if (!digitsEl || !sp) return;\n\n      let targetX = 0;\n      if (shownDraft.length > 0) {\n        const clamped = clamp(rawIdx, 0, shownDraft.length);\n        const children = digitsEl.children;\n        // Find last glyph whose rawAfter <= clamped\n        let lastMatch = -1;\n        for (let i = 0; i < tokens.length; i++) {\n          if (tokens[i].rawAfter <= clamped) lastMatch = i;\n        }\n        if (lastMatch >= 0 && children[lastMatch]) {\n          const el = children[lastMatch] as HTMLElement;\n          targetX = el.offsetLeft + el.offsetWidth;\n        } else if (children[0]) {\n          targetX = (children[0] as HTMLElement).offsetLeft;\n        }\n      }\n\n      if (jumpNow || reduced) sp.jump(targetX);\n      else sp.set(targetX);\n    },\n    [shownDraft.length, tokens, reduced],\n  );\n\n  const bumpCaretActive = React.useCallback(() => {\n    setCaretIdle(false);\n    window.clearTimeout(idleTimerRef.current);\n    idleTimerRef.current = window.setTimeout(() => setCaretIdle(true), 420);\n  }, []);\n\n  React.useEffect(() => () => window.clearTimeout(idleTimerRef.current), []);\n\n  // Core springs: fluid optical auto-scale, gliding velocity-stretch caret, overdraft recoil\n  React.useEffect(() => {\n    const scaleSp = createSpring(\n      1,\n      { stiffness: 250, damping: 25 },\n      () => {\n        if (!scalerRef.current) return;\n        const s = scaleSp.get();\n        const rx = recoilSpringRef.current?.get() ?? 0;\n        scalerRef.current.style.transform = `translate3d(${rx.toFixed(2)}px, 0, 0) scale(${s.toFixed(4)})`;\n      },\n      0.001,\n    );\n\n    const recoilSp = createSpring(\n      0,\n      { stiffness: 450, damping: 17 },\n      () => {\n        if (!scalerRef.current) return;\n        const s = scaleSp.get();\n        const rx = recoilSp.get();\n        scalerRef.current.style.transform = `translate3d(${rx.toFixed(2)}px, 0, 0) scale(${s.toFixed(4)})`;\n      },\n      0.04,\n    );\n\n    const caretSp = createSpring(\n      0,\n      { stiffness: 360, damping: 28 },\n      () => {\n        const el = caretElRef.current;\n        if (!el) return;\n        const x = caretSp.get();\n        const vel = Math.abs(caretSp.getVelocity());\n        // Subtle velocity stretch as the hairline caret glides between digits\n        const stretch = clamp(1 + vel / 900, 1, 1.85);\n        el.style.transform = `translate3d(${x.toFixed(2)}px, 0, 0) scaleX(${stretch.toFixed(3)})`;\n      },\n      0.1,\n    );\n\n    scaleSpringRef.current = scaleSp;\n    recoilSpringRef.current = recoilSp;\n    caretSpringRef.current = caretSp;\n\n    const ro = new ResizeObserver(() => updateScale(true));\n    if (stageRef.current) ro.observe(stageRef.current);\n\n    return () => {\n      ro.disconnect();\n      scaleSp.stop();\n      recoilSp.stop();\n      caretSp.stop();\n      cancelAnimationFrame(rollRafRef.current);\n      scaleSpringRef.current = null;\n      recoilSpringRef.current = null;\n      caretSpringRef.current = null;\n    };\n  }, [updateScale]);\n\n  // Re-evaluate scale & caret position whenever displayed tokens change\n  React.useLayoutEffect(() => {\n    updateScale(false);\n    updateCaretPos(caretRawIdx, false);\n  }, [shownDraft, tokens, caretRawIdx, updateScale, updateCaretPos]);\n\n  // Optical 8×8 Bayer edge floor pulse (runs strictly during a 0.48s overdraft or Max roll flash -> 0% CPU at rest!)\n  React.useEffect(() => {\n    const canvas = floorCanvasRef.current;\n    const ctx = canvas?.getContext(\"2d\");\n    if (!canvas || !ctx) return;\n\n    const gridCanvas = document.createElement(\"canvas\");\n    const gridCtx = gridCanvas.getContext(\"2d\");\n    if (!gridCtx) return;\n\n    let raf = 0;\n    let flashKind: \"none\" | \"over\" | \"roll\" = \"none\";\n    let age = 0;\n    let last = 0;\n    let gCols = 0;\n    let gRows = 0;\n    let gridImg: ImageData | null = null;\n    let gridU32: Uint32Array | null = null;\n\n    const tick = (now: number) => {\n      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;\n      last = now;\n      age += dt;\n      const life = flashKind === \"over\" ? 0.5 : 0.48;\n      if (age >= life || !onScreen || reduced) {\n        flashKind = \"none\";\n        raf = 0;\n        ctx.clearRect(0, 0, canvas.width, canvas.height);\n        return;\n      }\n\n      const rect = canvas.getBoundingClientRect();\n      const w = Math.round(rect.width);\n      const h = Math.round(rect.height);\n      if (w > 0 && h > 0) {\n        const dpr = Math.min(2, window.devicePixelRatio || 1);\n        if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) {\n          canvas.width = Math.round(w * dpr);\n          canvas.height = Math.round(h * dpr);\n        }\n        const pitch = 1.5;\n        const cols = Math.max(1, Math.ceil(w / pitch));\n        const rows = Math.max(1, Math.ceil(h / pitch));\n        if (cols !== gCols || rows !== gRows || !gridImg || !gridU32) {\n          gCols = cols;\n          gRows = rows;\n          gridCanvas.width = cols;\n          gridCanvas.height = rows;\n          gridImg = gridCtx.createImageData(cols, rows);\n          gridU32 = new Uint32Array(gridImg.data.buffer);\n        }\n        const u32 = gridU32;\n        u32.fill(0);\n        const k = age / life;\n        const fade = Math.sin(Math.PI * Math.pow(k, 0.72));\n        const front = (1 - Math.pow(1 - k, 2.2)) * 1.16 - 0.06;\n        const rgb: [number, number, number] = flashKind === \"over\" ? [239, 68, 68] : [52, 211, 153];\n\n        for (let r = 0; r < rows; r++) {\n          const v = (r + 0.5) / rows;\n          const floorV = Math.pow(v, 1.8);\n          const bRow = (r & 7) << 3;\n          const rowOff = r * cols;\n          for (let c = 0; c < cols; c++) {\n            const u = (c + 0.5) / cols;\n            let boost = 0;\n            if (flashKind === \"over\") {\n              boost = floorV * (0.45 + 0.55 * Math.pow(1 - Math.abs(u - 0.5) * 2, 0.6)) * fade;\n            } else {\n              const df = u - front;\n              const lead = Math.exp(-(df * df) / 0.022);\n              const tail = df < 0 ? Math.exp(df / 0.24) * 0.45 : 0;\n              boost = floorV * (lead + tail) * fade;\n            }\n            const bayer = BAYER8[bRow | (c & 7)];\n            const hit = clamp01((boost * 0.85 - bayer + 0.05) / 0.14);\n            if (hit > 0.02) {\n              u32[rowOff + c] = packRgba(rgb[0], rgb[1], rgb[2], hit * 0.68 * 255);\n            }\n          }\n        }\n        gridCtx.putImageData(gridImg, 0, 0);\n        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);\n        ctx.clearRect(0, 0, w, h);\n        ctx.imageSmoothingEnabled = false;\n        ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch);\n      }\n\n      raf = requestAnimationFrame(tick);\n    };\n\n    flashTriggerRef.current = (kind) => {\n      if (reduced || !onScreen) return;\n      flashKind = kind;\n      age = 0;\n      last = 0;\n      if (!raf) raf = requestAnimationFrame(tick);\n    };\n\n    return () => {\n      flashTriggerRef.current = null;\n      cancelAnimationFrame(raf);\n    };\n  }, [onScreen, reduced]);\n\n  // Fire overdraft recoil + Bayer floor pulse strictly on crossing into overdraft (never spamming every keystroke)\n  React.useEffect(() => {\n    if (isOverBalance && !prevOverRef.current) {\n      if (!reduced) recoilSpringRef.current?.push(165);\n      flashTriggerRef.current?.(\"over\");\n      if (sound) playSound(\"error\", 0.34);\n    }\n    prevOverRef.current = isOverBalance;\n  }, [isOverBalance, reduced, sound]);\n\n  const commitDraft = React.useCallback(\n    (nextDraft: string, nextCaret?: number) => {\n      cancelAnimationFrame(rollRafRef.current);\n      setRollingDraft(null);\n      setDraft(nextDraft);\n      const parsed = parseDraft(nextDraft);\n      onChange?.(parsed);\n      setCaretRawIdx(nextCaret ?? nextDraft.length);\n      bumpCaretActive();\n    },\n    [onChange, bumpCaretActive],\n  );\n\n  // Smooth bounded ease-out roll-up / roll-down for Max and quick preset pills (commits cleanly in 260ms at any scale!)\n  const rollToAmount = React.useCallback(\n    (targetAmount: number, announceLabel?: string) => {\n      if (disabled) return;\n      const start = effectiveNum ?? 0;\n      const cleanTarget = Math.max(0, Number(targetAmount.toFixed(maxDecimals)));\n      const finalStr = numberToDraft(cleanTarget, maxDecimals);\n\n      cancelAnimationFrame(rollRafRef.current);\n      setDraft(finalStr);\n      onChange?.(cleanTarget);\n      setCaretRawIdx(finalStr.length);\n      if (announceLabel) setLiveStatus(announceLabel);\n\n      if (reduced || Math.abs(cleanTarget - start) < 1e-6) {\n        setRollingDraft(null);\n        if (sound) playSound(\"pop\", 0.32);\n        return;\n      }\n\n      flashTriggerRef.current?.(\"roll\");\n      if (sound) playSound(\"pop\", 0.32);\n\n      const duration = 260;\n      const t0 = performance.now();\n      let lastPaint = 0;\n\n      const step = (now: number) => {\n        const k = clamp01((now - t0) / duration);\n        if (k >= 1) {\n          setRollingDraft(null);\n          rollRafRef.current = 0;\n          return;\n        }\n        // Throttle visual roll updates to ~30fps (~8 smooth steps) so 4x CPU stays locked at 60fps\n        if (now - lastPaint >= 28) {\n          lastPaint = now;\n          const eased = 1 - Math.pow(1 - k, 3);\n          const cur = start + (cleanTarget - start) * eased;\n          const rounded = maxDecimals > 0 && Math.abs(cleanTarget - start) < 100 ? Number(cur.toFixed(maxDecimals)) : Math.round(cur);\n          setRollingDraft(numberToDraft(Math.max(0, rounded), maxDecimals));\n        }\n        rollRafRef.current = requestAnimationFrame(step);\n      };\n\n      rollRafRef.current = requestAnimationFrame(step);\n    },\n    [disabled, effectiveNum, maxDecimals, reduced, sound, onChange],\n  );\n\n  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const raw = e.target.value;\n    const sel = e.target.selectionStart ?? raw.length;\n    const clean = sanitizeDraft(raw, maxDecimals, meta.decimal);\n    const delta = raw.length - clean.length;\n    const nextSel = clamp(sel - delta, 0, clean.length);\n    commitDraft(clean, nextSel);\n    if (sound && clean.length > shownDraft.length) playSound(\"tick\", 0.24);\n  };\n\n  const syncSelectionFromInput = () => {\n    const el = inputRef.current;\n    if (!el) return;\n    setCaretRawIdx(clamp(el.selectionStart ?? shownDraft.length, 0, shownDraft.length));\n    bumpCaretActive();\n  };\n\n  // Click anywhere on the hero figure to place the caret at the nearest character boundary\n  const handleStagePointerDown = (e: React.PointerEvent<HTMLDivElement>) => {\n    if (disabled) return;\n    if ((e.target as HTMLElement).closest(\"button\")) return;\n    e.preventDefault();\n    const input = inputRef.current;\n    if (!input) return;\n    input.focus();\n\n    const digitsEl = digitsRef.current;\n    if (digitsEl && tokens.length > 0) {\n      let bestRaw = shownDraft.length;\n      let bestDist = Infinity;\n      const children = digitsEl.children;\n      // Check position before first glyph\n      if (children[0]) {\n        const r0 = (children[0] as HTMLElement).getBoundingClientRect();\n        bestDist = Math.abs(e.clientX - r0.left);\n        bestRaw = 0;\n      }\n      for (let i = 0; i < tokens.length; i++) {\n        const el = children[i] as HTMLElement | undefined;\n        if (!el) continue;\n        const r = el.getBoundingClientRect();\n        const dist = Math.abs(e.clientX - r.right);\n        if (dist < bestDist) {\n          bestDist = dist;\n          bestRaw = tokens[i].rawAfter;\n        }\n      }\n      input.setSelectionRange(bestRaw, bestRaw);\n      setCaretRawIdx(bestRaw);\n      bumpCaretActive();\n    } else {\n      input.setSelectionRange(shownDraft.length, shownDraft.length);\n      setCaretRawIdx(shownDraft.length);\n      bumpCaretActive();\n    }\n  };\n\n  // Live conversion output\n  const convertedText = React.useMemo(() => {\n    if (!conversion) return null;\n    const base = effectiveNum ?? 0;\n    const out = base * conversion.rate;\n    const dec = conversion.decimals ?? (conversion.currency ? 2 : 0);\n    if (conversion.currency) {\n      return formatMoney(out, locale, conversion.currency, undefined, \"prefix\", dec);\n    }\n    const numStr = new Intl.NumberFormat(locale, {\n      minimumFractionDigits: dec,\n      maximumFractionDigits: dec,\n    }).format(out);\n    return conversion.unit ? `${numStr} ${conversion.unit}` : numStr;\n  }, [conversion, effectiveNum, locale]);\n\n  const showFooterRow = balance !== undefined || Boolean(conversion);\n  const showPresetsRow = Boolean(presets && presets.length > 0);\n\n  return (\n    <div ref={rootRef} className={`flex w-full flex-col gap-2.5 ${className}`} {...props}>\n      {/* Hairline hero composer card */}\n      <div\n        data-focused={focused ? \"true\" : \"false\"}\n        data-over-balance={isOverBalance ? \"true\" : \"false\"}\n        className={`relative overflow-hidden rounded-[18px] border bg-card text-card-foreground transition-[border-color,box-shadow] duration-200 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          isOverBalance\n            ? \"border-red-500/45 dark:border-red-400/45\"\n            : focused\n              ? \"border-foreground/25\"\n              : \"border-border hover:border-foreground/20\"\n        } ${disabled ? \"opacity-55\" : \"\"}`}\n      >\n        {/* Subtle 8×8 Bayer optical floor pulse on overdraft or Max roll (0% CPU at rest) */}\n        <canvas\n          ref={floorCanvasRef}\n          aria-hidden=\"true\"\n          className=\"pointer-events-none absolute inset-x-1 bottom-1 z-0 h-8 w-[calc(100%_-_8px)] rounded-b-[13px]\"\n        />\n\n        {/* Hero auto-scaling interactive figure stage */}\n        <div\n          ref={stageRef}\n          onPointerDown={handleStagePointerDown}\n          className={`relative z-10 flex h-[108px] w-full items-center justify-center px-4 ${\n            disabled ? \"cursor-not-allowed\" : \"cursor-text\"\n          }`}\n        >\n          {/* Native decimal input: owns real keyboard, paste, selection, undo & mobile numeric keypad */}\n          <input\n            ref={inputRef}\n            type=\"text\"\n            inputMode={maxDecimals > 0 ? \"decimal\" : \"numeric\"}\n            autoComplete=\"off\"\n            spellCheck={false}\n            disabled={disabled}\n            aria-label={label}\n            aria-invalid={isOverBalance || undefined}\n            value={shownDraft}\n            onChange={handleInputChange}\n            onSelect={syncSelectionFromInput}\n            onKeyUp={syncSelectionFromInput}\n            onFocus={() => {\n              setFocused(true);\n              syncSelectionFromInput();\n            }}\n            onBlur={() => setFocused(false)}\n            className=\"sr-only\"\n          />\n\n          {/* Spring-scaled hero typography */}\n          <div ref={scalerRef} className=\"origin-center will-change-transform\">\n            <span\n              ref={measureRef}\n              aria-hidden=\"true\"\n              className={`inline-flex items-baseline whitespace-nowrap font-sans text-[54px] font-medium leading-none tracking-[-0.04em] tabular-nums transition-colors duration-200 ${\n                isOverBalance ? \"text-red-600 dark:text-red-400\" : \"text-foreground\"\n              }`}\n            >\n              {symbolPosition === \"prefix\" && (\n                <span\n                  className={`mr-1 text-[0.62em] font-normal tracking-normal transition-colors duration-200 ${\n                    isOverBalance\n                      ? \"text-red-500/80 dark:text-red-400/80\"\n                      : shownDraft\n                        ? \"text-muted-foreground\"\n                        : \"text-muted-foreground/45\"\n                  }`}\n                >\n                  {displaySymbol}\n                </span>\n              )}\n\n              {/* Digit tokens + smooth spring-gliding hairline caret */}\n              <span className=\"relative inline-flex items-baseline\">\n                <span ref={digitsRef} className=\"inline-flex items-baseline\">\n                  {tokens.length === 0 ? (\n                    <span className=\"text-muted-foreground/35\">0</span>\n                  ) : (\n                    tokens.map((tok) => (\n                      <span\n                        key={tok.key}\n                        className={\n                          tok.kind === \"sep\"\n                            ? `inline-block ${isOverBalance ? \"text-red-500/70 dark:text-red-400/70\" : \"text-muted-foreground/65\"}`\n                            : tok.kind === \"dot\" || tok.kind === \"frac\"\n                              ? `inline-block ${isOverBalance ? \"text-red-500/85 dark:text-red-400/85\" : \"text-foreground/75\"}`\n                              : \"inline-block\"\n                        }\n                      >\n                        {tok.ch}\n                      </span>\n                    ))\n                  )}\n                </span>\n\n                {/* Spring-gliding hairline caret (blinks only at rest!) */}\n                <span\n                  ref={caretElRef}\n                  aria-hidden=\"true\"\n                  className={`pointer-events-none absolute left-0 top-[0.06em] h-[0.92em] w-[2px] origin-left rounded-full transition-opacity duration-150 ${\n                    isOverBalance ? \"bg-red-500\" : \"bg-primary\"\n                  } ${focused ? (caretIdle && !reduced ? \"animate-pulse opacity-100\" : \"opacity-100\") : \"opacity-0\"}`}\n                />\n              </span>\n\n              {symbolPosition === \"suffix\" && (\n                <span\n                  className={`ml-2 text-[0.42em] font-medium tracking-normal uppercase transition-colors duration-200 ${\n                    isOverBalance ? \"text-red-500/80 dark:text-red-400/80\" : \"text-muted-foreground\"\n                  }`}\n                >\n                  {displaySymbol}\n                </span>\n              )}\n            </span>\n          </div>\n        </div>\n\n        {/* Hairline balance / overdraft / conversion footer */}\n        {showFooterRow && (\n          <div className=\"relative z-10 flex flex-wrap items-center justify-between gap-2 border-t border-border/80 bg-muted/20 px-3.5 py-2.5 text-[12px]\">\n            {balance !== undefined ? (\n              isOverBalance ? (\n                <div className=\"flex w-full items-center justify-between gap-2\">\n                  <span role=\"alert\" className=\"font-medium tabular-nums text-red-600 dark:text-red-400\">\n                    {formatMoney(shortfall, locale, currency, symbol, symbolPosition, maxDecimals)} over balance\n                  </span>\n                  <button\n                    type=\"button\"\n                    disabled={disabled}\n                    onClick={() => rollToAmount(balance, `Set to maximum ${balance}`)}\n                    className={`inline-flex h-6 cursor-pointer items-center rounded-[7px] border border-red-500/30 bg-background px-2 text-[11.5px] font-medium text-foreground hover:bg-accent ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    Set to max\n                  </button>\n                </div>\n              ) : (\n                <div className=\"flex items-center gap-2 text-muted-foreground\">\n                  <span className=\"tabular-nums\">\n                    Available {formatMoney(balance, locale, currency, symbol, symbolPosition, maxDecimals)}\n                  </span>\n                  <button\n                    type=\"button\"\n                    disabled={disabled || effectiveNum === balance}\n                    onClick={() => rollToAmount(balance, `Set to maximum ${balance}`)}\n                    className={`inline-flex h-5 cursor-pointer items-center rounded-[6px] border border-border bg-background px-1.5 text-[11px] font-medium text-foreground hover:bg-accent disabled:cursor-default disabled:opacity-40 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    Max\n                  </button>\n                </div>\n              )\n            ) : (\n              <span />\n            )}\n\n            {conversion && !isOverBalance && (\n              <div className=\"ml-auto flex items-center gap-1.5 text-right tabular-nums\">\n                <span className=\"font-medium text-foreground\">≈ {convertedText}</span>\n                {conversion.rateLabel && <span className=\"hidden text-muted-foreground sm:inline\">· {conversion.rateLabel}</span>}\n              </div>\n            )}\n          </div>\n        )}\n      </div>\n\n      {/* Optional quick-pick preset hairline pills */}\n      {showPresetsRow && (\n        <div className=\"flex flex-wrap items-center justify-center gap-1.5\">\n          {presets!.map((amt) => {\n            const active = effectiveNum === amt;\n            return (\n              <button\n                key={amt}\n                type=\"button\"\n                disabled={disabled}\n                onClick={() => rollToAmount(amt, `Amount set to ${amt}`)}\n                className={`inline-flex h-8 cursor-pointer items-center rounded-full border px-3 text-[12.5px] font-medium tabular-nums transition-colors duration-150 ${\n                  active\n                    ? \"border-foreground/25 bg-accent text-foreground\"\n                    : \"border-border bg-card text-muted-foreground hover:bg-accent hover:text-foreground\"\n                } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                {formatMoney(amt, locale, currency, symbol, symbolPosition, 0)}\n              </button>\n            );\n          })}\n        </div>\n      )}\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {liveStatus}\n      </span>\n    </div>\n  );\n}\n\nexport default AmountField;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · amount-field · 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 · amount-field · 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/amount-field. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}