clicktone 2.0.0-dev.1 → 2.1.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,7 +6,7 @@ A lightweight helper for UI sound feedback. It wraps the Web Audio API with a ti
6
6
  - Reliable autoplay unlock: eager gesture listeners, synchronous resume, silent priming ping, re-resume on `visibilitychange`.
7
7
  - Self-healing on iOS/Safari: detects a "zombie" context after tab/app switch or lock-screen and transparently rebuilds it on the next interaction.
8
8
  - Automatic format fallback via `canPlayType` (great for Safari, which dislikes OGG/Opus).
9
- - Shared decode cache, throttling, volume control, and subtle pitch variation.
9
+ - Shared decode cache, throttling, volume control, loop playback, stop control, and subtle pitch variation.
10
10
  - Event-based (`EventTarget`) with a typed `on()` / `once()` API; `play()` also returns a `Promise`.
11
11
  - [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
12
12
 
@@ -83,6 +83,7 @@ onBeforeUnmount(() => {
83
83
  const off = sound.on('end', () => console.log('finished'));
84
84
  sound.on('error', (error) => console.error(error));
85
85
  sound.once('unlock', () => console.log('audio unlocked'));
86
+ sound.on('stop', () => console.log('stopped'));
86
87
 
87
88
  off();
88
89
 
@@ -90,13 +91,14 @@ off();
90
91
  await sound.play();
91
92
  ```
92
93
 
93
- | Event | Detail | Fired when |
94
- |:---------|:--------------|:-------------------------------------------|
95
- | `play` | — | A buffer source has started. |
96
- | `end` | — | Playback finished. |
97
- | `unlock` | — | The shared `AudioContext` became playable. |
98
- | `load` | `AudioBuffer` | A source was fetched and decoded. |
99
- | `error` | `Error` | Loading, decoding, or playback failed. |
94
+ | Event | Detail | Fired when |
95
+ |:---------|:--------------|:--------------------------------------------|
96
+ | `play` | — | A buffer source has started. |
97
+ | `end` | — | Playback finished naturally. |
98
+ | `stop` | — | Active playback was stopped explicitly. |
99
+ | `unlock` | — | The shared `AudioContext` became playable. |
100
+ | `load` | `AudioBuffer` | A source was fetched and decoded. |
101
+ | `error` | `Error` | Loading, decoding, or playback failed. |
100
102
 
101
103
  ## iOS / Safari unlock
102
104
 
@@ -127,14 +129,20 @@ document.addEventListener('pointerdown', () => ClickTone.unlock(), { once: true
127
129
  | `throttle` | `number` | `0` | Debounce interval in ms. Requests arriving sooner are ignored. |
128
130
  | `pitchVariation` | `number` | `0` | `0`–`1`. Random playback-rate jitter so repeated clicks don't sound identical. |
129
131
  | `preload` | `boolean` | `false` | Fetch and decode the buffer on construction. |
132
+ | `loop` | `boolean` | `false` | Keep playback running until `stop()` is called. |
133
+ | `replay` | `'overlap' \| 'interrupt' \| 'ignore-if-playing' \| 'restart'` | `'overlap'` | Behavior when `play()` is called while this instance is already playing. |
130
134
  | `debug` | `boolean` | `false` | Log internal errors to the console (in addition to the `error` event). |
131
135
 
132
136
  ## Methods
133
137
 
134
138
  ```ts
135
139
  await sound.play(); // optionally play(src) to override the source
140
+ await sound.play({ loop: true });
141
+ await sound.play({ src: '/win.mp3', replay: 'interrupt' });
136
142
  await sound.preload(); // optionally preload(src)
137
143
  sound.unlock();
144
+ sound.stop();
145
+ sound.playing; // whether this instance has active playback
138
146
  sound.setVolume(0.5); // smoothly ramped
139
147
  sound.setMuted(true);
140
148
  sound.toggleMuted();
@@ -145,6 +153,50 @@ ClickTone.unlock(); // static: unlock the shared context
145
153
  ClickTone.unlocked; // static: whether the shared context is unlocked
146
154
  ```
147
155
 
156
+ ### Replay behavior
157
+
158
+ - `overlap` (default): preserve classic SFX behavior — every accepted `play()` call starts another buffer source.
159
+ - `interrupt`: stop active playback, then start the requested sound.
160
+ - `ignore-if-playing`: ignore the request while this instance is already playing.
161
+ - `restart`: stop active playback and start again, bypassing `throttle`.
162
+
163
+ For looped playback, `play()` resolves after the loop starts rather than waiting forever for a natural end. Use `stop()` to end it.
164
+
165
+ ## Interruptible sounds / game patterns
166
+
167
+ Use one `ClickTone` instance for a long-running process sound and separate instances for terminal SFX:
168
+
169
+ ```ts
170
+ const flying = new ClickTone({
171
+ src: new URL('./assets/flying.mp3', import.meta.url).href,
172
+ loop: true,
173
+ preload: true,
174
+ });
175
+
176
+ const bonus = new ClickTone({
177
+ src: new URL('./assets/bonus.mp3', import.meta.url).href,
178
+ preload: true,
179
+ });
180
+
181
+ await flying.play(); // resolves once the loop starts
182
+
183
+ // Later, when the player wins:
184
+ flying.stop();
185
+ await bonus.play();
186
+ ```
187
+
188
+ You can also encode the interruption policy on a single instance:
189
+
190
+ ```ts
191
+ const terminal = new ClickTone({
192
+ src: new URL('./assets/explosion.mp3', import.meta.url).href,
193
+ replay: 'interrupt',
194
+ preload: true,
195
+ });
196
+
197
+ await terminal.play();
198
+ ```
199
+
148
200
  ## License
149
201
 
150
202
  MIT
package/dist/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var w=["pointerdown","pointerup","touchstart","touchend","keydown"],p={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},c=typeof window<"u"&&typeof document<"u",u=()=>{},y=()=>{if(!c)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},l=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,g=class f{static#a=200;#i=null;#t=!1;#n=!1;#s=!1;#c=!1;#u=new Map;#l=new Set;get unlocked(){return this.#t}prime(){this.#n||!c||(this.#n=!0,this.#w(),this.#m())}context(){if(this.#i||!c)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#s&&this.#h();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#o():this.#r();return}t.resume().then(()=>{this.#t?this.#o():this.#r()}).catch(u)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#e(t))return this.#t?this.#o():this.#r(),!0;try{await t.resume()}catch{}return this.#e(t)?(this.#t?this.#o():this.#r(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#e(t){return t.state==="running"}async#d(){if(this.#c||this.#s)return;const t=this.#i;if(!(!t||!this.#t)){this.#c=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#s=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,f.#a)),t.state==="running"&&t.currentTime<=i&&(this.#s=!0)}finally{this.#c=!1}}}#h(){this.#s=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(u);const i=this.context();i&&i.resume().then(()=>this.#o()).catch(u)}onUnlock(t){if(this.#t){t();return}this.#l.add(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const s=await fetch(t);if(!s.ok)throw new Error(`Failed to fetch "${t}": ${s.status} ${s.statusText}`);return n.decodeAudioData(await s.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#r(){if(this.#t)return;this.#t=!0,this.#o();const t=[...this.#l];this.#l.clear(),t.forEach(i=>{i()})}#o(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#w(){const t={passive:!0,capture:!0},i=()=>this.unlock();w.forEach(n=>{window.addEventListener(n,i,t)})}#m(){const t=y(),i=()=>{if(this.#t){if(t){this.#d();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},a=new g,v=e=>{const t=e.split(/[?#]/,1)[0];return p[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},m=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(c&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(c&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!c)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return m(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},d=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(m);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!c)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const s=r.type??v(r.src);if(!s)continue;const o=i.canPlayType(s);if(o==="probably")return r.src;o==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},E=class extends EventTarget{#a=null;#i=null;#t;#n;#s;#c;#u;#l=0;#e=null;#d=!1;#h=null;#r=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:s=!1,debug:o=!1}){super(),this.#t=l(t),this.#n=i,this.#s=Math.max(0,n),this.#c=Math.min(1,Math.max(0,r)),this.#u=o;try{this.#a=d(e)}catch(h){this.#i=h}a.prime(),a.onUnlock(()=>this.#f("unlock")),typeof document<"u"&&(this.#h=()=>{document.hidden||(this.#d=!0)},document.addEventListener("visibilitychange",this.#h)),s&&this.preload()}static unlock(){a.prime(),a.unlock()}static get unlocked(){return a.unlocked}get volume(){return this.#t}get muted(){return this.#n}async preload(){if(!(this.#r||!this.#a))try{const e=await a.decode(this.#a);return this.#f("load",e),e}catch(e){this.#p(e);return}}unlock(){a.unlock()}setVolume(e){this.#t=l(e),this.#e&&!this.#n&&this.#m(this.#t)}setMuted(e){this.#n=e,this.#e&&this.#m(e?0:this.#t),e||a.unlock()}toggleMuted(){return this.setMuted(!this.#n),this.#n}async play(e){if(this.#r)return;const t=Date.now();if(t-this.#l<this.#s)return;this.#l=t,a.unlock();let i;try{i=e?d(e):this.#o()}catch(n){this.#p(n);return}try{const n=await a.ensureRunning();if(!n||this.#r)return;if(n.state!=="running")throw new Error("AudioContext is not running.");const r=await a.decode(i);n.state!=="running"&&await n.resume().catch(u);const s=this.#w(n),o=n.createBufferSource();o.buffer=r,this.#c>0&&(o.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#c)),o.connect(s),this.#f("play"),await new Promise(h=>{o.onended=()=>{o.disconnect(),h()},o.start(0)}),this.#f("end")}catch(n){this.#p(n)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#r||(this.#r=!0,this.#h&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#h),this.#h=null),this.#e?.disconnect(),this.#e=null)}#o(){if(this.#a)return this.#a;throw this.#i??new Error("No valid sound source.")}#w(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#n?0:this.#t,this.#e.connect(e.destination),this.#d=!1):this.#d&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#d=!1),this.#e}#m(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#f(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#p(e){this.#u,this.#f("error",e)}};exports.ClickTone=E;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var E=["pointerdown","pointerup","touchstart","touchend","keydown"],b={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},h=typeof window<"u"&&typeof document<"u",u=()=>{},k=()=>{if(!h)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},p=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,T=class y{static#c=200;#i=null;#t=!1;#r=!1;#o=!1;#h=!1;#u=new Map;#d=new Set;#f=new Set;get unlocked(){return this.#t}prime(){this.#r||!h||(this.#r=!0,this.#y(),this.#a())}context(){if(this.#i||!h)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#o&&this.#l();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#n():this.#s();return}t.resume().then(()=>{this.#t?this.#n():this.#s()}).catch(u)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#m(t))return this.#t?this.#n():this.#s(),!0;try{await t.resume()}catch{}return this.#m(t)?(this.#t?this.#n():this.#s(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#m(t){return t.state==="running"}async#e(){if(this.#h||this.#o)return;const t=this.#i;if(!(!t||!this.#t)){this.#h=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#o=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,y.#c)),t.state==="running"&&t.currentTime<=i&&(this.#o=!0)}finally{this.#h=!1}}}#l(){this.#o=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(u);const i=this.context();i&&([...this.#f].forEach(n=>{n()}),i.resume().then(()=>this.#n()).catch(u))}onUnlock(t){if(this.#t){t();return}this.#d.add(t)}onRecreate(t){return this.#f.add(t),()=>this.#f.delete(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);return n.decodeAudioData(await o.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#s(){if(this.#t)return;this.#t=!0,this.#n();const t=[...this.#d];this.#d.clear(),t.forEach(i=>{i()})}#n(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#y(){const t={passive:!0,capture:!0},i=()=>this.unlock();E.forEach(n=>{window.addEventListener(n,i,t)})}#a(){const t=k(),i=()=>{if(this.#t){if(t){this.#e();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},a=new T,x=e=>{const t=e.split(/[?#]/,1)[0];return b[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},w=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(h&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(h&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!h)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return w(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},m=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(w);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!h)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const o=r.type??x(r.src);if(!o)continue;const s=i.canPlayType(o);if(s==="probably")return r.src;s==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},M=class extends EventTarget{#c=null;#i=null;#t;#r;#o;#h;#u;#d;#f;#m=0;#e=null;#l=new Set;#s=!1;#n=null;#y=null;#a=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:o=!1,loop:s=!1,replay:l="overlap",debug:d=!1}){super(),this.#t=p(t),this.#r=i,this.#o=Math.max(0,n),this.#h=Math.min(1,Math.max(0,r)),this.#u=s,this.#d=l,this.#f=d;try{this.#c=m(e)}catch(c){this.#i=c}a.prime(),a.onUnlock(()=>this.#p("unlock")),this.#y=a.onRecreate(()=>this.#x()),typeof document<"u"&&(this.#n=()=>{document.hidden||(this.#s=!0)},document.addEventListener("visibilitychange",this.#n)),o&&this.preload()}static unlock(){a.prime(),a.unlock()}static get unlocked(){return a.unlocked}get volume(){return this.#t}get muted(){return this.#r}get playing(){return this.#l.size>0}async preload(){if(!(this.#a||!this.#c))try{const e=await a.decode(this.#c);return this.#p("load",e),e}catch(e){this.#g(e);return}}unlock(){a.unlock()}setVolume(e){this.#t=p(e),this.#e&&!this.#r&&this.#b(this.#t)}setMuted(e){this.#r=e,this.#e&&this.#b(e?0:this.#t),e||a.unlock()}toggleMuted(){return this.setMuted(!this.#r),this.#r}async play(e){await this.#v(this.#k(e))}stop(){this.#w(!0)}async#v({src:e,loop:t=this.#u,replay:i=this.#d},{skipThrottle:n=!1}={}){if(this.#a||this.playing&&i==="ignore-if-playing")return;const r=Date.now();if(!n&&i!=="restart"&&r-this.#m<this.#o)return;this.playing&&(i==="interrupt"||i==="restart")&&this.#w(!0),this.#m=r,a.unlock();let o;try{o=e?m(e):this.#M()}catch(s){this.#g(s);return}try{const s=await a.ensureRunning();if(!s||this.#a)return;if(s.state!=="running")throw new Error("AudioContext is not running.");const l=await a.decode(o);s.state!=="running"&&await s.resume().catch(u);const d=this.#A(s),c=s.createBufferSource();c.buffer=l,c.loop=t,this.#h>0&&(c.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#h)),c.connect(d);const f={source:c,url:o,loop:t,stopped:!1};this.#l.add(f);const g=new Promise(v=>{c.onended=()=>{this.#E(f,!f.stopped),v()}});c.start(0),this.#p("play"),t||await g}catch(s){this.#g(s)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#a||(this.#a=!0,this.#w(!1),this.#n&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#n),this.#n=null),this.#y?.(),this.#y=null,this.#e?.disconnect(),this.#e=null)}#k(e){return this.#T(e)?e:{src:e}}#T(e){return typeof e=="object"&&e!==null&&("loop"in e||"replay"in e)}#w(e){const t=[...this.#l];t.length&&(t.forEach(i=>{i.stopped=!0;try{i.source.stop(0)}catch{}this.#E(i,!1)}),e&&this.#p("stop"))}#E(e,t){if(this.#l.delete(e)){try{e.source.disconnect()}catch{}t&&this.#p("end")}}#x(){if(this.#a)return;const e=[...this.#l].filter(t=>t.loop).map(t=>t.url);e.length&&(this.#w(!1),e.forEach(t=>{this.#v({src:t,loop:!0,replay:"overlap"},{skipThrottle:!0})}))}#M(){if(this.#c)return this.#c;throw this.#i??new Error("No valid sound source.")}#A(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#r?0:this.#t,this.#e.connect(e.destination),this.#s=!1):this.#s&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#s=!1),this.#e}#b(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#p(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#g(e){this.#f,this.#p("error",e)}};exports.ClickTone=M;
2
2
 
3
3
  //# sourceMappingURL=index.cjs.js.map
package/dist/index.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- export * from './main'
1
+ export * from './main.js'
2
2
  export {}
package/dist/index.es.js CHANGED
@@ -1,10 +1,10 @@
1
- var w = [
1
+ var E = [
2
2
  "pointerdown",
3
3
  "pointerup",
4
4
  "touchstart",
5
5
  "touchend",
6
6
  "keydown"
7
- ], p = {
7
+ ], b = {
8
8
  mp3: "audio/mpeg",
9
9
  m4a: "audio/mp4",
10
10
  mp4: "audio/mp4",
@@ -15,28 +15,29 @@ var w = [
15
15
  wav: "audio/wav",
16
16
  webm: "audio/webm",
17
17
  flac: "audio/flac"
18
- }, c = typeof window < "u" && typeof document < "u", h = () => {
19
- }, y = () => {
20
- if (!c) return !1;
21
- const e = navigator.userAgent, t = /iP(hone|ad|od)/.test(e) || navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1, i = /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);
18
+ }, h = typeof window < "u" && typeof document < "u", u = () => {
19
+ }, k = () => {
20
+ if (!h) return !1;
21
+ const e = navigator.userAgent, t = /iP(hone|ad|od)/.test(e) || /Macintosh/.test(e) && navigator.maxTouchPoints > 1, i = /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);
22
22
  return t || i;
23
- }, l = (e) => !Number.isFinite(e) || e < 0 ? 0 : e > 1 ? 1 : e, g = class f {
24
- static #a = 200;
23
+ }, p = (e) => !Number.isFinite(e) || e < 0 ? 0 : e > 1 ? 1 : e, x = class w {
24
+ static #c = 200;
25
25
  #i = null;
26
26
  #t = !1;
27
- #n = !1;
28
- #s = !1;
29
- #c = !1;
30
- #h = /* @__PURE__ */ new Map();
31
- #l = /* @__PURE__ */ new Set();
27
+ #r = !1;
28
+ #o = !1;
29
+ #h = !1;
30
+ #u = /* @__PURE__ */ new Map();
31
+ #d = /* @__PURE__ */ new Set();
32
+ #f = /* @__PURE__ */ new Set();
32
33
  get unlocked() {
33
34
  return this.#t;
34
35
  }
35
36
  prime() {
36
- this.#n || !c || (this.#n = !0, this.#w(), this.#m());
37
+ this.#r || !h || (this.#r = !0, this.#w(), this.#a());
37
38
  }
38
39
  context() {
39
- if (this.#i || !c) return this.#i;
40
+ if (this.#i || !h) return this.#i;
40
41
  const t = window.AudioContext ?? window.webkitAudioContext;
41
42
  if (!t) return null;
42
43
  try {
@@ -47,91 +48,96 @@ var w = [
47
48
  return this.#i;
48
49
  }
49
50
  unlock() {
50
- this.#s && this.#u();
51
+ this.#o && this.#l();
51
52
  const t = this.context();
52
53
  if (t) {
53
54
  if (t.state === "running") {
54
- this.#t ? this.#o() : this.#r();
55
+ this.#t ? this.#n() : this.#s();
55
56
  return;
56
57
  }
57
58
  t.resume().then(() => {
58
- this.#t ? this.#o() : this.#r();
59
- }).catch(h);
59
+ this.#t ? this.#n() : this.#s();
60
+ }).catch(u);
60
61
  }
61
62
  }
62
63
  async ensureRunning() {
63
64
  const t = this.context();
64
65
  if (!t) return null;
65
66
  const i = async () => {
66
- if (this.#e(t))
67
- return this.#t ? this.#o() : this.#r(), !0;
67
+ if (this.#m(t))
68
+ return this.#t ? this.#n() : this.#s(), !0;
68
69
  try {
69
70
  await t.resume();
70
71
  } catch {
71
72
  }
72
- return this.#e(t) ? (this.#t ? this.#o() : this.#r(), !0) : !1;
73
+ return this.#m(t) ? (this.#t ? this.#n() : this.#s(), !0) : !1;
73
74
  };
74
75
  return await i() || (await new Promise((n) => setTimeout(n, 120)), await i()) || (await new Promise((n) => setTimeout(n, 600)), await i()), t;
75
76
  }
76
- #e(t) {
77
+ #m(t) {
77
78
  return t.state === "running";
78
79
  }
79
- async #d() {
80
- if (this.#c || this.#s) return;
80
+ async #e() {
81
+ if (this.#h || this.#o) return;
81
82
  const t = this.#i;
82
83
  if (!(!t || !this.#t)) {
83
- this.#c = !0;
84
+ this.#h = !0;
84
85
  try {
85
86
  if (t.state !== "running") try {
86
87
  await t.resume();
87
88
  } catch {
88
89
  }
89
90
  if (t.state !== "running") {
90
- this.#s = !0;
91
+ this.#o = !0;
91
92
  return;
92
93
  }
93
94
  const i = t.currentTime;
94
- await new Promise((n) => setTimeout(n, f.#a)), t.state === "running" && t.currentTime <= i && (this.#s = !0);
95
+ await new Promise((n) => setTimeout(n, w.#c)), t.state === "running" && t.currentTime <= i && (this.#o = !0);
95
96
  } finally {
96
- this.#c = !1;
97
+ this.#h = !1;
97
98
  }
98
99
  }
99
100
  }
100
- #u() {
101
- this.#s = !1;
101
+ #l() {
102
+ this.#o = !1;
102
103
  const t = this.#i;
103
- this.#i = null, this.#h.clear(), t && t.close().catch(h);
104
+ this.#i = null, this.#u.clear(), t && t.close().catch(u);
104
105
  const i = this.context();
105
- i && i.resume().then(() => this.#o()).catch(h);
106
+ i && ([...this.#f].forEach((n) => {
107
+ n();
108
+ }), i.resume().then(() => this.#n()).catch(u));
106
109
  }
107
110
  onUnlock(t) {
108
111
  if (this.#t) {
109
112
  t();
110
113
  return;
111
114
  }
112
- this.#l.add(t);
115
+ this.#d.add(t);
116
+ }
117
+ onRecreate(t) {
118
+ return this.#f.add(t), () => this.#f.delete(t);
113
119
  }
114
120
  decode(t) {
115
- const i = this.#h.get(t);
121
+ const i = this.#u.get(t);
116
122
  if (i) return i;
117
123
  const n = this.context();
118
124
  if (!n) return Promise.reject(/* @__PURE__ */ new Error("Web Audio API is not available."));
119
125
  const r = (async () => {
120
- const s = await fetch(t);
121
- if (!s.ok) throw new Error(`Failed to fetch "${t}": ${s.status} ${s.statusText}`);
122
- return n.decodeAudioData(await s.arrayBuffer());
126
+ const o = await fetch(t);
127
+ if (!o.ok) throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);
128
+ return n.decodeAudioData(await o.arrayBuffer());
123
129
  })();
124
- return this.#h.set(t, r), r.catch(() => this.#h.delete(t)), r;
130
+ return this.#u.set(t, r), r.catch(() => this.#u.delete(t)), r;
125
131
  }
126
- #r() {
132
+ #s() {
127
133
  if (this.#t) return;
128
- this.#t = !0, this.#o();
129
- const t = [...this.#l];
130
- this.#l.clear(), t.forEach((i) => {
134
+ this.#t = !0, this.#n();
135
+ const t = [...this.#d];
136
+ this.#d.clear(), t.forEach((i) => {
131
137
  i();
132
138
  });
133
139
  }
134
- #o() {
140
+ #n() {
135
141
  const t = this.#i;
136
142
  if (t)
137
143
  try {
@@ -147,15 +153,15 @@ var w = [
147
153
  passive: !0,
148
154
  capture: !0
149
155
  }, i = () => this.unlock();
150
- w.forEach((n) => {
156
+ E.forEach((n) => {
151
157
  window.addEventListener(n, i, t);
152
158
  });
153
159
  }
154
- #m() {
155
- const t = y(), i = () => {
160
+ #a() {
161
+ const t = k(), i = () => {
156
162
  if (this.#t) {
157
163
  if (t) {
158
- this.#d();
164
+ this.#e();
159
165
  return;
160
166
  }
161
167
  this.unlock(), setTimeout(() => this.unlock(), 120), setTimeout(() => this.unlock(), 600);
@@ -165,20 +171,20 @@ var w = [
165
171
  };
166
172
  document.addEventListener("visibilitychange", n), window.addEventListener("pageshow", i);
167
173
  }
168
- }, a = new g(), v = (e) => {
174
+ }, a = new x(), T = (e) => {
169
175
  const t = e.split(/[?#]/, 1)[0];
170
- return p[t.slice(t.lastIndexOf(".") + 1).toLowerCase()];
171
- }, m = (e) => {
176
+ return b[t.slice(t.lastIndexOf(".") + 1).toLowerCase()];
177
+ }, y = (e) => {
172
178
  if (typeof e == "string") return [{ src: e }];
173
179
  if (e instanceof URL) return [{ src: e.href }];
174
- if (c && e instanceof HTMLSourceElement) {
180
+ if (h && e instanceof HTMLSourceElement) {
175
181
  if (!e.src) throw new Error('<source> element has no "src" attribute.');
176
182
  return [{
177
183
  src: e.src,
178
184
  type: e.type || void 0
179
185
  }];
180
186
  }
181
- if (c && e instanceof HTMLAudioElement) {
187
+ if (h && e instanceof HTMLAudioElement) {
182
188
  const t = Array.from(e.querySelectorAll("source")).filter((i) => i.src).map((i) => ({
183
189
  src: i.src,
184
190
  type: i.type || void 0
@@ -188,10 +194,10 @@ var w = [
188
194
  throw new Error("<audio> element has no playable sources.");
189
195
  }
190
196
  if (typeof e == "object" && e !== null && "id" in e) {
191
- if (!c) throw new Error("Cannot resolve element by id outside the DOM.");
197
+ if (!h) throw new Error("Cannot resolve element by id outside the DOM.");
192
198
  const t = document.getElementById(String(e.id));
193
199
  if (!t) throw new Error(`No element found with id "${e.id}".`);
194
- if (t instanceof HTMLSourceElement || t instanceof HTMLAudioElement) return m(t);
200
+ if (t instanceof HTMLSourceElement || t instanceof HTMLAudioElement) return y(t);
195
201
  throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`);
196
202
  }
197
203
  if (typeof e == "object" && e !== null && "src" in e) {
@@ -202,43 +208,47 @@ var w = [
202
208
  }];
203
209
  }
