clicktone 1.8.0 → 2.0.0-dev.1

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
@@ -1,75 +1,150 @@
1
- <br>
2
- <p align="center"><strong>clicktone</strong></p>
1
+ # clicktone
3
2
 
4
- <div align="center">
3
+ 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
4
 
6
- [![npm](https://img.shields.io/npm/v/clicktone.svg?colorB=brightgreen)](https://www.npmjs.com/package/clicktone)
7
- [![GitHub package version](https://img.shields.io/github/package-json/v/ux-ui-pro/clicktone.svg)](https://github.com/ux-ui-pro/clicktone)
8
- [![NPM Downloads](https://img.shields.io/npm/dm/clicktone.svg?style=flat)](https://www.npmjs.org/package/clicktone)
5
+ - Single shared `AudioContext` for every instance (no iOS context-limit issues).
6
+ - Reliable autoplay unlock: eager gesture listeners, synchronous resume, silent priming ping, re-resume on `visibilitychange`.
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
+ - Automatic format fallback via `canPlayType` (great for Safari, which dislikes OGG/Opus).
9
+ - Shared decode cache, throttling, volume control, and subtle pitch variation.
10
+ - Event-based (`EventTarget`) with a typed `on()` / `once()` API; `play()` also returns a `Promise`.
11
+ - [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
9
12
 
10
- </div>
13
+ ## Install
11
14
 
12
- <p align="center">ClickTone is a lightweight helper for UI sound feedback. It wraps the Web Audio API, giving you instant click‑sounds with volume control, throttling, callbacks, and an iOS resume workaround.</p>
13
- <p align="center"><sup>1.2kB gzipped</sup></p>
14
- <p align="center"><a href="https://codepen.io/ux-ui/pen/yLwbmMr">Demo</a></p>
15
- <br>
16
-
17
- &#10148; **Install**
18
-
19
- ```console
15
+ ```bash
20
16
  yarn add clicktone
21
17
  ```
22
18
 
23
- <br>
19
+ ## Usage (TypeScript)
24
20
 
25
- &#10148; **Import**
26
-
27
- ```javascript
28
- import ClickTone from 'clicktone';
29
- ```
30
- <br>
21
+ ```ts
22
+ import { ClickTone } from 'clicktone';
31
23
 
32
- &#10148; **Usage**
24
+ const button = document.getElementById('clickBtn');
33
25
 
34
- ```html
35
- <audio preload="auto">
36
- <source id="click-source" src="./click.mp3" type="audio/mpeg" />
37
- <source src="./click.ogg" type="audio/ogg" />
38
- </audio>
39
- ```
26
+ if (!button) {
27
+ throw new Error('Demo DOM is not ready');
28
+ }
40
29
 
41
- ```javascript
42
30
  const sound = new ClickTone({
43
- // Any of the forms work:
44
- // file: './sound.mp3',
45
- // file: new URL('./sound.mp3', import.meta.url).href,
46
- // file: document.querySelector('#click-source') as HTMLSourceElement,
47
- file: { id: 'click-source' },
31
+ // A single source…
32
+ src: new URL('./assets/click.mp3', import.meta.url).href,
33
+
34
+ // …or a fallback list; the best supported format is picked automatically:
35
+ // src: ['./click.aac', './click.ogg', './click.mp3'],
48
36
 
49
37
  volume: 0.7,
50
38
  throttle: 100,
51
- callback: () => console.log('done'),
52
- debug: true,
39
+ pitchVariation: 0.08,
40
+ preload: true,
41
+ });
42
+
43
+ sound.on('error', (error) => console.error(error));
44
+ button.addEventListener('click', () => sound.play());
45
+ ```
46
+
47
+ The `src` option also accepts DOM elements: an `HTMLSourceElement`, an `HTMLAudioElement` (its child `<source>` elements become the fallback list), or `{ id }` referencing either of those by id.
48
+
49
+ ## Usage (Vue 3)
50
+
51
+ ```vue
52
+ <script setup lang="ts">
53
+ import { onBeforeUnmount, onMounted, shallowRef } from 'vue';
54
+ import { ClickTone } from 'clicktone';
55
+
56
+ const sound = shallowRef<ClickTone | null>(null);
57
+
58
+ onMounted(() => {
59
+ sound.value = new ClickTone({
60
+ src: new URL('./assets/click.mp3', import.meta.url).href,
61
+ volume: 0.7,
62
+ pitchVariation: 0.08,
63
+ preload: true,
64
+ });
65
+ });
66
+
67
+ onBeforeUnmount(() => {
68
+ sound.value?.destroy();
69
+ sound.value = null;
53
70
  });
71
+ </script>
72
+
73
+ <template>
74
+ <button @click="sound?.play()">Click</button>
75
+ </template>
76
+ ```
77
+
78
+ ## Events
54
79
 
55
- button.addEventListener('click', () => click.play());
80
+ `ClickTone` extends `EventTarget`. Subscribe with the typed `on()` / `once()` helpers (which return an unsubscribe function) or with native `addEventListener`.
81
+
82
+ ```ts
83
+ const off = sound.on('end', () => console.log('finished'));
84
+ sound.on('error', (error) => console.error(error));
85
+ sound.once('unlock', () => console.log('audio unlocked'));
86
+
87
+ off();
88
+
89
+ // play() also resolves when playback ends:
90
+ await sound.play();
56
91
  ```
57
- <sup>ClickTone uses the Web Audio API, which supports many audio file formats: MP3, WAV, OGG, AAC and others. Note that not all browsers support these formats.</sup>
58
- <br>
59
- <sup>Tip: you can also override the source at call‑time: click.play('./alt.wav').</sup>
60
- <br><br>
61
92
 
62
- &#10148; **Options**
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. |
100
+
101
+ ## iOS / Safari unlock
63
102
 
64
- | Option | Type | Default | Description |
65
- |:----------:|:-----------------------------------------------:|:-------:|:--------------------------------------------------------------------------------------------------------------------------------|
66
- | `file` | `string \| HTMLSourceElement \| { id: string }` | – | Audio source. Either a direct URL, an actual `<source>` element, or an object whose id maps to a `<source>` already in the DOM. |
67
- | `volume` | `number` | `1` | Playback volume `0`–`1`. |
68
- | `callback` | `((error?: Error) => void) \| null` | `null` | Called after playback ends or if an error occurs. |
69
- | `throttle` | `number` | `0` | Debounce interval in ms. Playback requests arriving sooner are ignored. |
70
- | `debug` | `boolean` | `false` | Log internal errors/warnings to the console. |
71
- <br>
103
+ Mobile browsers (especially Safari on iOS) block audio until the user interacts with the page, an `AudioContext` must be resumed synchronously inside a user gesture, and iOS caps the number of contexts you may create. ClickTone handles all of this:
104
+
105
+ - One shared `AudioContext` (with `latencyHint: 'interactive'`) — one unlock unlocks every instance.
106
+ - Global gesture listeners (`pointerdown` / `pointerup` / `touchstart` / `touchend` / `keydown`) resume the context on the first interaction anywhere on the page.
107
+ - A silent priming ping is played right after unlock, and the context is re-resumed on `visibilitychange`.
108
+ - Lifecycle recovery for Safari/iOS: after a tab switch, app switch, or lock-screen, WebKit can leave the context in a "zombie" state (it reports `running` but stays silent). ClickTone probes for this on return and, if the context is dead, rebuilds it inside the next user gesture — buffers re-decode and the gain graph rebinds automatically.
109
+ - Decoded buffers are cached and shared, so the first click is not delayed by the network.
110
+
111
+ Pass `preload: true` (or call `sound.preload()`) so the buffer is decoded ahead of the first click. Include an MP3/AAC source for Safari — OGG/Opus is not reliably supported there.
112
+
113
+ ```ts
114
+ await sound.preload();
115
+
116
+ // Or unlock the shared context on a known first interaction:
117
+ document.addEventListener('pointerdown', () => ClickTone.unlock(), { once: true });
118
+ ```
119
+
120
+ ## Options
121
+
122
+ | Option | Type | Default | Description |
123
+ |:-----------------|:--------------------------------------------------------------------------------------------|:-------:|:-----------------------------------------------------------------------------|
124
+ | `src` | `string \| URL \| {src,type?} \| {id} \| HTMLSourceElement \| HTMLAudioElement \| Array<…>` | — | Audio source(s). Pass an array to enable automatic format fallback. |
125
+ | `volume` | `number` | `1` | Playback volume `0`–`1`. |
126
+ | `muted` | `boolean` | `false` | Start muted. Toggle later via `setMuted()` / `toggleMuted()`. |
127
+ | `throttle` | `number` | `0` | Debounce interval in ms. Requests arriving sooner are ignored. |
128
+ | `pitchVariation` | `number` | `0` | `0`–`1`. Random playback-rate jitter so repeated clicks don't sound identical. |
129
+ | `preload` | `boolean` | `false` | Fetch and decode the buffer on construction. |
130
+ | `debug` | `boolean` | `false` | Log internal errors to the console (in addition to the `error` event). |
131
+
132
+ ## Methods
133
+
134
+ ```ts
135
+ await sound.play(); // optionally play(src) to override the source
136
+ await sound.preload(); // optionally preload(src)
137
+ sound.unlock();
138
+ sound.setVolume(0.5); // smoothly ramped
139
+ sound.setMuted(true);
140
+ sound.toggleMuted();
141
+ sound.on('end', () => {}); // on(type, fn) / once(type, fn)
142
+ sound.destroy();
143
+
144
+ ClickTone.unlock(); // static: unlock the shared context
145
+ ClickTone.unlocked; // static: whether the shared context is unlocked
146
+ ```
72
147
 
73
- &#10148; **License**
148
+ ## License
74
149
 
75
- clicktone is released under MIT license.
150
+ MIT
package/dist/index.cjs.js CHANGED
@@ -1 +1,3 @@
1
- "use strict";var s=Object.defineProperty;var a=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var n=(t,e,i)=>a(t,typeof e!="symbol"?e+"":e,i);module.exports=class{constructor({file:t,volume:e=1,callback:i=null,throttle:o=0,debug:r=!1}){n(this,"fileSource");n(this,"volume");n(this,"callback");n(this,"throttle");n(this,"debug");n(this,"lastClickTime");n(this,"audioCache");n(this,"audioContext");this.fileSource=t,this.volume=e,this.callback=i,this.throttle=o,this.debug=r,this.lastClickTime=0,this.audioCache={},this.audioContext=null}resolveFileUrl(t){if(typeof t=="string")return t;if(t instanceof HTMLSourceElement){if(!t.src)throw new Error('<source> element has no "src" attribute.');return t.src}if(typeof t=="object"&&t!==null&&"id"in t){const e=document.getElementById(String(t.id));if(!e)throw new Error(`No element found with id "${t.id}".`);if(!(e instanceof HTMLSourceElement))throw new Error(`Element with id "${t.id}" is not a <source> element.`);if(!e.src)throw new Error(`<source> element with id "${t.id}" has no "src" attribute.`);return e.src}throw new Error('Invalid "file" value. Expected string, HTMLSourceElement, or { id: string }.')}initAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.iOSFixAudioContext())}iOSFixAudioContext(){if(this.audioContext&&this.audioContext.state==="suspended"&&"ontouchstart"in window){const t=()=>{this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{document.body.removeEventListener("touchstart",t),document.body.removeEventListener("touchend",t)}).catch(e=>{this.debug})};document.body.addEventListener("touchstart",t,!1),document.body.addEventListener("touchend",t,!1)}}async fetchAndDecodeAudio(t){try{if(this.audioCache[t])return this.audioCache[t];const e=await fetch(t),i=await e.arrayBuffer(),o=await this.audioContext.decodeAudioData(i);return this.audioCache[t]=o,o}catch(e){throw this.debug,new Error(`Something went wrong when loading and decoding the audio: ${e.message}`)}}async playAudio(t){this.initAudioContext();try{const e=await this.fetchAndDecodeAudio(t),i=this.audioContext.createBufferSource(),o=this.audioContext.createGain();i.buffer=e,o.gain.value=this.volume,i.connect(o),o.connect(this.audioContext.destination),i.onended=()=>{this.callback&&this.callback()},i.start(0)}catch(e){throw this.debug,new Error(`Something went wrong while playing audio: ${e.message}`)}}throttleFn(t){return()=>{const e=Date.now();e-this.lastClickTime>=this.throttle&&(t().catch(i=>{this.debug}),this.lastClickTime=e)}}play(t){let e;try{e=this.resolveFileUrl(t??this.fileSource)}catch(o){if(this.callback)return void this.callback(o);throw o}const i=this.throttleFn(()=>this.playAudio(e));try{i()}catch(o){if(this.debug,!this.callback)throw o;this.callback(o)}}};
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;
2
+
3
+ //# sourceMappingURL=index.cjs.js.map
package/dist/index.d.ts CHANGED
@@ -1,33 +1,2 @@
1
- declare global {
2
- interface Window {
3
- webkitAudioContext?: typeof AudioContext;
4
- }
5
- }
6
- type FileSource = string | HTMLSourceElement | {
7
- id: string;
8
- };
9
- declare class ClickTone {
10
- private readonly fileSource;
11
- private readonly volume;
12
- private readonly callback;
13
- private readonly throttle;
14
- private readonly debug;
15
- private lastClickTime;
16
- private readonly audioCache;
17
- private audioContext;
18
- constructor({ file, volume, callback, throttle, debug, }: {
19
- file: FileSource;
20
- volume?: number;
21
- callback?: ((error?: Error) => void) | null;
22
- throttle?: number;
23
- debug?: boolean;
24
- });
25
- private resolveFileUrl;
26
- private initAudioContext;
27
- private iOSFixAudioContext;
28
- private fetchAndDecodeAudio;
29
- private playAudio;
30
- private throttleFn;
31
- play(file?: FileSource): void;
32
- }
33
- export default ClickTone;
1
+ export * from './main'
2
+ export {}
package/dist/index.es.js CHANGED
@@ -1,93 +1,344 @@
1
- var s = Object.defineProperty;
2
- var c = (r, t, e) => t in r ? s(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
3
- var n = (r, t, e) => c(r, typeof t != "symbol" ? t + "" : t, e);
4
- class h {
5
- constructor({ file: t, volume: e = 1, callback: o = null, throttle: i = 0, debug: a = !1 }) {
6
- n(this, "fileSource");
7
- n(this, "volume");
8
- n(this, "callback");
9
- n(this, "throttle");
10
- n(this, "debug");
11
- n(this, "lastClickTime");
12
- n(this, "audioCache");
13
- n(this, "audioContext");
14
- this.fileSource = t, this.volume = e, this.callback = o, this.throttle = i, this.debug = a, this.lastClickTime = 0, this.audioCache = {}, this.audioContext = null;
15
- }
16
- resolveFileUrl(t) {
17
- if (typeof t == "string") return t;
18
- if (t instanceof HTMLSourceElement) {
19
- if (!t.src) throw new Error('<source> element has no "src" attribute.');
20
- return t.src;
1
+ var w = [
2
+ "pointerdown",
3
+ "pointerup",
4
+ "touchstart",
5
+ "touchend",
6
+ "keydown"
7
+ ], p = {
8
+ mp3: "audio/mpeg",
9
+ m4a: "audio/mp4",
10
+ mp4: "audio/mp4",
11
+ aac: "audio/aac",
12
+ oga: "audio/ogg",
13
+ ogg: "audio/ogg",
14
+ opus: "audio/ogg; codecs=opus",
15
+ wav: "audio/wav",
16
+ webm: "audio/webm",
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);
22
+ return t || i;
23
+ }, l = (e) => !Number.isFinite(e) || e < 0 ? 0 : e > 1 ? 1 : e, g = class f {
24
+ static #a = 200;
25
+ #i = null;
26
+ #t = !1;
27
+ #n = !1;
28
+ #s = !1;
29
+ #c = !1;
30
+ #h = /* @__PURE__ */ new Map();
31
+ #l = /* @__PURE__ */ new Set();
32
+ get unlocked() {
33
+ return this.#t;
34
+ }
35
+ prime() {
36
+ this.#n || !c || (this.#n = !0, this.#w(), this.#m());
37
+ }
38
+ context() {
39
+ if (this.#i || !c) return this.#i;
40
+ const t = window.AudioContext ?? window.webkitAudioContext;
41
+ if (!t) return null;
42
+ try {
43
+ this.#i = new t({ latencyHint: "interactive" });
44
+ } catch {
45
+ this.#i = new t();
21
46
  }
22
- if (typeof t == "object" && t !== null && "id" in t) {
23
- const e = document.getElementById(String(t.id));
24
- if (!e) throw new Error(`No element found with id "${t.id}".`);
25
- if (!(e instanceof HTMLSourceElement)) throw new Error(`Element with id "${t.id}" is not a <source> element.`);
26
- if (!e.src) throw new Error(`<source> element with id "${t.id}" has no "src" attribute.`);
27
- return e.src;
47
+ return this.#i;
48
+ }
49
+ unlock() {
50
+ this.#s && this.#u();
51
+ const t = this.context();
52
+ if (t) {
53
+ if (t.state === "running") {
54
+ this.#t ? this.#o() : this.#r();
55
+ return;
56
+ }
57
+ t.resume().then(() => {
58
+ this.#t ? this.#o() : this.#r();
59
+ }).catch(h);
28
60
  }
29
- throw new Error('Invalid "file" value. Expected string, HTMLSourceElement, or { id: string }.');
30
- }
31
- initAudioContext() {
32
- this.audioContext || (this.audioContext = new (window.AudioContext || window.webkitAudioContext)(), this.iOSFixAudioContext());
33
- }
34
- iOSFixAudioContext() {
35
- if (this.audioContext && this.audioContext.state === "suspended" && "ontouchstart" in window) {
36
- const t = () => {
37
- this.audioContext.state === "suspended" && this.audioContext.resume().then(() => {
38
- document.body.removeEventListener("touchstart", t), document.body.removeEventListener("touchend", t);
39
- }).catch((e) => {
40
- this.debug;
41
- });
42
- };
43
- document.body.addEventListener("touchstart", t, !1), document.body.addEventListener("touchend", t, !1);
61
+ }
62
+ async ensureRunning() {
63
+ const t = this.context();
64
+ if (!t) return null;
65
+ const i = async () => {
66
+ if (this.#e(t))
67
+ return this.#t ? this.#o() : this.#r(), !0;
68
+ try {
69
+ await t.resume();
70
+ } catch {
71
+ }
72
+ return this.#e(t) ? (this.#t ? this.#o() : this.#r(), !0) : !1;
73
+ };
74
+ return await i() || (await new Promise((n) => setTimeout(n, 120)), await i()) || (await new Promise((n) => setTimeout(n, 600)), await i()), t;
75
+ }
76
+ #e(t) {
77
+ return t.state === "running";
78
+ }
79
+ async #d() {
80
+ if (this.#c || this.#s) return;
81
+ const t = this.#i;
82
+ if (!(!t || !this.#t)) {
83
+ this.#c = !0;
84
+ try {
85
+ if (t.state !== "running") try {
86
+ await t.resume();
87
+ } catch {
88
+ }
89
+ if (t.state !== "running") {
90
+ this.#s = !0;
91
+ return;
92
+ }
93
+ const i = t.currentTime;
94
+ await new Promise((n) => setTimeout(n, f.#a)), t.state === "running" && t.currentTime <= i && (this.#s = !0);
95
+ } finally {
96
+ this.#c = !1;
97
+ }
44
98
  }
45
99
  }
46
- async fetchAndDecodeAudio(t) {
47
- try {
48
- if (this.audioCache[t]) return this.audioCache[t];
49
- const e = await fetch(t), o = await e.arrayBuffer(), i = await this.audioContext.decodeAudioData(o);
50
- return this.audioCache[t] = i, i;
51
- } catch (e) {
52
- throw this.debug, new Error(`Something went wrong when loading and decoding the audio: ${e.message}`);
100
+ #u() {
101
+ this.#s = !1;
102
+ const t = this.#i;
103
+ this.#i = null, this.#h.clear(), t && t.close().catch(h);
104
+ const i = this.context();
105
+ i && i.resume().then(() => this.#o()).catch(h);
106
+ }
107
+ onUnlock(t) {
108
+ if (this.#t) {
109
+ t();
110
+ return;
53
111
  }
112
+ this.#l.add(t);
113
+ }
114
+ decode(t) {
115
+ const i = this.#h.get(t);
116
+ if (i) return i;
117
+ const n = this.context();
118
+ if (!n) return Promise.reject(/* @__PURE__ */ new Error("Web Audio API is not available."));
119
+ 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());
123
+ })();
124
+ return this.#h.set(t, r), r.catch(() => this.#h.delete(t)), r;
125
+ }
126
+ #r() {
127
+ if (this.#t) return;
128
+ this.#t = !0, this.#o();
129
+ const t = [...this.#l];
130
+ this.#l.clear(), t.forEach((i) => {
131
+ i();
132
+ });
133
+ }
134
+ #o() {
135
+ const t = this.#i;
136
+ if (t)
137
+ try {
138
+ const i = t.createBuffer(1, 1, Math.max(22050, t.sampleRate)), n = t.createBufferSource();
139
+ n.buffer = i;
140
+ const r = t.createGain();
141
+ r.gain.value = 1e-5, n.connect(r), r.connect(t.destination), n.start(0), n.stop(0);
142
+ } catch {
143
+ }
144
+ }
145
+ #w() {
146
+ const t = {
147
+ passive: !0,
148
+ capture: !0
149
+ }, i = () => this.unlock();
150
+ w.forEach((n) => {
151
+ window.addEventListener(n, i, t);
152
+ });
153
+ }
154
+ #m() {
155
+ const t = y(), i = () => {
156
+ if (this.#t) {
157
+ if (t) {
158
+ this.#d();
159
+ return;
160
+ }
161
+ this.unlock(), setTimeout(() => this.unlock(), 120), setTimeout(() => this.unlock(), 600);
162
+ }
163
+ }, n = () => {
164
+ document.hidden || !this.#t || i();
165
+ };
166
+ document.addEventListener("visibilitychange", n), window.addEventListener("pageshow", i);
167
+ }
168
+ }, a = new g(), v = (e) => {
169
+ const t = e.split(/[?#]/, 1)[0];
170
+ return p[t.slice(t.lastIndexOf(".") + 1).toLowerCase()];
171
+ }, m = (e) => {
172
+ if (typeof e == "string") return [{ src: e }];
173
+ if (e instanceof URL) return [{ src: e.href }];
174
+ if (c && e instanceof HTMLSourceElement) {
175
+ if (!e.src) throw new Error('<source> element has no "src" attribute.');
176
+ return [{
177
+ src: e.src,
178
+ type: e.type || void 0
179
+ }];
180
+ }
181
+ if (c && e instanceof HTMLAudioElement) {
182
+ const t = Array.from(e.querySelectorAll("source")).filter((i) => i.src).map((i) => ({
183
+ src: i.src,
184
+ type: i.type || void 0
185
+ }));
186
+ if (t.length) return t;
187
+ if (e.src) return [{ src: e.src }];
188
+ throw new Error("<audio> element has no playable sources.");
189
+ }
190
+ if (typeof e == "object" && e !== null && "id" in e) {
191
+ if (!c) throw new Error("Cannot resolve element by id outside the DOM.");
192
+ const t = document.getElementById(String(e.id));
193
+ if (!t) throw new Error(`No element found with id "${e.id}".`);
194
+ if (t instanceof HTMLSourceElement || t instanceof HTMLAudioElement) return m(t);
195
+ throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`);
196
+ }
197
+ if (typeof e == "object" && e !== null && "src" in e) {
198
+ if (!e.src) throw new Error('Source descriptor has an empty "src".');
199
+ return [{
200
+ src: e.src,
201
+ type: e.type
202
+ }];
54
203
  }
55
- async playAudio(t) {
56
- this.initAudioContext();
204
+ throw new Error("Invalid sound source.");
205
+ }, d = (e) => {
206
+ const t = (Array.isArray(e) ? e : [e]).flatMap(m);
207
+ if (!t.length) throw new Error("No sound source provided.");
208
+ if (t.length === 1 || !c) return t[0].src;
209
+ const i = document.createElement("audio");
210
+ let n = null;
211
+ 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);
217
+ }
218
+ return n ?? t[0].src;
219
+ }, E = class extends EventTarget {
220
+ #a = null;
221
+ #i = null;
222
+ #t;
223
+ #n;
224
+ #s;
225
+ #c;
226
+ #h;
227
+ #l = 0;
228
+ #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;
57
234
  try {
58
- const e = await this.fetchAndDecodeAudio(t), o = this.audioContext.createBufferSource(), i = this.audioContext.createGain();
59
- o.buffer = e, i.gain.value = this.volume, o.connect(i), i.connect(this.audioContext.destination), o.onended = () => {
60
- this.callback && this.callback();
61
- }, o.start(0);
62
- } catch (e) {
63
- throw this.debug, new Error(`Something went wrong while playing audio: ${e.message}`);
235
+ this.#a = d(e);
236
+ } catch (u) {
237
+ this.#i = u;
64
238
  }
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();
65
242
  }
66
- throttleFn(t) {
67
- return () => {
68
- const e = Date.now();
69
- e - this.lastClickTime >= this.throttle && (t().catch((o) => {
70
- this.debug;
71
- }), this.lastClickTime = e);
72
- };
243
+ static unlock() {
244
+ a.prime(), a.unlock();
245
+ }
246
+ static get unlocked() {
247
+ return a.unlocked;
248
+ }
249
+ get volume() {
250
+ return this.#t;
251
+ }
252
+ get muted() {
253
+ return this.#n;
254
+ }
255
+ async preload() {
256
+ if (!(this.#r || !this.#a))
257
+ try {
258
+ const e = await a.decode(this.#a);
259
+ return this.#f("load", e), e;
260
+ } catch (e) {
261
+ this.#p(e);
262
+ return;
263
+ }
264
+ }
265
+ unlock() {
266
+ a.unlock();
267
+ }
268
+ setVolume(e) {
269
+ this.#t = l(e), this.#e && !this.#n && this.#m(this.#t);
270
+ }
271
+ setMuted(e) {
272
+ this.#n = e, this.#e && this.#m(e ? 0 : this.#t), e || a.unlock();
273
+ }
274
+ toggleMuted() {
275
+ return this.setMuted(!this.#n), this.#n;
73
276
  }
74
- play(t) {
75
- let e;
277
+ 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;
76
283
  try {
77
- e = this.resolveFileUrl(t ?? this.fileSource);
78
- } catch (i) {
79
- if (this.callback) return void this.callback(i);
80
- throw i;
284
+ i = e ? d(e) : this.#o();
285
+ } catch (n) {
286
+ this.#p(n);
287
+ return;
81
288
  }
82
- const o = this.throttleFn(() => this.playAudio(e));
83
289
  try {
84
- o();
85
- } catch (i) {
86
- if (this.debug, !this.callback) throw i;
87
- this.callback(i);
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);
88
303
  }
89
304
  }
90
- }
305
+ on(e, t) {
306
+ const i = (n) => t(n.detail);
307
+ return this.addEventListener(e, i), () => this.removeEventListener(e, i);
308
+ }
309
+ once(e, t) {
310
+ const i = (n) => t(n.detail);
311
+ this.addEventListener(e, i, { once: !0 });
312
+ }
313
+ 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);
315
+ }
316
+ #o() {
317
+ if (this.#a) return this.#a;
318
+ throw this.#i ?? /* @__PURE__ */ new Error("No valid sound source.");
319
+ }
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;
322
+ }
323
+ #m(e) {
324
+ const t = this.#e;
325
+ if (!t) return;
326
+ const i = t.context.currentTime;
327
+ t.gain.cancelScheduledValues(i), t.gain.setValueAtTime(t.gain.value, i), t.gain.linearRampToValueAtTime(e, i + 0.015);
328
+ }
329
+ #f(e, t) {
330
+ if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(e, { detail: t }));
331
+ else if (typeof Event < "u") {
332
+ const i = new Event(e);
333
+ i.detail = t, this.dispatchEvent(i);
334
+ }
335
+ }
336
+ #p(e) {
337
+ this.#h, this.#f("error", e);
338
+ }
339
+ };
91
340
  export {
92
- h as default
341
+ E as ClickTone
93
342
  };
343
+
344
+ //# sourceMappingURL=index.es.js.map
package/dist/index.umd.js CHANGED
@@ -1 +1,3 @@
1
- (function(t,e){typeof exports=="object"&&typeof module<"u"?module.exports=e():typeof define=="function"&&define.amd?define(e):(t=typeof globalThis<"u"?globalThis:t||self).ClickTone=e()})(this,function(){"use strict";var s=Object.defineProperty;var a=(t,e,i)=>e in t?s(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i;var n=(t,e,i)=>a(t,typeof e!="symbol"?e+"":e,i);return class{constructor({file:t,volume:e=1,callback:i=null,throttle:o=0,debug:r=!1}){n(this,"fileSource");n(this,"volume");n(this,"callback");n(this,"throttle");n(this,"debug");n(this,"lastClickTime");n(this,"audioCache");n(this,"audioContext");this.fileSource=t,this.volume=e,this.callback=i,this.throttle=o,this.debug=r,this.lastClickTime=0,this.audioCache={},this.audioContext=null}resolveFileUrl(t){if(typeof t=="string")return t;if(t instanceof HTMLSourceElement){if(!t.src)throw new Error('<source> element has no "src" attribute.');return t.src}if(typeof t=="object"&&t!==null&&"id"in t){const e=document.getElementById(String(t.id));if(!e)throw new Error(`No element found with id "${t.id}".`);if(!(e instanceof HTMLSourceElement))throw new Error(`Element with id "${t.id}" is not a <source> element.`);if(!e.src)throw new Error(`<source> element with id "${t.id}" has no "src" attribute.`);return e.src}throw new Error('Invalid "file" value. Expected string, HTMLSourceElement, or { id: string }.')}initAudioContext(){this.audioContext||(this.audioContext=new(window.AudioContext||window.webkitAudioContext),this.iOSFixAudioContext())}iOSFixAudioContext(){if(this.audioContext&&this.audioContext.state==="suspended"&&"ontouchstart"in window){const t=()=>{this.audioContext.state==="suspended"&&this.audioContext.resume().then(()=>{document.body.removeEventListener("touchstart",t),document.body.removeEventListener("touchend",t)}).catch(e=>{this.debug})};document.body.addEventListener("touchstart",t,!1),document.body.addEventListener("touchend",t,!1)}}async fetchAndDecodeAudio(t){try{if(this.audioCache[t])return this.audioCache[t];const e=await fetch(t),i=await e.arrayBuffer(),o=await this.audioContext.decodeAudioData(i);return this.audioCache[t]=o,o}catch(e){throw this.debug,new Error(`Something went wrong when loading and decoding the audio: ${e.message}`)}}async playAudio(t){this.initAudioContext();try{const e=await this.fetchAndDecodeAudio(t),i=this.audioContext.createBufferSource(),o=this.audioContext.createGain();i.buffer=e,o.gain.value=this.volume,i.connect(o),o.connect(this.audioContext.destination),i.onended=()=>{this.callback&&this.callback()},i.start(0)}catch(e){throw this.debug,new Error(`Something went wrong while playing audio: ${e.message}`)}}throttleFn(t){return()=>{const e=Date.now();e-this.lastClickTime>=this.throttle&&(t().catch(i=>{this.debug}),this.lastClickTime=e)}}play(t){let e;try{e=this.resolveFileUrl(t??this.fileSource)}catch(o){if(this.callback)return void this.callback(o);throw o}const i=this.throttleFn(()=>this.playAudio(e));try{i()}catch(o){if(this.debug,!this.callback)throw o;this.callback(o)}}}});
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});
2
+
3
+ //# sourceMappingURL=index.umd.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "1.8.0",
4
- "description": "ClickTone is a lightweight helper for UI sound feedback. It wraps the Web Audio API, giving you instant click‑sounds with volume control, throttling, callbacks, and an iOS resume workaround.",
3
+ "version": "2.0.0-dev.1",
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",
7
7
  "repository": {
@@ -13,46 +13,56 @@
13
13
  },
14
14
  "homepage": "https://github.com/ux-ui-pro/clicktone",
15
15
  "sideEffects": false,
16
+ "type": "module",
17
+ "packageManager": "yarn@1.22.22",
18
+ "engines": {
19
+ "node": ">=18.0.0"
20
+ },
16
21
  "scripts": {
17
22
  "clean": "rimraf dist",
18
23
  "build": "vite build",
19
- "lint:js": "eslint src/**/*.{ts,js}",
20
- "lint:fix:js": "eslint src/**/*.{ts,js} --fix",
21
- "format:js": "prettier --write src/**/*.{ts,js}",
22
- "lint:fix": "yarn lint:fix:js && yarn format:js"
24
+ "dev": "vite",
25
+ "verify": "yarn build && yarn lint && yarn typecheck && yarn test:unit && yarn test:smoke",
26
+ "lint": "biome check src",
27
+ "lint:fix": "biome check --write src",
28
+ "format": "biome format --write src",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit",
30
+ "test:unit": "vitest run --environment jsdom tests/unit",
31
+ "test:smoke": "node --test tests/*.js",
32
+ "prepublishOnly": "yarn clean && yarn verify"
23
33
  },
24
- "source": "src/index.ts",
34
+ "source": "src/main.ts",
25
35
  "main": "dist/index.cjs.js",
26
36
  "module": "dist/index.es.js",
27
37
  "browser": "./dist/index.umd.js",
28
38
  "types": "dist/index.d.ts",
29
39
  "exports": {
30
40
  ".": {
31
- "require": "./dist/index.cjs.js",
41
+ "types": "./dist/index.d.ts",
32
42
  "import": "./dist/index.es.js",
43
+ "require": "./dist/index.cjs.js",
33
44
  "default": "./dist/index.umd.js"
34
45
  },
35
46
  "./dist/*": "./dist/*"
36
47
  },
37
48
  "files": [
38
- "dist/"
49
+ "dist/index.es.js",
50
+ "dist/index.cjs.js",
51
+ "dist/index.umd.js",
52
+ "dist/index.d.ts",
53
+ "README.md",
54
+ "LICENSE"
39
55
  ],
40
56
  "devDependencies": {
41
- "@eslint/js": "9.22.0",
42
- "@rollup/plugin-terser": "0.4.4",
43
- "@types/node": "22.13.10",
44
- "@typescript-eslint/eslint-plugin": "8.26.0",
45
- "@typescript-eslint/parser": "8.26.0",
46
- "eslint": "9.22.0",
47
- "eslint-config-prettier": "10.1.1",
48
- "eslint-import-resolver-typescript": "3.8.3",
49
- "eslint-plugin-import": "2.31.0",
50
- "globals": "16.0.0",
51
- "prettier": "3.5.3",
52
- "rimraf": "6.0.1",
53
- "typescript": "5.8.2",
54
- "vite": "6.2.1",
55
- "vite-plugin-dts": "4.5.3"
57
+ "@biomejs/biome": "2.4.16",
58
+ "@types/node": "25.9.1",
59
+ "esbuild": "0.28.0",
60
+ "jsdom": "29.1.1",
61
+ "rimraf": "6.1.3",
62
+ "typescript": "6.0.3",
63
+ "vite": "8.0.16",
64
+ "vite-plugin-dts": "5.0.2",
65
+ "vitest": "4.1.8"
56
66
  },
57
67
  "keywords": [
58
68
  "MP3",