{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"backup-codes","type":"registry:component","title":"Backup codes","description":"A 2FA recovery codes panel with 1.5px 8×8 Bayer secret veiling, copy-while-veiled, .txt export, used-code audit stamps and inline regeneration.","author":"Hairline UI","dependencies":["lucide-react"],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency","https://hairlineui.com/r/number-roll.json?as=dependency"],"files":[{"path":"registry/backup-codes.tsx","type":"registry:component","content":"// Hairline UI · backup-codes · 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  AlertTriangle,\n  Check,\n  Copy,\n  Download,\n  Eye,\n  EyeOff,\n  Loader2,\n  Printer,\n  RefreshCw,\n  ShieldCheck,\n} from \"lucide-react\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  interactionIcon,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n} from \"./ui-interaction-motion\";\nimport { NumberRoll } from \"./number-roll\";\nimport { TextMorph } from \"./text-morph\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * BACKUP CODES: 2FA recovery codes vault with Bayer veiling\n *\n *   veil      active recovery codes sit behind a 1.5px 8×8 Bayer\n *             optical veil by default (0% CPU at rest, crisp dark\n *             and light) while already-used codes remain visibly\n *             struck through so remaining count is auditable even\n *             on screen share\n *\n *   copy      Copy all writes all unused codes directly to the\n *             clipboard even while veiled and sweeps an emerald\n *             Bayer wavefront across the veiled slots; individual\n *             revealed codes copy with one click\n *\n *   infra     ships real .txt Blob export, print sheet helper,\n *             cryptographically clean generateBackupCodes(), low-\n *             remaining amber warning and an inline two-step\n *             Regenerate confirmation with zero browser dialogs\n * ───────────────────────────────────────────────────────── */\n\nexport interface BackupCodeItem {\n  /** Formatted recovery code (e.g. \"k7m2-9x4p\"). */\n  code: string;\n  /** Whether this recovery code has already been redeemed. */\n  used?: boolean;\n  /** Optional label shown when used (e.g. \"Used 14 Nov\"). */\n  usedAt?: string;\n}\n\nexport interface BackupCodesProps extends Omit<React.HTMLAttributes<HTMLDivElement>, \"onChange\"> {\n  /** Recovery codes as strings or structured objects. */\n  codes: Array<string | BackupCodeItem>;\n  /** Service or organisation name written into exported .txt and print headers (default \"Hairline\"). */\n  issuer?: string;\n  /** Account email or handle written into exported .txt and print headers. */\n  account?: string;\n  /** Filename for the downloaded plain-text export (default \"recovery-codes.txt\"). */\n  filename?: string;\n  /** Start with unused codes veiled behind 8×8 Bayer grain (default true). */\n  defaultVeiled?: boolean;\n  /** Allow clicking a single revealed code to copy it (default true). */\n  allowCopyIndividual?: boolean;\n  /** Optional handler to toggle a code's used status (enables interactive audit buttons). */\n  onToggleUsed?: (code: string, used: boolean) => void;\n  /** Optional handler to generate a fresh batch of codes (enables two-step inline Regenerate). */\n  onRegenerate?: () => Promise<unknown> | unknown;\n  /** Optional override for Download .txt action. */\n  onDownload?: (content: string) => void;\n  /** Optional override for Print action. */\n  onPrint?: () => void;\n  /** Warn in amber when unused codes fall at or below this count (default 2). */\n  lowThreshold?: number;\n  /** Card header title (default \"Recovery codes\"). */\n  title?: string;\n  /** Opt-in Web Audio cues (from ui-sounds.ts). */\n  sound?: boolean;\n}\n\n// Crockford-inspired unambiguous alphabet (omits 0, O, 1, I, L)\nconst CODE_ALPHABET = \"23456789abcdefghjkmnpqrstuvwxyz\";\n\n/** Generate cryptographically clean `xxxx-xxxx` recovery codes. */\nexport function generateBackupCodes(count = 8): BackupCodeItem[] {\n  const out: BackupCodeItem[] = [];\n  const bytes = new Uint8Array(8);\n  for (let i = 0; i < count; i++) {\n    if (typeof crypto !== \"undefined\" && typeof crypto.getRandomValues === \"function\") {\n      crypto.getRandomValues(bytes);\n    } else {\n      for (let j = 0; j < 8; j++) bytes[j] = Math.floor(Math.random() * 256);\n    }\n    let s = \"\";\n    for (let j = 0; j < 8; j++) {\n      if (j === 4) s += \"-\";\n      s += CODE_ALPHABET[bytes[j] % CODE_ALPHABET.length];\n    }\n    out.push({ code: s, used: false });\n  }\n  return out;\n}\n\n/** Format recovery codes into a clean plain-text `.txt` sheet for safe offline storage. */\nexport function formatBackupCodesFile(\n  codes: Array<string | BackupCodeItem>,\n  meta?: { issuer?: string; account?: string },\n): string {\n  const issuer = meta?.issuer || \"Account\";\n  const dateStr = new Date().toISOString().slice(0, 10);\n  const items = codes.map((c) => (typeof c === \"string\" ? { code: c, used: false } : c));\n  const unused = items.filter((i) => !i.used);\n  const lines = [\n    `${issuer} — Two-Factor Recovery Codes`,\n    ...(meta?.account ? [`Account: ${meta.account}`] : []),\n    `Saved:   ${dateStr}`,\n    `Unused:  ${unused.length} of ${items.length}`,\n    \"\",\n    \"Each code can be used once to sign in if you lose access to your authenticator.\",\n    \"Store this file in a password manager or locked physical copy.\",\n    \"\",\n    ...items.map((item, idx) => `${String(idx + 1).padStart(2, \"0\")}. ${item.code}${item.used ? \"  [USED]\" : \"\"}`),\n    \"\",\n  ];\n  return lines.join(\"\\n\");\n}\n\nconst BAYER8: Float32Array = (() => {\n  const m = [\n    [0, 32, 8, 40, 2, 34, 10, 42],\n    [48, 16, 56, 24, 50, 18, 58, 26],\n    [12, 44, 4, 36, 14, 46, 6, 38],\n    [60, 28, 52, 20, 62, 30, 54, 22],\n    [3, 35, 11, 43, 1, 33, 9, 41],\n    [51, 19, 59, 27, 49, 17, 57, 25],\n    [15, 47, 7, 39, 13, 45, 5, 37],\n    [63, 31, 55, 23, 61, 29, 53, 21],\n  ];\n  const out = new Float32Array(64);\n  for (let y = 0; y < 8; y++) {\n    for (let x = 0; x < 8; x++) out[(y << 3) | x] = (m[y][x] + 0.5) / 64;\n  }\n  return out;\n})();\n\nconst IS_LE = (() => {\n  const b = new ArrayBuffer(4);\n  new Uint32Array(b)[0] = 0x0a0b0c0d;\n  return new Uint8Array(b)[0] === 0x0d;\n})();\n\nfunction packRgba(r: number, g: number, b: number, a: number): number {\n  const ri = r < 0 ? 0 : r > 255 ? 255 : r | 0;\n  const gi = g < 0 ? 0 : g > 255 ? 255 : g | 0;\n  const bi = b < 0 ? 0 : b > 255 ? 255 : b | 0;\n  const ai = a < 0 ? 0 : a > 255 ? 255 : a | 0;\n  return IS_LE ? ((ai << 24) | (bi << 16) | (gi << 8) | ri) >>> 0 : ((ri << 24) | (gi << 16) | (bi << 8) | ai) >>> 0;\n}\n\nfunction clamp(v: number, lo: number, hi: number) {\n  return v < lo ? lo : v > hi ? hi : v;\n}\n\n/**\n * 1.5px 8×8 Bayer cell:\n *   mode=\"veil\"  -> static optical veil at rest (0% CPU) + emerald sweep on flashToken\n *   mode=\"burst\" -> transparent at rest (0% CPU) + staggered emerald Bayer materialise curtain on flashToken\n */\nfunction BayerCodeVeil({\n  seed,\n  flashToken,\n  delayMs,\n  mode = \"veil\",\n  active,\n  reduced,\n  className = \"pointer-events-none block h-5 w-full rounded-[4px] [image-rendering:pixelated]\",\n}: {\n  seed: number;\n  flashToken: number;\n  delayMs: number;\n  mode?: \"veil\" | \"burst\";\n  active: boolean;\n  reduced: boolean;\n  className?: string;\n}) {\n  const canvasRef = React.useRef<HTMLCanvasElement | null>(null);\n  const lastFlashRef = React.useRef(flashToken);\n\n  React.useEffect(() => {\n    const canvas = canvasRef.current;\n    if (!canvas) return;\n    const ctx = canvas.getContext(\"2d\");\n    if (!ctx) return;\n\n    const isDark = () => document.documentElement.classList.contains(\"dark\");\n    let w = 0;\n    let h = 0;\n    let img: ImageData | null = null;\n    let u32: Uint32Array | null = null;\n\n    const resize = () => {\n      const rect = canvas.getBoundingClientRect();\n      const cssW = Math.max(80, Math.round(rect.width));\n      const cssH = Math.max(20, Math.round(rect.height));\n      w = Math.max(40, Math.round(cssW / 1.5));\n      h = Math.max(12, Math.round(cssH / 1.5));\n      if (canvas.width !== w || canvas.height !== h) {\n        canvas.width = w;\n        canvas.height = h;\n      }\n      img = ctx.createImageData(w, h);\n      u32 = new Uint32Array(img.data.buffer);\n    };\n\n    const draw = (sweepProgress: number | null) => {\n      if (!img || !u32 || w === 0 || h === 0) return;\n      if (mode === \"burst\" && sweepProgress === null) {\n        ctx.clearRect(0, 0, w, h);\n        return;\n      }\n      const dark = isDark();\n      const baseRgb: [number, number, number] = dark ? [168, 176, 192] : [72, 80, 96];\n      const accentRgb: [number, number, number] = dark ? [52, 211, 153] : [16, 185, 129];\n      const baseAlpha = dark ? 150 : 122;\n\n      u32.fill(0);\n      for (let y = 0; y < h; y++) {\n        const ny = y / Math.max(1, h - 1);\n        for (let x = 0; x < w; x++) {\n          const nx = x / Math.max(1, w - 1);\n          const thr = BAYER8[((y & 7) << 3) | (x & 7)];\n\n          if (mode === \"burst\" && sweepProgress !== null) {\n            const front = sweepProgress * 1.5 - 0.25;\n            const env = Math.sin(sweepProgress * Math.PI);\n            const band = Math.exp(-Math.pow((nx - front) / 0.24, 2));\n            const density = clamp(band * env * 0.94, 0, 0.96);\n            if (density > thr) {\n              const mix = clamp(band * 1.15, 0, 1);\n              const r = Math.round(baseRgb[0] + (accentRgb[0] - baseRgb[0]) * mix);\n              const g = Math.round(baseRgb[1] + (accentRgb[1] - baseRgb[1]) * mix);\n              const b = Math.round(baseRgb[2] + (accentRgb[2] - baseRgb[2]) * mix);\n              u32[y * w + x] = packRgba(r, g, b, Math.round(230 * env));\n            }\n            continue;\n          }\n\n          const wave =\n            0.5 +\n            0.16 * Math.sin(nx * 6.5 + seed * 1.7 + ny * 1.9) +\n            0.09 * Math.cos(nx * 13.0 - seed * 2.3);\n          let density = clamp(wave * 0.62, 0.14, 0.72);\n          let r = baseRgb[0];\n          let g = baseRgb[1];\n          let b = baseRgb[2];\n          let a = baseAlpha;\n\n          if (sweepProgress !== null) {\n            const front = sweepProgress * 1.4 - 0.2;\n            const pulse = Math.exp(-Math.pow((nx - front) / 0.2, 2)) * Math.sin(sweepProgress * Math.PI);\n            if (pulse > 0.04) {\n              density = clamp(density + pulse * 0.45, 0, 0.96);\n              r = Math.round(baseRgb[0] + (accentRgb[0] - baseRgb[0]) * pulse);\n              g = Math.round(baseRgb[1] + (accentRgb[1] - baseRgb[1]) * pulse);\n              b = Math.round(baseRgb[2] + (accentRgb[2] - baseRgb[2]) * pulse);\n              a = Math.round(baseAlpha + (235 - baseAlpha) * pulse);\n            }\n          }\n\n          if (density > thr) {\n            u32[y * w + x] = packRgba(r, g, b, a);\n          }\n        }\n      }\n      ctx.putImageData(img, 0, 0);\n    };\n\n    resize();\n    draw(null);\n\n    const ro = new ResizeObserver(() => {\n      resize();\n      draw(null);\n    });\n    ro.observe(canvas);\n\n    const mo = new MutationObserver(() => draw(null));\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\"] });\n\n    let raf = 0;\n    let delayTimer = 0;\n    const shouldFlash = flashToken !== lastFlashRef.current;\n    lastFlashRef.current = flashToken;\n\n    if (shouldFlash && !reduced && active) {\n      const startSweep = () => {\n        const start = performance.now();\n        const duration = mode === \"burst\" ? 600 : 520;\n        const step = (now: number) => {\n          const p = clamp((now - start) / duration, 0, 1);\n          draw(p);\n          if (p < 1) raf = window.requestAnimationFrame(step);\n          else draw(null);\n        };\n        raf = window.requestAnimationFrame(step);\n      };\n      if (delayMs > 0) {\n        delayTimer = window.setTimeout(startSweep, delayMs);\n      } else {\n        startSweep();\n      }\n    }\n\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      window.clearTimeout(delayTimer);\n      window.cancelAnimationFrame(raf);\n    };\n  }, [seed, flashToken, delayMs, mode, active, reduced]);\n\n  return <canvas ref={canvasRef} aria-hidden=\"true\" className={className} />;\n}\n\nexport function BackupCodes({\n  codes,\n  issuer = \"Hairline\",\n  account,\n  filename = \"recovery-codes.txt\",\n  defaultVeiled = true,\n  allowCopyIndividual = true,\n  onToggleUsed,\n  onRegenerate,\n  onDownload,\n  onPrint,\n  lowThreshold = 2,\n  title = \"Recovery codes\",\n  sound = false,\n  className = \"\",\n  ...props\n}: BackupCodesProps) {\n  const reduced = useInteractionReducedMotion();\n  const { ref: rootRef, active: onScreen } = useInteractionActivity<HTMLDivElement>();\n\n  const items: BackupCodeItem[] = React.useMemo(\n    () => codes.map((c) => (typeof c === \"string\" ? { code: c, used: false } : c)),\n    [codes],\n  );\n\n  const [allRevealed, setAllRevealed] = React.useState(!defaultVeiled);\n  const [peekedMap, setPeekedMap] = React.useState<Record<string, boolean>>({});\n  const [copiedCode, setCopiedCode] = React.useState<string | null>(null);\n  const [copiedAll, setCopiedAll] = React.useState(false);\n  const [downloaded, setDownloaded] = React.useState(false);\n  const [confirmRegen, setConfirmRegen] = React.useState(false);\n  const [regenerating, setRegenerating] = React.useState(false);\n  const [regeneratedBanner, setRegeneratedBanner] = React.useState(false);\n  const [flashSeq, setFlashSeq] = React.useState(0);\n  const [regenSeq, setRegenSeq] = React.useState(0);\n  const [liveStatus, setLiveStatus] = React.useState(\"\");\n\n  const copyAllTimerRef = React.useRef(0);\n  const copyOneTimerRef = React.useRef(0);\n  const downloadTimerRef = React.useRef(0);\n  const regenBannerTimerRef = React.useRef(0);\n\n  React.useEffect(\n    () => () => {\n      window.clearTimeout(copyAllTimerRef.current);\n      window.clearTimeout(copyOneTimerRef.current);\n      window.clearTimeout(downloadTimerRef.current);\n      window.clearTimeout(regenBannerTimerRef.current);\n    },\n    [],\n  );\n\n  const unusedItems = React.useMemo(() => items.filter((i) => !i.used), [items]);\n  const isLow = unusedItems.length <= lowThreshold;\n\n  const isRowRevealed = (item: BackupCodeItem) => Boolean(item.used || allRevealed || peekedMap[item.code]);\n\n  const handleToggleRevealAll = () => {\n    const next = !allRevealed;\n    setAllRevealed(next);\n    if (!next) setPeekedMap({});\n    if (sound) playSound(next ? \"unfold\" : \"fold\", 0.3);\n    setLiveStatus(next ? \"All recovery codes revealed\" : \"Recovery codes veiled\");\n  };\n\n  const handleCopyAll = async () => {\n    const text = unusedItems.map((i) => i.code).join(\"\\n\");\n    if (!text) return;\n    try {\n      await navigator.clipboard?.writeText(text);\n    } catch {}\n    setCopiedAll(true);\n    setFlashSeq((n) => n + 1);\n    if (sound) playSound(\"success\", 0.36);\n    setLiveStatus(`Copied ${unusedItems.length} unused recovery codes`);\n    window.clearTimeout(copyAllTimerRef.current);\n    copyAllTimerRef.current = window.setTimeout(() => setCopiedAll(false), 1800);\n  };\n\n  const handleCopySingle = async (code: string) => {\n    if (!allowCopyIndividual) return;\n    try {\n      await navigator.clipboard?.writeText(code);\n    } catch {}\n    setCopiedCode(code);\n    if (sound) playSound(\"tick\", 0.3);\n    setLiveStatus(`Copied recovery code ${code}`);\n    window.clearTimeout(copyOneTimerRef.current);\n    copyOneTimerRef.current = window.setTimeout(() => setCopiedCode(null), 1500);\n  };\n\n  const handleDownload = () => {\n    const content = formatBackupCodesFile(items, { issuer, account });\n    if (onDownload) {\n      onDownload(content);\n    } else {\n      const blob = new Blob([content], { type: \"text/plain;charset=utf-8\" });\n      const url = URL.createObjectURL(blob);\n      const a = document.createElement(\"a\");\n      a.href = url;\n      a.download = filename;\n      document.body.appendChild(a);\n      a.click();\n      a.remove();\n      window.setTimeout(() => URL.revokeObjectURL(url), 1000);\n    }\n    setDownloaded(true);\n    setFlashSeq((n) => n + 1);\n    if (sound) playSound(\"success\", 0.34);\n    setLiveStatus(`Downloaded ${filename}`);\n    window.clearTimeout(downloadTimerRef.current);\n    downloadTimerRef.current = window.setTimeout(() => setDownloaded(false), 1800);\n  };\n\n  const handlePrint = () => {\n    if (onPrint) {\n      onPrint();\n      return;\n    }\n    const content = formatBackupCodesFile(items, { issuer, account });\n    const win = window.open(\"\", \"_blank\", \"width=560,height=640\");\n    if (!win) {\n      window.print();\n      return;\n    }\n    win.document.write(\n      `<!doctype html><html><head><title>${issuer} Recovery Codes</title><style>body{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;padding:32px;line-height:1.6;color:#111}pre{white-space:pre-wrap;font-size:13px}</style></head><body><pre>${content.replace(/</g, \"&lt;\")}</pre></body></html>`,\n    );\n    win.document.close();\n    win.focus();\n    win.print();\n  };\n\n  const handleConfirmRegenerate = async () => {\n    if (!onRegenerate) return;\n    setRegenerating(true);\n    try {\n      await onRegenerate();\n      setConfirmRegen(false);\n      setPeekedMap({});\n      setRegeneratedBanner(true);\n      // Fire BOTH veil sweep & revealed burst curtain after the new codes commit to DOM\n      window.requestAnimationFrame(() => {\n        setFlashSeq((n) => n + 1);\n        setRegenSeq((n) => n + 1);\n      });\n      if (sound) playSound(\"success\", 0.4);\n      setLiveStatus(\"Generated fresh recovery codes\");\n      window.clearTimeout(regenBannerTimerRef.current);\n      regenBannerTimerRef.current = window.setTimeout(() => setRegeneratedBanner(false), 2600);\n    } finally {\n      setRegenerating(false);\n    }\n  };\n\n  const lowMessage =\n    unusedItems.length === 0\n      ? \"All recovery codes have been used. Regenerate a new set right away.\"\n      : `Only ${unusedItems.length} recovery code${unusedItems.length === 1 ? \"\" : \"s\"} left. Consider regenerating soon.`;\n\n  return (\n    <div\n      ref={rootRef}\n      role=\"region\"\n      aria-label={title}\n      data-veiled={!allRevealed ? \"true\" : \"false\"}\n      data-unused={unusedItems.length}\n      data-regenerating={regenerating ? \"true\" : \"false\"}\n      className={`@container flex w-full max-w-[480px] flex-col overflow-hidden rounded-[16px] border border-border bg-card text-card-foreground shadow-[inset_0_0.5px_0_rgb(255_255_255/0.75)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.06)] ${className}`}\n      {...props}\n    >\n      {/* Hairline header */}\n      <div className=\"flex flex-wrap items-center justify-between gap-2 border-b border-border/80 bg-muted/20 px-4 py-3\">\n        <div className=\"flex flex-wrap items-center gap-2\">\n          <ShieldCheck className=\"size-4 text-muted-foreground\" strokeWidth={1.9} />\n          <div className=\"flex items-center gap-2\">\n            <span className=\"text-[13px] font-medium tracking-[-0.01em] text-foreground\">{title}</span>\n            <span\n              className={`inline-flex items-center gap-1 font-mono text-[11px] tabular-nums transition-colors ${\n                isLow ? \"font-medium text-amber-600 dark:text-amber-400\" : \"text-muted-foreground\"\n              }`}\n            >\n              <NumberRoll value={unusedItems.length} />\n              <span>of</span>\n              <NumberRoll value={items.length} />\n              <span>unused</span>\n            </span>\n          </div>\n          <span\n            aria-hidden={!regeneratedBanner || undefined}\n            className=\"grid\"\n            style={{\n              gridTemplateColumns: regeneratedBanner ? \"1fr\" : \"0fr\",\n              opacity: regeneratedBanner ? 1 : 0,\n              transition: reduced ? \"none\" : `grid-template-columns 340ms ${EASE_OUT}, opacity 220ms ${EASE_OUT}`,\n            }}\n          >\n            <span className=\"min-w-0 overflow-hidden\">\n              <span className=\"inline-flex w-max items-center gap-1 whitespace-nowrap rounded-full border border-emerald-500/30 bg-emerald-500/10 px-2 py-0.5 text-[10.5px] font-medium text-emerald-700 dark:text-emerald-300\">\n                <Check className=\"size-2.5\" strokeWidth={2.5} />\n                New codes issued\n              </span>\n            </span>\n          </span>\n        </div>\n\n        <button\n          type=\"button\"\n          onClick={handleToggleRevealAll}\n          className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n        >\n          <span className=\"relative flex size-3.5 shrink-0 items-center justify-center\">\n            <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!allRevealed, reduced)}>\n              <Eye className=\"size-3.5\" strokeWidth={1.9} />\n            </span>\n            <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(allRevealed, reduced)}>\n              <EyeOff className=\"size-3.5\" strokeWidth={1.9} />\n            </span>\n          </span>\n          <TextMorph>{allRevealed ? \"Hide codes\" : \"Reveal codes\"}</TextMorph>\n        </button>\n      </div>\n\n      {/* Low remaining warning banner (smooth grid-template-rows fold!) */}\n      <div\n        aria-hidden={!isLow || undefined}\n        className={`grid ${!isLow ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          gridTemplateRows: isLow ? \"1fr\" : \"0fr\",\n          opacity: isLow ? 1 : 0,\n          transition: reduced ? \"none\" : `grid-template-rows 360ms ${EASE_OUT}, opacity 240ms ${EASE_OUT}`,\n        }}\n      >\n        <div className=\"min-h-0 overflow-clip\">\n          <div\n            role=\"status\"\n            className=\"flex items-center gap-2 border-b border-amber-500/25 bg-amber-500/[0.08] px-4 py-2 text-[11.5px] text-amber-800 dark:text-amber-200\"\n          >\n            <AlertTriangle className=\"size-3.5 shrink-0 text-amber-600 dark:text-amber-400\" strokeWidth={2} />\n            <TextMorph animateWidth={false}>{lowMessage}</TextMorph>\n          </div>\n        </div>\n      </div>\n\n      {/* 2-column hairline code grid (keyed stably by index so Bayer canvases animate cleanly across regenerations!) */}\n      <div className=\"grid grid-cols-1 gap-2 p-3.5 @[420px]:grid-cols-2\">\n        {items.map((item, idx) => {\n          const revealed = isRowRevealed(item);\n          const isCopied = copiedCode === item.code;\n\n          if (item.used) {\n            return (\n              <div\n                key={idx}\n                data-code-slot={idx}\n                data-used=\"true\"\n                className=\"relative flex h-10 items-center justify-between gap-2 overflow-hidden rounded-[10px] border border-border/60 bg-muted/25 px-3 text-muted-foreground/65\"\n              >\n                <div className=\"flex min-w-0 items-center gap-2\">\n                  <span className=\"font-mono text-[10px] tabular-nums opacity-60\">{String(idx + 1).padStart(2, \"0\")}</span>\n                  <span className=\"truncate font-mono text-[13px] tracking-[0.04em] line-through\">{item.code}</span>\n                </div>\n                {onToggleUsed ? (\n                  <button\n                    type=\"button\"\n                    aria-label={`Restore code ${idx + 1}`}\n                    onClick={() => onToggleUsed(item.code, false)}\n                    className={`shrink-0 cursor-pointer rounded-[5px] border border-border/70 bg-background px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground hover:text-foreground ${INTERACTION_FOCUS}`}\n                  >\n                    Used\n                  </button>\n                ) : (\n                  <span className=\"shrink-0 rounded-[5px] border border-border/70 px-1.5 py-0.5 text-[10px] font-medium\">\n                    {item.usedAt ?? \"Used\"}\n                  </span>\n                )}\n              </div>\n            );\n          }\n\n          if (!revealed) {\n            return (\n              <button\n                key={idx}\n                type=\"button\"\n                data-code-slot={idx}\n                data-veiled=\"true\"\n                aria-label={`Reveal recovery code ${idx + 1}`}\n                onClick={() => {\n                  setPeekedMap((prev) => ({ ...prev, [item.code]: true }));\n                  if (sound) playSound(\"unfold\", 0.25);\n                }}\n                className={`group flex h-10 w-full cursor-pointer items-center gap-2 rounded-[10px] border border-border/85 bg-background px-2.5 text-left transition-colors hover:border-foreground/25 ${INTERACTION_FOCUS}`}\n              >\n                <span className=\"shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/65\">\n                  {String(idx + 1).padStart(2, \"0\")}\n                </span>\n                <div className=\"min-w-0 flex-1\">\n                  <BayerCodeVeil\n                    seed={idx + 1}\n                    flashToken={flashSeq}\n                    delayMs={idx * 28}\n                    mode=\"veil\"\n                    active={onScreen}\n                    reduced={reduced}\n                  />\n                </div>\n              </button>\n            );\n          }\n\n          return (\n            <div\n              key={idx}\n              data-code-slot={idx}\n              data-veiled=\"false\"\n              className=\"group relative flex h-10 items-center justify-between gap-1.5 overflow-hidden rounded-[10px] border border-border/85 bg-background px-2.5 transition-colors hover:border-foreground/20\"\n            >\n              {/* Staggered 8×8 Bayer materialise curtain when fresh codes are regenerated while revealed */}\n              <BayerCodeVeil\n                seed={idx + 1}\n                flashToken={regenSeq}\n                delayMs={idx * 34}\n                mode=\"burst\"\n                active={onScreen}\n                reduced={reduced}\n                className=\"pointer-events-none absolute inset-1 z-20 h-[calc(100%_-_8px)] w-[calc(100%_-_8px)] rounded-[6px] [image-rendering:pixelated]\"\n              />\n\n              <button\n                type=\"button\"\n                disabled={!allowCopyIndividual}\n                aria-label={isCopied ? `Copied recovery code ${idx + 1}` : `Copy recovery code ${idx + 1}`}\n                onClick={() => void handleCopySingle(item.code)}\n                className={`relative z-10 flex min-w-0 flex-1 cursor-pointer items-center gap-2 text-left disabled:cursor-default ${INTERACTION_FOCUS}`}\n              >\n                <span className=\"shrink-0 font-mono text-[10px] tabular-nums text-muted-foreground/65\">\n                  {String(idx + 1).padStart(2, \"0\")}\n                </span>\n                <span className=\"truncate font-mono text-[13px] font-medium tracking-[0.04em] text-foreground\">\n                  <TextMorph duration={420}>{item.code}</TextMorph>\n                </span>\n              </button>\n\n              <div className=\"relative z-10 flex shrink-0 items-center gap-1\">\n                {onToggleUsed && (\n                  <button\n                    type=\"button\"\n                    aria-label={`Mark code ${idx + 1} as used`}\n                    title=\"Mark as used\"\n                    onClick={() => onToggleUsed(item.code, true)}\n                    className={`cursor-pointer rounded-[5px] px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground/75 opacity-0 transition-opacity hover:bg-accent hover:text-foreground focus-visible:opacity-100 group-hover:opacity-100 ${INTERACTION_FOCUS}`}\n                  >\n                    Use\n                  </button>\n                )}\n                {allowCopyIndividual && (\n                  <button\n                    type=\"button\"\n                    aria-label={isCopied ? `Copied ${item.code}` : `Copy ${item.code}`}\n                    onClick={() => void handleCopySingle(item.code)}\n                    className={`relative flex size-6 cursor-pointer items-center justify-center rounded-[6px] hover:bg-accent ${\n                      isCopied ? \"text-emerald-600 dark:text-emerald-400\" : \"text-muted-foreground/70 hover:text-foreground\"\n                    } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n                  >\n                    <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!isCopied, reduced)}>\n                      <Copy className=\"size-3\" strokeWidth={2} />\n                    </span>\n                    <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(isCopied, reduced)}>\n                      <Check className=\"size-3\" strokeWidth={2.4} />\n                    </span>\n                  </button>\n                )}\n              </div>\n            </div>\n          );\n        })}\n      </div>\n\n      {/* Hairline action bar OR inline two-step regenerate confirmation */}\n      <div className=\"border-t border-border/80 bg-muted/15 px-3.5 py-2.5\">\n        {confirmRegen ? (\n          <div className=\"flex flex-wrap items-center justify-between gap-2\" data-confirm-regenerate=\"true\">\n            <span className=\"text-[12px] text-foreground\">Invalidate old codes and issue {items.length} new ones?</span>\n            <div className=\"flex items-center gap-1.5\">\n              <button\n                type=\"button\"\n                disabled={regenerating}\n                onClick={() => setConfirmRegen(false)}\n                className={`inline-flex h-7 cursor-pointer items-center rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                Cancel\n              </button>\n              <button\n                type=\"button\"\n                disabled={regenerating}\n                onClick={() => void handleConfirmRegenerate()}\n                className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] bg-primary px-2.5 text-[11.5px] font-medium text-primary-foreground hover:opacity-90 disabled:opacity-60 ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                {regenerating && <Loader2 className=\"size-3 animate-spin\" strokeWidth={2.2} />}\n                <TextMorph>{regenerating ? \"Regenerating…\" : \"Confirm\"}</TextMorph>\n              </button>\n            </div>\n          </div>\n        ) : (\n          <div className=\"flex flex-wrap items-center justify-between gap-2\">\n            <div className=\"flex flex-wrap items-center gap-1.5\">\n              <button\n                type=\"button\"\n                disabled={unusedItems.length === 0}\n                onClick={() => void handleCopyAll()}\n                className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium hover:bg-accent disabled:opacity-40 ${\n                  copiedAll ? \"border-emerald-500/40 text-emerald-700 dark:text-emerald-300\" : \"text-foreground\"\n                } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <span className=\"relative flex size-3.5 shrink-0 items-center justify-center\">\n                  <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!copiedAll, reduced)}>\n                    <Copy className=\"size-3.5 text-muted-foreground\" strokeWidth={1.9} />\n                  </span>\n                  <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(copiedAll, reduced)}>\n                    <Check className=\"size-3.5\" strokeWidth={2.3} />\n                  </span>\n                </span>\n                <TextMorph>{copiedAll ? \"Copied\" : \"Copy all\"}</TextMorph>\n              </button>\n\n              <button\n                type=\"button\"\n                onClick={handleDownload}\n                className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2.5 text-[11.5px] font-medium hover:bg-accent ${\n                  downloaded ? \"border-emerald-500/40 text-emerald-700 dark:text-emerald-300\" : \"text-foreground\"\n                } ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <span className=\"relative flex size-3.5 shrink-0 items-center justify-center\">\n                  <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(!downloaded, reduced)}>\n                    <Download className=\"size-3.5 text-muted-foreground\" strokeWidth={1.9} />\n                  </span>\n                  <span aria-hidden=\"true\" className=\"absolute inset-0 flex items-center justify-center\" style={interactionIcon(downloaded, reduced)}>\n                    <Check className=\"size-3.5\" strokeWidth={2.3} />\n                  </span>\n                </span>\n                <TextMorph>{downloaded ? \"Saved .txt\" : \"Download .txt\"}</TextMorph>\n              </button>\n\n              <button\n                type=\"button\"\n                onClick={handlePrint}\n                className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] border border-border bg-background px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <Printer className=\"size-3.5\" strokeWidth={1.9} />\n                Print\n              </button>\n            </div>\n\n            {onRegenerate && (\n              <button\n                type=\"button\"\n                onClick={() => {\n                  setConfirmRegen(true);\n                  if (sound) playSound(\"tick\", 0.25);\n                }}\n                className={`inline-flex h-7 cursor-pointer items-center gap-1.5 rounded-[8px] px-2 text-[11.5px] font-medium text-muted-foreground hover:bg-accent hover:text-foreground ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n              >\n                <RefreshCw className=\"size-3\" strokeWidth={2} />\n                Regenerate\n              </button>\n            )}\n          </div>\n        )}\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {liveStatus}\n      </span>\n    </div>\n  );\n}\n\nexport default BackupCodes;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · backup-codes · 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 · backup-codes · 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/backup-codes. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}