{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"passkey-button","type":"registry:component","title":"Passkey button","description":"A biometric passkey button whose 9-ridge fingerprint scans optically ridge by ridge while pending, then sweeps an 8×8 Bayer wave across the pill as the ridges draw into a check.","author":"Hairline UI","dependencies":[],"registryDependencies":["https://hairlineui.com/r/text-morph.json?as=dependency"],"files":[{"path":"registry/passkey-button.tsx","type":"registry:component","content":"// Hairline UI · passkey-button · MIT License\n// Copyright (c) 2026 Hairline UI · https://hairlineui.com/license#components\n\n\"use client\";\n\nimport * as React from \"react\";\nimport { TextMorph } from \"./text-morph\";\nimport {\n  EASE_OUT,\n  INTERACTION_FOCUS,\n  INTERACTION_PRESS,\n  createSpring,\n  useInteractionActivity,\n  useInteractionReducedMotion,\n} from \"./ui-interaction-motion\";\nimport { playSound } from \"./ui-sounds\";\n\n/* ─────────────────────────────────────────────────────────\n * PASSKEY BUTTON: biometric auth with optical ridge scan & 8×8 Bayer sweep\n *\n *   idle       quiet hairline pill with a 9-ridge biometric fingerprint\n *              inside a recessed sensor well; hovering gently wakes the\n *              ridges in ink\n *   scanning   while onVerify() is pending, a laser scanline sweeps\n *              vertically through the 9 ridges illuminating each ridge\n *              and minutiae junction in turn, while a cool 8×8 Bayer\n *              optical band glides across the button surface\n *   verified   the 9 ridges spring-compress inward and collapse along\n *              their strokes directly into a self-drawing emerald check\n *              as a celebratory 8×8 Bayer wavefront sweeps left-to-right\n *              across the pill and dissolves cleanly to 0% CPU rest\n *   error      a taut crimson Bayer recoil snaps back into the sensor\n *              well, the button gives a damped shake, the label morphs\n *              to \"Try again\" and any reason folds cleanly underneath\n *\n * Drop-in Promise<unknown> contract for WebAuthn / Better Auth / Clerk.\n * Zero animation libraries, light & dark adaptive, reduced-motion safe.\n * ───────────────────────────────────────────────────────── */\n\nexport type PasskeyStatus = \"idle\" | \"scanning\" | \"verified\" | \"error\";\nexport type PasskeyVariant = \"surface\" | \"primary\" | \"outline\";\nexport type PasskeySize = \"default\" | \"lg\";\n\nexport interface PasskeyButtonProps extends Omit<React.ButtonHTMLAttributes<HTMLButtonElement>, \"children\" | \"onError\"> {\n  /** Async WebAuthn / passkey handler. Resolve to verify; throw an Error to show the error state and message. */\n  onVerify?: () => void | Promise<unknown>;\n  /** Controlled status. Omit to let the button manage idle → scanning → verified / error from onVerify. */\n  status?: PasskeyStatus;\n  onStatusChange?: (status: PasskeyStatus) => void;\n  /** Label overrides per state. */\n  labels?: Partial<Record<PasskeyStatus, string>>;\n  /** Optional inline error message shown beneath the button when status is \"error\". */\n  errorMessage?: React.ReactNode;\n  /** Visual surface: \"surface\" (card hairline, default), \"primary\" (brand action), or \"outline\". */\n  variant?: PasskeyVariant;\n  /** \"default\" (48px) or \"lg\" (54px hero auth button). */\n  size?: PasskeySize;\n  /** Stretch to fill its container (e.g. a sign-in card). */\n  fullWidth?: boolean;\n  /** Optional ms after verified to return automatically to idle (0 disables auto-reset). */\n  resetAfter?: number;\n  /** Called when resetting from verified back to idle. */\n  onReset?: () => void;\n  /** Opt-in quiet Web Audio cues (tick on press, success chime, error low tone). */\n  sound?: boolean;\n}\n\nconst DEFAULT_LABELS: Record<PasskeyStatus, string> = {\n  idle: \"Sign in with passkey\",\n  scanning: \"Verifying passkey\",\n  verified: \"Verified\",\n  error: \"Try again\",\n};\n\n// 9 concentric biometric fingerprint ridges sorted top-to-bottom for optical scanline illumination.\nconst RIDGES: readonly { d: string; yNorm: number; delay: number }[] = [\n  { d: \"M6.4 8.9 A7.1 7.1 0 0 1 17.6 8.9\", yNorm: 0.22, delay: 0 },\n  { d: \"M4.9 12.1 A7.3 7.3 0 0 1 19.1 11.7\", yNorm: 0.34, delay: 20 },\n  { d: \"M6.5 15.6 C5.8 11.2 8.2 7.7 12 7.7 C15.8 7.7 18.2 11.2 17.4 15.4\", yNorm: 0.46, delay: 40 },\n  { d: \"M8.1 17.5 C7.5 13.7 8.9 10.1 12 10.1 C15.1 10.1 16.3 13.3 15.7 16.6\", yNorm: 0.56, delay: 60 },\n  { d: \"M10.1 18.9 C9.6 15.7 10.1 12.4 12 12.4 C13.9 12.4 14.3 15.2 13.9 17.7\", yNorm: 0.65, delay: 80 },\n  { d: \"M12 14.5 C12 16.4 11.8 18.2 11.1 19.7\", yNorm: 0.72, delay: 100 },\n  { d: \"M5.1 16.0 C4.8 14.8 4.8 13.7 4.9 12.8\", yNorm: 0.6, delay: 70 },\n  { d: \"M18.6 14.8 C18.2 16.6 17.4 18.1 16.3 19.2\", yNorm: 0.73, delay: 95 },\n  { d: \"M6.7 18.4 C7.4 19.1 8.2 19.6 9.1 20.0\", yNorm: 0.81, delay: 110 },\n];\n\n// Four minutiae junction points that briefly lock-glint as the optical scanline passes over them.\nconst MINUTIAE: readonly { cx: number; cy: number; yNorm: number }[] = [\n  { cx: 12, cy: 5.8, yNorm: 0.24 },\n  { cx: 7.4, cy: 10.4, yNorm: 0.43 },\n  { cx: 16.5, cy: 11.2, yNorm: 0.47 },\n  { cx: 12, cy: 14.5, yNorm: 0.61 },\n];\n\n// Recursive 8×8 ordered Bayer threshold matrix (64 tonal steps for crisp optical pill sweeps).\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\ntype Rgb = [number, number, number];\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 lerp = (a: number, b: number, t: number) => a + (b - a) * t;\n\nlet swatchCtx: CanvasRenderingContext2D | null = null;\nfunction cssToRgb(host: Element, cssColor: string, fallback: Rgb): Rgb {\n  const probe = document.createElement(\"span\");\n  probe.style.display = \"none\";\n  probe.style.color = cssColor;\n  host.appendChild(probe);\n  const resolved = getComputedStyle(probe).color;\n  probe.remove();\n  if (/^rgba?\\(/.test(resolved)) {\n    const m = resolved.match(/[\\d.]+/g)?.map(Number);\n    if (m && m.length >= 3) return [m[0], m[1], m[2]];\n  }\n  if (!swatchCtx) {\n    const c = document.createElement(\"canvas\");\n    c.width = 1;\n    c.height = 1;\n    swatchCtx = c.getContext(\"2d\", { willReadFrequently: true });\n  }\n  if (swatchCtx) {\n    swatchCtx.clearRect(0, 0, 1, 1);\n    swatchCtx.fillStyle = \"#808080\";\n    swatchCtx.fillStyle = resolved;\n    swatchCtx.fillRect(0, 0, 1, 1);\n    const d = swatchCtx.getImageData(0, 0, 1, 1).data;\n    return [d[0], d[1], d[2]];\n  }\n  return fallback;\n}\n\nfunction isLightButton(el: Element | null): boolean {\n  if (!el) return false;\n  const rgb = cssToRgb(el, getComputedStyle(el).color, [240, 240, 240]);\n  return (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255 < 0.52;\n}\n\n/**\n * Full-pill 8×8 Bayer optical sweep + synchronized ridge scanline driver.\n * Writes directly to DOM refs & offscreen Uint32Array buffer (0 React renders per frame, sleeps at 0% CPU when quiet).\n */\ninterface BiometricEngineProps {\n  status: PasskeyStatus;\n  variant: PasskeyVariant;\n  onScreen: boolean;\n  reduced: boolean;\n  canvasRef: React.RefObject<HTMLCanvasElement | null>;\n  scanBeamRef: React.RefObject<SVGGElement | null>;\n  ridgeRefs: React.RefObject<(SVGPathElement | null)[]>;\n  dotRefs: React.RefObject<(SVGCircleElement | null)[]>;\n}\n\nfunction useBiometricEngine({\n  status,\n  variant,\n  onScreen,\n  reduced,\n  canvasRef,\n  scanBeamRef,\n  ridgeRefs,\n  dotRefs,\n}: BiometricEngineProps) {\n  const statusRef = React.useRef(status);\n  const variantRef = React.useRef(variant);\n  React.useLayoutEffect(() => {\n    statusRef.current = status;\n    variantRef.current = variant;\n  });\n\n  const engineRef = React.useRef<{\n    w: number;\n    h: number;\n    dpr: number;\n    isLight: boolean;\n    primary: Rgb;\n    time: number;\n    scanWeight: ReturnType<typeof createSpring>;\n    burstKind: \"none\" | \"verify\" | \"error\";\n    burstAge: number;\n    burstLife: number;\n    lastStatus: PasskeyStatus;\n    refreshTheme: () => void;\n    onStatusChange: (prev: PasskeyStatus, next: PasskeyStatus) => void;\n    stepAndDraw: (dt: number) => boolean;\n    wake: () => void;\n  } | null>(null);\n\n  const rafRef = React.useRef(0);\n  const runningRef = React.useRef(false);\n  const wakeRef = React.useRef<() => void>(() => {});\n\n  React.useEffect(() => {\n    const canvas = canvasRef.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    let gridImg: ImageData | null = null;\n    let gridU32: Uint32Array | null = null;\n    let gCols = 0;\n    let gRows = 0;\n\n    const ensureGrid = (cols: number, rows: number) => {\n      if (cols === gCols && rows === gRows && gridImg && gridU32) return;\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\n    const quiet = () => {};\n    const initScan = statusRef.current === \"scanning\" ? 1 : 0;\n    const scanWeight = createSpring(initScan, { stiffness: 170, damping: 22 }, quiet, 0.002);\n    const lastRidgeOp = new Float32Array(RIDGES.length).fill(-1);\n    const lastDotOp = new Float32Array(MINUTIAE.length).fill(-1);\n    let lastBeamOp = -1;\n\n    const eng: NonNullable<typeof engineRef.current> = {\n      w: 0,\n      h: 0,\n      dpr: Math.min(2, window.devicePixelRatio || 1),\n      isLight: false,\n      primary: [48, 93, 222],\n      time: 0,\n      scanWeight,\n      burstKind: \"none\",\n      burstAge: 0,\n      burstLife: 0.6,\n      lastStatus: statusRef.current,\n\n      refreshTheme() {\n        const btn = canvas.parentElement;\n        eng.isLight = isLightButton(btn);\n        if (btn) {\n          eng.primary = cssToRgb(btn, \"var(--primary)\", [48, 93, 222]);\n        }\n      },\n\n      onStatusChange(prev, next) {\n        if (next === \"verified\" && prev !== \"verified\") {\n          eng.burstKind = \"verify\";\n          eng.burstAge = 0;\n          eng.burstLife = 0.64;\n        } else if (next === \"error\" && prev !== \"error\") {\n          eng.burstKind = \"error\";\n          eng.burstAge = 0;\n          eng.burstLife = 0.42;\n        } else if (next === \"scanning\") {\n          eng.burstKind = \"none\";\n          eng.time = 0;\n        }\n      },\n\n      stepAndDraw(dt: number): boolean {\n        const w = eng.w;\n        const h = eng.h;\n        if (w <= 0 || h <= 0) return false;\n\n        const cur = statusRef.current;\n        const isPrimary = variantRef.current === \"primary\";\n        const sw = clamp01(eng.scanWeight.get());\n        eng.time += dt;\n\n        if (eng.burstKind !== \"none\") {\n          eng.burstAge += dt;\n          if (eng.burstAge >= eng.burstLife) {\n            eng.burstKind = \"none\";\n          }\n        }\n\n        // 1) Synchronized optical ridge illumination inside the 24×24 fingerprint sensor well\n        // Single transform on the scan beam group + dirty-checked ridge opacity avoids unnecessary SVG invalidation at 4× CPU.\n        const scanY = 0.52 - 0.36 * Math.cos(eng.time * 4.5);\n        const beamEl = scanBeamRef.current;\n        if (beamEl) {\n          const beamOp = sw > 0.02 ? sw : 0;\n          if (beamOp > 0) {\n            beamEl.style.transform = `translate3d(0, ${(scanY * 24 - 12).toFixed(2)}px, 0)`;\n          }\n          if (Math.abs(beamOp - lastBeamOp) > 0.02) {\n            lastBeamOp = beamOp;\n            beamEl.style.opacity = beamOp.toFixed(2);\n          }\n        }\n\n        const ridges = ridgeRefs.current;\n        if (ridges) {\n          for (let i = 0; i < RIDGES.length; i++) {\n            const path = ridges[i];\n            if (!path) continue;\n            const nextOp = sw > 0.02 ? 0.14 + 0.86 * Math.exp(-((RIDGES[i].yNorm - scanY) ** 2) / 0.024) * sw : 0;\n            if (Math.abs(nextOp - lastRidgeOp[i]) > 0.03) {\n              lastRidgeOp[i] = nextOp;\n              path.style.opacity = nextOp.toFixed(2);\n            }\n          }\n        }\n        const dots = dotRefs.current;\n        if (dots) {\n          for (let i = 0; i < MINUTIAE.length; i++) {\n            const dot = dots[i];\n            if (!dot) continue;\n            const nextOp = sw > 0.02 ? Math.exp(-((MINUTIAE[i].yNorm - scanY) ** 2) / 0.014) * sw : 0;\n            if (Math.abs(nextOp - lastDotOp[i]) > 0.04) {\n              lastDotOp[i] = nextOp;\n              dot.style.opacity = nextOp.toFixed(2);\n            }\n          }\n        }\n\n        // 2) Full-pill 8×8 ordered Bayer optical sweep canvas\n        ctx.setTransform(eng.dpr, 0, 0, eng.dpr, 0, 0);\n        ctx.clearRect(0, 0, w, h);\n\n        const activeBurst = eng.burstKind !== \"none\";\n        if (sw > 0.008 || activeBurst) {\n          const pitch = 2;\n          const cols = Math.max(1, Math.ceil(w / pitch));\n          const rows = Math.max(1, Math.ceil(h / pitch));\n          ensureGrid(cols, rows);\n          const u32 = gridU32!;\n          u32.fill(0);\n\n          // Colors calibrated for dark surface, light surface, and primary brand button\n          const scanRgbA: Rgb = isPrimary\n            ? [186, 230, 253]\n            : eng.isLight\n              ? eng.primary\n              : [56, 189, 248];\n          const scanRgbB: Rgb = isPrimary\n            ? [255, 255, 255]\n            : eng.isLight\n              ? [14, 165, 233]\n              : [129, 140, 248];\n          const verifyRgb: Rgb = isPrimary\n            ? [167, 243, 208]\n            : eng.isLight\n              ? [5, 150, 105]\n              : [52, 211, 153];\n          const verifyHot: Rgb = isPrimary ? [255, 255, 255] : eng.isLight ? [16, 185, 129] : [209, 250, 229];\n          const errRgb: Rgb = isPrimary ? [254, 202, 202] : eng.isLight ? [220, 38, 38] : [248, 113, 113];\n\n          // Scanning horizontal glider sweeps gently out from the sensor well on the left (u ≈ 0.12)\n          const scanU = 0.08 + ((eng.time * 0.72) % 1.24) - 0.1;\n          const bk = activeBurst ? eng.burstAge / eng.burstLife : 0;\n          // Verify wavefront launches out of the sensor well (u = 0.1) across the entire pill left -> right\n          const verifyFront = 0.06 + (1 - Math.pow(1 - bk, 2.3)) * 1.12;\n          const verifyFade = Math.sin(Math.PI * Math.pow(bk, 0.72));\n          // Error recoil snaps sharply back toward the sensor well\n          const errFront = 0.65 * Math.pow(1 - bk, 1.8);\n          const errFade = Math.sin(Math.PI * Math.pow(bk, 0.6));\n\n          for (let r = 0; r < rows; r++) {\n            const v = (r + 0.5) / rows;\n            const vEdge = Math.sin(Math.PI * v);\n            const rowOff = r * cols;\n            const bRow = (r & 7) << 3;\n\n            for (let c = 0; c < cols; c++) {\n              const u = (c + 0.5) / cols;\n              const bayer = BAYER8[bRow | (c & 7)];\n\n              let energy = 0;\n              let cr = scanRgbA[0];\n              let cg = scanRgbA[1];\n              let cb = scanRgbA[2];\n              let maxAlpha = eng.isLight ? 0.24 : 0.34;\n\n              // Subtle optical scanning band emanating from the sensor well across the pill\n              if (sw > 0.008) {\n                const wellAura = Math.exp(-((u - 0.09) ** 2) / 0.022) * 0.52;\n                const dScan = u - scanU;\n                const band = Math.exp(-(dScan * dScan) / 0.026) * 0.72;\n                const wake = dScan < 0 ? Math.exp(dScan / 0.18) * 0.28 : 0;\n                const bottomRim = Math.pow(v, 3.2) * 0.42;\n                const scanE = (wellAura + (band + wake) * (0.45 + 0.55 * vEdge) + bottomRim * (0.4 + 0.6 * band)) * sw;\n                if (scanE > energy) {\n                  energy = scanE;\n                  const mixT = clamp01(band * 1.1);\n                  cr = lerp(scanRgbA[0], scanRgbB[0], mixT);\n                  cg = lerp(scanRgbA[1], scanRgbB[1], mixT);\n                  cb = lerp(scanRgbA[2], scanRgbB[2], mixT);\n                  maxAlpha = isPrimary ? 0.34 : eng.isLight ? 0.22 : 0.32;\n                }\n              }\n\n              // Celebratory emerald 8×8 Bayer verification wavefront sweeping cleanly across the entire pill!\n              if (eng.burstKind === \"verify\") {\n                const d = u - verifyFront;\n                const lead = Math.exp(-(d * d) / 0.014);\n                const tail = d < 0 ? Math.exp(d / 0.22) * 0.78 : 0;\n                const ve = (lead + tail) * verifyFade * (0.55 + 0.45 * vEdge);\n                if (ve > energy) {\n                  energy = ve;\n                  const hot = clamp01(lead * 0.9);\n                  cr = lerp(verifyRgb[0], verifyHot[0], hot);\n                  cg = lerp(verifyRgb[1], verifyHot[1], hot);\n                  cb = lerp(verifyRgb[2], verifyHot[2], hot);\n                  maxAlpha = isPrimary ? 0.44 : eng.isLight ? 0.3 : 0.46;\n                }\n              }\n\n              // Crimson recoil flash snapping back toward the sensor well on error\n              if (eng.burstKind === \"error\") {\n                const d = u - errFront;\n                const ee = Math.exp(-(d * d) / 0.045) * errFade * (0.5 + 0.5 * vEdge);\n                if (ee > energy) {\n                  energy = ee;\n                  cr = errRgb[0];\n                  cg = errRgb[1];\n                  cb = errRgb[2];\n                  maxAlpha = isPrimary ? 0.4 : eng.isLight ? 0.28 : 0.42;\n                }\n              }\n\n              if (energy <= 0.04) continue;\n              const hit = clamp01((energy - bayer + 0.04) / 0.09);\n              if (hit <= 0.02) continue;\n\n              u32[rowOff + c] = packRgba(cr, cg, cb, hit * maxAlpha * 255);\n            }\n          }\n\n          gridCtx.putImageData(gridImg!, 0, 0);\n          ctx.save();\n          ctx.imageSmoothingEnabled = false;\n          ctx.drawImage(gridCanvas, 0, 0, cols * pitch, rows * pitch);\n          ctx.restore();\n        }\n\n        // Sleep completely when idle/verified/error and every sweep has finished!\n        return cur === \"scanning\" || sw > 0.008 || eng.burstKind !== \"none\" || Math.abs(eng.scanWeight.getVelocity()) > 0.005;\n      },\n\n      wake() {\n        wakeRef.current();\n      },\n    };\n\n    engineRef.current = eng;\n\n    const resize = () => {\n      const rect = canvas.getBoundingClientRect();\n      const nw = Math.round(rect.width);\n      const nh = Math.round(rect.height);\n      if (nw <= 0 || nh <= 0) return;\n      const dpr = Math.min(2, window.devicePixelRatio || 1);\n      if (nw !== eng.w || nh !== eng.h || dpr !== eng.dpr) {\n        eng.w = nw;\n        eng.h = nh;\n        eng.dpr = dpr;\n        canvas.width = Math.round(nw * dpr);\n        canvas.height = Math.round(nh * dpr);\n      }\n      eng.refreshTheme();\n      eng.stepAndDraw(0);\n    };\n\n    resize();\n    const ro = new ResizeObserver(resize);\n    ro.observe(canvas);\n\n    const mo = new MutationObserver(() => {\n      eng.refreshTheme();\n      eng.stepAndDraw(0);\n    });\n    mo.observe(document.documentElement, { attributes: true, attributeFilter: [\"class\", \"style\", \"data-theme\"] });\n\n    return () => {\n      ro.disconnect();\n      mo.disconnect();\n      scanWeight.stop();\n      engineRef.current = null;\n    };\n  }, [canvasRef, scanBeamRef, ridgeRefs, dotRefs]);\n\n  React.useEffect(() => {\n    const eng = engineRef.current;\n    if (!eng) return;\n    const prev = eng.lastStatus;\n    eng.lastStatus = status;\n\n    if (reduced) {\n      eng.burstKind = \"none\";\n      eng.scanWeight.jump(status === \"scanning\" ? 1 : 0);\n      eng.time = 0.5;\n      eng.stepAndDraw(0);\n      return;\n    }\n\n    if (prev !== status) {\n      eng.onStatusChange(prev, status);\n    }\n    eng.scanWeight.set(status === \"scanning\" ? 1 : 0);\n    eng.wake();\n  }, [status, reduced]);\n\n  React.useEffect(() => {\n    if (!onScreen || reduced) {\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n      if (reduced) engineRef.current?.stepAndDraw(0);\n      return;\n    }\n\n    let last = 0;\n    const tick = (now: number) => {\n      const dt = last ? Math.min(1 / 24, (now - last) / 1000) : 1 / 60;\n      last = now;\n      const eng = engineRef.current;\n      if (!eng) {\n        rafRef.current = 0;\n        runningRef.current = false;\n        return;\n      }\n      if (eng.stepAndDraw(dt)) {\n        rafRef.current = requestAnimationFrame(tick);\n      } else {\n        rafRef.current = 0;\n        runningRef.current = false;\n      }\n    };\n\n    const start = () => {\n      if (runningRef.current) return;\n      runningRef.current = true;\n      last = 0;\n      rafRef.current = requestAnimationFrame(tick);\n    };\n    wakeRef.current = start;\n    start();\n\n    return () => {\n      wakeRef.current = () => {};\n      if (rafRef.current) {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = 0;\n      }\n      runningRef.current = false;\n    };\n  }, [onScreen, reduced]);\n}\n\nexport function PasskeyButton({\n  onVerify,\n  status: controlledStatus,\n  onStatusChange,\n  labels: labelOverrides,\n  errorMessage,\n  variant = \"surface\",\n  size = \"default\",\n  fullWidth = false,\n  resetAfter = 0,\n  onReset,\n  sound = false,\n  disabled = false,\n  className = \"\",\n  onClick,\n  ...props\n}: PasskeyButtonProps) {\n  const reduced = useInteractionReducedMotion();\n  const labels = React.useMemo(() => ({ ...DEFAULT_LABELS, ...labelOverrides }), [labelOverrides]);\n\n  const [ownStatus, setOwnStatus] = React.useState<PasskeyStatus>(\"idle\");\n  const [caughtError, setCaughtError] = React.useState<string | null>(null);\n  const [hovered, setHovered] = React.useState(false);\n\n  const status = controlledStatus ?? ownStatus;\n  const setStatus = React.useCallback(\n    (next: PasskeyStatus) => {\n      if (controlledStatus === undefined) setOwnStatus(next);\n      onStatusChange?.(next);\n    },\n    [controlledStatus, onStatusChange],\n  );\n\n  const { ref: buttonRef, active: onScreen } = useInteractionActivity<HTMLButtonElement>();\n  const canvasRef = React.useRef<HTMLCanvasElement>(null);\n  const scanBeamRef = React.useRef<SVGGElement>(null);\n  const ridgeRefs = React.useRef<(SVGPathElement | null)[]>([]);\n  const dotRefs = React.useRef<(SVGCircleElement | null)[]>([]);\n  const mountedRef = React.useRef(true);\n  const scanClipId = React.useId();\n\n  React.useEffect(() => {\n    mountedRef.current = true;\n    return () => {\n      mountedRef.current = false;\n    };\n  }, []);\n\n  useBiometricEngine({\n    status,\n    variant,\n    onScreen,\n    reduced,\n    canvasRef,\n    scanBeamRef,\n    ridgeRefs,\n    dotRefs,\n  });\n\n  // Damped tactile shake on error\n  React.useEffect(() => {\n    if (status !== \"error\" || reduced) return;\n    buttonRef.current?.animate(\n      [\n        { transform: \"none\" },\n        { transform: \"translateX(-4.5px)\" },\n        { transform: \"translateX(4px)\" },\n        { transform: \"translateX(-2px)\" },\n        { transform: \"translateX(1px)\" },\n        { transform: \"none\" },\n      ],\n      { duration: 360, easing: \"ease-out\" },\n    );\n  }, [status, reduced, buttonRef]);\n\n  // Optional auto-reset timer after verified\n  React.useEffect(() => {\n    if (status !== \"verified\" || resetAfter <= 0) return;\n    const timer = window.setTimeout(() => {\n      if (controlledStatus === undefined) setOwnStatus(\"idle\");\n      onReset?.();\n    }, resetAfter);\n    return () => window.clearTimeout(timer);\n  }, [status, resetAfter, controlledStatus, onReset]);\n\n  const scanning = status === \"scanning\";\n  const verified = status === \"verified\";\n  const isError = status === \"error\";\n  const displayError = isError ? (errorMessage ?? caughtError) : null;\n  const isPrimary = variant === \"primary\";\n  const isLg = size === \"lg\";\n\n  const handleClick = (event: React.MouseEvent<HTMLButtonElement>) => {\n    onClick?.(event);\n    if (event.defaultPrevented || disabled || scanning) return;\n    if (verified && !onReset && controlledStatus === undefined) {\n      // Allow re-verifying cleanly if already verified in uncontrolled mode\n      setStatus(\"idle\");\n      return;\n    }\n    if (!onVerify) return;\n    setCaughtError(null);\n    if (sound) playSound(\"tick\", 0.45);\n    const res = onVerify();\n    if (res && typeof (res as Promise<unknown>).then === \"function\") {\n      setStatus(\"scanning\");\n      void (res as Promise<unknown>).then(\n        () => {\n          if (!mountedRef.current) return;\n          setStatus(\"verified\");\n          if (sound) playSound(\"success\", 0.45);\n        },\n        (err: unknown) => {\n          if (!mountedRef.current) return;\n          setCaughtError(err instanceof Error && err.message ? err.message : \"Passkey verification was cancelled.\");\n          setStatus(\"error\");\n          if (sound) playSound(\"error\", 0.45);\n        },\n      );\n    } else {\n      setStatus(\"verified\");\n      if (sound) playSound(\"success\", 0.45);\n    }\n  };\n\n  const surfaceClasses = isPrimary\n    ? \"bg-primary text-primary-foreground border-transparent hover:bg-primary/92\"\n    : variant === \"outline\"\n      ? \"bg-background text-foreground border-border hover:bg-accent/60\"\n      : \"bg-card text-card-foreground border-border hover:bg-accent/45 shadow-[inset_0_0.5px_0_rgb(255_255_255/0.8)] dark:shadow-[inset_0_0.5px_0_rgb(255_255_255/0.07)]\";\n\n  const wellClasses = verified\n    ? isPrimary\n      ? \"bg-white/20 border-white/30 text-white\"\n      : \"bg-emerald-600 dark:bg-emerald-500 border-transparent text-white\"\n    : isError\n      ? isPrimary\n        ? \"bg-red-500/35 border-red-200/45 text-white\"\n        : \"bg-red-500/12 border-red-500/35 text-red-600 dark:text-red-400\"\n      : isPrimary\n        ? \"bg-white/14 border-white/20 text-primary-foreground\"\n        : \"bg-muted border-border text-foreground\";\n\n  return (\n    <div className={`inline-flex flex-col ${fullWidth ? \"w-full\" : \"w-fit max-w-full items-center\"} ${className}`}>\n      <button\n        ref={buttonRef}\n        type=\"button\"\n        data-status={status}\n        disabled={disabled}\n        aria-busy={scanning || undefined}\n        onClick={handleClick}\n        onPointerEnter={() => setHovered(true)}\n        onPointerLeave={() => setHovered(false)}\n        className={`group relative isolate inline-flex cursor-pointer items-center overflow-clip rounded-full border font-medium select-none disabled:cursor-default disabled:opacity-45 ${\n          isLg ? \"h-[54px] gap-3.5 pl-2.5 pr-6 text-[15px]\" : \"h-[46px] gap-3 pl-2 pr-5 text-[14px]\"\n        } ${fullWidth ? \"w-full justify-center\" : \"\"} ${surfaceClasses} ${INTERACTION_PRESS} ${INTERACTION_FOCUS}`}\n        {...props}\n      >\n        {/* Full-pill 8×8 optical Bayer scanning & emerald verification wavefront canvas */}\n        <canvas ref={canvasRef} aria-hidden=\"true\" className=\"pointer-events-none absolute inset-0 z-0 size-full\" />\n\n        {/* Recessed concentric biometric sensor well */}\n        <span\n          aria-hidden=\"true\"\n          className={`relative z-10 flex shrink-0 items-center justify-center overflow-hidden rounded-full border transition-[background-color,border-color,color] duration-300 ${\n            isLg ? \"size-9\" : \"size-8\"\n          } ${wellClasses}`}\n        >\n          {/* 9-ridge biometric fingerprint + optical scanline & minutiae lock points */}\n          <svg\n            viewBox=\"0 0 24 24\"\n            fill=\"none\"\n            className=\"absolute inset-0 m-auto size-[20px]\"\n            style={{\n              transform: verified ? \"scale(0.68)\" : scanning ? \"scale(1.03)\" : hovered ? \"scale(1.02)\" : \"scale(1)\",\n              opacity: verified ? 0 : 1,\n              transition: reduced ? \"none\" : `transform 340ms ${EASE_OUT}, opacity 240ms ${EASE_OUT}`,\n            }}\n          >\n            <defs>\n              <clipPath id={scanClipId}>\n                <circle cx=\"12\" cy=\"12\" r=\"9.5\" />\n              </clipPath>\n              <linearGradient id={`${scanClipId}-grad`} x1=\"0\" y1=\"0\" x2=\"0\" y2=\"1\">\n                <stop offset=\"0%\" stopColor=\"currentColor\" stopOpacity=\"0\" />\n                <stop offset=\"50%\" stopColor=\"currentColor\" stopOpacity=\"0.65\" />\n                <stop offset=\"100%\" stopColor=\"currentColor\" stopOpacity=\"0\" />\n              </linearGradient>\n            </defs>\n\n            {/* Base dormant ridges that wake softly on hover & collapse radially on verified */}\n            <g\n              stroke=\"currentColor\"\n              strokeWidth=\"1.4\"\n              strokeLinecap=\"round\"\n              style={{\n                opacity: isError ? 0.85 : scanning ? 0.24 : hovered ? 0.92 : 0.62,\n                transition: reduced ? \"none\" : `opacity 240ms ${EASE_OUT}`,\n              }}\n            >\n              {RIDGES.map((ridge) => (\n                <path\n                  key={ridge.d}\n                  d={ridge.d}\n                  pathLength={1}\n                  strokeDasharray={1}\n                  style={{\n                    strokeDashoffset: verified ? 1 : 0,\n                    transition: reduced ? \"none\" : `stroke-dashoffset 260ms ${EASE_OUT} ${verified ? ridge.delay * 0.4 : 0}ms`,\n                  }}\n                />\n              ))}\n            </g>\n\n            {/* Illuminated scan ridges (driven directly from the 60fps biometric rAF loop) */}\n            <g\n              stroke={isPrimary ? \"#ffffff\" : \"var(--primary)\"}\n              strokeWidth=\"1.65\"\n              strokeLinecap=\"round\"\n            >\n              {RIDGES.map((ridge, i) => (\n                <path\n                  key={`lit-${ridge.d}`}\n                  ref={(el) => {\n                    ridgeRefs.current[i] = el;\n                  }}\n                  d={ridge.d}\n                  style={{ opacity: 0 }}\n                />\n              ))}\n            </g>\n\n            {/* Precision minutiae junction lock dots */}\n            <g fill={isPrimary ? \"#e0f2fe\" : \"#0ea5e9\"}>\n              {MINUTIAE.map((pt, i) => (\n                <circle\n                  key={`${pt.cx}-${pt.cy}`}\n                  ref={(el) => {\n                    dotRefs.current[i] = el;\n                  }}\n                  cx={pt.cx}\n                  cy={pt.cy}\n                  r={1}\n                  style={{ opacity: 0 }}\n                />\n              ))}\n            </g>\n\n            {/* Razor-thin horizontal optical scan beam inside the circular well */}\n            <g clipPath={`url(#${scanClipId})`} className={isPrimary ? \"text-sky-200\" : \"text-primary\"}>\n              <g ref={scanBeamRef} style={{ opacity: 0 }}>\n                <rect x=\"2\" y=\"8.4\" width=\"20\" height=\"7.2\" fill={`url(#${scanClipId}-grad)`} opacity={0.5} />\n                <line x1=\"2.5\" x2=\"21.5\" y1=\"12\" y2=\"12\" stroke=\"currentColor\" strokeWidth=\"1.15\" opacity={0.92} />\n              </g>\n            </g>\n          </svg>\n\n          {/* Self-drawing precision checkmark emerging straight out of the collapsing ridges */}\n          <svg\n            viewBox=\"0 0 18 18\"\n            fill=\"none\"\n            className=\"absolute inset-0 m-auto size-[16px]\"\n            style={{\n              opacity: verified ? 1 : 0,\n              transform: verified ? \"scale(1)\" : \"scale(0.65)\",\n              transition: reduced ? \"none\" : `opacity 200ms ${EASE_OUT} 90ms, transform 340ms ${EASE_OUT} 70ms`,\n            }}\n          >\n            <path\n              d=\"M3.75 9.35 7.25 12.85 14.25 5.4\"\n              stroke=\"currentColor\"\n              strokeWidth=\"2.1\"\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              pathLength={1}\n              strokeDasharray={1}\n              style={{\n                strokeDashoffset: verified ? 0 : 1,\n                transition: verified && !reduced ? `stroke-dashoffset 360ms ${EASE_OUT} 110ms` : \"none\",\n              }}\n            />\n          </svg>\n        </span>\n\n        {/* Morphing label */}\n        <span className=\"relative z-10 whitespace-nowrap tracking-[-0.01em]\">\n          <TextMorph animateWidth={!fullWidth}>{labels[status]}</TextMorph>\n        </span>\n      </button>\n\n      {/* Inline error reason folding cleanly beneath the pill without jumping layout */}\n      <div\n        aria-hidden={!displayError || undefined}\n        className={`grid ${!displayError ? \"pointer-events-none\" : \"\"}`}\n        style={{\n          gridTemplateRows: displayError ? \"1fr\" : \"0fr\",\n          opacity: displayError ? 1 : 0,\n          transition: reduced ? \"none\" : `grid-template-rows 300ms ${EASE_OUT}, opacity 220ms ${EASE_OUT}`,\n        }}\n      >\n        <div className=\"min-h-0 overflow-hidden\">\n          <p role=\"alert\" className=\"max-w-[300px] pt-2 text-center text-[12.5px] leading-5 text-red-600 dark:text-red-400\">\n            {displayError}\n          </p>\n        </div>\n      </div>\n\n      <span className=\"sr-only\" role=\"status\" aria-live=\"polite\">\n        {scanning ? labels.scanning : verified ? labels.verified : isError ? labels.error : \"\"}\n      </span>\n    </div>\n  );\n}\n\nexport default PasskeyButton;\n"},{"path":"registry/ui-interaction-motion.ts","type":"registry:component","content":"// Hairline UI · passkey-button · 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 · passkey-button · 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/passkey-button. MIT licensed: https://hairlineui.com/license#components","meta":{"license":"MIT"}}