{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"phone-input","type":"registry:component","title":"Phone input","description":"An international hairline phone input with searchable calling codes, caret-safe national formatting, automatic +E.164 country detection and structured output.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/phone-input.tsx","type":"registry:component","content":"// Hairline UI · phone-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 { Check, ChevronDown, Search, X } from \"lucide-react\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  MATERIAL_LIFT,\n  createSpring,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n  type Spring,\n} from \"./ui-interaction-motion\";\nimport { TextMorph } from \"./text-morph\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * PHONE INPUT: international hairline phone field & E.164 parser\n *\n *   format    formats national digits as you type using each\n *             country's grouping template while locking the caret\n *             to the exact digit you edited (zero caret jumps)\n *\n *   paste     pasting any full international number (+44 7700...,\n *             +91 98765..., +81 90-1234...) automatically detects\n *             the country, switches the dial code, strips trunk 0s\n *             and sweeps an optical 8×8 Bayer lock-in confirmation\n *\n *   infra     zero external phone libraries or flag image assets;\n *             emits structured { e164, national, digits, country,\n *             dialCode, valid } and exports parsePhoneNumber()\n * ───────────────────────────────────────────────────────── */\n\nexport interface PhoneCountry {\n  /** ISO 3166-1 alpha-2 code (e.g. \"US\", \"GB\", \"IN\"). */\n  iso: string;\n  /** English country name for search and screen readers. */\n  name: string;\n  /** Calling code without leading \"+\" (e.g. \"1\", \"44\", \"91\"). */\n  dial: string;\n  /** National grouping mask using \"#\" placeholders. */\n  pattern: string;\n  /** Minimum valid national digit count. */\n  minDigits: number;\n  /** Maximum valid national digit count. */\n  maxDigits: number;\n  /** Realistic placeholder example. */\n  example: string;\n  /** Strip a leading trunk \"0\" when pasted after the international dial code. */\n  stripTrunkZero?: boolean;\n}\n\nexport interface PhoneValue {\n  /** Full E.164 string (e.g. \"+14155550192\"), or \"\" when empty. */\n  e164: string;\n  /** Formatted national representation (e.g. \"(415) 555-0192\"). */\n  national: string;\n  /** Raw national digits only (e.g. \"4155550192\"). */\n  digits: string;\n  /** Active ISO country code. */\n  country: string;\n  /** Calling code with leading \"+\" (e.g. \"+1\"). */\n  dialCode: string;\n  /** True when digits fall cleanly within the country's valid length range. */\n  valid: boolean;\n}\n\nexport interface PhoneInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"defaultValue\" | \"onChange\"> {\n  /** Controlled E.164 value (e.g. \"+14155550192\") or raw phone string. */\n  value?: string;\n  /** Initial uncontrolled phone value. */\n  defaultValue?: string;\n  /** Default ISO country code when value has no dial prefix (default \"US\"). */\n  defaultCountry?: string;\n  /** Controlled ISO country code. */\n  country?: string;\n  onCountryChange?: (iso: string) => void;\n  /** Fires on every edit or country switch with full structured phone details. */\n  onChange?: (value: PhoneValue) => void;\n  /** Optional subset or custom list of countries (defaults to built-in 36-country table). */\n  countries?: PhoneCountry[];\n  /** Validate and surface inline error on blur when partially entered (default true). */\n  validateOnBlur?: boolean;\n  /** Show inline clear button when populated (default true). */\n  clearable?: boolean;\n  /** Accessible name for the phone input (default \"Phone number\"). */\n  label?: string;\n  /** Disabled state. */\n  disabled?: boolean;\n  /** Opt-in quiet Web Audio ticks on country switch and valid completion (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\nexport const PHONE_COUNTRIES: PhoneCountry[] = [\n  { iso: \"US\", name: \"United States\", dial: \"1\", pattern: \"(###) ###-####\", minDigits: 10, maxDigits: 10, example: \"(415) 555-0192\" },\n  { iso: \"GB\", name: \"United Kingdom\", dial: \"44\", pattern: \"#### ######\", minDigits: 10, maxDigits: 10, example: \"7700 900077\", stripTrunkZero: true },\n  { iso: \"IN\", name: \"India\", dial: \"91\", pattern: \"##### #####\", minDigits: 10, maxDigits: 10, example: \"98765 43210\", stripTrunkZero: true },\n  { iso: \"CA\", name: \"Canada\", dial: \"1\", pattern: \"(###) ###-####\", minDigits: 10, maxDigits: 10, example: \"(416) 555-0148\" },\n  { iso: \"AU\", name: \"Australia\", dial: \"61\", pattern: \"### ### ###\", minDigits: 9, maxDigits: 9, example: \"412 345 678\", stripTrunkZero: true },\n  { iso: \"DE\", name: \"Germany\", dial: \"49\", pattern: \"### ########\", minDigits: 10, maxDigits: 11, example: \"151 23456789\", stripTrunkZero: true },\n  { iso: \"FR\", name: \"France\", dial: \"33\", pattern: \"# ## ## ## ##\", minDigits: 9, maxDigits: 9, example: \"6 12 34 56 78\", stripTrunkZero: true },\n  { iso: \"JP\", name: \"Japan\", dial: \"81\", pattern: \"##-####-####\", minDigits: 10, maxDigits: 10, example: \"90-1234-5678\", stripTrunkZero: true },\n  { iso: \"SG\", name: \"Singapore\", dial: \"65\", pattern: \"#### ####\", minDigits: 8, maxDigits: 8, example: \"8123 4567\" },\n  { iso: \"AE\", name: \"United Arab Emirates\", dial: \"971\", pattern: \"## ### ####\", minDigits: 9, maxDigits: 9, example: \"50 123 4567\", stripTrunkZero: true },\n  { iso: \"NL\", name: \"Netherlands\", dial: \"31\", pattern: \"# ########\", minDigits: 9, maxDigits: 9, example: \"6 12345678\", stripTrunkZero: true },\n  { iso: \"ES\", name: \"Spain\", dial: \"34\", pattern: \"### ### ###\", minDigits: 9, maxDigits: 9, example: \"612 345 678\" },\n  { iso: \"IT\", name: \"Italy\", dial: \"39\", pattern: \"### ### ####\", minDigits: 9, maxDigits: 10, example: \"312 345 6789\" },\n  { iso: \"CH\", name: \"Switzerland\", dial: \"41\", pattern: \"## ### ## ##\", minDigits: 9, maxDigits: 9, example: \"79 123 45 67\", stripTrunkZero: true },\n  { iso: \"SE\", name: \"Sweden\", dial: \"46\", pattern: \"##-### ## ##\", minDigits: 9, maxDigits: 9, example: \"70-123 45 67\", stripTrunkZero: true },\n  { iso: \"IE\", name: \"Ireland\", dial: \"353\", pattern: \"## ### ####\", minDigits: 9, maxDigits: 9, example: \"85 123 4567\", stripTrunkZero: true },\n  { iso: \"BR\", name: \"Brazil\", dial: \"55\", pattern: \"(##) #####-####\", minDigits: 10, maxDigits: 11, example: \"(11) 91234-5678\" },\n  { iso: \"MX\", name: \"Mexico\", dial: \"52\", pattern: \"## #### ####\", minDigits: 10, maxDigits: 10, example: \"55 1234 5678\" },\n  { iso: \"KR\", name: \"South Korea\", dial: \"82\", pattern: \"##-####-####\", minDigits: 9, maxDigits: 10, example: \"10-1234-5678\", stripTrunkZero: true },\n  { iso: \"CN\", name: \"China\", dial: \"86\", pattern: \"### #### ####\", minDigits: 11, maxDigits: 11, example: \"138 0013 8000\" },\n  { iso: \"HK\", name: \"Hong Kong\", dial: \"852\", pattern: \"#### ####\", minDigits: 8, maxDigits: 8, example: \"5123 4567\" },\n  { iso: \"NZ\", name: \"New Zealand\", dial: \"64\", pattern: \"## ### ####\", minDigits: 8, maxDigits: 9, example: \"21 123 4567\", stripTrunkZero: true },\n  { iso: \"ZA\", name: \"South Africa\", dial: \"27\", pattern: \"## ### ####\", minDigits: 9, maxDigits: 9, example: \"82 123 4567\", stripTrunkZero: true },\n  { iso: \"PL\", name: \"Poland\", dial: \"48\", pattern: \"### ### ###\", minDigits: 9, maxDigits: 9, example: \"512 345 678\" },\n  { iso: \"PT\", name: \"Portugal\", dial: \"351\", pattern: \"### ### ###\", minDigits: 9, maxDigits: 9, example: \"912 345 678\" },\n  { iso: \"NO\", name: \"Norway\", dial: \"47\", pattern: \"### ## ###\", minDigits: 8, maxDigits: 8, example: \"412 34 567\" },\n  { iso: \"DK\", name: \"Denmark\", dial: \"45\", pattern: \"## ## ## ##\", minDigits: 8, maxDigits: 8, example: \"20 12 34 56\" },\n  { iso: \"FI\", name: \"Finland\", dial: \"358\", pattern: \"## ### ####\", minDigits: 9, maxDigits: 10, example: \"40 123 4567\", stripTrunkZero: true },\n  { iso: \"BE\", name: \"Belgium\", dial: \"32\", pattern: \"### ## ## ##\", minDigits: 9, maxDigits: 9, example: \"470 12 34 56\", stripTrunkZero: true },\n  { iso: \"AT\", name: \"Austria\", dial: \"43\", pattern: \"### #######\", minDigits: 10, maxDigits: 11, example: \"664 1234567\", stripTrunkZero: true },\n  { iso: \"IL\", name: \"Israel\", dial: \"972\", pattern: \"##-###-####\", minDigits: 9, maxDigits: 9, example: \"50-123-4567\", stripTrunkZero: true },\n  { iso: \"TR\", name: \"Turkey\", dial: \"90\", pattern: \"### ### ## ##\", minDigits: 10, maxDigits: 10, example: \"532 123 45 67\", stripTrunkZero: true },\n  { iso: \"ID\", name: \"Indonesia\", dial: \"62\", pattern: \"###-####-####\", minDigits: 9, maxDigits: 12, example: \"812-3456-7890\", stripTrunkZero: true },\n  { iso: \"PH\", name: \"Philippines\", dial: \"63\", pattern: \"### ### ####\", minDigits: 10, maxDigits: 10, example: \"917 123 4567\", stripTrunkZero: true },\n  { iso: \"VN\", name: \"Vietnam\", dial: \"84\", pattern: \"## ### ####\", minDigits: 9, maxDigits: 10, example: \"91 234 5678\", stripTrunkZero: true },\n  { iso: \"NG\", name: \"Nigeria\", dial: \"234\", pattern: \"### ### ####\", minDigits: 10, maxDigits: 10, example: \"802 123 4567\", stripTrunkZero: true },\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 onlyDigits(s: string): string {\n  return s.replace(/\\D+/g, \"\");\n}\n\n/** Format national digits according to a country's \"#\" grouping template (never leaves dangling separators). */\nfunction formatNational(digits: string, pattern: string): string {\n  if (!digits) return \"\";\n  let out = \"\";\n  let dIdx = 0;\n  for (let i = 0; i < pattern.length && dIdx < digits.length; i++) {\n    const ch = pattern[i];\n    if (ch === \"#\") {\n      out += digits[dIdx++];\n    } else {\n      // Only append literal separator if another digit follows (or leading \"(\" before first digit)\n      if (dIdx < digits.length) out += ch;\n    }\n  }\n  if (dIdx < digits.length) out += digits.slice(dIdx);\n  return out;\n}\n\n/** Find the formatted string index sitting immediately after the Nth digit (caret-safe grouping). */\nfunction caretAfterDigitCount(formatted: string, digitCount: number): number {\n  if (digitCount <= 0) return 0;\n  let seen = 0;\n  for (let i = 0; i < formatted.length; i++) {\n    if (formatted[i] >= \"0\" && formatted[i] <= \"9\") {\n      seen++;\n      if (seen === digitCount) return i + 1;\n    }\n  }\n  return formatted.length;\n}\n\n/** Detect a country from a \"+<dial>...\" or \"00<dial>...\" international prefix (longest dial match first). */\nfunction detectCountryFromInternational(\n  raw: string,\n  countries: PhoneCountry[],\n  preferredIso?: string,\n): { country: PhoneCountry; nationalDigits: string } | null {\n  const trimmed = raw.trim();\n  const isIntl = trimmed.startsWith(\"+\") || trimmed.startsWith(\"00\");\n  if (!isIntl) return null;\n  let allDigits = onlyDigits(trimmed);\n  if (trimmed.startsWith(\"00\")) allDigits = allDigits.slice(2);\n  if (!allDigits) return null;\n\n  // Sort longest dial code first so +971 matches before +9, +353 before +35, etc.\n  const sorted = [...countries].sort((a, b) => {\n    if (b.dial.length !== a.dial.length) return b.dial.length - a.dial.length;\n    if (a.iso === preferredIso) return -1;\n    if (b.iso === preferredIso) return 1;\n    return 0;\n  });\n\n  for (const c of sorted) {\n    if (allDigits.startsWith(c.dial)) {\n      let rest = allDigits.slice(c.dial.length);\n      if (c.stripTrunkZero && rest.startsWith(\"0\") && rest.length > c.minDigits) {\n        rest = rest.slice(1);\n      }\n      return { country: c, nationalDigits: rest.slice(0, c.maxDigits) };\n    }\n  }\n  return null;\n}\n\n/** Parse any phone string (E.164 or national) into a structured PhoneValue using the built-in country table. */\nexport function parsePhoneNumber(\n  raw: string,\n  fallbackIso = \"US\",\n  countries: PhoneCountry[] = PHONE_COUNTRIES,\n): PhoneValue {\n  const fallback = countries.find((c) => c.iso === fallbackIso.toUpperCase()) ?? countries[0];\n  const detected = detectCountryFromInternational(raw, countries, fallback.iso);\n  const country = detected?.country ?? fallback;\n  const digits = detected ? detected.nationalDigits : onlyDigits(raw).slice(0, country.maxDigits);\n  const national = formatNational(digits, country.pattern);\n  const valid = digits.length >= country.minDigits && digits.length <= country.maxDigits;\n  return {\n    e164: digits ? `+${country.dial}${digits}` : \"\",\n    national,\n    digits,\n    country: country.iso,\n    dialCode: `+${country.dial}`,\n    valid,\n  };\n}\n\nexport function PhoneInput({\n  value: controlledValue,\n  defaultValue = \"\",\n  defaultCountry = \"US\",\n  country: controlledCountry,\n  onCountryChange,\n  onChange,\n  countries = PHONE_COUNTRIES,\n  validateOnBlur = true,\n  clearable = true,\n  label = \"Phone number\",\n  disabled = false,\n  sound = false,\n  className = \"\",\n  ...props\n}: PhoneInputProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();\n\n  const initialParsed = React.useMemo(\n    () => parsePhoneNumber(controlledValue ?? defaultValue, controlledCountry ?? defaultCountry, countries),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    [],\n  );\n\n  const [ownCountryIso, setOwnCountryIso] = React.useState(initialParsed.country);\n  const [ownDigits, setOwnDigits] = React.useState(initialParsed.digits);\n  const [intlDraft, setIntlDraft] = React.useState<string | null>(null);\n  const [focused, setFocused] = React.useState(false);\n  const [touched, setTouched] = React.useState(false);\n  const [open, setOpen] = React.useState(false);\n  const [query, setQuery] = React.useState(\"\");\n  const [activeIdx, setActiveIdx] = React.useState(0);\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n\n  // Derive active country & digits cleanly for both controlled and uncontrolled usage\n  const activeCountryIso = controlledCountry ?? ownCountryIso;\n  const parsedControlled = React.useMemo(() => {\n    if (controlledValue === undefined) return null;\n    return parsePhoneNumber(controlledValue, activeCountryIso, countries);\n  }, [controlledValue, activeCountryIso, countries]);\n\n  const resolvedIso = controlledCountry ?? parsedControlled?.country ?? ownCountryIso;\n  const activeCountry = React.useMemo(\n    () => countries.find((c) => c.iso === resolvedIso) ?? countries[0],\n    [countries, resolvedIso],\n  );\n  const digits = parsedControlled ? parsedControlled.digits : ownDigits;\n  const national = React.useMemo(() => formatNational(digits, activeCountry.pattern), [digits, activeCountry.pattern]);\n  const isValid = digits.length >= activeCountry.minDigits && digits.length <= activeCountry.maxDigits;\n  const showError = validateOnBlur && touched && !focused && digits.length > 0 && !isValid;\n\n  const shellRef = React.useRef<HTMLDivElement>(null);\n  const inputRef = React.useRef<HTMLInputElement>(null);\n  const searchRef = React.useRef<HTMLInputElement>(null);\n  const floorCanvasRef = React.useRef<HTMLCanvasElement>(null);\n  const recoilRef = React.useRef<Spring | null>(null);\n  const flashRef = React.useRef<((kind: \"valid\" | \"detect\" | \"error\") => void) | null>(null);\n  const prevValidRef = React.useRef(isValid);\n\n  const filteredCountries = React.useMemo(() => {\n    const q = query.trim().toLowerCase();\n    if (!q) return countries;\n    const digitsQ = q.replace(/^\\+/, \"\");\n    return countries.filter(\n      (c) =>\n        c.name.toLowerCase().includes(q) ||\n        c.iso.toLowerCase().includes(q) ||\n        c.dial.startsWith(digitsQ) ||\n        `+${c.dial}`.startsWith(q),\n    );\n  }, [countries, query]);\n\n  // Horizontal recoil spring on invalid blur\n  React.useEffect(() => {\n    const sp = createSpring(\n      0,\n      { stiffness: 450, damping: 17 },\n      () => {\n        const el = shellRef.current;\n        if (!el) return;\n        const x = sp.get();\n        el.style.transform = Math.abs(x) > 0.04 ? `translate3d(${x.toFixed(2)}px, 0, 0)` : \"\";\n      },\n      0.04,\n    );\n    recoilRef.current = sp;\n    return () => {\n      sp.stop();\n      recoilRef.current = null;\n    };\n  }, []);\n\n  // Optical 8×8 Bayer floor pulse (strictly wakes for ~0.48s on valid completion, E.164 auto-detect, or error -> 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 kind: \"none\" | \"valid\" | \"detect\" | \"error\" = \"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 = kind === \"error\" ? 0.44 : 0.54;\n      if (age >= life || !onScreen || reduced) {\n        kind = \"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\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.18 - 0.06;\n        const rgb: [number, number, number] =\n          kind === \"error\" ? [239, 68, 68] : kind === \"detect\" ? [96, 165, 250] : [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.7);\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 (kind === \"error\") {\n              boost = floorV * (0.45 + 0.55 * (1 - Math.abs(u - 0.5) * 1.6)) * fade;\n            } else {\n              const df = u - front;\n              const lead = Math.exp(-(df * df) / 0.02);\n              const tail = df < 0 ? Math.exp(df / 0.22) * 0.48 : 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.72 * 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      raf = requestAnimationFrame(tick);\n    };\n\n    flashRef.current = (nextKind) => {\n      if (reduced || !onScreen) return;\n      kind = nextKind;\n      age = 0;\n      last = 0;\n      if (!raf) raf = requestAnimationFrame(tick);\n    };\n\n    return () => {\n      flashRef.current = null;\n      cancelAnimationFrame(raf);\n    };\n  }, [onScreen, reduced]);\n\n  // Fire emerald lock-in sweep strictly when transitioning into a valid phone number\n  React.useEffect(() => {\n    if (isValid && !prevValidRef.current) {\n      flashRef.current?.(\"valid\");\n      if (sound) playSound(\"success\", 0.34);\n    }\n    prevValidRef.current = isValid;\n  }, [isValid, sound]);\n\n  // Close country picker on click-outside or Escape\n  React.useEffect(() => {\n    if (!open) return;\n    const onPointerDown = (e: PointerEvent) => {\n      if (rootRef.current && !rootRef.current.contains(e.target as Node)) {\n        setOpen(false);\n        setQuery(\"\");\n      }\n    };\n    window.addEventListener(\"pointerdown\", onPointerDown, true);\n    return () => window.removeEventListener(\"pointerdown\", onPointerDown, true);\n  }, [open, rootRef]);\n\n  const emitChange = React.useCallback(\n    (nextCountry: PhoneCountry, nextDigits: string) => {\n      const trimmed = nextDigits.slice(0, nextCountry.maxDigits);\n      if (controlledValue === undefined) setOwnDigits(trimmed);\n      if (controlledCountry === undefined) setOwnCountryIso(nextCountry.iso);\n      const nextNational = formatNational(trimmed, nextCountry.pattern);\n      const valid = trimmed.length >= nextCountry.minDigits && trimmed.length <= nextCountry.maxDigits;\n      onChange?.({\n        e164: trimmed ? `+${nextCountry.dial}${trimmed}` : \"\",\n        national: nextNational,\n        digits: trimmed,\n        country: nextCountry.iso,\n        dialCode: `+${nextCountry.dial}`,\n        valid,\n      });\n    },\n    [controlledValue, controlledCountry, onChange],\n  );\n\n  const selectCountry = React.useCallback(\n    (next: PhoneCountry, keepFocus = true) => {\n      if (controlledCountry === undefined) setOwnCountryIso(next.iso);\n      onCountryChange?.(next.iso);\n      emitChange(next, digits);\n      setOpen(false);\n      setQuery(\"\");\n      flashRef.current?.(\"detect\");\n      if (sound) playSound(\"tick\", 0.3);\n      setLiveStatus(`Country set to ${next.name} +${next.dial}`);\n      if (keepFocus) {\n        window.requestAnimationFrame(() => inputRef.current?.focus());\n      }\n    },\n    [controlledCountry, onCountryChange, emitChange, digits, sound],\n  );\n\n  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const el = e.currentTarget;\n    const raw = el.value;\n    const selStart = el.selectionStart ?? raw.length;\n    const trimmed = raw.trimStart();\n\n    // 1) Auto-detect full international numbers when pasted OR typed starting with \"+\" / \"00\"\n    if (trimmed.startsWith(\"+\") || trimmed.startsWith(\"00\")) {\n      const codeDigits = trimmed.startsWith(\"00\") ? onlyDigits(trimmed).slice(2) : onlyDigits(trimmed);\n      const hasSpaceAfterCode = /^[+0]\\d+\\s/.test(trimmed);\n      const hasLongerPrefix = codeDigits.length > 0 && countries.some((c) => c.dial.length > codeDigits.length && c.dial.startsWith(codeDigits));\n      const detected = detectCountryFromInternational(trimmed, countries, activeCountry.iso);\n\n      if (detected && (hasSpaceAfterCode || codeDigits.length > detected.country.dial.length || !hasLongerPrefix)) {\n        setIntlDraft(null);\n        const switched = detected.country.iso !== activeCountry.iso;\n        if (switched) {\n          onCountryChange?.(detected.country.iso);\n          flashRef.current?.(\"detect\");\n          if (sound) playSound(\"pop\", 0.34);\n          setLiveStatus(`Detected ${detected.country.name} +${detected.country.dial}`);\n        }\n        emitChange(detected.country, detected.nationalDigits);\n        const nextFormatted = formatNational(detected.nationalDigits, detected.country.pattern);\n        window.requestAnimationFrame(() => {\n          if (inputRef.current) inputRef.current.setSelectionRange(nextFormatted.length, nextFormatted.length);\n        });\n        return;\n      }\n\n      // Still typing an ambiguous calling-code prefix (e.g. \"+\", \"+4\", \"+35\") -> preserve verbatim until disambiguated\n      if (trimmed.startsWith(\"+\") && codeDigits.length <= 3) {\n        setIntlDraft(trimmed);\n        return;\n      }\n    }\n\n    setIntlDraft(null);\n\n    // 2) Standard national typing with exact digit-count caret restoration\n    const digitsBeforeCaret = onlyDigits(raw.slice(0, selStart)).length;\n    const nextDigits = onlyDigits(raw).slice(0, activeCountry.maxDigits);\n    emitChange(activeCountry, nextDigits);\n\n    const nextFormatted = formatNational(nextDigits, activeCountry.pattern);\n    const nextCaret = caretAfterDigitCount(nextFormatted, Math.min(digitsBeforeCaret, nextDigits.length));\n    window.requestAnimationFrame(() => {\n      if (inputRef.current) inputRef.current.setSelectionRange(nextCaret, nextCaret);\n    });\n  };\n\n  const handleInputBlur = () => {\n    setIntlDraft(null);\n    setFocused(false);\n    setTouched(true);\n    if (validateOnBlur && digits.length > 0 && !isValid) {\n      if (!reduced) recoilRef.current?.push(140);\n      flashRef.current?.(\"error\");\n      if (sound) playSound(\"error\", 0.32);\n    }\n  };\n\n  const handlePickerKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {\n    if (e.key === \"ArrowDown\") {\n      e.preventDefault();\n      setActiveIdx((i) => Math.min(Math.max(0, filteredCountries.length - 1), i + 1));\n    } else if (e.key === \"ArrowUp\") {\n      e.preventDefault();\n      setActiveIdx((i) => Math.max(0, i - 1));\n    } else if (e.key === \"Enter\" && filteredCountries[activeIdx]) {\n      e.preventDefault();\n      selectCountry(filteredCountries[activeIdx]);\n    } else if (e.key === \"Escape\") {\n      e.preventDefault();\n      setOpen(false);\n      setQuery(\"\");\n      inputRef.current?.focus();\n    }\n  };\n\n  const expectedLenLabel =\n    activeCountry.minDigits === activeCountry.maxDigits\n      ? `${activeCountry.minDigits}-digit`\n      : `${activeCountry.minDigits} to ${activeCountry.maxDigits}-digit`;\n\n  return (\n    <div ref={rootRef} className={`relative flex w-full flex-col ${className}`} {...props}>\n      <div\n        ref={shellRef}\n        data-valid={isValid ? \"true\" : \"false\"}\n        data-country={activeCountry.iso}\n        className={`relative flex h-11 w-full items-center rounded-[13px] 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          showError\n            ? \"border-red-500/45 dark:border-red-400/45\"\n            : focused || open\n              ? \"border-foreground/25\"\n              : \"border-border hover:border-foreground/20\"\n        } ${disabled ? \"opacity-55\" : \"\"}`}\n      >\n        {/* Optical 8×8 Bayer floor pulse (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-5 w-[calc(100%_-_8px)] rounded-b-[9px]\"\n        />\n\n        {/* Country dial selector button */}\n        <button\n          type=\"button\"\n          disabled={disabled}\n          aria-haspopup=\"listbox\"\n          aria-expanded={open}\n          aria-label={`Country code, ${activeCountry.name} +${activeCountry.dial}`}\n          onClick={() => {\n            if (disabled) return;\n            setOpen((prev) => {\n              const next = !prev;\n              if (next) {\n                setQuery(\"\");\n                const idx = countries.findIndex((c) => c.iso === activeCountry.iso);\n                setActiveIdx(idx >= 0 ? idx : 0);\n                window.requestAnimationFrame(() => searchRef.current?.focus());\n              }\n              return next;\n            });\n          }}\n          className={`relative z-10 flex h-full shrink-0 cursor-pointer items-center gap-1.5 rounded-l-[12px] pl-2.5 pr-2 text-foreground hover:bg-accent/70 disabled:cursor-not-allowed ${INTERACTION_FOCUS}`}\n        >\n          <span className=\"inline-flex h-5 items-center rounded-[5px] border border-border bg-background px-1.5 font-mono text-[10.5px] font-semibold tracking-[0.04em] text-foreground\">\n            <TextMorph>{activeCountry.iso}</TextMorph>\n          </span>\n          <span className=\"font-mono text-[13px] tabular-nums text-muted-foreground\">\n            <TextMorph>{`+${activeCountry.dial}`}</TextMorph>\n          </span>\n          <ChevronDown\n            className={`size-3.5 text-muted-foreground transition-transform duration-200 ${open ? \"rotate-180\" : \"\"}`}\n            strokeWidth={2}\n            aria-hidden=\"true\"\n          />\n        </button>\n\n        {/* Crisp 1px vertical instrument divider */}\n        <span aria-hidden=\"true\" className=\"relative z-10 h-5 w-px shrink-0 bg-border\" />\n\n        {/* Caret-safe formatted national number input */}\n        <input\n          ref={inputRef}\n          type=\"tel\"\n          inputMode=\"tel\"\n          autoComplete=\"tel-national\"\n          disabled={disabled}\n          aria-label={label}\n          aria-invalid={showError || undefined}\n          placeholder={activeCountry.example}\n          value={intlDraft ?? national}\n          onChange={handleInputChange}\n          onFocus={() => setFocused(true)}\n          onBlur={handleInputBlur}\n          className=\"relative z-10 h-full min-w-0 flex-1 bg-transparent px-3 font-mono text-[14px] tracking-[-0.01em] tabular-nums text-foreground placeholder:text-muted-foreground/45 focus:outline-none disabled:cursor-not-allowed\"\n        />\n\n        {/* Right slot: self-drawing valid check + optional clear */}\n        <div className=\"relative z-10 flex shrink-0 items-center gap-0.5 pr-2\">\n          <span\n            aria-hidden=\"true\"\n            className=\"flex size-6 items-center justify-center text-emerald-600 dark:text-emerald-400\"\n          >\n            <svg viewBox=\"0 0 16 16\" fill=\"none\" className=\"size-4\">\n              <path\n                d=\"M3.25 8.5 6.5 11.75 12.75 4.75\"\n                stroke=\"currentColor\"\n                strokeWidth=\"2.1\"\n                strokeLinecap=\"round\"\n                strokeLinejoin=\"round\"\n                pathLength={1}\n                style={{\n                  strokeDasharray: 1,\n                  strokeDashoffset: isValid ? 0 : 1,\n                  opacity: isValid ? 1 : 0,\n                  transition: reduced ? \"none\" : `stroke-dashoffset 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n                }}\n              />\n            </svg>\n          </span>\n\n          {clearable && digits.length > 0 && !disabled && (\n            <button\n              type=\"button\"\n              aria-label={`Clear ${label}`}\n              onMouseDown={(e) => e.preventDefault()}\n              onClick={() => {\n                setIntlDraft(null);\n                setTouched(false);\n                emitChange(activeCountry, \"\");\n                inputRef.current?.focus();\n              }}\n              className={`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              <X className=\"size-3.5\" strokeWidth={2} />\n            </button>\n          )}\n        </div>\n      </div>\n\n      {/* Searchable hairline country popover */}\n      {open && (\n        <div\n          role=\"dialog\"\n          aria-label=\"Choose country calling code\"\n          className={`absolute left-0 top-[calc(100%_+_6px)] z-40 w-full overflow-hidden rounded-[14px] border border-border bg-card text-card-foreground ${MATERIAL_LIFT}`}\n        >\n          <div className=\"flex items-center gap-2 border-b border-border px-3 py-2\">\n            <Search className=\"size-3.5 shrink-0 text-muted-foreground\" strokeWidth={2} aria-hidden=\"true\" />\n            <input\n              ref={searchRef}\n              type=\"text\"\n              value={query}\n              placeholder=\"Search country or +code…\"\n              aria-label=\"Search country or calling code\"\n              onChange={(e) => {\n                setQuery(e.target.value);\n                setActiveIdx(0);\n              }}\n              onKeyDown={handlePickerKeyDown}\n              className=\"min-w-0 flex-1 bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none\"\n            />\n          </div>\n\n          <ul role=\"listbox\" aria-label=\"Countries\" className=\"max-h-[216px] overflow-y-auto p-1\">\n            {filteredCountries.length === 0 ? (\n              <li className=\"px-3 py-4 text-center text-[12.5px] text-muted-foreground\">No matching country</li>\n            ) : (\n              filteredCountries.map((c, idx) => {\n                const selected = c.iso === activeCountry.iso;\n                const highlighted = idx === activeIdx;\n                return (\n                  <li key={c.iso} role=\"option\" aria-selected={selected}>\n                    <button\n                      type=\"button\"\n                      onMouseEnter={() => setActiveIdx(idx)}\n                      onClick={() => selectCountry(c)}\n                      className={`flex w-full cursor-pointer items-center justify-between gap-2.5 rounded-[9px] px-2.5 py-2 text-left text-[13px] transition-colors duration-100 ${\n                        highlighted ? \"bg-accent text-foreground\" : \"text-foreground/90\"\n                      }`}\n                    >\n                      <span className=\"flex min-w-0 items-center gap-2\">\n                        <span className=\"inline-flex h-5 w-8 shrink-0 items-center justify-center rounded-[5px] border border-border bg-background font-mono text-[10.5px] font-semibold tracking-[0.04em] text-foreground\">\n                          {c.iso}\n                        </span>\n                        <span className=\"truncate font-medium\">{c.name}</span>\n                      </span>\n                      <span className=\"flex shrink-0 items-center gap-2\">\n                        <span className=\"font-mono text-[12px] tabular-nums text-muted-foreground\">+{c.dial}</span>\n                        {selected && <Check className=\"size-3.5 text-emerald-600 dark:text-emerald-400\" strokeWidth={2.4} aria-hidden=\"true\" />}\n                      </span>\n                    </button>\n                  </li>\n                );\n              })\n            )}\n          </ul>\n        </div>\n      )}\n\n      {/* Inline error fold on incomplete blur */}\n      <div\n        aria-hidden={!showError || undefined}\n        className={`grid ${!showError ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          gridTemplateRows: showError ? \"1fr\" : \"0fr\",\n          opacity: showError ? 1 : 0,\n          transition: reduced ? \"none\" : `grid-template-rows 240ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n        }}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          <p role=\"alert\" className=\"px-1 pt-1.5 text-[12px] leading-5 text-red-600 dark:text-red-400\">\n            Enter a {expectedLenLabel} {activeCountry.name} number.\n          </p>\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 PhoneInput;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · phone-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"},{"path":"registry/ui-sounds.ts","type":"registry:component","content":"// Hairline UI · phone-input · 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/phone-input. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}