{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"download-button","type":"registry:component","title":"Download Button","description":"A download where the whole button is the progress bar: colour sweeps across with drifting stripes, the label turns white as the fill passes, then it folds into a round check badge.","author":"Saurabh <saurabh10102@gmail.com>","dependencies":["clsx","motion","tailwind-merge"],"registryDependencies":["https://beui.dev/r/theme.json"],"docs":"Download Button: usage, props and types at https://beui.dev/micro-interactions/download-button.md It uses beUI's theme tokens, added with this install.","files":[{"path":"components/motion/download-button.tsx","type":"registry:component","target":"@components/motion/download-button.tsx","content":"\"use client\";\n// beui.dev/micro-interactions/download-button\n\nimport {\n  AnimatePresence,\n  type AnimationPlaybackControls,\n  animate,\n  type HTMLMotionProps,\n  motion,\n  useMotionTemplate,\n  useMotionValue,\n  useReducedMotion,\n  useSpring,\n  useTransform,\n} from \"motion/react\";\nimport { useEffect, useRef, useState } from \"react\";\nimport { TextMorph } from \"@/components/motion/text-morph\";\nimport { EASE_IN, EASE_IN_OUT, EASE_OUT, SPRING_GLIDE, SPRING_PRESS, SPRING_SWAP } from \"@/lib/ease\";\nimport { useMessages } from \"@/lib/i18n\";\nimport { useSound } from \"@/lib/sound\";\nimport { successSound } from \"@/lib/sounds/success\";\nimport { tapSound } from \"@/lib/sounds/tap\";\nimport { cn } from \"@/lib/utils\";\n\nexport const downloadButtonMessages = {\n  download: \"Download\",\n  downloading: \"Downloading\",\n  downloaded: \"Downloaded\",\n  progress: \"Download progress\",\n};\n\nexport type DownloadButtonMessages = typeof downloadButtonMessages;\n\ntype Phase = \"idle\" | \"downloading\" | \"done\";\n\nexport interface DownloadButtonProps\n  extends Omit<HTMLMotionProps<\"button\">, \"children\" | \"onChange\"> {\n  /**\n   * Runs the download. Call `report` with progress from 0 to 1 to move the\n   * fill; return a promise to finish when it settles. Without it the fill\n   * runs on its own, as a demo.\n   */\n  onDownload?: (report: (progress: number) => void) => unknown;\n  /** Override any built-in string, e.g. for translation. */\n  labels?: Partial<DownloadButtonMessages>;\n  /** Play a tap on start and a success chime when done. Off by default; a `SoundProvider` can mute it app-wide. */\n  sound?: boolean;\n}\n\n// The pill, and the round badge it folds into when the download is done.\nconst WIDE = 192;\nconst ROUND = 40;\n// The badge holds this long before it opens back into the button.\nconst DONE_MS = 1300;\n// Without onDownload, the fill runs over this long.\nconst DEMO_SECONDS = 2.4;\n// One stripe period, in px: the stripe layer slides this far per loop.\nconst STRIPE = 16;\n\nconst EXIT = { duration: 0.14, ease: EASE_OUT } as const;\nconst FADE = { duration: 0.16, ease: EASE_OUT } as const;\n// The check pops in a beat after the pill has folded.\nconst DRAW = { duration: 0.32, ease: EASE_OUT, delay: 0.22 } as const;\nconst POP = { ...SPRING_PRESS, delay: 0.18 } as const;\n// While it works, an arrow keeps dropping into the tray.\nconst DROP = { duration: 0.9, ease: EASE_IN, repeat: Number.POSITIVE_INFINITY } as const;\n// The stripes drift evenly; easing would make them pulse.\nconst DRIFT = { duration: 0.7, ease: \"linear\", repeat: Number.POSITIVE_INFINITY } as const;\n\n/**\n * A download where the whole button is the progress bar. Colour sweeps\n * across the pill with a bright leading edge and drifting stripes, and the\n * label and icon turn white exactly where the fill passes. When it is done\n * the pill folds into a round badge where a check pops in, then opens back\n * into the button as the colour drains away.\n */\nexport function DownloadButton({\n  onDownload,\n  labels,\n  sound = false,\n  className,\n  onClick,\n  ...rest\n}: DownloadButtonProps) {\n  const t = useMessages(\"DownloadButton\", downloadButtonMessages, labels);\n  const playStart = useSound(tapSound, { enabled: sound });\n  const playDone = useSound(successSound, { enabled: sound });\n  const reduce = Boolean(useReducedMotion());\n  const [phase, setPhase] = useState<Phase>(\"idle\");\n  const [percent, setPercent] = useState(0);\n\n  // Progress drives one value; a critically damped spring smooths uneven\n  // reports into a steady sweep, and the clip and the edge both read it.\n  const target = useMotionValue(0);\n  const smooth = useSpring(target, SPRING_GLIDE);\n  const progress = reduce ? target : smooth;\n  const right = useTransform(progress, (value) => `${(1 - value) * 100}%`);\n  const clip = useMotionTemplate`inset(0 ${right} 0 0)`;\n  // The leading edge rides the fill: a full-width layer whose right edge\n  // sits at the progress, moved by transform only.\n  const edgeX = useTransform(progress, (value) => `${(value - 1) * 100}%`);\n  const fillOpacity = useMotionValue(0);\n  const drainRef = useRef<AnimationPlaybackControls | null>(null);\n\n  const report = (value: number) => {\n    const clamped = Math.min(1, Math.max(0, value));\n    target.set(clamped);\n    setPercent(Math.round(clamped * 100));\n  };\n\n  const reset = () => {\n    target.jump(0);\n    smooth.jump(0);\n    setPercent(0);\n  };\n\n  // Done: hold the badge, then open back into the button as the colour\n  // drains, and reset the fill under it once it is gone.\n  useEffect(() => {\n    if (phase !== \"done\") return;\n    const id = setTimeout(() => {\n      setPhase(\"idle\");\n      const drain = animate(fillOpacity, 0, { duration: 0.3, ease: EASE_OUT });\n      drainRef.current = drain;\n      drain.then(() => {\n        if (drainRef.current !== drain) return;\n        drainRef.current = null;\n        target.jump(0);\n        smooth.jump(0);\n        setPercent(0);\n      });\n    }, DONE_MS);\n    return () => clearTimeout(id);\n  }, [phase, fillOpacity, target, smooth]);\n\n  const start = async () => {\n    // A press during the drain stops it, so it cannot pull the new fill to 0.\n    drainRef.current?.stop();\n    drainRef.current = null;\n    reset();\n    fillOpacity.set(1);\n    setPhase(\"downloading\");\n    try {\n      if (onDownload) await onDownload(report);\n      else await animate(0, 1, { duration: DEMO_SECONDS, ease: EASE_IN_OUT, onUpdate: report });\n    } catch {\n      fillOpacity.set(0);\n      reset();\n      setPhase(\"idle\");\n      return;\n    }\n    report(1);\n    playDone();\n    setPhase(\"done\");\n  };\n\n  const instant = { duration: 0 };\n  const done = phase === \"done\";\n  const label = t(phase === \"idle\" ? \"download\" : phase === \"downloading\" ? \"downloading\" : \"downloaded\");\n\n  // The content is drawn twice, identically: in ink on the button, and in\n  // white on the fill, clipped to the progress. Where the fill has reached,\n  // you see the white copy.\n  const content = (onFill: boolean) => (\n    <motion.span\n      aria-hidden={onFill || undefined}\n      className=\"flex items-center justify-center gap-2 whitespace-nowrap\"\n      initial={false}\n      animate={{ opacity: done ? 0 : 1, scale: done && !reduce ? 0.9 : 1 }}\n      transition={done ? FADE : { ...FADE, delay: 0.12 }}\n    >\n      <svg\n        viewBox=\"0 0 24 24\"\n        fill=\"none\"\n        stroke=\"currentColor\"\n        strokeWidth={2}\n        strokeLinecap=\"round\"\n        strokeLinejoin=\"round\"\n        aria-hidden=\"true\"\n        className=\"size-4 shrink-0 overflow-hidden\"\n      >\n        <path d=\"M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3\" />\n        <motion.g\n          initial={false}\n          animate={\n            phase === \"downloading\" && !reduce\n              ? { y: [-12, 0, 3], opacity: [0, 1, 0] }\n              : { y: 0, opacity: 1 }\n          }\n          transition={phase === \"downloading\" && !reduce ? { ...DROP, times: [0, 0.6, 1] } : SPRING_PRESS}\n        >\n          <path d=\"M12 3v11\" />\n          <path d=\"M7.5 9.5L12 14l4.5-4.5\" />\n        </motion.g>\n      </svg>\n      <span className=\"inline-flex items-center gap-1\">\n        <TextMorph>{label}</TextMorph>\n        {phase === \"downloading\" ? (\n          // A fixed slot, so the label never shifts as the number grows.\n          <motion.span\n            className=\"inline-block w-[4ch] text-left tabular-nums\"\n            initial={{ opacity: 0 }}\n            animate={{ opacity: 1 }}\n            transition={FADE}\n          >\n            {percent}%\n          </motion.span>\n        ) : null}\n      </span>\n    </motion.span>\n  );\n\n  return (\n    <>\n      <motion.button\n        type=\"button\"\n        aria-busy={phase === \"downloading\" || undefined}\n        aria-label={done ? t(\"downloaded\") : undefined}\n        whileTap={reduce || phase !== \"idle\" ? undefined : { scale: 0.96 }}\n        initial={false}\n        // Folds into a round badge when done, and opens back out after.\n        animate={{ width: done ? ROUND : WIDE }}\n        transition={{ width: reduce ? instant : SPRING_SWAP, scale: SPRING_PRESS }}\n        onClick={(event) => {\n          onClick?.(event);\n          if (event.defaultPrevented || phase !== \"idle\") return;\n          playStart();\n          void start();\n        }}\n        className={cn(\n          \"relative isolate inline-flex h-10 items-center justify-center overflow-hidden rounded-full border border-border bg-background text-sm font-medium text-foreground transition-colors duration-200\",\n          \"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50\",\n          \"disabled:pointer-events-none disabled:opacity-50\",\n          phase === \"idle\" && \"hover:bg-muted/60\",\n          className,\n        )}\n        {...rest}\n      >\n        {content(false)}\n\n        {/* The fill, clipped to the progress, with the white copy of the content on it. */}\n        <motion.span\n          aria-hidden=\"true\"\n          className=\"absolute inset-0 flex items-center justify-center overflow-hidden bg-primary text-primary-foreground\"\n          style={{ clipPath: clip, opacity: fillOpacity }}\n        >\n          {/* Fine stripes drifting through the fill while it works. */}\n          {!reduce ? (\n            <motion.span\n              className=\"absolute inset-y-0 -left-4 -right-4\"\n              style={{\n                backgroundImage:\n                  \"repeating-linear-gradient(-45deg, transparent 0 6px, color-mix(in oklab, currentColor 12%, transparent) 6px 8px)\",\n              }}\n              initial={false}\n              animate={phase === \"downloading\" ? { x: [0, -STRIPE], opacity: 1 } : { x: 0, opacity: 0 }}\n              transition={phase === \"downloading\" ? { x: DRIFT, opacity: FADE } : FADE}\n            />\n          ) : null}\n          {/* The bright leading edge, riding the front of the fill. */}\n          <motion.span className=\"absolute inset-0\" style={{ x: edgeX }}>\n            <motion.span\n              className=\"absolute inset-y-0 right-0 w-10 bg-gradient-to-r from-transparent to-white/30\"\n              initial={false}\n              animate={{ opacity: phase === \"downloading\" ? 1 : 0 }}\n              transition={FADE}\n            />\n          </motion.span>\n          <span className=\"relative\">{content(true)}</span>\n        </motion.span>\n\n        {/* The badge's check, popping in once the pill has folded. */}\n        <AnimatePresence>\n          {done ? (\n            <motion.svg\n              key=\"check\"\n              viewBox=\"0 0 24 24\"\n              fill=\"none\"\n              stroke=\"currentColor\"\n              strokeWidth={2.75}\n              strokeLinecap=\"round\"\n              strokeLinejoin=\"round\"\n              aria-hidden=\"true\"\n              className=\"absolute size-5 text-primary-foreground\"\n              initial={{ scale: reduce ? 1 : 0.4, opacity: 0 }}\n              animate={{ scale: 1, opacity: 1 }}\n              exit={{ scale: reduce ? 1 : 0.6, opacity: 0, transition: EXIT }}\n              transition={{ scale: reduce ? instant : POP, opacity: { ...FADE, delay: reduce ? 0 : 0.16 } }}\n            >\n              <motion.path\n                d=\"M4.5 12.5l5 5L19.5 7\"\n                initial={{ pathLength: reduce ? 1 : 0 }}\n                animate={{ pathLength: 1 }}\n                transition={reduce ? instant : DRAW}\n              />\n            </motion.svg>\n          ) : null}\n        </AnimatePresence>\n\n        {phase === \"downloading\" ? (\n          <span\n            role=\"progressbar\"\n            aria-label={t(\"progress\")}\n            aria-valuemin={0}\n            aria-valuemax={100}\n            aria-valuenow={percent}\n            className=\"sr-only\"\n          />\n        ) : null}\n      </motion.button>\n      <span aria-live=\"polite\" className=\"sr-only\">\n        {done ? t(\"downloaded\") : \"\"}\n      </span>\n    </>\n  );\n}\n"},{"path":"components/motion/text-morph.tsx","type":"registry:component","target":"@components/motion/text-morph.tsx","content":"\"use client\";\n\nimport { AnimatePresence, animate, motion, useReducedMotion } from \"motion/react\";\nimport { useLayoutEffect, useRef, useState } from \"react\";\nimport { EASE_OUT, SPRING_LAYOUT, SPRING_SWAP } from \"@/lib/ease\";\nimport { cn } from \"@/lib/utils\";\n\nexport interface TextMorphProps {\n  /** The text to show. Changing it morphs from the previous string. */\n  children: string;\n  /** Classes merged onto the root element. */\n  className?: string;\n}\n\ntype Glyph = { id: number; char: string };\n\ntype Morph = {\n  text: string;\n  glyphs: Glyph[];\n  nextId: number;\n  /** For each new glyph, the kept neighbour it travels in with. */\n  enterAnchor: Map<number, number>;\n  /** For each leaving glyph, the kept neighbour it rides out with. */\n  leaveAnchor: Map<number, number>;\n  /** Arrival order of new glyphs, left to right. */\n  enterOrder: Map<number, number>;\n  /** Departure order of leaving glyphs, last letter first. */\n  leaveOrder: Map<number, number>;\n};\n\n// Letters arrive one at a time and spring up into place. This spring is a\n// little looser than SPRING_SWAP on purpose: a small settle on each letter is\n// what makes the sequence read as letters landing rather than a fade.\nconst SPRING_LETTER = { type: \"spring\", stiffness: 520, damping: 22, mass: 0.6 } as const;\nconst STAGGER_IN = 0.035;\n// Leaving letters go faster than new ones arrive, so the exit never holds up the entry.\nconst STAGGER_OUT = 0.02;\nconst RISE = 8;\nconst FADE_IN = { duration: 0.16, ease: EASE_OUT } as const;\nconst FADE_OUT = { duration: 0.12, ease: EASE_OUT } as const;\n\n/** Index pairs (old, new) of the longest common subsequence of two lists. */\nfunction lcsPairs(a: string[], b: string[]): [number, number][] {\n  const cols = b.length + 1;\n  const table = new Uint16Array((a.length + 1) * cols);\n  for (let i = a.length - 1; i >= 0; i--) {\n    for (let j = b.length - 1; j >= 0; j--) {\n      table[i * cols + j] =\n        a[i] === b[j]\n          ? table[(i + 1) * cols + j + 1] + 1\n          : Math.max(table[(i + 1) * cols + j], table[i * cols + j + 1]);\n    }\n  }\n  const pairs: [number, number][] = [];\n  let i = 0;\n  let j = 0;\n  while (i < a.length && j < b.length) {\n    if (a[i] === b[j]) {\n      pairs.push([i, j]);\n      i++;\n      j++;\n    } else if (table[(i + 1) * cols + j] >= table[i * cols + j + 1]) i++;\n    else j++;\n  }\n  return pairs;\n}\n\n/** The nearest id in `ids` that is kept, searching one way first and then the other. */\nfunction nearestKept(index: number, ids: number[], kept: Set<number>, forwardFirst: boolean) {\n  const scan = (step: number) => {\n    for (let k = index + step; k >= 0 && k < ids.length; k += step) {\n      if (kept.has(ids[k])) return ids[k];\n    }\n    return undefined;\n  };\n  return forwardFirst ? (scan(1) ?? scan(-1)) : (scan(-1) ?? scan(1));\n}\n\nfunction firstMorph(text: string): Morph {\n  const glyphs = Array.from(text, (char, id) => ({ id, char }));\n  return {\n    text,\n    glyphs,\n    nextId: glyphs.length,\n    enterAnchor: new Map(),\n    leaveAnchor: new Map(),\n    enterOrder: new Map(),\n    leaveOrder: new Map(),\n  };\n}\n\n/**\n * Pairs the old glyphs with the new string by their longest common\n * subsequence: paired glyphs keep their id (and their element), the rest\n * leave or arrive, each tied to the nearest glyph that stays.\n */\nfunction nextMorph(previous: Morph, text: string): Morph {\n  const chars = Array.from(text);\n  const pairs = lcsPairs(\n    previous.glyphs.map((glyph) => glyph.char),\n    chars,\n  );\n  const reuse = new Map(pairs.map(([o, n]) => [n, previous.glyphs[o].id]));\n  let nextId = previous.nextId;\n  const glyphs = chars.map((char, index) => ({ id: reuse.get(index) ?? nextId++, char }));\n\n  const kept = new Set(reuse.values());\n  const oldIds = previous.glyphs.map((glyph) => glyph.id);\n  const newIds = glyphs.map((glyph) => glyph.id);\n  const leaveAnchor = new Map<number, number>();\n  oldIds.forEach((id, index) => {\n    if (kept.has(id)) return;\n    const anchor = nearestKept(index, oldIds, kept, true);\n    if (anchor !== undefined) leaveAnchor.set(id, anchor);\n  });\n  const enterAnchor = new Map<number, number>();\n  newIds.forEach((id, index) => {\n    if (kept.has(id)) return;\n    const anchor = nearestKept(index, newIds, kept, false);\n    if (anchor !== undefined) enterAnchor.set(id, anchor);\n  });\n  const enterOrder = new Map(newIds.filter((id) => !kept.has(id)).map((id, order) => [id, order]));\n  const leaveOrder = new Map(\n    oldIds\n      .filter((id) => !kept.has(id))\n      .reverse()\n      .map((id, order) => [id, order]),\n  );\n  return { text, glyphs, nextId, enterAnchor, leaveAnchor, enterOrder, leaveOrder };\n}\n\n/** The x a glyph is drawn at right now, mid-slide included. */\nfunction drawnX(el: HTMLElement) {\n  const transform = getComputedStyle(el).transform;\n  return transform && transform !== \"none\" ? new DOMMatrixReadOnly(transform).m41 : 0;\n}\n\n/**\n * Morphs one string into another. Letters the two strings share (paired by\n * their longest common subsequence) glide on a spring from where they are\n * drawn to their new place. Letters that leave ride along with their nearest\n * neighbour that stays while they shrink and fade; new letters grow in from\n * where theirs came from; the box springs to the new width. A change mid-morph\n * retargets every spring from where it is.\n */\nexport function TextMorph({ children: text, className }: TextMorphProps) {\n  const reduce = Boolean(useReducedMotion());\n  const [morph, setMorph] = useState(() => firstMorph(text));\n  // Derive the next morph during render, so the new glyphs and their ids\n  // land in the same commit as the text.\n  let current = morph;\n  if (morph.text !== text) {\n    current = nextMorph(morph, text);\n    setMorph(current);\n  }\n\n  const rootRef = useRef<HTMLSpanElement>(null);\n  const nodes = useRef(new Map<number, HTMLSpanElement>());\n  // Each glyph's layout x inside the root from the last commit, transforms excluded.\n  const layout = useRef(new Map<number, number>());\n  const [width, setWidth] = useState<number>();\n\n  useLayoutEffect(() => {\n    const root = rootRef.current;\n    if (!root) return;\n    const origin = root.getBoundingClientRect().left;\n    const next = new Map<number, number>();\n    for (const glyph of current.glyphs) {\n      const el = nodes.current.get(glyph.id);\n      if (el) next.set(glyph.id, el.getBoundingClientRect().left - origin - drawnX(el));\n    }\n    const before = layout.current;\n    layout.current = next;\n    setWidth(root.offsetWidth);\n    if (reduce || before.size === 0) return;\n\n    const travel = (id: number) => {\n      const from = before.get(id);\n      const to = next.get(id);\n      return from === undefined || to === undefined ? 0 : to - from;\n    };\n\n    for (const glyph of current.glyphs) {\n      const el = nodes.current.get(glyph.id);\n      if (!el) continue;\n      if (before.has(glyph.id)) {\n        // Kept: jump back to where it is drawn, then spring to the new place.\n        const from = drawnX(el) - travel(glyph.id);\n        if (Math.abs(from) > 0.5) animate(el, { x: [from, 0] }, SPRING_LAYOUT);\n      } else {\n        // New: start where its anchor came from and travel in with it.\n        const anchor = current.enterAnchor.get(glyph.id);\n        const from = anchor === undefined ? 0 : -travel(anchor);\n        if (Math.abs(from) > 0.5) animate(el, { x: [from, 0] }, SPRING_LAYOUT);\n      }\n    }\n    // Leaving: popLayout has pinned them where they were; ride the anchor out.\n    for (const [id, anchor] of current.leaveAnchor) {\n      const el = nodes.current.get(id);\n      const shift = travel(anchor);\n      if (el && Math.abs(shift) > 0.5) animate(el, { x: drawnX(el) + shift }, SPRING_LAYOUT);\n    }\n  }, [current, reduce]);\n\n  return (\n    <motion.span\n      initial={false}\n      animate={width === undefined ? undefined : { width }}\n      transition={reduce ? { duration: 0 } : SPRING_SWAP}\n      className={cn(\"inline-block whitespace-pre\", className)}\n    >\n      <span className=\"sr-only\">{text}</span>\n      <span ref={rootRef} aria-hidden=\"true\" className=\"relative inline-flex whitespace-pre\">\n        {/* `custom` hands the latest morph to leaving letters too, so each\n            one knows its place in the departure order. */}\n        <AnimatePresence initial={false} mode=\"popLayout\" custom={current}>\n          {current.glyphs.map((glyph) => (\n            <motion.span\n              key={glyph.id}\n              ref={(node: HTMLSpanElement | null) => {\n                if (node) nodes.current.set(glyph.id, node);\n                else nodes.current.delete(glyph.id);\n              }}\n              className=\"inline-block\"\n              custom={current}\n              variants={{\n                // Each new letter springs up from just below, on its own beat.\n                enter: { opacity: 0, y: reduce ? 0 : RISE },\n                shown: (morph: Morph) => {\n                  const delay = reduce ? 0 : (morph.enterOrder.get(glyph.id) ?? 0) * STAGGER_IN;\n                  return {\n                    opacity: 1,\n                    y: 0,\n                    transition: { y: { ...SPRING_LETTER, delay }, opacity: { ...FADE_IN, delay } },\n                  };\n                },\n                // Leaving letters drop back down the way new ones rise, last letter first.\n                gone: (morph: Morph) => {\n                  const delay = reduce ? 0 : (morph.leaveOrder.get(glyph.id) ?? 0) * STAGGER_OUT;\n                  return {\n                    opacity: 0,\n                    y: reduce ? 0 : RISE,\n                    transition: { y: { ...SPRING_LETTER, delay }, opacity: { ...FADE_OUT, delay } },\n                  };\n                },\n              }}\n              initial=\"enter\"\n              animate=\"shown\"\n              exit=\"gone\"\n            >\n              {glyph.char}\n            </motion.span>\n          ))}\n        </AnimatePresence>\n      </span>\n    </motion.span>\n  );\n}\n"},{"path":"lib/ease.ts","type":"registry:lib","target":"@lib/ease.ts","content":"// Shared motion tokens. Easing curves mirror the CSS custom properties in\n// globals.css; springs are the canonical physics used across components.\n// Strong custom variants — defaults like `ease-in`/`ease-out` feel weak.\n\nexport const EASE_OUT = [0.16, 1, 0.3, 1] as const;\n/** Accelerating curve for things that fall (a dropped ball, a toppled block). Not for UI entrances. */\nexport const EASE_IN = [0.55, 0, 1, 0.45] as const;\nexport const EASE_IN_OUT = [0.77, 0, 0.175, 1] as const;\nexport const EASE_DRAWER = [0.32, 0.72, 0, 1] as const;\n\n/** CSS string form of EASE_OUT for inline style transitions. */\nexport const EASE_OUT_CSS = \"cubic-bezier(0.16, 1, 0.3, 1)\";\n\n/** Press feedback on buttons and other tappable surfaces. */\nexport const SPRING_PRESS = {\n  type: \"spring\",\n  stiffness: 500,\n  damping: 30,\n  mass: 0.6,\n} as const;\n\n/** Content swaps — label/icon slots trading places inside a control. */\nexport const SPRING_SWAP = {\n  type: \"spring\",\n  stiffness: 460,\n  damping: 30,\n  mass: 0.55,\n} as const;\n\n/** Overlay panel entrances — modals and sheets summoned by pointer. */\nexport const SPRING_PANEL = {\n  type: \"spring\",\n  stiffness: 420,\n  damping: 40,\n  mass: 0.5,\n} as const;\n\n/** Shared-layout glides — pills, indicators and panels morphing between positions. */\nexport const SPRING_LAYOUT = {\n  type: \"spring\",\n  stiffness: 360,\n  damping: 32,\n  mass: 0.6,\n} as const;\n\n/** Cursor-follow physics for decorative mouse tracking (magnetic, tilt, dock). */\nexport const SPRING_MOUSE = {\n  stiffness: 200,\n  damping: 15,\n  mass: 0.3,\n} as const;\n\n/** Dragged handles and fills (sliders) — critically damped `useSpring` config,\n * so the value follows the pointer butterily and never rebounds off an end. */\nexport const SPRING_GLIDE = {\n  stiffness: 700,\n  damping: 50,\n  mass: 0.5,\n} as const;\n\n/** Shared-surface morphs: a trigger growing into its panel and back on one\n * weighted spring, so opening and closing travel the same path. */\nexport const SPRING_MORPH = {\n  type: \"spring\",\n  duration: 0.5,\n  bounce: 0.22,\n} as const;\n"},{"path":"lib/i18n.tsx","type":"registry:lib","target":"@lib/i18n.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useMemo,\n} from \"react\";\n\n/**\n * A component's messages. Plain strings with `{name}` placeholders, so a\n * dictionary stays JSON-serializable and can be passed from a server layout.\n * There are no plural forms: write messages that read correctly for any count.\n */\nexport type Messages = Record<string, string>;\n\n/** A language file: component namespace → any subset of that component's messages. */\nexport type LocaleMessages = Record<string, Partial<Messages>>;\n\ntype LocaleContextValue = {\n  locale?: string;\n  messages: LocaleMessages;\n};\n\nconst NO_MESSAGES: LocaleMessages = {};\n\nconst LocaleContext = createContext<LocaleContextValue>({ messages: NO_MESSAGES });\n\n/** Without a locale, digits stay plain so server and client render the same text. */\nexport function formatNumber(value: number, locale?: string) {\n  return locale ? new Intl.NumberFormat(locale).format(value) : String(value);\n}\n\nexport interface LocaleProviderProps {\n  /** BCP 47 tag, e.g. `de`, `pt-BR`. Drives `Intl` number formatting. */\n  locale: string;\n  /**\n   * Component namespace → translated strings. Missing keys fall back to English.\n   * Pass a stable object (a module constant, imported JSON or a memoized value):\n   * a new object each render gives every translated component a new `t`.\n   */\n  messages?: LocaleMessages;\n  children: ReactNode;\n}\n\nexport function LocaleProvider({ locale, messages = NO_MESSAGES, children }: LocaleProviderProps) {\n  const value = useMemo(() => ({ locale, messages }), [locale, messages]);\n  return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;\n}\n\nexport function useLocale(): { locale?: string } {\n  return { locale: useContext(LocaleContext).locale };\n}\n\n/**\n * Resolves a component's strings: `labels` prop, then the provider's\n * messages for `namespace`, then the component's English `defaults`.\n * Numbers passed as values are formatted for the provider's locale.\n */\nexport function useMessages<T extends Messages>(\n  namespace: string,\n  defaults: T,\n  labels?: Partial<T>,\n) {\n  const { locale, messages } = useContext(LocaleContext);\n  const provided = messages[namespace];\n  // Inline `labels={{ … }}` is a new object every render. Keying it by content\n  // keeps `t` one identity until a label changes, so effects and memos that\n  // depend on `t` don't re-run per render, and render-time reads never lag.\n  const labelsKey = labels ? JSON.stringify(labels) : \"\";\n  const stableLabels = useMemo(\n    () => (labelsKey ? (JSON.parse(labelsKey) as Partial<T>) : undefined),\n    [labelsKey],\n  );\n\n  return useCallback(\n    (key: keyof T & string, values?: Record<string, string | number>) => {\n      const template = stableLabels?.[key] ?? provided?.[key] ?? defaults[key];\n      if (!values) return template;\n      return template.replace(/\\{(\\w+)\\}/g, (match, name: string) => {\n        const value = values[name];\n        if (value === undefined) return match;\n        return typeof value === \"number\" ? formatNumber(value, locale) : value;\n      });\n    },\n    [defaults, stableLabels, locale, provided],\n  );\n}\n"},{"path":"lib/sound.tsx","type":"registry:lib","target":"@lib/sound.tsx","content":"\"use client\";\n\nimport {\n  createContext,\n  type ReactNode,\n  useCallback,\n  useContext,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n} from \"react\";\nimport {\n  registerSoundSettings,\n  retainAudioContext,\n  type SoundSettingsEntry,\n} from \"@/lib/audio-context\";\nimport type { PlayOptions, Sound } from \"@/lib/sounds/engine\";\n\nexport interface SoundSettings {\n  /** False mutes every beUI sound under the provider. */\n  enabled: boolean;\n  /** 0 to 1, scales every beUI sound. */\n  volume: number;\n}\n\nconst SoundContext = createContext<SoundSettings & { depth: number }>({\n  enabled: true,\n  volume: 1,\n  depth: 0,\n});\n\n/**\n * App-wide sound settings. `enabled={false}` mutes every beUI sound, from\n * component `sound` props and `useSound` to the games, Wheel Picker and\n * Bookshelf, and `volume` scales them all. Without a provider, sounds play at\n * full volume. A nested provider overrides the one around it.\n */\nexport function SoundProvider({\n  enabled = true,\n  volume = 1,\n  children,\n}: Partial<SoundSettings> & { children: ReactNode }) {\n  const depth = useContext(SoundContext).depth + 1;\n  const value = useMemo(() => ({ enabled, volume, depth }), [enabled, volume, depth]);\n\n  // Module-level as well (lib/audio-context.ts), so players outside React\n  // and `sound.play()` obey it too.\n  const entry = useRef<SoundSettingsEntry>({ depth, enabled, volume });\n  const registration = useRef<ReturnType<typeof registerSoundSettings> | null>(null);\n  useEffect(() => {\n    registration.current = registerSoundSettings(entry.current);\n    return () => {\n      registration.current?.release();\n      registration.current = null;\n    };\n  }, []);\n  useEffect(() => {\n    Object.assign(entry.current, { depth, enabled, volume });\n    registration.current?.update();\n  }, [depth, enabled, volume]);\n\n  return <SoundContext.Provider value={value}>{children}</SoundContext.Provider>;\n}\n\nexport function useSoundSettings(): SoundSettings {\n  return useContext(SoundContext);\n}\n\nexport interface UseSoundOptions {\n  /** False makes `play` do nothing, for a component's `sound` prop. */\n  enabled?: boolean;\n  /** 0 to 1 for this sound, on top of the provider volume. */\n  volume?: number;\n}\n\n/**\n * A stable `play()` for one sound. It does nothing while disabled or muted,\n * and keeps the shared audio context warm only while it can play.\n */\nexport function useSound(sound: Sound, { enabled = true, volume = 1 }: UseSoundOptions = {}) {\n  const settings = useSoundSettings();\n  const on = enabled && settings.enabled && settings.volume > 0 && volume > 0;\n  // Read by the stable callback, so a caller's effects don't re-run when\n  // the settings change.\n  const latest = useRef({ on, volume, sound });\n  useLayoutEffect(() => {\n    latest.current = { on, volume, sound };\n  });\n\n  useEffect(() => {\n    if (!on) return;\n    return retainAudioContext();\n  }, [on]);\n\n  return useCallback((options?: PlayOptions) => {\n    const current = latest.current;\n    if (!current.on) return;\n    current.sound.play({ ...options, volume: (options?.volume ?? 1) * current.volume });\n  }, []);\n}\n"},{"path":"lib/sounds/success.ts","type":"registry:lib","target":"@lib/sounds/success.ts","content":"import { defineSound } from \"./engine\";\n\n/** Two soft mallet notes on a wooden bar, rising a fifth, for a saved or completed action. */\nexport const successSound = defineSound({\n  name: \"Success\",\n  duration: 0.5,\n  room: 0.25,\n  build: (v) => {\n    v.click({ freq: 2500, q: 1, decay: 0.004, gain: 0.18 });\n    v.strike({ freq: 1047, material: \"mallet\", decay: 0.28, gain: 0.5 });\n    v.click({ freq: 2500, q: 1, at: 0.085, decay: 0.004, gain: 0.18 });\n    v.strike({ freq: 1568, material: \"mallet\", at: 0.085, decay: 0.38, gain: 0.5 });\n  },\n});\n"},{"path":"lib/sounds/tap.ts","type":"registry:lib","target":"@lib/sounds/tap.ts","content":"import { defineSound } from \"./engine\";\n\n/** A fingertip on glass: a crisp contact, a small glass ring and a soft knock under it. */\nexport const tapSound = defineSound({\n  name: \"Tap\",\n  duration: 0.08,\n  vary: 0.04,\n  room: 0.1,\n  build: (v) => {\n    v.click({ freq: 3600, q: 1.6, decay: 0.004, gain: 0.55 });\n    v.strike({ freq: 2150, material: \"glass\", decay: 0.04, gain: 0.32 });\n    v.strike({ freq: 210, material: \"wood\", bend: 1.25, decay: 0.03, gain: 0.45 });\n  },\n});\n"},{"path":"lib/utils.ts","type":"registry:lib","target":"@lib/utils.ts","content":"import { clsx, type ClassValue } from \"clsx\"\nimport { twMerge } from \"tailwind-merge\"\n\nexport function cn(...inputs: ClassValue[]) {\n  return twMerge(clsx(inputs))\n}\n"},{"path":"lib/audio-context.ts","type":"registry:lib","target":"@lib/audio-context.ts","content":"// One AudioContext for every synthesized sound on the page: the sounds\n// library (lib/sounds/), the WheelPicker tick (lib/tick-sound.ts), the casino\n// games (lib/game-sounds.ts) and Bookshelf (lib/book-sounds.ts). Browsers cap\n// concurrent contexts, and a page can show a date made of several WheelPickers\n// next to a game, so they all share this one. It is created on first use and\n// closed once every player is disposed.\n//\n// Every player connects to `audioOutput()` rather than the context's\n// destination, so the page-wide volume and mute from `SoundProvider`\n// (lib/sound.tsx) reach all of them in one place.\n\ntype AudioContextCtor = typeof AudioContext;\n\nlet context: AudioContext | null = null;\nlet master: GainNode | null = null;\nlet users = 0;\n\n/** Settings one mounted `SoundProvider` asks for. */\nexport interface SoundSettingsEntry {\n  /** Nesting depth: the deepest provider decides. */\n  depth: number;\n  enabled: boolean;\n  volume: number;\n}\n\n// Mounted providers in mount order. Module state, so `sound.play()` called\n// outside React obeys them too. The deepest provider wins; among equals, the\n// one mounted last. Effects run child first, so this can't be \"whoever ran\n// last\".\nconst providers = new Set<SoundSettingsEntry>();\nlet allowed = true;\nlet volume = 1;\n\nfunction applySettings() {\n  let chosen: SoundSettingsEntry | undefined;\n  for (const entry of providers) {\n    if (!chosen || entry.depth >= chosen.depth) chosen = entry;\n  }\n  allowed = chosen?.enabled ?? true;\n  volume = Math.min(1, Math.max(0, chosen?.volume ?? 1));\n  if (master) master.gain.value = volume;\n}\n\n/**\n * Registers a provider's settings; call `update` after changing the entry and\n * the returned release function when the provider unmounts.\n */\nexport function registerSoundSettings(entry: SoundSettingsEntry) {\n  providers.add(entry);\n  applySettings();\n  return {\n    update: applySettings,\n    release() {\n      providers.delete(entry);\n      applySettings();\n    },\n  };\n}\n\n/**\n * Registers a sound player. Call the returned function when the player is\n * disposed; the context closes after the last one.\n */\nexport function retainAudioContext() {\n  users++;\n  let released = false;\n  return () => {\n    if (released) return;\n    released = true;\n    users--;\n    if (users === 0 && context) {\n      void context.close();\n      context = null;\n      master = null;\n    }\n  };\n}\n\n/**\n * The shared context, created on first call and resumed if suspended. Null\n * during SSR, in browsers without Web Audio, and while sounds are muted or at\n * zero volume.\n */\nexport function getAudioContext(): AudioContext | null {\n  if (!allowed || volume <= 0) return null;\n  if (!context) {\n    if (typeof window === \"undefined\") return null;\n    const Ctor =\n      window.AudioContext ??\n      (window as unknown as { webkitAudioContext?: AudioContextCtor }).webkitAudioContext;\n    if (!Ctor) return null;\n    context = new Ctor();\n  }\n  // Browsers may refuse outside a user gesture. Players call this from\n  // pointer and key handlers first, so a later call finds it running.\n  if (context.state === \"suspended\") void context.resume().catch(() => undefined);\n  return context;\n}\n\n/** The node every player connects to: the page-wide volume, then the speakers. */\nexport function audioOutput(ctx: AudioContext): AudioNode {\n  if (master?.context !== ctx) {\n    master = ctx.createGain();\n    master.gain.value = volume;\n    master.connect(ctx.destination);\n  }\n  return master;\n}\n\nconst gains = new WeakMap<BaseAudioContext, Map<string, GainNode>>();\n\n/**\n * A player's own level, made once per context and routed into `audioOutput`.\n * Players keep their mix this way without rebuilding nodes on every play, and\n * a context closed and recreated gets fresh ones.\n */\nexport function playerGain(ctx: AudioContext, key: string, level: number): GainNode {\n  let byKey = gains.get(ctx);\n  if (!byKey) {\n    byKey = new Map();\n    gains.set(ctx, byKey);\n  }\n  let gain = byKey.get(key);\n  if (!gain) {\n    gain = ctx.createGain();\n    gain.gain.value = level;\n    gain.connect(audioOutput(ctx));\n    byKey.set(key, gain);\n  }\n  return gain;\n}\n"},{"path":"lib/sounds/engine.ts","type":"registry:lib","target":"@lib/sounds/engine.ts","content":"import { audioOutput, getAudioContext } from \"@/lib/audio-context\";\n\n// Every beUI sound is a short recipe played with Web Audio the moment it is\n// asked for. Nothing is downloaded. Recipes are built the way a real tap\n// sounds: a contact click (a millisecond of filtered noise), a body that\n// rings at a few inharmonic partials of a material and settles in pitch, and\n// a little of a small room behind it.\n\n/** Options for one play of a sound. */\nexport interface PlayOptions {\n  /** 0 to 1, multiplied with the page-wide volume from `SoundProvider`. */\n  volume?: number;\n  /** Pitch multiplier; 1 is the designed pitch. */\n  pitch?: number;\n}\n\n/** Where a sound renders: the live context, or an offline one for drawing. */\nexport interface SoundTarget {\n  context: BaseAudioContext;\n  destination: AudioNode;\n  /** Start time on the context clock, in seconds. */\n  when: number;\n  volume: number;\n  pitch: number;\n}\n\n/** A plain oscillator with an attack, a decay and an optional glide. */\nexport interface ToneSpec {\n  type?: OscillatorType;\n  /** Start frequency in Hz. */\n  freq: number;\n  /** End frequency in Hz; glides from `freq` over `glide`. */\n  to?: number;\n  /** Glide time in seconds; defaults to the attack plus decay. */\n  glide?: number;\n  /** Starts this many times higher and settles to `freq` in about 15 ms, like a struck object. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** A burst of filtered white noise. */\nexport interface NoiseSpec {\n  filter?: BiquadFilterType;\n  /** Filter frequency in Hz. */\n  freq: number;\n  /** End filter frequency in Hz; sweeps from `freq` over the decay. */\n  to?: number;\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Fade-in time in seconds. */\n  attack?: number;\n  /** Time to fade to silence after the attack, in seconds. */\n  decay: number;\n  gain: number;\n}\n\n/** The contact of a tap: a few milliseconds of band-passed noise with an instant attack. */\nexport interface ClickSpec {\n  /** Band center in Hz: 1-2 kHz is a soft knock, 3-5 kHz a crisp click. */\n  freq: number;\n  /** Band width; higher is narrower and more tonal. */\n  q?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time to fade to silence, in seconds. */\n  decay?: number;\n  gain: number;\n}\n\n/** How a material rings: partials as [frequency ratio, level], and how fast high ones die. */\nexport interface Material {\n  partials: readonly (readonly [ratio: number, level: number])[];\n  /** Higher partials decay in `decay / ratio ** damping`; wood is high, metal low. */\n  damping: number;\n}\n\n// Partial ratios follow the modes of small struck objects: a free bar for\n// wood and metal, a cup for glass, a tuned bar for the mallet.\nexport const MATERIALS = {\n  wood: { partials: [[1, 1], [2.76, 0.3], [5.4, 0.08]], damping: 1.3 },\n  plastic: { partials: [[1, 1], [2.43, 0.4], [4.86, 0.14]], damping: 0.9 },\n  glass: { partials: [[1, 1], [2.32, 0.42], [4.25, 0.2], [6.63, 0.08]], damping: 0.55 },\n  metal: { partials: [[1, 1], [2.76, 0.5], [5.4, 0.26], [8.93, 0.1]], damping: 0.4 },\n  mallet: { partials: [[1, 1], [3.99, 0.2], [9.14, 0.05]], damping: 0.8 },\n  bell: { partials: [[1, 1], [2.0, 0.34], [2.76, 0.2], [5.4, 0.07]], damping: 0.5 },\n} satisfies Record<string, Material>;\n\n/** A struck object: one partial per mode of its material, each with its own decay. */\nexport interface StrikeSpec {\n  /** Fundamental in Hz. */\n  freq: number;\n  /** A name from `MATERIALS` or your own partials. Default: \"plastic\". */\n  material?: keyof typeof MATERIALS | Material;\n  /** Starts this many times higher and settles in about 15 ms. Default: 1.01. */\n  bend?: number;\n  /** Delay from the sound's start, in seconds. */\n  at?: number;\n  /** Time for the fundamental to fade to silence, in seconds. */\n  decay: number;\n  gain: number;\n}\n\nexport interface Voice {\n  tone(spec: ToneSpec): void;\n  noise(spec: NoiseSpec): void;\n  click(spec: ClickSpec): void;\n  strike(spec: StrikeSpec): void;\n}\n\nexport interface Sound {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Plays the sound now. Silent during SSR and while sounds are muted. */\n  play(options?: PlayOptions): void;\n  /** Schedules the sound on any context; `play` uses the live one. */\n  render(target: SoundTarget): void;\n}\n\nexport interface SoundRecipe {\n  /** Display name, like \"Tap\". */\n  name: string;\n  /** Length in seconds; the room tail rings a little past it. */\n  duration: number;\n  /** Random pitch spread per play (0.04 = ±4%), so repeats don't sound stamped. */\n  vary?: number;\n  /** How much of the small room the sound is played in, 0 (dry) to 1. Default: 0.12. */\n  room?: number;\n  /** Adds the sound's layers to the voice on each play. */\n  build: (voice: Voice) => void;\n}\n\n// Keeps a sum of voices well under clipping at volume 1.\nconst MASTER_GAIN = 0.16;\nconst SILENT = 0.0001;\n// Time a strike or bend takes to settle onto its pitch.\nconst SETTLE = 0.015;\n\nconst noiseBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\n/** One second of white noise per context, shared by every noise voice. */\nexport function noiseBuffer(context: BaseAudioContext) {\n  let buffer = noiseBuffers.get(context);\n  if (!buffer) {\n    buffer = context.createBuffer(1, context.sampleRate, context.sampleRate);\n    const data = buffer.getChannelData(0);\n    for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1;\n    noiseBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// A small, soft room: 8 early reflections, then a diffuse tail that falls\n// 60 dB in 0.3 s and darkens as it fades, the way air and soft walls\n// absorb highs first. Generated once per context.\nconst ROOM_LENGTH = 0.3;\n// The convolver's equal-power normalization leaves the room about 15 dB\n// under the dry sound; this brings `room: 0.12` to a tail heard only as space.\nconst ROOM_GAIN = 6;\nconst roomBuffers = new WeakMap<BaseAudioContext, AudioBuffer>();\n\nfunction roomBuffer(context: BaseAudioContext) {\n  let buffer = roomBuffers.get(context);\n  if (!buffer) {\n    const rate = context.sampleRate;\n    const length = Math.ceil(ROOM_LENGTH * rate);\n    buffer = context.createBuffer(2, length, rate);\n    for (let channel = 0; channel < 2; channel++) {\n      const data = buffer.getChannelData(channel);\n      let smooth = 0;\n      for (let i = Math.floor(0.004 * rate); i < length; i++) {\n        const t = i / rate;\n        // One-pole low-pass whose cutoff closes over the tail.\n        const brightness = 0.7 * Math.exp(-t / 0.08) + 0.08;\n        smooth += brightness * (Math.random() * 2 - 1 - smooth);\n        data[i] = smooth * Math.exp(-t / 0.043);\n      }\n      for (let r = 0; r < 8; r++) {\n        const at = Math.floor((0.005 + Math.random() * 0.022) * rate);\n        data[at] += (Math.random() < 0.5 ? -1 : 1) * (0.5 - r * 0.05);\n      }\n    }\n    roomBuffers.set(context, buffer);\n  }\n  return buffer;\n}\n\n// One convolver per output node, shared by every play: building one is the\n// expensive part, sending to it is cheap.\nconst rooms = new WeakMap<AudioNode, ConvolverNode>();\n\nfunction roomFor(context: BaseAudioContext, destination: AudioNode) {\n  let room = rooms.get(destination);\n  if (!room) {\n    room = context.createConvolver();\n    room.buffer = roomBuffer(context);\n    room.connect(destination);\n    rooms.set(destination, room);\n  }\n  return room;\n}\n\n/** A linear attack to `peak`, then an exponential fall to silence. */\nfunction envelope(param: AudioParam, start: number, attack: number, decay: number, peak: number) {\n  param.setValueAtTime(0, start);\n  param.linearRampToValueAtTime(Math.max(peak, SILENT), start + attack);\n  param.exponentialRampToValueAtTime(SILENT, start + attack + decay);\n}\n\nfunction voiceFor(target: SoundTarget, output: AudioNode): Voice {\n  const { context, when, pitch } = target;\n  // Partials above this only add hiss on small speakers, or alias near Nyquist.\n  const ceiling = Math.min(12000, context.sampleRate * 0.45);\n\n  const tone: Voice[\"tone\"] = ({ type = \"sine\", freq, to, glide, bend, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const osc = context.createOscillator();\n    const amp = context.createGain();\n    osc.type = type;\n    const base = freq * pitch;\n    osc.frequency.setValueAtTime(base * (bend ?? 1), start);\n    if (bend !== undefined) osc.frequency.exponentialRampToValueAtTime(base, start + SETTLE);\n    if (to !== undefined) {\n      osc.frequency.exponentialRampToValueAtTime(to * pitch, start + Math.max(glide ?? attack + decay, SETTLE));\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    osc.connect(amp).connect(output);\n    osc.start(start);\n    osc.stop(start + attack + decay + 0.02);\n  };\n\n  const noise: Voice[\"noise\"] = ({ filter = \"bandpass\", freq, to, q = 1, at = 0, attack = 0.002, decay, gain }) => {\n    const start = when + at;\n    const source = context.createBufferSource();\n    const shape = context.createBiquadFilter();\n    const amp = context.createGain();\n    source.buffer = noiseBuffer(context);\n    shape.type = filter;\n    shape.Q.value = q;\n    shape.frequency.setValueAtTime(freq * pitch, start);\n    if (to !== undefined) {\n      shape.frequency.exponentialRampToValueAtTime(to * pitch, start + attack + decay);\n    }\n    envelope(amp.gain, start, attack, decay, gain);\n    source.connect(shape).connect(amp).connect(output);\n    // A random offset into the buffer keeps each burst a little different.\n    source.start(start, Math.random() * 0.5);\n    source.stop(start + attack + decay + 0.02);\n  };\n\n  return {\n    tone,\n    noise,\n    click({ freq, q = 2, at = 0, decay = 0.005, gain }) {\n      // A little spread on the band, so no two contacts are identical.\n      noise({ freq: freq * (0.94 + Math.random() * 0.12), q, at, attack: 0.0005, decay, gain });\n    },\n    strike({ freq, material = \"plastic\", bend = 1.01, at = 0, decay, gain }) {\n      const { partials, damping } = typeof material === \"string\" ? MATERIALS[material] : material;\n      for (const [ratio, level] of partials) {\n        if (freq * ratio * pitch * bend > ceiling) continue;\n        tone({\n          // Real objects are never perfectly tuned; a hair of detune per partial.\n          freq: freq * ratio * (1 + (Math.random() * 2 - 1) * 0.003),\n          bend,\n          at,\n          attack: 0.001,\n          decay: decay / ratio ** damping,\n          gain: gain * level,\n        });\n      }\n    },\n  };\n}\n\n/** Turns a recipe into a playable sound. */\nexport function defineSound({ name, duration, vary = 0, room = 0.12, build }: SoundRecipe): Sound {\n  const render = (target: SoundTarget) => {\n    const { context, destination } = target;\n    const output = context.createGain();\n    output.gain.value = MASTER_GAIN * target.volume;\n    output.connect(destination);\n    if (room > 0) {\n      const send = context.createGain();\n      send.gain.value = room * ROOM_GAIN;\n      output.connect(send).connect(roomFor(context, destination));\n    }\n    build(voiceFor(target, output));\n  };\n\n  return {\n    name,\n    duration,\n    render,\n    play({ volume = 1, pitch = 1 } = {}) {\n      const context = getAudioContext();\n      if (!context || volume <= 0) return;\n      const spread = vary ? 1 + (Math.random() * 2 - 1) * vary : 1;\n      render({\n        context,\n        // The page-wide volume is applied there.\n        destination: audioOutput(context),\n        when: context.currentTime + 0.005,\n        volume,\n        pitch: pitch * spread,\n      });\n    },\n  };\n}\n"}]}