{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "sounds",
  "title": "goodui sounds",
  "description": "24 synthesized UI sounds with no audio files (tap, toggle, success, error, notify, celebrate…): Web Audio recipes, play(), useSound(), <SoundProvider> and data-sound attributes. Off until the visitor opts in.",
  "files": [
    {
      "path": "lib/sounds.ts",
      "content": "\"use client\"\n\nimport * as React from \"react\"\n\n/*\n * goodui sounds: synthesized UI sounds with no audio files.\n *\n * Every sound is a small recipe (two or three sine partials, a short filtered-noise click, an envelope) rendered\n * with the Web Audio API the moment it is played, so there is nothing to download and nothing to host.\n * Pitches sit on a C major pentatonic (C D E G A), attacks are soft and the master bus sits at about -14 dBFS,\n * so the kit stays polite in an office.\n *\n *   play(\"success\")                     play a named sound (does nothing until the user turned sounds on)\n *   useSound()                          { enabled, toggle, setEnabled, play } for a settings switch\n *   <SoundProvider enabled>             app default; the visitor's own choice (localStorage) wins\n *   <button data-sound=\"tap\">           any element gets a sound without code (data-sound-hover for hover)\n *   defineSound(\"cha-ching\", [...])     your own recipe; renderSound() renders one offline for tests\n *\n * Sounds are off by default and only ever start after a user gesture (browsers require it, people prefer it).\n * They are independent from prefers-reduced-motion: motion and sound are separate preferences.\n */\n\nexport type SoundName =\n  | \"tap\"\n  | \"toggle-on\"\n  | \"toggle-off\"\n  | \"success\"\n  | \"error\"\n  | \"warning\"\n  | \"notify\"\n  | \"send\"\n  | \"receive\"\n  | \"delete\"\n  | \"undo\"\n  | \"pop\"\n  | \"whoosh\"\n  | \"slide\"\n  | \"tick\"\n  | \"confirm\"\n  | \"open\"\n  | \"close\"\n  | \"hover\"\n  | \"drag-start\"\n  | \"drop\"\n  | \"count-tick\"\n  | \"celebrate\"\n  | \"unlock\"\n\n/** Every built-in sound, in display order. */\nexport const SOUND_NAMES: readonly SoundName[] = [\n  \"tap\",\n  \"toggle-on\",\n  \"toggle-off\",\n  \"success\",\n  \"error\",\n  \"warning\",\n  \"notify\",\n  \"send\",\n  \"receive\",\n  \"delete\",\n  \"undo\",\n  \"pop\",\n  \"whoosh\",\n  \"slide\",\n  \"tick\",\n  \"confirm\",\n  \"open\",\n  \"close\",\n  \"hover\",\n  \"drag-start\",\n  \"drop\",\n  \"count-tick\",\n  \"celebrate\",\n  \"unlock\",\n]\n\n/** One voice of a recipe: an oscillator partial or a filtered noise burst with its own envelope. */\nexport type Voice = {\n  /** Oscillator shape, or \"noise\" for filtered white noise. Default \"sine\". */\n  wave?: OscillatorType | \"noise\"\n  /** Start pitch in Hz (oscillators). */\n  freq?: number\n  /** Pitch to glide to, in Hz. */\n  to?: number\n  /** Seconds the pitch (or noise filter) glide takes. Defaults to `dur`. */\n  glide?: number\n  /** Start offset from the beginning of the sound, in seconds. */\n  at?: number\n  /** Length in seconds; the level decays exponentially to silence by then. */\n  dur: number\n  /** Peak level 0..1 before the master bus. */\n  gain?: number\n  /** Attack in seconds. Default 0.004; use 0.01–0.02 for a soft chord. */\n  attack?: number\n  /** Filter cutoff in Hz: a lowpass on oscillators, the bandpass center for noise. */\n  filter?: number\n  /** Cutoff to sweep to by the end of `glide`. */\n  filterTo?: number\n  /** Filter resonance. */\n  q?: number\n  /** Detune in cents. */\n  detune?: number\n}\n\nexport type Recipe = Voice[]\n\nexport type PlayOptions = {\n  /** 0..1, relative to the master bus. */\n  volume?: number\n  /** Pitch and speed multiplier: 1.2 is higher and shorter, 0.8 lower and longer. */\n  rate?: number\n  /** Play even while sounds are off (previews, a settings screen). */\n  force?: boolean\n}\n\n/** Master bus level, about -14 dBFS. */\nexport const MASTER_GAIN = 0.2\n\n/* ------------------------------------------------------------------ recipes */\n\n// C major pentatonic across the octaves the sounds use.\nconst C4 = 261.63\nconst E4 = 329.63\nconst G4 = 392\nconst A4 = 440\nconst C5 = 523.25\nconst D5 = 587.33\nconst E5 = 659.25\nconst G5 = 783.99\nconst A5 = 880\nconst C6 = 1046.5\nconst E6 = 1318.51\nconst A6 = 1760\n\n/**\n * A pitched note with its octave partial: the building block of most recipes.\n * `shine` is the level of the octave relative to the fundamental (0 for a pure sine).\n */\nexport function tone(\n  freq: number,\n  dur: number,\n  o: { at?: number; gain?: number; to?: number; glide?: number; wave?: OscillatorType; attack?: number; shine?: number } = {},\n): Voice[] {\n  const { at = 0, gain = 0.5, to, glide, wave = \"sine\", attack, shine = 0.22 } = o\n  const voices: Voice[] = [{ wave, freq, to, glide, at, dur, gain, attack }]\n  if (shine > 0) voices.push({ wave: \"sine\", freq: freq * 2, to: to ? to * 2 : undefined, glide, at, dur: dur * 0.7, gain: gain * shine, attack })\n  return voices\n}\n\n/** A short burst of filtered noise: clicks, thuds and whooshes. */\nexport function noise(dur: number, o: { at?: number; gain?: number; filter?: number; filterTo?: number; q?: number; attack?: number } = {}): Voice {\n  const { at = 0, gain = 0.2, filter = 2400, filterTo, q = 1, attack = 0.001 } = o\n  return { wave: \"noise\", at, dur, gain, filter, filterTo, q, attack }\n}\n\nexport const RECIPES: Record<SoundName, Recipe> = {\n  tap: [...tone(C6, 0.06, { gain: 0.42, to: A5, glide: 0.05, shine: 0.15 }), noise(0.012, { gain: 0.1, filter: 4000 })],\n  \"toggle-on\": [...tone(E5, 0.09, { gain: 0.38 }), ...tone(A5, 0.14, { at: 0.055, gain: 0.42 })],\n  \"toggle-off\": [...tone(A5, 0.09, { gain: 0.38 }), ...tone(E5, 0.14, { at: 0.055, gain: 0.38 })],\n  success: [...tone(C5, 0.16, { gain: 0.34 }), ...tone(E5, 0.16, { at: 0.07, gain: 0.36 }), ...tone(G5, 0.2, { at: 0.14, gain: 0.4 })],\n  error: [...tone(E4, 0.14, { gain: 0.4, wave: \"triangle\", shine: 0.1 }), ...tone(C4, 0.2, { at: 0.12, gain: 0.42, wave: \"triangle\", shine: 0.1 })],\n  warning: [...tone(G5, 0.08, { gain: 0.38, wave: \"triangle\", shine: 0.12 }), ...tone(G5, 0.12, { at: 0.13, gain: 0.38, wave: \"triangle\", shine: 0.12 })],\n  notify: [...tone(G5, 0.16, { gain: 0.36 }), ...tone(C6, 0.2, { at: 0.11, gain: 0.38 })],\n  send: [...tone(A4, 0.16, { gain: 0.34, to: A5, shine: 0.2 }), noise(0.14, { gain: 0.1, filter: 900, filterTo: 2600, attack: 0.02 })],\n  receive: [...tone(C6, 0.14, { gain: 0.32, to: G5, shine: 0.2 }), noise(0.018, { gain: 0.08, filter: 2500 })],\n  delete: [...tone(220, 0.14, { gain: 0.45, to: 110, shine: 0.1 }), noise(0.05, { gain: 0.12, filter: 500, q: 0.7 })],\n  undo: [...tone(220, 0.12, { gain: 0.36, to: 440, shine: 0.15 }), ...tone(E5, 0.1, { at: 0.1, gain: 0.28 })],\n  pop: [...tone(300, 0.07, { gain: 0.5, to: 1000, glide: 0.03, shine: 0.1, attack: 0.002 })],\n  whoosh: [noise(0.22, { gain: 0.24, filter: 300, filterTo: 2400, q: 0.9, attack: 0.06 })],\n  slide: [noise(0.16, { gain: 0.14, filter: 1800, filterTo: 500, q: 0.8, attack: 0.02 }), ...tone(G4, 0.12, { gain: 0.14, to: D5, shine: 0 })],\n  tick: [...tone(A6, 0.022, { gain: 0.3, shine: 0, attack: 0.001 }), noise(0.01, { gain: 0.1, filter: 5000 })],\n  confirm: [\n    ...tone(C5, 0.26, { gain: 0.26, attack: 0.012, shine: 0.15 }),\n    ...tone(E5, 0.26, { gain: 0.22, attack: 0.012, shine: 0.15 }),\n    ...tone(G5, 0.3, { gain: 0.24, attack: 0.012, shine: 0.15 }),\n  ],\n  open: [...tone(G4, 0.08, { gain: 0.3, shine: 0.15 }), ...tone(D5, 0.14, { at: 0.06, gain: 0.34, shine: 0.15 }), noise(0.12, { gain: 0.07, filter: 600, filterTo: 2000, q: 0.8, attack: 0.03 })],\n  close: [...tone(D5, 0.08, { gain: 0.3, shine: 0.15 }), ...tone(G4, 0.14, { at: 0.06, gain: 0.32, shine: 0.15 }), noise(0.12, { gain: 0.07, filter: 2000, filterTo: 500, q: 0.8, attack: 0.03 })],\n  hover: [...tone(1500, 0.012, { gain: 0.07, shine: 0, attack: 0.001 })],\n  \"drag-start\": [...tone(200, 0.09, { gain: 0.4, to: 420, shine: 0.1 }), noise(0.015, { gain: 0.07, filter: 2000 })],\n  drop: [...tone(320, 0.11, { gain: 0.42, to: 130, shine: 0.1 }), noise(0.035, { gain: 0.12, filter: 700, q: 0.7 })],\n  \"count-tick\": [...tone(E6, 0.014, { gain: 0.28, shine: 0, attack: 0.001 })],\n  celebrate: [\n    ...tone(C5, 0.14, { gain: 0.3, shine: 0.3 }),\n    ...tone(E5, 0.14, { at: 0.05, gain: 0.32, shine: 0.3 }),\n    ...tone(G5, 0.14, { at: 0.1, gain: 0.34, shine: 0.3 }),\n    ...tone(A5, 0.14, { at: 0.15, gain: 0.36, shine: 0.3 }),\n    ...tone(C6, 0.15, { at: 0.2, gain: 0.4, shine: 0.3 }),\n  ],\n  unlock: [noise(0.015, { gain: 0.18, filter: 2500 }), noise(0.015, { at: 0.06, gain: 0.18, filter: 3200 }), ...tone(E5, 0.2, { at: 0.11, gain: 0.3, attack: 0.008 }), ...tone(A5, 0.22, { at: 0.11, gain: 0.3, attack: 0.008 })],\n}\n\nconst custom = new Map<string, Recipe>()\n\n/** Add or replace a sound. Custom names play with `play(name)` and `data-sound={name}`. */\nexport function defineSound(name: string, recipe: Recipe) {\n  custom.set(name, recipe)\n}\n\nexport function recipeOf(name: string): Recipe | undefined {\n  return custom.get(name) ?? RECIPES[name as SoundName]\n}\n\n/** Length of a recipe in seconds at the given rate. */\nexport function durationOf(recipe: Recipe, rate = 1) {\n  return recipe.reduce((m, v) => Math.max(m, (v.at ?? 0) + v.dur), 0) / rate\n}\n\n/* ------------------------------------------------------------------- engine */\n\nconst noiseCache = new WeakMap<BaseAudioContext, AudioBuffer>()\n\n// Half a second of white noise from a fixed-seed LCG, so renders are reproducible.\nfunction noiseBuffer(ctx: BaseAudioContext) {\n  const cached = noiseCache.get(ctx)\n  if (cached) return cached\n  const len = Math.floor(ctx.sampleRate * 0.5)\n  const buffer = ctx.createBuffer(1, len, ctx.sampleRate)\n  const data = buffer.getChannelData(0)\n  let s = 0x2f6e2b1\n  for (let i = 0; i < len; i++) {\n    s = (Math.imul(s, 1664525) + 1013904223) >>> 0\n    data[i] = (s / 0xffffffff) * 2 - 1\n  }\n  noiseCache.set(ctx, buffer)\n  return buffer\n}\n\nconst clamp = (n: number, lo: number, hi: number) => Math.min(hi, Math.max(lo, n))\n\n/** Builds the audio graph of a recipe into `out` starting at `at` (context time). Used by play() and renderSound(). */\nexport function schedule(ctx: BaseAudioContext, out: AudioNode, recipe: Recipe, at: number, o: PlayOptions = {}) {\n  const rate = clamp(o.rate ?? 1, 0.25, 4)\n  const vol = clamp(o.volume ?? 1, 0, 1)\n  for (const v of recipe) {\n    const t0 = at + (v.at ?? 0) / rate\n    const dur = Math.max(0.005, v.dur / rate)\n    const attack = Math.min(dur * 0.5, Math.max(0.0015, (v.attack ?? 0.004) / rate))\n    const glide = Math.max(0.002, (v.glide ?? v.dur) / rate)\n    const peak = Math.max(0.0001, (v.gain ?? 0.5) * vol)\n\n    const env = ctx.createGain()\n    env.gain.setValueAtTime(0, t0)\n    env.gain.linearRampToValueAtTime(peak, t0 + attack)\n    env.gain.exponentialRampToValueAtTime(0.0004, t0 + dur)\n    env.gain.setValueAtTime(0, t0 + dur + 0.001)\n\n    let source: AudioScheduledSourceNode\n    let head: AudioNode\n    if (v.wave === \"noise\") {\n      const src = ctx.createBufferSource()\n      src.buffer = noiseBuffer(ctx)\n      src.loop = true\n      const filter = ctx.createBiquadFilter()\n      filter.type = \"bandpass\"\n      filter.Q.value = v.q ?? 1\n      filter.frequency.setValueAtTime(v.filter ?? 2400, t0)\n      if (v.filterTo) filter.frequency.exponentialRampToValueAtTime(v.filterTo, t0 + glide)\n      src.connect(filter)\n      source = src\n      head = filter\n    } else {\n      const osc = ctx.createOscillator()\n      osc.type = v.wave ?? \"sine\"\n      osc.frequency.setValueAtTime((v.freq ?? A4) * rate, t0)\n      if (v.to) osc.frequency.exponentialRampToValueAtTime(v.to * rate, t0 + glide)\n      if (v.detune) osc.detune.value = v.detune\n      source = osc\n      head = osc\n      if (v.filter) {\n        const filter = ctx.createBiquadFilter()\n        filter.type = \"lowpass\"\n        filter.frequency.value = v.filter\n        filter.Q.value = v.q ?? 0.7\n        osc.connect(filter)\n        head = filter\n      }\n    }\n    head.connect(env)\n    env.connect(out)\n    source.start(t0)\n    source.stop(t0 + dur + 0.02)\n    source.onended = () => {\n      head.disconnect()\n      env.disconnect()\n    }\n  }\n}\n\n/**\n * Renders a sound offline and returns the buffer: draw a waveform, or assert in tests that a recipe is neither\n * silent nor clipping. Includes the master bus, so levels match what play() produces at volume 1.\n */\nexport async function renderSound(name: string, o: PlayOptions = {}, sampleRate = 44100): Promise<AudioBuffer> {\n  const recipe = recipeOf(name)\n  if (!recipe) throw new Error(`Unknown sound \"${name}\"`)\n  const length = durationOf(recipe, clamp(o.rate ?? 1, 0.25, 4)) + 0.05\n  const ctx = new OfflineAudioContext(1, Math.ceil(length * sampleRate), sampleRate)\n  const master = ctx.createGain()\n  master.gain.value = MASTER_GAIN\n  master.connect(ctx.destination)\n  schedule(ctx, master, recipe, 0, o)\n  return ctx.startRendering()\n}\n\n/* -------------------------------------------------------------------- state */\n\nconst STORAGE_KEY = \"goodui-sound\"\n\nlet enabled = false\nlet loaded = false\nlet persist = true\nlet appDefault = false\nlet masterVolume = 1\nlet gestured = false\nlet listening = false\nlet ctx: AudioContext | null = null\nlet master: GainNode | null = null\nconst listeners = new Set<() => void>()\nconst lastPlayed = new Map<string, number>()\n\nfunction emit() {\n  for (const l of listeners) l()\n}\n\nfunction stored(): boolean | null {\n  try {\n    const v = localStorage.getItem(STORAGE_KEY)\n    return v === \"1\" ? true : v === \"0\" ? false : null\n  } catch {\n    return null\n  }\n}\n\n// Reads the visitor's saved choice once, outside render (never during hydration).\nfunction load() {\n  if (loaded || typeof window === \"undefined\") return\n  loaded = true\n  const choice = persist ? stored() : null\n  const next = choice ?? appDefault\n  if (next !== enabled) {\n    enabled = next\n    emit()\n  }\n}\n\nfunction hadGesture() {\n  if (gestured) return true\n  const nav = typeof navigator === \"undefined\" ? undefined : (navigator as Navigator & { userActivation?: { hasBeenActive: boolean } }).userActivation\n  return nav?.hasBeenActive === true\n}\n\nfunction context(): AudioContext | null {\n  if (ctx) return ctx\n  if (typeof window === \"undefined\") return null\n  const AC = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext\n  if (!AC) return null\n  ctx = new AC({ latencyHint: \"interactive\" })\n  master = ctx.createGain()\n  master.gain.value = MASTER_GAIN * masterVolume\n  master.connect(ctx.destination)\n  return ctx\n}\n\n// Creating or resuming the context inside the gesture keeps Safari happy; later plays can then happen any time.\nfunction warm() {\n  const c = context()\n  if (c && c.state === \"suspended\") c.resume().catch(() => {})\n}\n\nfunction listen() {\n  if (listening || typeof document === \"undefined\") return\n  listening = true\n  const onGesture = () => {\n    gestured = true\n    if (enabled) warm()\n  }\n  for (const type of [\"pointerdown\", \"keydown\", \"touchend\"]) document.addEventListener(type, onGesture, { capture: true, passive: true })\n}\n\n/** Whether the visitor has sounds on. */\nexport function isSoundEnabled() {\n  return enabled\n}\n\n/** Turn sounds on or off for this visitor (saved in localStorage unless the provider has persist={false}). */\nexport function setSoundEnabled(on: boolean) {\n  load()\n  if (persist) {\n    try {\n      localStorage.setItem(STORAGE_KEY, on ? \"1\" : \"0\")\n    } catch {}\n  }\n  if (on === enabled) return\n  enabled = on\n  if (on && hadGesture()) warm()\n  emit()\n}\n\nexport function subscribeSound(listener: () => void) {\n  listeners.add(listener)\n  listen()\n  load()\n  return () => {\n    listeners.delete(listener)\n  }\n}\n\n/** Master volume 0..1 on top of the -14 dBFS bus. */\nexport function setSoundVolume(volume: number) {\n  masterVolume = clamp(volume, 0, 1)\n  if (master) master.gain.value = MASTER_GAIN * masterVolume\n}\n\n/**\n * Plays a sound. Returns false when it did not play: sounds are off, the page has not seen a user gesture yet,\n * the name is unknown or the browser has no Web Audio. The same sound is skipped within 25 ms, so a stepper\n * held down or a counter never stacks clicks.\n */\nexport function play(name: SoundName | (string & {}), o: PlayOptions = {}): boolean {\n  listen()\n  load()\n  if (!enabled && !o.force) return false\n  const recipe = recipeOf(name)\n  if (!recipe || !hadGesture()) return false\n  const c = context()\n  if (!c || !master) return false\n  const now = performance.now()\n  if (now - (lastPlayed.get(name) ?? -1000) < 25) return false\n  lastPlayed.set(name, now)\n  if (c.state === \"suspended\") c.resume().catch(() => {})\n  schedule(c, master, recipe, c.currentTime + 0.003, o)\n  return true\n}\n\n/* -------------------------------------------------------------------- react */\n\n/** Sound state for a settings switch or a header toggle. Safe during SSR (reports off). */\nexport function useSound() {\n  const on = React.useSyncExternalStore(subscribeSound, isSoundEnabled, () => false)\n  return React.useMemo(\n    () => ({\n      enabled: on,\n      play,\n      setEnabled: setSoundEnabled,\n      toggle: () => setSoundEnabled(!isSoundEnabled()),\n    }),\n    [on],\n  )\n}\n\nexport type SoundProviderProps = {\n  children?: React.ReactNode\n  /** Sounds on for visitors who have not chosen yet. Default false: people opt in. */\n  enabled?: boolean\n  /** Remember the visitor's choice in localStorage and let it win over `enabled`. Default true. */\n  persist?: boolean\n  /** Master volume 0..1. */\n  volume?: number\n  /** Listen for data-sound (click) and data-sound-hover (pointer enters) attributes anywhere on the page. Default true. */\n  attributes?: boolean\n}\n\nfunction installAttributes() {\n  const onClick = (e: Event) => {\n    const target = e.target as Element | null\n    const el = target?.closest?.(\"[data-sound]\")\n    if (!el || (el as HTMLButtonElement).disabled) return\n    const raw = el.getAttribute(\"data-sound\") || \"tap\"\n    if (raw === \"toggle\") {\n      // Read the state after the click: React has committed it by the time the event reaches the document.\n      const input = el instanceof HTMLInputElement ? el : el.querySelector(\"input\")\n      const checked = input ? input.checked : el.getAttribute(\"aria-checked\") === \"true\" || el.getAttribute(\"aria-pressed\") === \"true\"\n      play(checked ? \"toggle-on\" : \"toggle-off\")\n    } else play(raw)\n  }\n  const onOver = (e: Event) => {\n    const pe = e as PointerEvent\n    const target = pe.target as Element | null\n    const el = target?.closest?.(\"[data-sound-hover]\")\n    if (!el) return\n    const from = pe.relatedTarget as Node | null\n    if (from && el.contains(from)) return\n    play(el.getAttribute(\"data-sound-hover\") || \"hover\")\n  }\n  document.addEventListener(\"click\", onClick)\n  document.addEventListener(\"pointerover\", onOver)\n  return () => {\n    document.removeEventListener(\"click\", onClick)\n    document.removeEventListener(\"pointerover\", onOver)\n  }\n}\n\n/**\n * Mount once near the root. Sets the app default, the master volume and the data-sound attribute listener.\n * Components with a `sound` prop and play() work without it; the provider only adds defaults and attributes.\n */\nexport function SoundProvider({ children, enabled: enabledProp = false, persist: persistProp = true, volume = 1, attributes = true }: SoundProviderProps) {\n  React.useEffect(() => {\n    appDefault = enabledProp\n    persist = persistProp\n    setSoundVolume(volume)\n    listen()\n    const choice = persist ? stored() : null\n    loaded = true\n    const next = choice ?? enabledProp\n    if (next !== enabled) {\n      enabled = next\n      emit()\n    }\n  }, [enabledProp, persistProp, volume])\n\n  React.useEffect(() => (attributes ? installAttributes() : undefined), [attributes])\n\n  return React.createElement(React.Fragment, null, children)\n}\n",
      "type": "registry:lib",
      "target": "lib/goodui-sounds.ts"
    }
  ],
  "type": "registry:lib"
}