204
210
  throw new Error("Invalid sound source.");
205
- }, d = (e) => {
206
- const t = (Array.isArray(e) ? e : [e]).flatMap(m);
211
+ }, m = (e) => {
212
+ const t = (Array.isArray(e) ? e : [e]).flatMap(y);
207
213
  if (!t.length) throw new Error("No sound source provided.");
208
- if (t.length === 1 || !c) return t[0].src;
214
+ if (t.length === 1 || !h) return t[0].src;
209
215
  const i = document.createElement("audio");
210
216
  let n = null;
211
217
  for (const r of t) {
212
- const s = r.type ?? v(r.src);
213
- if (!s) continue;
214
- const o = i.canPlayType(s);
215
- if (o === "probably") return r.src;
216
- o === "maybe" && n === null && (n = r.src);
218
+ const o = r.type ?? T(r.src);
219
+ if (!o) continue;
220
+ const s = i.canPlayType(o);
221
+ if (s === "probably") return r.src;
222
+ s === "maybe" && n === null && (n = r.src);
217
223
  }
218
224
  return n ?? t[0].src;
219
- }, E = class extends EventTarget {
220
- #a = null;
225
+ }, M = class extends EventTarget {
226
+ #c = null;
221
227
  #i = null;
222
228
  #t;
223
- #n;
224
- #s;
225
- #c;
229
+ #r;
230
+ #o;
226
231
  #h;
227
- #l = 0;
232
+ #u;
233
+ #d;
234
+ #f;
235
+ #m = 0;
228
236
  #e = null;
229
- #d = !1;
230
- #u = null;
231
- #r = !1;
232
- constructor({ src: e, volume: t = 1, muted: i = !1, throttle: n = 0, pitchVariation: r = 0, preload: s = !1, debug: o = !1 }) {
233
- super(), this.#t = l(t), this.#n = i, this.#s = Math.max(0, n), this.#c = Math.min(1, Math.max(0, r)), this.#h = o;
237
+ #l = /* @__PURE__ */ new Set();
238
+ #s = !1;
239
+ #n = null;
240
+ #w = null;
241
+ #a = !1;
242
+ constructor({ src: e, volume: t = 1, muted: i = !1, throttle: n = 0, pitchVariation: r = 0, preload: o = !1, loop: s = !1, replay: l = "overlap", debug: d = !1 }) {
243
+ super(), this.#t = p(t), this.#r = i, this.#o = Math.max(0, n), this.#h = Math.min(1, Math.max(0, r)), this.#u = s, this.#d = l, this.#f = d;
234
244
  try {
235
- this.#a = d(e);
236
- } catch (u) {
237
- this.#i = u;
245
+ this.#c = m(e);
246
+ } catch (c) {
247
+ this.#i = c;
238
248
  }
239
- a.prime(), a.onUnlock(() => this.#f("unlock")), typeof document < "u" && (this.#u = () => {
240
- document.hidden || (this.#d = !0);
241
- }, document.addEventListener("visibilitychange", this.#u)), s && this.preload();
249
+ a.prime(), a.onUnlock(() => this.#p("unlock")), this.#w = a.onRecreate(() => this.#T()), typeof document < "u" && (this.#n = () => {
250
+ document.hidden || (this.#s = !0);
251
+ }, document.addEventListener("visibilitychange", this.#n)), o && this.preload();
242
252
  }
243
253
  static unlock() {
244
254
  a.prime(), a.unlock();
@@ -250,15 +260,18 @@ var w = [
250
260
  return this.#t;
251
261
  }
252
262
  get muted() {
253
- return this.#n;
263
+ return this.#r;
264
+ }
265
+ get playing() {
266
+ return this.#l.size > 0;
254
267
  }
255
268
  async preload() {
256
- if (!(this.#r || !this.#a))
269
+ if (!(this.#a || !this.#c))
257
270
  try {
258
- const e = await a.decode(this.#a);
259
- return this.#f("load", e), e;
271
+ const e = await a.decode(this.#c);
272
+ return this.#p("load", e), e;
260
273
  } catch (e) {
261
- this.#p(e);
274
+ this.#g(e);
262
275
  return;
263
276
  }
264
277
  }
@@ -266,40 +279,55 @@ var w = [
266
279
  a.unlock();
267
280
  }
268
281
  setVolume(e) {
269
- this.#t = l(e), this.#e && !this.#n && this.#m(this.#t);
282
+ this.#t = p(e), this.#e && !this.#r && this.#b(this.#t);
270
283
  }
271
284
  setMuted(e) {
272
- this.#n = e, this.#e && this.#m(e ? 0 : this.#t), e || a.unlock();
285
+ this.#r = e, this.#e && this.#b(e ? 0 : this.#t), e || a.unlock();
273
286
  }
274
287
  toggleMuted() {
275
- return this.setMuted(!this.#n), this.#n;
288
+ return this.setMuted(!this.#r), this.#r;
276
289
  }
277
290
  async play(e) {
278
- if (this.#r) return;
279
- const t = Date.now();
280
- if (t - this.#l < this.#s) return;
281
- this.#l = t, a.unlock();
282
- let i;
291
+ await this.#v(this.#k(e));
292
+ }
293
+ stop() {
294
+ this.#y(!0);
295
+ }
296
+ async #v({ src: e, loop: t = this.#u, replay: i = this.#d }, { skipThrottle: n = !1 } = {}) {
297
+ if (this.#a || this.playing && i === "ignore-if-playing") return;
298
+ const r = Date.now();
299
+ if (!n && i !== "restart" && r - this.#m < this.#o) return;
300
+ this.playing && (i === "interrupt" || i === "restart") && this.#y(!0), this.#m = r, a.unlock();
301
+ let o;
283
302
  try {
284
- i = e ? d(e) : this.#o();
285
- } catch (n) {
286
- this.#p(n);
303
+ o = e ? m(e) : this.#M();
304
+ } catch (s) {
305
+ this.#g(s);
287
306
  return;
288
307
  }
289
308
  try {
290
- const n = await a.ensureRunning();
291
- if (!n || this.#r) return;
292
- if (n.state !== "running") throw new Error("AudioContext is not running.");
293
- const r = await a.decode(i);
294
- n.state !== "running" && await n.resume().catch(h);
295
- const s = this.#w(n), o = n.createBufferSource();
296
- o.buffer = r, this.#c > 0 && (o.playbackRate.value = Math.max(0.5, 1 + (Math.random() * 2 - 1) * this.#c)), o.connect(s), this.#f("play"), await new Promise((u) => {
297
- o.onended = () => {
298
- o.disconnect(), u();
299
- }, o.start(0);
300
- }), this.#f("end");
301
- } catch (n) {
302
- this.#p(n);
309
+ const s = await a.ensureRunning();
310
+ if (!s || this.#a) return;
311
+ if (s.state !== "running") throw new Error("AudioContext is not running.");
312
+ const l = await a.decode(o);
313
+ s.state !== "running" && await s.resume().catch(u);
314
+ const d = this.#A(s), c = s.createBufferSource();
315
+ c.buffer = l, c.loop = t, this.#h > 0 && (c.playbackRate.value = Math.max(0.5, 1 + (Math.random() * 2 - 1) * this.#h)), c.connect(d);
316
+ const f = {
317
+ source: c,
318
+ url: o,
319
+ loop: t,
320
+ stopped: !1
321
+ };
322
+ this.#l.add(f);
323
+ const g = new Promise((v) => {
324
+ c.onended = () => {
325
+ this.#E(f, !f.stopped), v();
326
+ };
327
+ });
328
+ c.start(0), this.#p("play"), t || await g;
329
+ } catch (s) {
330
+ this.#g(s);
303
331
  }
304
332
  }
305
333
  on(e, t) {
@@ -311,34 +339,71 @@ var w = [
311
339
  this.addEventListener(e, i, { once: !0 });
312
340
  }
313
341
  destroy() {
314
- this.#r || (this.#r = !0, this.#u && typeof document < "u" && (document.removeEventListener("visibilitychange", this.#u), this.#u = null), this.#e?.disconnect(), this.#e = null);
342
+ this.#a || (this.#a = !0, this.#y(!1), this.#n && typeof document < "u" && (document.removeEventListener("visibilitychange", this.#n), this.#n = null), this.#w?.(), this.#w = null, this.#e?.disconnect(), this.#e = null);
343
+ }
344
+ #k(e) {
345
+ return this.#x(e) ? e : { src: e };
346
+ }
347
+ #x(e) {
348
+ return typeof e == "object" && e !== null && ("loop" in e || "replay" in e);
349
+ }
350
+ #y(e) {
351
+ const t = [...this.#l];
352
+ t.length && (t.forEach((i) => {
353
+ i.stopped = !0;
354
+ try {
355
+ i.source.stop(0);
356
+ } catch {
357
+ }
358
+ this.#E(i, !1);
359
+ }), e && this.#p("stop"));
360
+ }
361
+ #E(e, t) {
362
+ if (this.#l.delete(e)) {
363
+ try {
364
+ e.source.disconnect();
365
+ } catch {
366
+ }
367
+ t && this.#p("end");
368
+ }
369
+ }
370
+ #T() {
371
+ if (this.#a) return;
372
+ const e = [...this.#l].filter((t) => t.loop).map((t) => t.url);
373
+ e.length && (this.#y(!1), e.forEach((t) => {
374
+ this.#v({
375
+ src: t,
376
+ loop: !0,
377
+ replay: "overlap"
378
+ }, { skipThrottle: !0 });
379
+ }));
315
380
  }
316
- #o() {
317
- if (this.#a) return this.#a;
381
+ #M() {
382
+ if (this.#c) return this.#c;
318
383
  throw this.#i ?? /* @__PURE__ */ new Error("No valid sound source.");
319
384
  }
320
- #w(e) {
321
- return !this.#e || this.#e.context !== e ? (this.#e = e.createGain(), this.#e.gain.value = this.#n ? 0 : this.#t, this.#e.connect(e.destination), this.#d = !1) : this.#d && (this.#e.disconnect(), this.#e.connect(e.destination), this.#d = !1), this.#e;
385
+ #A(e) {
386
+ return !this.#e || this.#e.context !== e ? (this.#e = e.createGain(), this.#e.gain.value = this.#r ? 0 : this.#t, this.#e.connect(e.destination), this.#s = !1) : this.#s && (this.#e.disconnect(), this.#e.connect(e.destination), this.#s = !1), this.#e;
322
387
  }
323
- #m(e) {
388
+ #b(e) {
324
389
  const t = this.#e;
325
390
  if (!t) return;
326
391
  const i = t.context.currentTime;
327
392
  t.gain.cancelScheduledValues(i), t.gain.setValueAtTime(t.gain.value, i), t.gain.linearRampToValueAtTime(e, i + 0.015);
328
393
  }
329
- #f(e, t) {
394
+ #p(e, t) {
330
395
  if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(e, { detail: t }));
331
396
  else if (typeof Event < "u") {
332
397
  const i = new Event(e);
333
398
  i.detail = t, this.dispatchEvent(i);
334
399
  }
335
400
  }
336
- #p(e) {
337
- this.#h, this.#f("error", e);
401
+ #g(e) {
402
+ this.#f, this.#p("error", e);
338
403
  }
339
404
  };
340
405
  export {
341
- E as ClickTone
406
+ M as ClickTone
342
407
  };
343
408
 
344
409
  //# sourceMappingURL=index.es.js.map
package/dist/index.umd.js CHANGED
@@ -1,3 +1,3 @@
1
- (function(u,h){typeof exports=="object"&&typeof module<"u"?h(exports):typeof define=="function"&&define.amd?define(["exports"],h):(u=typeof globalThis<"u"?globalThis:u||self,h(u.ClickTone={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var h=["pointerdown","pointerup","touchstart","touchend","keydown"],y={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},c=typeof window<"u"&&typeof document<"u",l=()=>{},g=()=>{if(!c)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},f=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,v=class w{static#a=200;#i=null;#t=!1;#n=!1;#s=!1;#c=!1;#u=new Map;#l=new Set;get unlocked(){return this.#t}prime(){this.#n||!c||(this.#n=!0,this.#p(),this.#m())}context(){if(this.#i||!c)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#s&&this.#h();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#o():this.#r();return}t.resume().then(()=>{this.#t?this.#o():this.#r()}).catch(l)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#e(t))return this.#t?this.#o():this.#r(),!0;try{await t.resume()}catch{}return this.#e(t)?(this.#t?this.#o():this.#r(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#e(t){return t.state==="running"}async#d(){if(this.#c||this.#s)return;const t=this.#i;if(!(!t||!this.#t)){this.#c=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#s=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,w.#a)),t.state==="running"&&t.currentTime<=i&&(this.#s=!0)}finally{this.#c=!1}}}#h(){this.#s=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(l);const i=this.context();i&&i.resume().then(()=>this.#o()).catch(l)}onUnlock(t){if(this.#t){t();return}this.#l.add(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);return n.decodeAudioData(await o.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#r(){if(this.#t)return;this.#t=!0,this.#o();const t=[...this.#l];this.#l.clear(),t.forEach(i=>{i()})}#o(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#p(){const t={passive:!0,capture:!0},i=()=>this.unlock();h.forEach(n=>{window.addEventListener(n,i,t)})}#m(){const t=g(),i=()=>{if(this.#t){if(t){this.#d();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},s=new v,E=e=>{const t=e.split(/[?#]/,1)[0];return y[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},m=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(c&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(c&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!c)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return m(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},p=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(m);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!c)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const o=r.type??E(r.src);if(!o)continue;const a=i.canPlayType(o);if(a==="probably")return r.src;a==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},b=class extends EventTarget{#a=null;#i=null;#t;#n;#s;#c;#u;#l=0;#e=null;#d=!1;#h=null;#r=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:o=!1,debug:a=!1}){super(),this.#t=f(t),this.#n=i,this.#s=Math.max(0,n),this.#c=Math.min(1,Math.max(0,r)),this.#u=a;try{this.#a=p(e)}catch(d){this.#i=d}s.prime(),s.onUnlock(()=>this.#f("unlock")),typeof document<"u"&&(this.#h=()=>{document.hidden||(this.#d=!0)},document.addEventListener("visibilitychange",this.#h)),o&&this.preload()}static unlock(){s.prime(),s.unlock()}static get unlocked(){return s.unlocked}get volume(){return this.#t}get muted(){return this.#n}async preload(){if(!(this.#r||!this.#a))try{const e=await s.decode(this.#a);return this.#f("load",e),e}catch(e){this.#w(e);return}}unlock(){s.unlock()}setVolume(e){this.#t=f(e),this.#e&&!this.#n&&this.#m(this.#t)}setMuted(e){this.#n=e,this.#e&&this.#m(e?0:this.#t),e||s.unlock()}toggleMuted(){return this.setMuted(!this.#n),this.#n}async play(e){if(this.#r)return;const t=Date.now();if(t-this.#l<this.#s)return;this.#l=t,s.unlock();let i;try{i=e?p(e):this.#o()}catch(n){this.#w(n);return}try{const n=await s.ensureRunning();if(!n||this.#r)return;if(n.state!=="running")throw new Error("AudioContext is not running.");const r=await s.decode(i);n.state!=="running"&&await n.resume().catch(l);const o=this.#p(n),a=n.createBufferSource();a.buffer=r,this.#c>0&&(a.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#c)),a.connect(o),this.#f("play"),await new Promise(d=>{a.onended=()=>{a.disconnect(),d()},a.start(0)}),this.#f("end")}catch(n){this.#w(n)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#r||(this.#r=!0,this.#h&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#h),this.#h=null),this.#e?.disconnect(),this.#e=null)}#o(){if(this.#a)return this.#a;throw this.#i??new Error("No valid sound source.")}#p(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#n?0:this.#t,this.#e.connect(e.destination),this.#d=!1):this.#d&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#d=!1),this.#e}#m(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#f(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#w(e){this.#u,this.#f("error",e)}};u.ClickTone=b});
1
+ (function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.ClickTone={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var l=["pointerdown","pointerup","touchstart","touchend","keydown"],E={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},h=typeof window<"u"&&typeof document<"u",f=()=>{},b=()=>{if(!h)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},y=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,k=class v{static#c=200;#i=null;#t=!1;#r=!1;#o=!1;#h=!1;#u=new Map;#f=new Set;#d=new Set;get unlocked(){return this.#t}prime(){this.#r||!h||(this.#r=!0,this.#y(),this.#a())}context(){if(this.#i||!h)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#o&&this.#l();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#n():this.#s();return}t.resume().then(()=>{this.#t?this.#n():this.#s()}).catch(f)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#m(t))return this.#t?this.#n():this.#s(),!0;try{await t.resume()}catch{}return this.#m(t)?(this.#t?this.#n():this.#s(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#m(t){return t.state==="running"}async#e(){if(this.#h||this.#o)return;const t=this.#i;if(!(!t||!this.#t)){this.#h=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#o=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,v.#c)),t.state==="running"&&t.currentTime<=i&&(this.#o=!0)}finally{this.#h=!1}}}#l(){this.#o=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(f);const i=this.context();i&&([...this.#d].forEach(n=>{n()}),i.resume().then(()=>this.#n()).catch(f))}onUnlock(t){if(this.#t){t();return}this.#f.add(t)}onRecreate(t){return this.#d.add(t),()=>this.#d.delete(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);return n.decodeAudioData(await o.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#s(){if(this.#t)return;this.#t=!0,this.#n();const t=[...this.#f];this.#f.clear(),t.forEach(i=>{i()})}#n(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#y(){const t={passive:!0,capture:!0},i=()=>this.unlock();l.forEach(n=>{window.addEventListener(n,i,t)})}#a(){const t=b(),i=()=>{if(this.#t){if(t){this.#e();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},a=new k,T=e=>{const t=e.split(/[?#]/,1)[0];return E[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},w=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(h&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(h&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!h)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return w(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},g=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(w);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!h)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const o=r.type??T(r.src);if(!o)continue;const s=i.canPlayType(o);if(s==="probably")return r.src;s==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},x=class extends EventTarget{#c=null;#i=null;#t;#r;#o;#h;#u;#f;#d;#m=0;#e=null;#l=new Set;#s=!1;#n=null;#y=null;#a=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:o=!1,loop:s=!1,replay:d="overlap",debug:p=!1}){super(),this.#t=y(t),this.#r=i,this.#o=Math.max(0,n),this.#h=Math.min(1,Math.max(0,r)),this.#u=s,this.#f=d,this.#d=p;try{this.#c=g(e)}catch(c){this.#i=c}a.prime(),a.onUnlock(()=>this.#p("unlock")),this.#y=a.onRecreate(()=>this.#x()),typeof document<"u"&&(this.#n=()=>{document.hidden||(this.#s=!0)},document.addEventListener("visibilitychange",this.#n)),o&&this.preload()}static unlock(){a.prime(),a.unlock()}static get unlocked(){return a.unlocked}get volume(){return this.#t}get muted(){return this.#r}get playing(){return this.#l.size>0}async preload(){if(!(this.#a||!this.#c))try{const e=await a.decode(this.#c);return this.#p("load",e),e}catch(e){this.#g(e);return}}unlock(){a.unlock()}setVolume(e){this.#t=y(e),this.#e&&!this.#r&&this.#b(this.#t)}setMuted(e){this.#r=e,this.#e&&this.#b(e?0:this.#t),e||a.unlock()}toggleMuted(){return this.setMuted(!this.#r),this.#r}async play(e){await this.#v(this.#k(e))}stop(){this.#w(!0)}async#v({src:e,loop:t=this.#u,replay:i=this.#f},{skipThrottle:n=!1}={}){if(this.#a||this.playing&&i==="ignore-if-playing")return;const r=Date.now();if(!n&&i!=="restart"&&r-this.#m<this.#o)return;this.playing&&(i==="interrupt"||i==="restart")&&this.#w(!0),this.#m=r,a.unlock();let o;try{o=e?g(e):this.#M()}catch(s){this.#g(s);return}try{const s=await a.ensureRunning();if(!s||this.#a)return;if(s.state!=="running")throw new Error("AudioContext is not running.");const d=await a.decode(o);s.state!=="running"&&await s.resume().catch(f);const p=this.#A(s),c=s.createBufferSource();c.buffer=d,c.loop=t,this.#h>0&&(c.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#h)),c.connect(p);const m={source:c,url:o,loop:t,stopped:!1};this.#l.add(m);const M=new Promise(A=>{c.onended=()=>{this.#E(m,!m.stopped),A()}});c.start(0),this.#p("play"),t||await M}catch(s){this.#g(s)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#a||(this.#a=!0,this.#w(!1),this.#n&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#n),this.#n=null),this.#y?.(),this.#y=null,this.#e?.disconnect(),this.#e=null)}#k(e){return this.#T(e)?e:{src:e}}#T(e){return typeof e=="object"&&e!==null&&("loop"in e||"replay"in e)}#w(e){const t=[...this.#l];t.length&&(t.forEach(i=>{i.stopped=!0;try{i.source.stop(0)}catch{}this.#E(i,!1)}),e&&this.#p("stop"))}#E(e,t){if(this.#l.delete(e)){try{e.source.disconnect()}catch{}t&&this.#p("end")}}#x(){if(this.#a)return;const e=[...this.#l].filter(t=>t.loop).map(t=>t.url);e.length&&(this.#w(!1),e.forEach(t=>{this.#v({src:t,loop:!0,replay:"overlap"},{skipThrottle:!0})}))}#M(){if(this.#c)return this.#c;throw this.#i??new Error("No valid sound source.")}#A(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#r?0:this.#t,this.#e.connect(e.destination),this.#s=!1):this.#s&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#s=!1),this.#e}#b(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#p(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#g(e){this.#d,this.#p("error",e)}};u.ClickTone=x});
2
2
 
3
3
  //# sourceMappingURL=index.umd.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "2.0.0-dev.1",
3
+ "version": "2.1.0-dev.0",
4
4
  "description": "A lightweight helper for UI sound feedback. It wraps the Web Audio API with a tiny, event-based API and a rock-solid iOS/Safari unlock.",
5
5
  "author": "ux-ui.pro",
6
6
  "license": "MIT",