{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"credit-card-input","type":"registry:component","title":"Credit card input","description":"A single-line hairline card composer with live Visa, Mastercard, Amex and Discover detection, 3D CVC back-stripe flip, Luhn validation and seamless field handoff.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/credit-card-input.tsx","type":"registry:component","content":"// Hairline UI · credit-card-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 {\n  EASE_OUT,\n  INTERACTION_FOCUS,\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 * CREDIT CARD INPUT: single-line hairline card composer\n *\n *   network   detects Visa, Mastercard, Amex and Discover on the\n *             first digits, switching formatting (4-4-4-4 vs Amex\n *             4-6-5), CVC length (3 vs 4) and the left vector\n *             card emblem automatically\n *\n *   cvc flip  focusing the CVC field rotates the left card emblem\n *             180° in 3D to show the security-code zone on the\n *             back stripe (or Amex front 4-digit badge)\n *\n *   flow      auto-pads months 2..9 to 02..09, auto-advances on\n *             valid Luhn completion -> MM / YY -> CVC, hands focus\n *             back on Backspace at position 0, compresses to\n *             \"•••• 4242\" in compact spaces, and sweeps an emerald\n *             8×8 Bayer floor pulse when the full card validates\n * ───────────────────────────────────────────────────────── */\n\nexport type CardBrand = \"visa\" | \"mastercard\" | \"amex\" | \"discover\" | \"unknown\";\n\nexport interface CardValue {\n  /** Raw digits only (no spaces). */\n  number: string;\n  /** Formatted number (e.g. \"4242 4242 4242 4242\"). */\n  formattedNumber: string;\n  /** Last four digits once available. */\n  last4: string;\n  /** Detected card network. */\n  brand: CardBrand;\n  /** Two-digit expiry month (\"01\"..\"12\") or partial draft. */\n  expMonth: string;\n  /** Two-digit expiry year (\"27\") or partial draft. */\n  expYear: string;\n  /** Security code (3 digits, or 4 for Amex). */\n  cvc: string;\n  /** Optional postal / ZIP code when `showPostal` is enabled. */\n  postal?: string;\n  /** True only when Luhn checksum, non-expired date, CVC length (and postal if shown) all pass. */\n  valid: boolean;\n  /** Specific field error message if any completed field fails validation. */\n  error: string | null;\n}\n\nexport interface CreditCardInputProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  /** Fires cleanly on every edit with structured card details and validation state. */\n  onChange?: (card: CardValue) => void;\n  /** Optional initial card number digits (useful for previews/tests; omit in production). */\n  defaultNumber?: string;\n  /** Optional initial expiry in \"MM/YY\" format. */\n  defaultExpiry?: string;\n  /** Optional initial CVC. */\n  defaultCvc?: string;\n  /** Compress valid card number to \"•••• 4242\" while editing Expiry / CVC so tight layouts never clip (default true). */\n  compactOnAdvance?: boolean;\n  /** Include an inline postal / ZIP code slot at the end (default false). */\n  showPostal?: boolean;\n  /** Accessible group label (default \"Card details\"). */\n  label?: string;\n  /** Disabled state. */\n  disabled?: boolean;\n  /** Opt-in quiet Web Audio ticks on valid lock-in and validation error (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\nconst BAYER8: Float32Array = (() => {\n  const m = [\n    [0, 32, 8, 40, 2, 34, 10, 42],\n    [48, 16, 56, 24, 50, 18, 58, 26],\n    [12, 44, 4, 36, 14, 46, 6, 38],\n    [60, 28, 52, 20, 62, 30, 54, 22],\n    [3, 35, 11, 43, 1, 33, 9, 41],\n    [51, 19, 59, 27, 49, 17, 57, 25],\n    [15, 47, 7, 39, 13, 45, 5, 37],\n    [63, 31, 55, 23, 61, 29, 53, 21],\n  ];\n  const out = new Float32Array(64);\n  for (let y = 0; y < 8; y++) {\n    for (let x = 0; x < 8; x++) {\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);\nconst onlyDigits = (s: string) => s.replace(/\\D+/g, \"\");\n\n/** Detect card network from leading digits (BIN prefix). */\nexport function detectCardBrand(digits: string): CardBrand {\n  const d = onlyDigits(digits);\n  if (!d) return \"unknown\";\n  if (/^4/.test(d)) return \"visa\";\n  if (/^3[47]/.test(d)) return \"amex\";\n  if (/^(5[1-5]|222[1-9]|22[3-9]\\d|2[3-6]\\d{2}|27[01]\\d|2720)/.test(d)) return \"mastercard\";\n  if (/^(6011|65|64[4-9])/.test(d)) return \"discover\";\n  return \"unknown\";\n}\n\n/** Standard Mod-10 Luhn checksum validation. */\nexport function isValidLuhn(digits: string): boolean {\n  const d = onlyDigits(digits);\n  if (d.length < 13) return false;\n  let sum = 0;\n  let dbl = false;\n  for (let i = d.length - 1; i >= 0; i--) {\n    let n = d.charCodeAt(i) - 48;\n    if (dbl) {\n      n *= 2;\n      if (n > 9) n -= 9;\n    }\n    sum += n;\n    dbl = !dbl;\n  }\n  return sum % 10 === 0;\n}\n\nfunction cardMaxDigits(brand: CardBrand): number {\n  return brand === \"amex\" ? 15 : 16;\n}\n\nfunction cardCvcLength(brand: CardBrand): number {\n  return brand === \"amex\" ? 4 : 3;\n}\n\nfunction formatCardNumber(digits: string, brand: CardBrand): string {\n  const d = onlyDigits(digits).slice(0, cardMaxDigits(brand));\n  if (brand === \"amex\") {\n    const p1 = d.slice(0, 4);\n    const p2 = d.slice(4, 10);\n    const p3 = d.slice(10, 15);\n    return [p1, p2, p3].filter(Boolean).join(\" \");\n  }\n  const groups: string[] = [];\n  for (let i = 0; i < d.length; i += 4) groups.push(d.slice(i, i + 4));\n  return groups.join(\" \");\n}\n\nfunction caretAfterDigits(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\nfunction validateExpiry(mm: string, yy: string): { complete: boolean; valid: boolean; reason: string | null } {\n  if (mm.length < 2 || yy.length < 2) return { complete: false, valid: false, reason: null };\n  const m = Number(mm);\n  const y = Number(yy);\n  if (!Number.isInteger(m) || m < 1 || m > 12) {\n    return { complete: true, valid: false, reason: \"Enter a valid expiry month.\" };\n  }\n  const now = new Date();\n  const curY = now.getFullYear() % 100;\n  const curM = now.getMonth() + 1;\n  if (y < curY || (y === curY && m < curM)) {\n    return { complete: true, valid: false, reason: \"Card has expired.\" };\n  }\n  return { complete: true, valid: true, reason: null };\n}\n\nfunction CardEmblem({ brand, flipped, reduced }: { brand: CardBrand; flipped: boolean; reduced: boolean }) {\n  return (\n    <span className=\"relative inline-block h-[20px] w-[30px] shrink-0\" style={{ perspective: \"220px\" }} aria-hidden=\"true\">\n      <span\n        className=\"relative block h-full w-full\"\n        style={{\n          transformStyle: \"preserve-3d\",\n          transform: flipped ? \"rotateY(180deg)\" : \"rotateY(0deg)\",\n          transition: reduced ? \"none\" : `transform 360ms ${EASE_OUT}`,\n        }}\n      >\n        {/* Front face: dynamic bespoke vector card emblem */}\n        <span\n          className=\"absolute inset-0 flex items-center justify-center overflow-hidden rounded-[4.5px] border border-border bg-background\"\n          style={{ backfaceVisibility: \"hidden\" }}\n        >\n          {brand === \"visa\" ? (\n            <svg width=\"30\" height=\"20\" viewBox=\"0 0 30 20\" fill=\"none\">\n              <rect width=\"30\" height=\"20\" fill=\"#1A369B\" />\n              <text x=\"15\" y=\"13.2\" textAnchor=\"middle\" fill=\"#FFFFFF\" fontSize=\"8\" fontWeight=\"700\" fontStyle=\"italic\" fontFamily=\"system-ui, sans-serif\" letterSpacing=\"0.4\">\n                VISA\n              </text>\n            </svg>\n          ) : brand === \"mastercard\" ? (\n            <svg width=\"30\" height=\"20\" viewBox=\"0 0 30 20\" fill=\"none\">\n              <rect width=\"30\" height=\"20\" fill=\"#18181B\" />\n              <circle cx=\"12\" cy=\"10\" r=\"5\" fill=\"#EB001B\" />\n              <circle cx=\"18\" cy=\"10\" r=\"5\" fill=\"#F79E1B\" fillOpacity=\"0.92\" />\n            </svg>\n          ) : brand === \"amex\" ? (\n            <svg width=\"30\" height=\"20\" viewBox=\"0 0 30 20\" fill=\"none\">\n              <rect width=\"30\" height=\"20\" fill=\"#0F769E\" />\n              <text x=\"15\" y=\"12.8\" textAnchor=\"middle\" fill=\"#FFFFFF\" fontSize=\"6.5\" fontWeight=\"700\" fontFamily=\"system-ui, sans-serif\" letterSpacing=\"0.3\">\n                AMEX\n              </text>\n            </svg>\n          ) : brand === \"discover\" ? (\n            <svg width=\"30\" height=\"20\" viewBox=\"0 0 30 20\" fill=\"none\">\n              <rect width=\"30\" height=\"20\" fill=\"#1E293B\" />\n              <circle cx=\"24\" cy=\"16\" r=\"7\" fill=\"#F97316\" />\n              <rect x=\"4\" y=\"6\" width=\"11\" height=\"2\" rx=\"1\" fill=\"#E2E8F0\" />\n            </svg>\n          ) : (\n            <svg width=\"30\" height=\"20\" viewBox=\"0 0 30 20\" fill=\"none\" className=\"text-muted-foreground\">\n              <rect x=\"3.5\" y=\"4.5\" width=\"7\" height=\"4.5\" rx=\"1\" stroke=\"currentColor\" strokeWidth=\"1.1\" strokeOpacity=\"0.6\" />\n              <line x1=\"3.5\" y1=\"14\" x2=\"12\" y2=\"14\" stroke=\"currentColor\" strokeWidth=\"1.2\" strokeLinecap=\"round\" strokeOpacity=\"0.45\" />\n              <line x1=\"15\" y1=\"14\" x2=\"22\" y2=\"14\" stroke=\"currentColor\" strokeWidth=\"1.2\" strokeLinecap=\"round\" strokeOpacity=\"0.3\" />\n            </svg>\n          )}\n        </span>\n\n        {/* Back face: magnetic stripe + highlighted security code zone when focused on CVC */}\n        <span\n          className=\"absolute inset-0 flex items-center justify-center overflow-hidden rounded-[4.5px] border border-border bg-muted\"\n          style={{ backfaceVisibility: \"hidden\", transform: \"rotateY(180deg)\" }}\n        >\n          <svg width=\"30\" height=\"20\" viewBox=\"0 0 30 20\" fill=\"none\">\n            <rect width=\"30\" height=\"20\" className=\"fill-zinc-800 dark:fill-zinc-900\" />\n            <rect y=\"3.5\" width=\"30\" height=\"4\" className=\"fill-zinc-950\" />\n            <rect x=\"3\" y=\"10.5\" width=\"15\" height=\"4.5\" rx=\"1\" className=\"fill-zinc-600/70\" />\n            <rect x=\"19.5\" y=\"10\" width=\"7.5\" height=\"5.5\" rx=\"1.2\" fill=\"#3B82F6\" fillOpacity=\"0.28\" stroke=\"#60A5FA\" strokeWidth=\"1\" />\n          </svg>\n        </span>\n      </span>\n    </span>\n  );\n}\n\nexport function CreditCardInput({\n  onChange,\n  defaultNumber = \"\",\n  defaultExpiry = \"\",\n  defaultCvc = \"\",\n  compactOnAdvance = true,\n  showPostal = false,\n  label = \"Card details\",\n  disabled = false,\n  sound = false,\n  className = \"\",\n  ...props\n}: CreditCardInputProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();\n\n  const [numDigits, setNumDigits] = React.useState(() => onlyDigits(defaultNumber).slice(0, 16));\n  const [expDigits, setExpDigits] = React.useState(() => onlyDigits(defaultExpiry).slice(0, 4));\n  const [cvcDigits, setCvcDigits] = React.useState(() => onlyDigits(defaultCvc).slice(0, 4));\n  const [postal, setPostal] = React.useState(\"\");\n  const [activeSlot, setActiveSlot] = React.useState<\"number\" | \"expiry\" | \"cvc\" | \"postal\" | null>(null);\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n\n  const shellRef = React.useRef<HTMLDivElement>(null);\n  const numberRef = React.useRef<HTMLInputElement>(null);\n  const expiryRef = React.useRef<HTMLInputElement>(null);\n  const cvcRef = React.useRef<HTMLInputElement>(null);\n  const postalRef = 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\" | \"error\") => void) | null>(null);\n\n  const brand = React.useMemo(() => detectCardBrand(numDigits), [numDigits]);\n  const maxNumLen = cardMaxDigits(brand);\n  const reqCvcLen = cardCvcLength(brand);\n  const cleanNum = numDigits.slice(0, maxNumLen);\n  const formattedNumber = React.useMemo(() => formatCardNumber(cleanNum, brand), [cleanNum, brand]);\n\n  const numComplete = cleanNum.length === maxNumLen;\n  const numValid = numComplete && isValidLuhn(cleanNum);\n  const numError = numComplete && !numValid ? \"Check the card number.\" : null;\n\n  const expMonth = expDigits.slice(0, 2);\n  const expYear = expDigits.slice(2, 4);\n  const formattedExpiry = expDigits.length > 2 ? `${expMonth} / ${expYear}` : expMonth;\n  const expCheck = React.useMemo(() => validateExpiry(expMonth, expYear), [expMonth, expYear]);\n\n  const cleanCvc = cvcDigits.slice(0, reqCvcLen);\n  const cvcValid = cleanCvc.length === reqCvcLen;\n  const postalValid = !showPostal || postal.trim().length >= 3;\n\n  const fieldError = numError ?? (expCheck.complete && !expCheck.valid ? expCheck.reason : null);\n  const allValid = numValid && expCheck.valid && cvcValid && postalValid;\n\n  // Compact the valid card number cleanly to \"•••• 4242\" while editing Expiry / CVC / Postal so nothing ever clips!\n  const isCompact = compactOnAdvance && numValid && activeSlot !== \"number\";\n\n  const prevValidRef = React.useRef(allValid);\n  const prevErrRef = React.useRef<string | null>(fieldError);\n\n  // Horizontal spring recoil on invalid Luhn or expired card\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 (wakes strictly for ~0.5s on valid card 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\" | \"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.45 : 0.56;\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] = kind === \"error\" ? [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.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.74 * 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  // Emit structured CardValue on changes + trigger subtle optical confirmation / recoil strictly on transitions\n  React.useEffect(() => {\n    onChange?.({\n      number: cleanNum,\n      formattedNumber,\n      last4: cleanNum.length >= 4 ? cleanNum.slice(-4) : \"\",\n      brand,\n      expMonth,\n      expYear,\n      cvc: cleanCvc,\n      ...(showPostal ? { postal } : {}),\n      valid: allValid,\n      error: fieldError,\n    });\n  }, [cleanNum, formattedNumber, brand, expMonth, expYear, cleanCvc, postal, showPostal, allValid, fieldError, onChange]);\n\n  React.useEffect(() => {\n    if (allValid && !prevValidRef.current) {\n      flashRef.current?.(\"valid\");\n      if (sound) playSound(\"success\", 0.36);\n    }\n    prevValidRef.current = allValid;\n  }, [allValid, sound]);\n\n  React.useEffect(() => {\n    if (fieldError && fieldError !== prevErrRef.current) {\n      if (!reduced) recoilRef.current?.push(145);\n      flashRef.current?.(\"error\");\n      if (sound) playSound(\"error\", 0.34);\n    }\n    prevErrRef.current = fieldError;\n  }, [fieldError, reduced, sound]);\n\n  const handleNumberChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const el = e.currentTarget;\n    const raw = el.value;\n    const sel = el.selectionStart ?? raw.length;\n    const digitsBefore = onlyDigits(raw.slice(0, sel)).length;\n\n    const nextDigits = onlyDigits(raw);\n    const nextBrand = detectCardBrand(nextDigits);\n    const nextMax = cardMaxDigits(nextBrand);\n    const clamped = nextDigits.slice(0, nextMax);\n    setNumDigits(clamped);\n\n    const nextFmt = formatCardNumber(clamped, nextBrand);\n    const nextCaret = caretAfterDigits(nextFmt, Math.min(digitsBefore, clamped.length));\n\n    if (clamped.length === nextMax && isValidLuhn(clamped)) {\n      if (sound) playSound(\"tick\", 0.28);\n      setLiveStatus(`${nextBrand === \"unknown\" ? \"Card\" : nextBrand} ending in ${clamped.slice(-4)} verified. Enter expiry date.`);\n      window.requestAnimationFrame(() => expiryRef.current?.focus());\n    } else {\n      window.requestAnimationFrame(() => {\n        if (numberRef.current) numberRef.current.setSelectionRange(nextCaret, nextCaret);\n      });\n    }\n  };\n\n  const handleExpiryChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    let raw = onlyDigits(e.currentTarget.value).slice(0, 4);\n    // Auto-pad months 2..9 to 02..09 as the first digit arrives\n    if (raw.length === 1 && Number(raw) >= 2 && expDigits.length === 0) {\n      raw = `0${raw}`;\n    }\n    setExpDigits(raw);\n    if (raw.length === 4) {\n      const check = validateExpiry(raw.slice(0, 2), raw.slice(2, 4));\n      if (check.valid) {\n        if (sound) playSound(\"tick\", 0.26);\n        window.requestAnimationFrame(() => cvcRef.current?.focus());\n      }\n    }\n  };\n\n  const handleCvcChange = (e: React.ChangeEvent<HTMLInputElement>) => {\n    const raw = onlyDigits(e.currentTarget.value).slice(0, reqCvcLen);\n    setCvcDigits(raw);\n    if (raw.length === reqCvcLen && showPostal) {\n      window.requestAnimationFrame(() => postalRef.current?.focus());\n    }\n  };\n\n  const expandNumber = () => {\n    setActiveSlot(\"number\");\n    window.requestAnimationFrame(() => {\n      const el = numberRef.current;\n      if (el) {\n        el.focus();\n        el.setSelectionRange(el.value.length, el.value.length);\n      }\n    });\n  };\n\n  const hasFocus = activeSlot !== null;\n  const [lastError, setLastError] = React.useState<string>(\"\");\n  if (fieldError && fieldError !== lastError) {\n    setLastError(fieldError);\n  }\n\n  return (\n    <div ref={rootRef} role=\"group\" aria-label={label} className={`@container flex w-full flex-col ${className}`} {...props}>\n      <div\n        ref={shellRef}\n        data-brand={brand}\n        data-valid={allValid ? \"true\" : \"false\"}\n        data-cvc-flipped={activeSlot === \"cvc\" ? \"true\" : \"false\"}\n        className={`relative flex w-full flex-col overflow-hidden 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)] @[440px]:h-11 @[440px]:flex-row @[440px]:items-center @[440px]:px-3 ${\n          fieldError\n            ? \"border-red-500/45 dark:border-red-400/45\"\n            : hasFocus\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        {/* Row 1 (mobile) / Left section (desktop): Network emblem + Card number */}\n        <div className=\"relative z-10 flex h-11 min-w-0 flex-1 items-center px-3 @[440px]:h-full @[440px]:px-0\">\n          {/* Dynamic network emblem -> flips 180° to CVC back-stripe when CVC has focus */}\n          <span className=\"mr-2.5 flex shrink-0 items-center\">\n            <CardEmblem brand={brand} flipped={activeSlot === \"cvc\"} reduced={reduced} />\n          </span>\n\n          {/* Card number slot (smoothly compresses to clickable \"•••• 4242\" pill when advancing on wide layouts) */}\n          {isCompact ? (\n            <button\n              type=\"button\"\n              disabled={disabled}\n              aria-label={`Card ending in ${cleanNum.slice(-4)}. Click to edit card number.`}\n              onClick={expandNumber}\n              className={`mr-1 inline-flex h-7 shrink-0 cursor-pointer items-center gap-1 rounded-[7px] bg-muted/60 px-2 font-mono text-[13px] tabular-nums text-foreground transition-colors hover:bg-accent ${INTERACTION_FOCUS}`}\n            >\n              <span className=\"tracking-[0.12em] text-muted-foreground\">••••</span>\n              <span>{cleanNum.slice(-4)}</span>\n            </button>\n          ) : (\n            <input\n              ref={numberRef}\n              type=\"text\"\n              inputMode=\"numeric\"\n              autoComplete=\"cc-number\"\n              disabled={disabled}\n              aria-label=\"Card number\"\n              aria-invalid={Boolean(numError) || undefined}\n              placeholder=\"1234 5678 9012 3456\"\n              value={formattedNumber}\n              onChange={handleNumberChange}\n              onFocus={() => setActiveSlot(\"number\")}\n              onBlur={() => setActiveSlot((s) => (s === \"number\" ? null : s))}\n              className={`h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13.5px] tracking-[-0.01em] tabular-nums placeholder:text-muted-foreground/45 focus:outline-none ${\n                numError ? \"text-red-600 dark:text-red-400\" : \"text-foreground\"\n              }`}\n            />\n          )}\n\n          {/* Drawn verification check (mobile top-right slot) */}\n          <span\n            aria-hidden=\"true\"\n            className=\"ml-2 flex size-5 shrink-0 items-center justify-center text-emerald-600 dark:text-emerald-400 @[440px]:hidden\"\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: allValid ? 0 : 1,\n                  opacity: allValid ? 1 : 0,\n                  transition: reduced ? \"none\" : `stroke-dashoffset 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n                }}\n              />\n            </svg>\n          </span>\n        </div>\n\n        {/* Row 2 (mobile, full hairline tier so MM/YY, CVC and ZIP never clip) / Right group (desktop) */}\n        <div\n          className={`relative z-10 flex h-10 shrink-0 items-center border-t border-border/75 px-3 @[440px]:h-full @[440px]:border-t-0 @[440px]:px-0 ${\n            isCompact ? \"@[440px]:flex-1 @[440px]:justify-end\" : \"\"\n          }`}\n        >\n          <span aria-hidden=\"true\" className=\"mx-2 hidden h-4 w-px bg-border/80 @[440px]:block\" />\n\n          <input\n            ref={expiryRef}\n            type=\"text\"\n            inputMode=\"numeric\"\n            autoComplete=\"cc-exp\"\n            disabled={disabled}\n            aria-label=\"Expiry date\"\n            aria-invalid={Boolean(expCheck.complete && !expCheck.valid) || undefined}\n            placeholder=\"MM / YY\"\n            value={formattedExpiry}\n            onChange={handleExpiryChange}\n            onKeyDown={(e) => {\n              if (e.key === \"Backspace\" && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {\n                e.preventDefault();\n                expandNumber();\n              }\n            }}\n            onFocus={() => setActiveSlot(\"expiry\")}\n            onBlur={() => setActiveSlot((s) => (s === \"expiry\" ? null : s))}\n            className={`h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13.5px] tabular-nums placeholder:text-muted-foreground/45 focus:outline-none @[440px]:w-[62px] @[440px]:flex-none ${\n              expCheck.complete && !expCheck.valid ? \"text-red-600 dark:text-red-400\" : \"text-foreground\"\n            }`}\n          />\n\n          <span aria-hidden=\"true\" className=\"mx-2.5 h-4 w-px shrink-0 bg-border/80 @[440px]:mx-2\" />\n\n          <input\n            ref={cvcRef}\n            type=\"text\"\n            inputMode=\"numeric\"\n            autoComplete=\"cc-csc\"\n            disabled={disabled}\n            aria-label={brand === \"amex\" ? \"4-digit security code\" : \"3-digit security code\"}\n            placeholder={brand === \"amex\" ? \"CID\" : \"CVC\"}\n            value={cleanCvc}\n            onChange={handleCvcChange}\n            onKeyDown={(e) => {\n              if (e.key === \"Backspace\" && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {\n                e.preventDefault();\n                expiryRef.current?.focus();\n              }\n            }}\n            onFocus={() => setActiveSlot(\"cvc\")}\n            onBlur={() => setActiveSlot((s) => (s === \"cvc\" ? null : s))}\n            className=\"h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13.5px] tabular-nums text-foreground placeholder:text-muted-foreground/45 focus:outline-none @[440px]:w-[40px] @[440px]:flex-none\"\n          />\n\n          {showPostal && (\n            <>\n              <span aria-hidden=\"true\" className=\"mx-2.5 h-4 w-px shrink-0 bg-border/80 @[440px]:mx-2\" />\n              <input\n                ref={postalRef}\n                type=\"text\"\n                autoComplete=\"postal-code\"\n                disabled={disabled}\n                aria-label=\"Postal code\"\n                placeholder=\"ZIP\"\n                value={postal}\n                onChange={(e) => setPostal(e.currentTarget.value.slice(0, 10))}\n                onKeyDown={(e) => {\n                  if (e.key === \"Backspace\" && e.currentTarget.selectionStart === 0 && e.currentTarget.selectionEnd === 0) {\n                    e.preventDefault();\n                    cvcRef.current?.focus();\n                  }\n                }}\n                onFocus={() => setActiveSlot(\"postal\")}\n                onBlur={() => setActiveSlot((s) => (s === \"postal\" ? null : s))}\n                className=\"h-full min-w-0 flex-1 bg-transparent text-left font-mono text-[13px] text-foreground placeholder:text-muted-foreground/45 focus:outline-none @[440px]:w-[58px] @[440px]:flex-none\"\n              />\n            </>\n          )}\n\n          {/* Drawn verification check (desktop right slot) */}\n          <span\n            aria-hidden=\"true\"\n            className=\"ml-1 hidden size-5 shrink-0 items-center justify-center text-emerald-600 dark:text-emerald-400 @[440px]:flex\"\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: allValid ? 0 : 1,\n                  opacity: allValid ? 1 : 0,\n                  transition: reduced ? \"none\" : `stroke-dashoffset 320ms ${EASE_OUT}, opacity 180ms ${EASE_OUT}`,\n                }}\n              />\n            </svg>\n          </span>\n        </div>\n      </div>\n\n      {/* Inline validation error fold (keeps last error while folding shut so text never vanishes mid-close) */}\n      <div\n        aria-hidden={!fieldError || undefined}\n        className={`grid ${!fieldError ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          gridTemplateRows: fieldError ? \"1fr\" : \"0fr\",\n          opacity: fieldError ? 1 : 0,\n          transition: reduced ? \"none\" : `grid-template-rows 280ms ${EASE_OUT}, opacity 200ms ${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            <TextMorph animateWidth={false}>{fieldError ?? lastError}</TextMorph>\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 CreditCardInput;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · credit-card-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 · credit-card-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/credit-card-input. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}