{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"currency-input","type":"registry:component","title":"Currency input","description":"A locale-aware money field with caret-safe typing, currency formatting, keyboard steps and clean numeric values for your backend.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/number-roll.json?as=dependency","https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/currency-input.tsx","type":"registry:component","content":"// Hairline UI · currency-input · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { Field, fieldSurface, useFieldIds, useShake, type FieldSize } from \"./field\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { EASE_OUT, interactionIcon, useInteractionReducedMotion } from \"./ui-interaction-motion\";\n\nexport interface CurrencyInputProps {\n  value?: number | null;\n  defaultValue?: number | null;\n  onValueChange?: (value: number | null) => void;\n  onValueCommit?: (value: number | null) => void;\n  locale?: string;\n  currency?: string;\n  min?: number;\n  max?: number;\n  step?: number;\n  label?: React.ReactNode;\n  hint?: React.ReactNode;\n  error?: React.ReactNode;\n  placeholder?: string;\n  clearable?: boolean;\n  required?: boolean;\n  disabled?: boolean;\n  name?: string;\n  size?: FieldSize;\n  id?: string;\n  className?: string;\n}\n\nfunction ClearIcon() {\n  return (\n    <svg viewBox=\"0 0 16 16\" fill=\"none\" aria-hidden=\"true\" className=\"size-3.5\">\n      <path d=\"M4.5 4.5l7 7M11.5 4.5l-7 7\" stroke=\"currentColor\" strokeWidth=\"1.6\" strokeLinecap=\"round\" />\n    </svg>\n  );\n}\n\nexport function CurrencyInput({\n  value,\n  defaultValue = null,\n  onValueChange,\n  onValueCommit,\n  locale = \"en-US\",\n  currency = \"USD\",\n  min = -Infinity,\n  max = Infinity,\n  step = 1,\n  label,\n  hint,\n  error,\n  placeholder,\n  clearable = false,\n  required,\n  disabled,\n  name,\n  size = \"md\",\n  id,\n  className = \"\",\n}: CurrencyInputProps) {\n  const reduced = useInteractionReducedMotion();\n  const ids = useFieldIds(id);\n  const input = React.useRef<HTMLInputElement>(null);\n  const [own, setOwn] = React.useState<number | null>(defaultValue);\n  const current = value !== undefined ? value : own;\n  const [draft, setDraft] = React.useState<string | null>(null);\n  const [badInput, setBadInput] = React.useState<string | null>(null);\n\n  const currencyFormat = React.useMemo(() => new Intl.NumberFormat(locale, { style: \"currency\", currency }), [locale, currency]);\n  const fractionDigits = currencyFormat.resolvedOptions().maximumFractionDigits ?? 2;\n  const numberFormat = React.useMemo(\n    () => new Intl.NumberFormat(locale, { minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }),\n    [locale, fractionDigits],\n  );\n  const currencyParts = React.useMemo(() => currencyFormat.formatToParts(1234.5), [currencyFormat]);\n  const symbol = currencyParts.filter((part) => part.type === \"currency\").map((part) => part.value).join(\"\");\n  const currencyIndex = currencyParts.findIndex((part) => part.type === \"currency\");\n  const numberIndex = currencyParts.findIndex((part) => part.type === \"integer\");\n  const symbolFirst = currencyIndex < numberIndex;\n  const separators = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 1 }).formatToParts(12345.6), [locale]);\n  const group = separators.find((part) => part.type === \"group\")?.value ?? \",\";\n  const decimal = separators.find((part) => part.type === \"decimal\")?.value ?? \".\";\n  const sm = size === \"sm\";\n  const integerFormat = React.useMemo(() => new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }), [locale]);\n  const [focused, setFocused] = React.useState(false);\n  const caret = React.useRef<number | null>(null);\n\n  /*\n   * What the field shows while typing: the integer part grouped as the locale groups it, the decimals as typed (no\n   * more than the currency allows). Separators appear under the caret without moving it: the caret is put back after\n   * the same number of digits it had before.\n   */\n  const live = (text: string) => {\n    const negative = /^\\s*-/.test(text);\n    const at = fractionDigits > 0 ? text.lastIndexOf(decimal) : -1;\n    const whole = (at >= 0 ? text.slice(0, at) : text).replace(/\\D/g, \"\").replace(/^0+(?=\\d)/, \"\");\n    const fraction = at >= 0 ? text.slice(at + decimal.length).replace(/\\D/g, \"\").slice(0, fractionDigits) : \"\";\n    const grouped = whole ? integerFormat.format(Number(whole)) : \"\";\n    return `${negative && min < 0 ? \"-\" : \"\"}${grouped}${at >= 0 ? decimal + fraction : \"\"}`;\n  };\n  /** How many digits, signs and decimal marks come before `end`: the caret's place, ignoring separators. */\n  const significant = (text: string, end: number) => {\n    let count = 0;\n    for (let i = 0; i < end; i++) if (/[\\d-]/.test(text[i]) || text.startsWith(decimal, i)) count++;\n    return count;\n  };\n  const caretAfter = (text: string, count: number) => {\n    if (count <= 0) return 0;\n    let seen = 0;\n    for (let i = 0; i < text.length; i++) {\n      if (/[\\d-]/.test(text[i]) || text.startsWith(decimal, i)) seen++;\n      if (seen === count) return i + 1;\n    }\n    return text.length;\n  };\n  React.useLayoutEffect(() => {\n    if (caret.current === null || !input.current) return;\n    input.current.setSelectionRange(caret.current, caret.current);\n    caret.current = null;\n  });\n\n  const parseAmount = (text: string): number | null => {\n    let normalised = text.trim().replaceAll(symbol, \"\").replace(/\\s/g, \"\");\n    if (group) normalised = normalised.replaceAll(group, \"\");\n    if (decimal !== \".\") normalised = normalised.replaceAll(decimal, \".\");\n    if (!/^[+-]?(?:\\d+\\.?\\d*|\\.\\d+)$/.test(normalised)) return null;\n    const parsed = Number(normalised);\n    return Number.isFinite(parsed) ? parsed : null;\n  };\n\n  const round = (amount: number) => Number(amount.toFixed(Math.max(fractionDigits, String(step).split(\".\")[1]?.length ?? 0)));\n  const store = (next: number | null, notify: boolean) => {\n    if (value === undefined) setOwn(next);\n    if (notify) onValueChange?.(next);\n  };\n\n  const settle = () => {\n    if (draft === null) return true;\n    const text = draft.trim();\n    if (!text) {\n      store(null, false);\n      onValueCommit?.(null);\n      setDraft(null);\n      setBadInput(null);\n      return true;\n    }\n    const parsed = parseAmount(text);\n    if (parsed === null) {\n      setBadInput(\"Enter a valid amount.\");\n      return false;\n    }\n    if (parsed < min || parsed > max) {\n      const range = Number.isFinite(min) && Number.isFinite(max) ? `between ${numberFormat.format(min)} and ${numberFormat.format(max)}` : Number.isFinite(min) ? `at least ${numberFormat.format(min)}` : `no more than ${numberFormat.format(max)}`;\n      setBadInput(`Use an amount ${range}.`);\n      return false;\n    }\n    const next = Number(parsed.toFixed(fractionDigits));\n    store(next, next !== current);\n    onValueCommit?.(next);\n    setDraft(null);\n    setBadInput(null);\n    return true;\n  };\n\n  const bump = () => {\n    if (reduced) return;\n    input.current?.parentElement?.animate(\n      [{ transform: \"none\" }, { transform: \"translateX(-3px)\" }, { transform: \"translateX(3px)\" }, { transform: \"translateX(-1px)\" }, { transform: \"none\" }],\n      { duration: 280, easing: \"ease-out\" },\n    );\n  };\n\n  const stepBy = (direction: 1 | -1, multiplier = 1) => {\n    const typed = draft !== null ? parseAmount(draft) : null;\n    const base = typed ?? current ?? 0;\n    const next = round(Math.min(max, Math.max(min, base + direction * step * multiplier)));\n    if (next === current || next === typed) {\n      bump();\n      return;\n    }\n    store(next, true);\n    onValueCommit?.(next);\n    setDraft(live(String(next).replace(\".\", decimal)));\n    setBadInput(null);\n    requestAnimationFrame(() => {\n      const length = input.current?.value.length ?? 0;\n      input.current?.setSelectionRange(length, length);\n    });\n  };\n\n  const shown = draft ?? (current === null ? \"\" : numberFormat.format(current));\n  // At rest the amount is drawn by NumberRoll over the field (same box, same type), so a new value rolls into place.\n  const rolling = !focused && draft === null && current !== null;\n  const showClear = clearable && !disabled && shown.length > 0;\n  const describedBy = [hint && !error && !badInput ? ids.hint : null, error || badInput ? ids.error : null].filter(Boolean).join(\" \") || undefined;\n  const shakeRef = useShake<HTMLDivElement>(!!error || !!badInput);\n  const symbolNode = (\n    <span className={`flex shrink-0 items-center text-muted-foreground ${sm ? \"text-[12px]\" : \"text-[13px]\"}`}>\n      <TextMorph animateWidth={false}>{symbol}</TextMorph>\n    </span>\n  );\n\n  return (\n    <Field id={ids.id} label={label} hint={hint} error={error ?? badInput} required={required} className={className}>\n      <div ref={shakeRef} className={`${fieldSurface({ invalid: !!error || !!badInput, disabled })} ${sm ? \"h-7 text-[16px] sm:text-[12.5px]\" : \"h-9 text-[16px] sm:text-[13.5px]\"}`}>\n        {symbolFirst && <span className={sm ? \"pl-3\" : \"pl-4\"}>{symbolNode}</span>}\n        <span className=\"relative flex h-full min-w-0 flex-1\">\n        <input\n          ref={input}\n          id={ids.id}\n          value={shown}\n          inputMode=\"decimal\"\n          autoComplete=\"off\"\n          spellCheck={false}\n          required={required}\n          disabled={disabled}\n          placeholder={placeholder ?? numberFormat.format(0)}\n          aria-invalid={error || badInput ? true : undefined}\n          aria-describedby={describedBy}\n          onFocus={() => {\n            setFocused(true);\n            setDraft(current === null ? \"\" : live(String(current).replace(\".\", decimal)));\n            setBadInput(null);\n          }}\n          onChange={(e) => {\n            const raw = e.target.value;\n            const nextText = live(raw);\n            caret.current = caretAfter(nextText, significant(raw, e.target.selectionStart ?? raw.length));\n            setDraft(nextText);\n            setBadInput(null);\n            const parsed = parseAmount(nextText);\n            if (!nextText.trim()) store(null, true);\n            else if (parsed !== null) store(parsed, true);\n          }}\n          onBlur={() => {\n            setFocused(false);\n            settle();\n          }}\n          onKeyDown={(e) => {\n            if (e.key === \"Enter\") {\n              e.preventDefault();\n              settle();\n            } else if (e.key === \"Escape\") {\n              e.preventDefault();\n              setDraft(null);\n              setBadInput(null);\n            } else if (e.key === \"ArrowUp\" || e.key === \"ArrowDown\") {\n              e.preventDefault();\n              stepBy(e.key === \"ArrowUp\" ? 1 : -1, e.shiftKey ? 10 : 1);\n            }\n          }}\n          className={`h-full w-full min-w-0 bg-transparent tabular-nums outline-none placeholder:text-muted-foreground/70 ${sm ? \"px-2.5\" : \"px-3\"} ${showClear ? \"pr-1\" : \"\"} ${rolling ? \"text-transparent\" : \"\"}`}\n        />\n        {rolling && (\n          <span aria-hidden=\"true\" className={`pointer-events-none absolute inset-y-0 left-0 flex items-center tabular-nums text-foreground ${sm ? \"px-2.5\" : \"px-3\"}`}>\n            <NumberRoll value={current} locales={locale} format={{ minimumFractionDigits: fractionDigits, maximumFractionDigits: fractionDigits }} />\n          </span>\n        )}\n        </span>\n        {!symbolFirst && <span className={showClear ? \"\" : sm ? \"pr-3\" : \"pr-4\"}>{symbolNode}</span>}\n        {clearable && (\n          <span className=\"grid shrink-0\" style={{ gridTemplateColumns: showClear ? \"1fr\" : \"0fr\", transition: reduced ? \"none\" : `grid-template-columns 320ms ${EASE_OUT}` }}>\n            <span className=\"min-w-0 overflow-hidden\">\n              <button\n                type=\"button\"\n                tabIndex={showClear ? 0 : -1}\n                aria-hidden={!showClear}\n                aria-label=\"Clear amount\"\n                onClick={() => {\n                  store(null, true);\n                  onValueCommit?.(null);\n                  setDraft(\"\");\n                  setBadInput(null);\n                  input.current?.focus();\n                }}\n                className={`mr-1 flex items-center justify-center rounded-full text-muted-foreground cursor-pointer outline-none hover:bg-accent hover:text-foreground focus-visible:shadow-[inset_0_0_0_2px_var(--ring)] ${sm ? \"size-5\" : \"size-7\"}`}\n                style={interactionIcon(showClear, reduced)}\n              >\n                <ClearIcon />\n              </button>\n            </span>\n          </span>\n        )}\n      </div>\n      {name && <input type=\"hidden\" name={name} value={current ?? \"\"} />}\n    </Field>\n  );\n}\n\nexport default CurrencyInput;\n"},{"path":"registry/field.tsx","type":"registry:component","content":"// Hairline UI · currency-input · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { EASE_OUT, useInteractionReducedMotion } from \"./ui-interaction-motion\";\n\n/* ─────────────────────────────────────────────────────────\n * FIELD: the column every text control sits in\n *\n *   label    above, with an optional aside on the right (a count)\n *   hint     under the control while all is well\n *   error    takes the hint's place: the hint folds away, the\n *            error rises in out of a blur, the control shakes once\n *\n * Shared by input, textarea, password, search and select so the\n * whole family has one surface, one focus ring and one error.\n * ───────────────────────────────────────────────────────── */\n\nexport interface FieldProps {\n  id: string;\n  label?: React.ReactNode;\n  /** Right side of the label row, e.g. a character count. */\n  aside?: React.ReactNode;\n  hint?: React.ReactNode;\n  error?: React.ReactNode;\n  required?: boolean;\n  className?: string;\n  children: React.ReactNode;\n}\n\nexport type FieldSize = \"sm\" | \"md\";\n\n/** The surface of a text control: a hairline that darkens on hover and turns to the ring on focus. */\nexport function fieldSurface({ invalid, disabled, round = true }: { invalid?: boolean; disabled?: boolean; round?: boolean }) {\n  const ring = invalid\n    ? \"shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--color-red-500)_55%,transparent)] focus-within:shadow-[inset_0_0_0_1px_var(--color-red-500),0_0_0_3px_color-mix(in_oklab,var(--color-red-500)_14%,transparent)]\"\n    : \"shadow-[inset_0_0_0_1px_var(--border)] [&:not(:focus-within)]:hover:shadow-[inset_0_0_0_1px_color-mix(in_oklab,var(--foreground)_24%,var(--border))] focus-within:shadow-[inset_0_0_0_1px_var(--ring),0_0_0_3px_color-mix(in_oklab,var(--ring)_16%,transparent)]\";\n  return `relative flex w-full items-center bg-background text-foreground transition-[box-shadow,background-color,opacity] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] ${round ? \"rounded-full\" : \"rounded-[14px]\"} ${ring} ${\n    disabled ? \"pointer-events-none opacity-50\" : \"\"\n  }`;\n}\n\n/** ids for the control's label, hint and error. */\nexport function useFieldIds(id?: string) {\n  const auto = React.useId();\n  const base = id ?? auto;\n  return { id: base, hint: `${base}-hint`, error: `${base}-error` };\n}\n\n/** One short shake whenever `on` turns true (an error arrives). */\nexport function useShake<T extends HTMLElement>(on: boolean) {\n  const ref = React.useRef<T>(null);\n  const reduced = useInteractionReducedMotion();\n  React.useEffect(() => {\n    if (!on || reduced) return;\n    ref.current?.animate(\n      [{ transform: \"none\" }, { transform: \"translateX(-4px)\" }, { transform: \"translateX(4px)\" }, { transform: \"translateX(-2px)\" }, { transform: \"none\" }],\n      { duration: 380, easing: \"ease-out\" },\n    );\n  }, [on, reduced]);\n  return ref;\n}\n\n/** Sets a native input's value so React's onChange still fires (clear buttons, pickers). */\nexport function setNativeValue(el: HTMLInputElement | HTMLTextAreaElement, value: string) {\n  const proto = el instanceof HTMLTextAreaElement ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;\n  Object.getOwnPropertyDescriptor(proto, \"value\")?.set?.call(el, value);\n  el.dispatchEvent(new Event(\"input\", { bubbles: true }));\n}\n\n/** A line under the control that folds open and closed; keeps its last words while closing. */\nfunction Line({ show, children, id, tone, reduced }: { show: boolean; children: React.ReactNode; id: string; tone: string; reduced: boolean }) {\n  const [kept, setKept] = React.useState(children);\n  if (show && children !== kept) setKept(children);\n  return (\n    <div\n      className=\"grid\"\n      style={{ gridTemplateRows: show ? \"1fr\" : \"0fr\", transition: reduced ? \"none\" : `grid-template-rows 320ms ${EASE_OUT}` }}\n    >\n      <div className=\"min-h-0 overflow-hidden\">\n        <p\n          id={id}\n          className={`pt-1.5 pl-3 text-[12.5px] leading-snug ${tone}`}\n          style={{\n            opacity: show ? 1 : 0,\n            filter: show ? \"blur(0px)\" : \"blur(4px)\",\n            transform: show ? \"none\" : \"translateY(-4px)\",\n            transition: reduced ? \"none\" : show ? `opacity 280ms ${EASE_OUT} 60ms, filter 280ms ${EASE_OUT} 60ms, transform 380ms ${EASE_OUT}` : `opacity 140ms ${EASE_OUT}, filter 140ms ${EASE_OUT}, transform 200ms ${EASE_OUT}`,\n          }}\n        >\n          {show ? children : kept}\n        </p>\n      </div>\n    </div>\n  );\n}\n\nexport function Field({ id, label, aside, hint, error, required, className = \"\", children }: FieldProps) {\n  const reduced = useInteractionReducedMotion();\n  const ids = { hint: `${id}-hint`, error: `${id}-error` };\n  return (\n    <div className={`flex w-full flex-col ${className}`}>\n      {(label || aside) && (\n        <div className=\"flex items-baseline justify-between gap-3 px-3 pb-1.5\">\n          {label && (\n            <label htmlFor={id} className=\"text-[13px] font-medium text-foreground\">\n              {label}\n              {required && (\n                <span aria-hidden=\"true\" className=\"ml-0.5 text-muted-foreground\">\n                  *\n                </span>\n              )}\n            </label>\n          )}\n          {aside && <span className=\"text-[12px] tabular-nums text-muted-foreground\">{aside}</span>}\n        </div>\n      )}\n      {children}\n      <Line show={!error && !!hint} id={ids.hint} tone=\"text-muted-foreground\" reduced={reduced}>\n        {hint}\n      </Line>\n      <Line show={!!error} id={ids.error} tone=\"text-red-600 dark:text-red-400\" reduced={reduced}>\n        {error}\n      </Line>\n    </div>\n  );\n}\n\nexport default Field;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · currency-input · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n'use client';\n\nimport * as React from 'react';\n\nexport const EASE_OUT = 'cubic-bezier(0.16, 1, 0.3, 1)';\nexport const EASE_SETTLE = 'cubic-bezier(0.22, 1.18, 0.36, 1)';\n/** Thrown things (indicators, thumbs): a slight overshoot on transform only. */\nexport const EASE_THROW = 'cubic-bezier(0.34, 1.36, 0.64, 1)';\n/**\n * The press every button primitive shares: a 3% give that eases in and settles back.\n * Tailwind v4's scale-* writes the `scale` property, so `scale` has to be in the list\n * or the press snaps.\n */\nexport const INTERACTION_PRESS =\n  'transition-[background-color,color,box-shadow,opacity,scale] duration-200 ease-[cubic-bezier(0.16,1,0.3,1)] active:scale-[0.97] motion-reduce:transition-none motion-reduce:active:scale-100';\nexport const INTERACTION_FOCUS ='focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:ring-offset-2 focus-visible:ring-offset-background';\n\nconst query = '(prefers-reduced-motion: reduce)';\nconst subscribe = (notify: () => void) => {\n  const media = window.matchMedia(query);\n  media.addEventListener('change', notify);\n  return () => media.removeEventListener('change', notify);\n};\nexport const useInteractionReducedMotion = () => React.useSyncExternalStore(subscribe, () => window.matchMedia(query).matches, () => false);\n\nexport function useInteractionActivity<T extends Element>() {\n  const ref = React.useRef<T>(null);\n  const [visible, setVisible] = React.useState(false);\n  const [hidden, setHidden] = React.useState(false);\n  React.useEffect(() => {\n    const el = ref.current;\n    if (!el) return;\n    const observer = new IntersectionObserver(([entry]) => setVisible(entry.isIntersecting));\n    observer.observe(el);\n    const visibility = () => setHidden(document.hidden);\n    visibility(); document.addEventListener('visibilitychange', visibility);\n    return () => { observer.disconnect(); document.removeEventListener('visibilitychange', visibility); };\n  }, []);\n  return { ref, active: visible && !hidden };\n}\n\nexport function interactionIcon(on: boolean, reduced: boolean): React.CSSProperties {\n  return { opacity: on ? 1 : 0, transform: on ? 'none' : 'scale(0.6)', filter: on ? 'blur(0px)' : 'blur(3px)', transition: reduced ? 'none' : `opacity 220ms ${EASE_OUT}, transform 380ms ${EASE_OUT}, filter 220ms ${EASE_OUT}` };\n}\n\n/** A raised object: one tight contact shadow, one short ambient, a hairline of light on its top edge. */\nexport const MATERIAL_LIFT =\n  'shadow-[0_1px_1.5px_rgb(0_0_0/0.07),0_3px_8px_-2px_rgb(0_0_0/0.1),inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[0_1px_2px_rgb(0_0_0/0.5),0_4px_10px_-2px_rgb(0_0_0/0.35),inset_0_0.5px_0_rgb(255_255_255/0.1)]';\n/** A trough something sits in, shaded from above, lit along its bottom edge. */\nexport const MATERIAL_RECESS =\n  'shadow-[inset_0_1px_2.5px_rgb(0_0_0/0.09),inset_0_-0.5px_0_rgb(255_255_255/0.7)] dark:shadow-[inset_0_1px_3px_rgb(0_0_0/0.45),inset_0_-0.5px_0_rgb(255_255_255/0.07)]';\n\nexport type SpringConfig = { stiffness: number; damping: number; mass?: number };\nexport interface Spring {\n  get(): number;\n  getVelocity(): number;\n  getTarget(): number;\n  /** Aim somewhere new from wherever it is now, keeping its speed. */\n  set(target: number): void;\n  /** Add speed (units per second), on top of what it already has. */\n  push(velocity: number): void;\n  /** Be there now, at rest. */\n  jump(value: number): void;\n  configure(config: SpringConfig): void;\n  stop(): void;\n}\n\n// Every moving spring on the page shares one frame loop, which sleeps when the last one rests. Each spring's onFrame runs\n// once per frame after all of them have stepped, so several springs that draw one shape paint it once.\nconst SPRING_STEP = 1 / 240;\ntype Running = { step: () => void };\nconst runningSprings = new Set<Running>();\nconst springPainters = new Set<() => void>();\nlet springFrame = 0;\nlet springLast = 0;\nlet springSpare = 0;\n\nfunction springTick(now: number) {\n  // A hidden tab stops the frames, so the first one back must not count the whole gap as time passed.\n  springSpare += Math.min((now - springLast) / 1000, 0.05);\n  springLast = now;\n  while (springSpare >= SPRING_STEP) {\n    runningSprings.forEach((spring) => spring.step());\n    springSpare -= SPRING_STEP;\n  }\n  const painters = [...springPainters];\n  springPainters.clear();\n  painters.forEach((paint) => paint());\n  springFrame = runningSprings.size ? requestAnimationFrame(springTick) : 0;\n}\n\nfunction wakeSprings(spring: Running) {\n  runningSprings.add(spring);\n  if (springFrame) return;\n  springSpare = 0;\n  springFrame = requestAnimationFrame((now) => {\n    springLast = now - 1000 / 60;\n    springTick(now);\n  });\n}\n\n/**\n * A spring that carries its speed: re-aim it mid-flight and it curves on from where it is, push it while it swings and the\n * push adds to the swing. Use it for anything that can be interrupted; a curve restarts from a standstill every time.\n * `onFrame` should write straight to the DOM. `precision` is how close counts as there, in the value's own units.\n */\nexport function createSpring(initial: number, config: SpringConfig, onFrame: () => void, precision = 0.01): Spring {\n  let value = initial;\n  let velocity = 0;\n  let target = initial;\n  let { stiffness, damping, mass = 1 } = config;\n  const running: Running = {\n    step() {\n      velocity += ((-stiffness * (value - target) - damping * velocity) / mass) * SPRING_STEP;\n      value += velocity * SPRING_STEP;\n      if (Math.abs(value - target) < precision && Math.abs(velocity) < precision * 10) {\n        value = target;\n        velocity = 0;\n        runningSprings.delete(running);\n      }\n      springPainters.add(onFrame);\n    },\n  };\n  return {\n    get: () => value,\n    getVelocity: () => velocity,\n    getTarget: () => target,\n    set(next) {\n      if (next === target && !runningSprings.has(running)) return;\n      target = next;\n      wakeSprings(running);\n    },\n    push(speed) {\n      velocity += speed;\n      wakeSprings(running);\n    },\n    jump(next) {\n      value = next;\n      target = next;\n      velocity = 0;\n      runningSprings.delete(running);\n      onFrame();\n    },\n    configure(next) {\n      ({ stiffness, damping, mass = 1 } = next);\n    },\n    stop() {\n      runningSprings.delete(running);\n    },\n  };\n}\n\n/** Sample recent movement rather than averaging a long drag and losing its release velocity. */\nexport type PointerSample = { x: number; time: number };\nexport function samplePointer(samples: PointerSample[], x: number, time: number) {\n  samples.push({ x, time });\n  while (samples.length > 2 && time - samples[0].time > 100) samples.shift();\n}\nexport function releaseVelocity(samples: PointerSample[], now: number) {\n  if (samples.length < 2 || now - samples[samples.length - 1].time > 100) return 0;\n  const first = samples[0], last = samples[samples.length - 1];\n  return (last.x - first.x) / Math.max(1, last.time - first.time);\n}\n\n/** Smooth Apple/rational rubber-band curve: continuous exponential-like resistance without linear kinks. */\nexport function rubberBand(overshoot: number, dimension = 320, constant = 0.55): number {\n  const d = dimension || 320;\n  const abs = Math.abs(overshoot);\n  return Math.sign(overshoot) * (1 - 1 / ((abs * constant) / d + 1)) * d;\n}\n\n/** Projects resting travel from release velocity (velocity in px/ms; time in seconds). */\nexport function projectInertia(distance: number, velocity: number, time = 0.12): number {\n  return distance + velocity * 1000 * time;\n}\n\n/** Smooths incoming release velocity toward a boundary so springs don't slam or clip into walls. */\nexport function softenVelocity(velocity: number, distanceToTarget: number, factor = 10): number {\n  const maxAllowed = Math.abs(distanceToTarget) * factor;\n  return Math.sign(velocity) * Math.min(Math.abs(velocity), maxAllowed);\n}\n\n/** A damped spring sampled by WAAPI: tuned for organic lightness with a hint of life (3% breath). */\nexport function springFrames(\n  from: number,\n  to: number,\n  velocity = 0,\n  duration = 480,\n  config: { omega?: number; damping?: number; steps?: number } = {},\n) {\n  const { omega = 16, damping = 0.74, steps = 36 } = config;\n  const damped = omega * Math.sqrt(Math.max(0.001, 1 - damping * damping));\n  const displacement = from - to;\n  const coefficient = (velocity * 1000 + damping * omega * displacement) / damped;\n  return Array.from({ length: steps + 1 }, (_, i) => {\n    const t = (i / steps) * (duration / 1000);\n    const value = to + Math.exp(-damping * omega * t) * (displacement * Math.cos(damped * t) + coefficient * Math.sin(damped * t));\n    return { value: i === steps ? to : value, offset: i / steps };\n  });\n}\n\n"}],"css":{},"docs":"Docs and live preview: https://hairlineui.com/ui/currency-input. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}