clicktone 2.0.0-dev.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
@@ -4,9 +4,11 @@ A lightweight helper for UI sound feedback. It wraps the Web Audio API with a ti
4
4
 
5
5
  - Single shared `AudioContext` for every instance (no iOS context-limit issues).
6
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.
7
8
  - Automatic format fallback via `canPlayType` (great for Safari, which dislikes OGG/Opus).
8
9
  - Shared decode cache, throttling, volume control, and subtle pitch variation.
9
10
  - Event-based (`EventTarget`) with a typed `on()` / `once()` API; `play()` also returns a `Promise`.
11
+ - [Demo](https://codepen.io/ux-ui/pen/yLwbmMr)
10
12
 
11
13
  ## Install
12
14
 
@@ -103,6 +105,7 @@ Mobile browsers (especially Safari on iOS) block audio until the user interacts
103
105
  - One shared `AudioContext` (with `latencyHint: 'interactive'`) — one unlock unlocks every instance.
104
106
  - Global gesture listeners (`pointerdown` / `pointerup` / `touchstart` / `touchend` / `keydown`) resume the context on the first interaction anywhere on the page.
105
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.
106
109
  - Decoded buffers are cached and shared, so the first click is not delayed by the network.
107
110
 
108
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.
package/dist/index.cjs.js CHANGED
@@ -1,3 +1,3 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var l=["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=()=>{},d=t=>!Number.isFinite(t)||t<0?0:t>1?1:t,w=class{#t=null;#r=!1;#i=!1;#n=null;#a=new Map;#s=new Set;get unlocked(){return this.#r}prime(){this.#i||!c||(this.#i=!0,this.#e(),this.#o())}context(){if(this.#t||!c)return this.#t;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#t=new t({latencyHint:"interactive"})}catch{this.#t=new t}return this.#t}unlock(){const t=this.context();if(t){if(t.state==="running"){this.#c();return}t.resume().then(()=>this.#c()).catch(u)}}onUnlock(t){if(this.#r){t();return}this.#s.add(t)}decode(t){const e=this.#a.get(t);if(e)return e;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const i=(async()=>{const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch "${t}": ${r.status} ${r.statusText}`);return n.decodeAudioData(await r.arrayBuffer())})();return this.#a.set(t,i),i.catch(()=>this.#a.delete(t)),i}#c(){if(this.#r)return;this.#r=!0,this.#u(),this.#n?.(),this.#n=null;const t=[...this.#s];this.#s.clear(),t.forEach(e=>{e()})}#u(){const t=this.#t;if(t)try{const e=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=e;const i=t.createGain();i.gain.value=1e-5,n.connect(i),i.connect(t.destination),n.start(0),n.stop(0)}catch{}}#e(){const t={passive:!0,capture:!0},e=()=>this.unlock();l.forEach(n=>{window.addEventListener(n,e,t)}),this.#n=()=>{l.forEach(n=>{window.removeEventListener(n,e,t)})}}#o(){const t=()=>{document.hidden||!this.#r||this.#t?.resume().catch(u)};document.addEventListener("visibilitychange",t)}},o=new w,y=t=>{const e=t.split(/[?#]/,1)[0];return p[e.slice(e.lastIndexOf(".")+1).toLowerCase()]},m=t=>{if(typeof t=="string")return[{src:t}];if(t instanceof URL)return[{src:t.href}];if(c&&t instanceof HTMLSourceElement){if(!t.src)throw new Error('<source> element has no "src" attribute.');return[{src:t.src,type:t.type||void 0}]}if(c&&t instanceof HTMLAudioElement){const e=Array.from(t.querySelectorAll("source")).filter(n=>n.src).map(n=>({src:n.src,type:n.type||void 0}));if(e.length)return e;if(t.src)return[{src:t.src}];throw new Error("<audio> element has no playable sources.")}if(typeof t=="object"&&t!==null&&"id"in t){if(!c)throw new Error("Cannot resolve element by id outside the DOM.");const e=document.getElementById(String(t.id));if(!e)throw new Error(`No element found with id "${t.id}".`);if(e instanceof HTMLSourceElement||e instanceof HTMLAudioElement)return m(e);throw new Error(`Element with id "${t.id}" is not a <source> or <audio> element.`)}if(typeof t=="object"&&t!==null&&"src"in t){if(!t.src)throw new Error('Source descriptor has an empty "src".');return[{src:t.src,type:t.type}]}throw new Error("Invalid sound source.")},f=t=>{const e=(Array.isArray(t)?t:[t]).flatMap(m);if(!e.length)throw new Error("No sound source provided.");if(e.length===1||!c)return e[0].src;const n=document.createElement("audio");let i=null;for(const r of e){const a=r.type??y(r.src);if(!a)continue;const s=n.canPlayType(a);if(s==="probably")return r.src;s==="maybe"&&i===null&&(i=r.src)}return i??e[0].src},v=class extends EventTarget{#t=null;#r=null;#i;#n;#a;#s;#c;#u=0;#e=null;#o=!1;constructor({src:t,volume:e=1,muted:n=!1,throttle:i=0,pitchVariation:r=0,preload:a=!1,debug:s=!1}){super(),this.#i=d(e),this.#n=n,this.#a=Math.max(0,i),this.#s=Math.min(1,Math.max(0,r)),this.#c=s;try{this.#t=f(t)}catch(h){this.#r=h}o.prime(),o.onUnlock(()=>this.#h("unlock")),a&&this.preload()}static unlock(){o.prime(),o.unlock()}static get unlocked(){return o.unlocked}get volume(){return this.#i}get muted(){return this.#n}async preload(){if(!(this.#o||!this.#t))try{const t=await o.decode(this.#t);return this.#h("load",t),t}catch(t){this.#l(t);return}}unlock(){o.unlock()}setVolume(t){this.#i=d(t),this.#e&&!this.#n&&this.#d(this.#i)}setMuted(t){this.#n=t,this.#e&&this.#d(t?0:this.#i),t||o.unlock()}toggleMuted(){return this.setMuted(!this.#n),this.#n}async play(t){if(this.#o)return;const e=Date.now();if(e-this.#u<this.#a)return;this.#u=e,o.unlock();let n;try{n=t?f(t):this.#f()}catch(i){this.#l(i);return}try{const i=await o.decode(n),r=o.context();if(!r||this.#o)return;r.state!=="running"&&await r.resume().catch(u);const a=this.#m(r),s=r.createBufferSource();s.buffer=i,this.#s>0&&(s.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#s)),s.connect(a),this.#h("play"),await new Promise(h=>{s.onended=()=>{s.disconnect(),h()},s.start(0)}),this.#h("end")}catch(i){this.#l(i)}}on(t,e){const n=i=>e(i.detail);return this.addEventListener(t,n),()=>this.removeEventListener(t,n)}once(t,e){const n=i=>e(i.detail);this.addEventListener(t,n,{once:!0})}destroy(){this.#o||(this.#o=!0,this.#e?.disconnect(),this.#e=null)}#f(){if(this.#t)return this.#t;throw this.#r??new Error("No valid sound source.")}#m(t){return(!this.#e||this.#e.context!==t)&&(this.#e=t.createGain(),this.#e.gain.value=this.#n?0:this.#i,this.#e.connect(t.destination)),this.#e}#d(t){const e=this.#e;if(!e)return;const n=e.context.currentTime;e.gain.cancelScheduledValues(n),e.gain.setValueAtTime(e.gain.value,n),e.gain.linearRampToValueAtTime(t,n+.015)}#h(t,e){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(t,{detail:e}));else if(typeof Event<"u"){const n=new Event(t);n.detail=e,this.dispatchEvent(n)}}#l(t){this.#c,this.#h("error",t)}};exports.ClickTone=v;
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
2
 
3
3
  //# sourceMappingURL=index.cjs.js.map
package/dist/index.es.js CHANGED
@@ -1,4 +1,4 @@
1
- var l = [
1
+ var w = [
2
2
  "pointerdown",
3
3
  "pointerup",
4
4
  "touchstart",
@@ -15,266 +15,330 @@ var l = [
15
15
  wav: "audio/wav",
16
16
  webm: "audio/webm",
17
17
  flac: "audio/flac"
18
- }, c = typeof window < "u" && typeof document < "u", u = () => {
19
- }, d = (t) => !Number.isFinite(t) || t < 0 ? 0 : t > 1 ? 1 : t, w = class {
20
- #t = null;
21
- #i = !1;
22
- #r = !1;
23
- #n = null;
24
- #a = /* @__PURE__ */ new Map();
25
- #s = /* @__PURE__ */ new Set();
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();
26
32
  get unlocked() {
27
- return this.#i;
33
+ return this.#t;
28
34
  }
29
35
  prime() {
30
- this.#r || !c || (this.#r = !0, this.#e(), this.#o());
36
+ this.#n || !c || (this.#n = !0, this.#w(), this.#m());
31
37
  }
32
38
  context() {
33
- if (this.#t || !c) return this.#t;
39
+ if (this.#i || !c) return this.#i;
34
40
  const t = window.AudioContext ?? window.webkitAudioContext;
35
41
  if (!t) return null;
36
42
  try {
37
- this.#t = new t({ latencyHint: "interactive" });
43
+ this.#i = new t({ latencyHint: "interactive" });
38
44
  } catch {
39
- this.#t = new t();
45
+ this.#i = new t();
40
46
  }
41
- return this.#t;
47
+ return this.#i;
42
48
  }
43
49
  unlock() {
50
+ this.#s && this.#u();
44
51
  const t = this.context();
45
52
  if (t) {
46
53
  if (t.state === "running") {
47
- this.#c();
54
+ this.#t ? this.#o() : this.#r();
48
55
  return;
49
56
  }
50
- t.resume().then(() => this.#c()).catch(u);
57
+ t.resume().then(() => {
58
+ this.#t ? this.#o() : this.#r();
59
+ }).catch(h);
51
60
  }
52
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
+ }
98
+ }
99
+ }
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
+ }
53
107
  onUnlock(t) {
54
- if (this.#i) {
108
+ if (this.#t) {
55
109
  t();
56
110
  return;
57
111
  }
58
- this.#s.add(t);
112
+ this.#l.add(t);
59
113
  }
60
114
  decode(t) {
61
- const e = this.#a.get(t);
62
- if (e) return e;
115
+ const i = this.#h.get(t);
116
+ if (i) return i;
63
117
  const n = this.context();
64
118
  if (!n) return Promise.reject(/* @__PURE__ */ new Error("Web Audio API is not available."));
65
119
  const r = (async () => {
66
- const i = await fetch(t);
67
- if (!i.ok) throw new Error(`Failed to fetch "${t}": ${i.status} ${i.statusText}`);
68
- return n.decodeAudioData(await i.arrayBuffer());
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());
69
123
  })();
70
- return this.#a.set(t, r), r.catch(() => this.#a.delete(t)), r;
71
- }
72
- #c() {
73
- if (this.#i) return;
74
- this.#i = !0, this.#u(), this.#n?.(), this.#n = null;
75
- const t = [...this.#s];
76
- this.#s.clear(), t.forEach((e) => {
77
- e();
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();
78
132
  });
79
133
  }
80
- #u() {
81
- const t = this.#t;
134
+ #o() {
135
+ const t = this.#i;
82
136
  if (t)
83
137
  try {
84
- const e = t.createBuffer(1, 1, Math.max(22050, t.sampleRate)), n = t.createBufferSource();
85
- n.buffer = e;
138
+ const i = t.createBuffer(1, 1, Math.max(22050, t.sampleRate)), n = t.createBufferSource();
139
+ n.buffer = i;
86
140
  const r = t.createGain();
87
141
  r.gain.value = 1e-5, n.connect(r), r.connect(t.destination), n.start(0), n.stop(0);
88
142
  } catch {
89
143
  }
90
144
  }
91
- #e() {
145
+ #w() {
92
146
  const t = {
93
147
  passive: !0,
94
148
  capture: !0
95
- }, e = () => this.unlock();
96
- l.forEach((n) => {
97
- window.addEventListener(n, e, t);
98
- }), this.#n = () => {
99
- l.forEach((n) => {
100
- window.removeEventListener(n, e, t);
101
- });
102
- };
149
+ }, i = () => this.unlock();
150
+ w.forEach((n) => {
151
+ window.addEventListener(n, i, t);
152
+ });
103
153
  }
104
- #o() {
105
- const t = () => {
106
- document.hidden || !this.#i || this.#t?.resume().catch(u);
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();
107
165
  };
108
- document.addEventListener("visibilitychange", t);
109
- }
110
- }, o = new w(), y = (t) => {
111
- const e = t.split(/[?#]/, 1)[0];
112
- return p[e.slice(e.lastIndexOf(".") + 1).toLowerCase()];
113
- }, m = (t) => {
114
- if (typeof t == "string") return [{ src: t }];
115
- if (t instanceof URL) return [{ src: t.href }];
116
- if (c && t instanceof HTMLSourceElement) {
117
- if (!t.src) throw new Error('<source> element has no "src" attribute.');
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.');
118
176
  return [{
119
- src: t.src,
120
- type: t.type || void 0
177
+ src: e.src,
178
+ type: e.type || void 0
121
179
  }];
122
180
  }
123
- if (c && t instanceof HTMLAudioElement) {
124
- const e = Array.from(t.querySelectorAll("source")).filter((n) => n.src).map((n) => ({
125
- src: n.src,
126
- type: n.type || void 0
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
127
185
  }));
128
- if (e.length) return e;
129
- if (t.src) return [{ src: t.src }];
186
+ if (t.length) return t;
187
+ if (e.src) return [{ src: e.src }];
130
188
  throw new Error("<audio> element has no playable sources.");
131
189
  }
132
- if (typeof t == "object" && t !== null && "id" in t) {
190
+ if (typeof e == "object" && e !== null && "id" in e) {
133
191
  if (!c) throw new Error("Cannot resolve element by id outside the DOM.");
134
- const e = document.getElementById(String(t.id));
135
- if (!e) throw new Error(`No element found with id "${t.id}".`);
136
- if (e instanceof HTMLSourceElement || e instanceof HTMLAudioElement) return m(e);
137
- throw new Error(`Element with id "${t.id}" is not a <source> or <audio> element.`);
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.`);
138
196
  }
139
- if (typeof t == "object" && t !== null && "src" in t) {
140
- if (!t.src) throw new Error('Source descriptor has an empty "src".');
197
+ if (typeof e == "object" && e !== null && "src" in e) {
198
+ if (!e.src) throw new Error('Source descriptor has an empty "src".');
141
199
  return [{
142
- src: t.src,
143
- type: t.type
200
+ src: e.src,
201
+ type: e.type
144
202
  }];
145
203
  }
146
204
  throw new Error("Invalid sound source.");
147
- }, f = (t) => {
148
- const e = (Array.isArray(t) ? t : [t]).flatMap(m);
149
- if (!e.length) throw new Error("No sound source provided.");
150
- if (e.length === 1 || !c) return e[0].src;
151
- const n = document.createElement("audio");
152
- let r = null;
153
- for (const i of e) {
154
- const a = i.type ?? y(i.src);
155
- if (!a) continue;
156
- const s = n.canPlayType(a);
157
- if (s === "probably") return i.src;
158
- s === "maybe" && r === null && (r = i.src);
159
- }
160
- return r ?? e[0].src;
161
- }, v = class extends EventTarget {
162
- #t = null;
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;
163
221
  #i = null;
164
- #r;
222
+ #t;
165
223
  #n;
166
- #a;
167
224
  #s;
168
225
  #c;
169
- #u = 0;
226
+ #h;
227
+ #l = 0;
170
228
  #e = null;
171
- #o = !1;
172
- constructor({ src: t, volume: e = 1, muted: n = !1, throttle: r = 0, pitchVariation: i = 0, preload: a = !1, debug: s = !1 }) {
173
- super(), this.#r = d(e), this.#n = n, this.#a = Math.max(0, r), this.#s = Math.min(1, Math.max(0, i)), this.#c = s;
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;
174
234
  try {
175
- this.#t = f(t);
176
- } catch (h) {
177
- this.#i = h;
235
+ this.#a = d(e);
236
+ } catch (u) {
237
+ this.#i = u;
178
238
  }
179
- o.prime(), o.onUnlock(() => this.#h("unlock")), a && this.preload();
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();
180
242
  }
181
243
  static unlock() {
182
- o.prime(), o.unlock();
244
+ a.prime(), a.unlock();
183
245
  }
184
246
  static get unlocked() {
185
- return o.unlocked;
247
+ return a.unlocked;
186
248
  }
187
249
  get volume() {
188
- return this.#r;
250
+ return this.#t;
189
251
  }
190
252
  get muted() {
191
253
  return this.#n;
192
254
  }
193
255
  async preload() {
194
- if (!(this.#o || !this.#t))
256
+ if (!(this.#r || !this.#a))
195
257
  try {
196
- const t = await o.decode(this.#t);
197
- return this.#h("load", t), t;
198
- } catch (t) {
199
- this.#l(t);
258
+ const e = await a.decode(this.#a);
259
+ return this.#f("load", e), e;
260
+ } catch (e) {
261
+ this.#p(e);
200
262
  return;
201
263
  }
202
264
  }
203
265
  unlock() {
204
- o.unlock();
266
+ a.unlock();
205
267
  }
206
- setVolume(t) {
207
- this.#r = d(t), this.#e && !this.#n && this.#d(this.#r);
268
+ setVolume(e) {
269
+ this.#t = l(e), this.#e && !this.#n && this.#m(this.#t);
208
270
  }
209
- setMuted(t) {
210
- this.#n = t, this.#e && this.#d(t ? 0 : this.#r), t || o.unlock();
271
+ setMuted(e) {
272
+ this.#n = e, this.#e && this.#m(e ? 0 : this.#t), e || a.unlock();
211
273
  }
212
274
  toggleMuted() {
213
275
  return this.setMuted(!this.#n), this.#n;
214
276
  }
215
- async play(t) {
216
- if (this.#o) return;
217
- const e = Date.now();
218
- if (e - this.#u < this.#a) return;
219
- this.#u = e, o.unlock();
220
- let n;
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;
221
283
  try {
222
- n = t ? f(t) : this.#f();
223
- } catch (r) {
224
- this.#l(r);
284
+ i = e ? d(e) : this.#o();
285
+ } catch (n) {
286
+ this.#p(n);
225
287
  return;
226
288
  }
227
289
  try {
228
- const r = await o.decode(n), i = o.context();
229
- if (!i || this.#o) return;
230
- i.state !== "running" && await i.resume().catch(u);
231
- const a = this.#m(i), s = i.createBufferSource();
232
- s.buffer = r, this.#s > 0 && (s.playbackRate.value = Math.max(0.5, 1 + (Math.random() * 2 - 1) * this.#s)), s.connect(a), this.#h("play"), await new Promise((h) => {
233
- s.onended = () => {
234
- s.disconnect(), h();
235
- }, s.start(0);
236
- }), this.#h("end");
237
- } catch (r) {
238
- this.#l(r);
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);
239
303
  }
240
304
  }
241
- on(t, e) {
242
- const n = (r) => e(r.detail);
243
- return this.addEventListener(t, n), () => this.removeEventListener(t, n);
305
+ on(e, t) {
306
+ const i = (n) => t(n.detail);
307
+ return this.addEventListener(e, i), () => this.removeEventListener(e, i);
244
308
  }
245
- once(t, e) {
246
- const n = (r) => e(r.detail);
247
- this.addEventListener(t, n, { once: !0 });
309
+ once(e, t) {
310
+ const i = (n) => t(n.detail);
311
+ this.addEventListener(e, i, { once: !0 });
248
312
  }
249
313
  destroy() {
250
- this.#o || (this.#o = !0, this.#e?.disconnect(), this.#e = null);
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);
251
315
  }
252
- #f() {
253
- if (this.#t) return this.#t;
316
+ #o() {
317
+ if (this.#a) return this.#a;
254
318
  throw this.#i ?? /* @__PURE__ */ new Error("No valid sound source.");
255
319
  }
256
- #m(t) {
257
- return (!this.#e || this.#e.context !== t) && (this.#e = t.createGain(), this.#e.gain.value = this.#n ? 0 : this.#r, this.#e.connect(t.destination)), this.#e;
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;
258
322
  }
259
- #d(t) {
260
- const e = this.#e;
261
- if (!e) return;
262
- const n = e.context.currentTime;
263
- e.gain.cancelScheduledValues(n), e.gain.setValueAtTime(e.gain.value, n), e.gain.linearRampToValueAtTime(t, n + 0.015);
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);
264
328
  }
265
- #h(t, e) {
266
- if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(t, { detail: e }));
329
+ #f(e, t) {
330
+ if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(e, { detail: t }));
267
331
  else if (typeof Event < "u") {
268
- const n = new Event(t);
269
- n.detail = e, this.dispatchEvent(n);
332
+ const i = new Event(e);
333
+ i.detail = t, this.dispatchEvent(i);
270
334
  }
271
335
  }
272
- #l(t) {
273
- this.#c, this.#h("error", t);
336
+ #p(e) {
337
+ this.#h, this.#f("error", e);
274
338
  }
275
339
  };
276
340
  export {
277
- v as ClickTone
341
+ E as ClickTone
278
342
  };
279
343
 
280
344
  //# sourceMappingURL=index.es.js.map
package/dist/index.umd.js CHANGED
@@ -1,3 +1,3 @@
1
- (function(a,c){typeof exports=="object"&&typeof module<"u"?c(exports):typeof define=="function"&&define.amd?define(["exports"],c):(a=typeof globalThis<"u"?globalThis:a||self,c(a.ClickTone={}))})(this,function(a){Object.defineProperty(a,Symbol.toStringTag,{value:"Module"});var c=["pointerdown","pointerup","touchstart","touchend","keydown"],w={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",l=()=>{},f=t=>!Number.isFinite(t)||t<0?0:t>1?1:t,y=class{#t=null;#r=!1;#i=!1;#n=null;#a=new Map;#s=new Set;get unlocked(){return this.#r}prime(){this.#i||!h||(this.#i=!0,this.#e(),this.#o())}context(){if(this.#t||!h)return this.#t;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#t=new t({latencyHint:"interactive"})}catch{this.#t=new t}return this.#t}unlock(){const t=this.context();if(t){if(t.state==="running"){this.#c();return}t.resume().then(()=>this.#c()).catch(l)}}onUnlock(t){if(this.#r){t();return}this.#s.add(t)}decode(t){const e=this.#a.get(t);if(e)return e;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const i=(async()=>{const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch "${t}": ${r.status} ${r.statusText}`);return n.decodeAudioData(await r.arrayBuffer())})();return this.#a.set(t,i),i.catch(()=>this.#a.delete(t)),i}#c(){if(this.#r)return;this.#r=!0,this.#u(),this.#n?.(),this.#n=null;const t=[...this.#s];this.#s.clear(),t.forEach(e=>{e()})}#u(){const t=this.#t;if(t)try{const e=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=e;const i=t.createGain();i.gain.value=1e-5,n.connect(i),i.connect(t.destination),n.start(0),n.stop(0)}catch{}}#e(){const t={passive:!0,capture:!0},e=()=>this.unlock();c.forEach(n=>{window.addEventListener(n,e,t)}),this.#n=()=>{c.forEach(n=>{window.removeEventListener(n,e,t)})}}#o(){const t=()=>{document.hidden||!this.#r||this.#t?.resume().catch(l)};document.addEventListener("visibilitychange",t)}},s=new y,v=t=>{const e=t.split(/[?#]/,1)[0];return w[e.slice(e.lastIndexOf(".")+1).toLowerCase()]},m=t=>{if(typeof t=="string")return[{src:t}];if(t instanceof URL)return[{src:t.href}];if(h&&t instanceof HTMLSourceElement){if(!t.src)throw new Error('<source> element has no "src" attribute.');return[{src:t.src,type:t.type||void 0}]}if(h&&t instanceof HTMLAudioElement){const e=Array.from(t.querySelectorAll("source")).filter(n=>n.src).map(n=>({src:n.src,type:n.type||void 0}));if(e.length)return e;if(t.src)return[{src:t.src}];throw new Error("<audio> element has no playable sources.")}if(typeof t=="object"&&t!==null&&"id"in t){if(!h)throw new Error("Cannot resolve element by id outside the DOM.");const e=document.getElementById(String(t.id));if(!e)throw new Error(`No element found with id "${t.id}".`);if(e instanceof HTMLSourceElement||e instanceof HTMLAudioElement)return m(e);throw new Error(`Element with id "${t.id}" is not a <source> or <audio> element.`)}if(typeof t=="object"&&t!==null&&"src"in t){if(!t.src)throw new Error('Source descriptor has an empty "src".');return[{src:t.src,type:t.type}]}throw new Error("Invalid sound source.")},p=t=>{const e=(Array.isArray(t)?t:[t]).flatMap(m);if(!e.length)throw new Error("No sound source provided.");if(e.length===1||!h)return e[0].src;const n=document.createElement("audio");let i=null;for(const r of e){const u=r.type??v(r.src);if(!u)continue;const o=n.canPlayType(u);if(o==="probably")return r.src;o==="maybe"&&i===null&&(i=r.src)}return i??e[0].src},g=class extends EventTarget{#t=null;#r=null;#i;#n;#a;#s;#c;#u=0;#e=null;#o=!1;constructor({src:t,volume:e=1,muted:n=!1,throttle:i=0,pitchVariation:r=0,preload:u=!1,debug:o=!1}){super(),this.#i=f(e),this.#n=n,this.#a=Math.max(0,i),this.#s=Math.min(1,Math.max(0,r)),this.#c=o;try{this.#t=p(t)}catch(d){this.#r=d}s.prime(),s.onUnlock(()=>this.#h("unlock")),u&&this.preload()}static unlock(){s.prime(),s.unlock()}static get unlocked(){return s.unlocked}get volume(){return this.#i}get muted(){return this.#n}async preload(){if(!(this.#o||!this.#t))try{const t=await s.decode(this.#t);return this.#h("load",t),t}catch(t){this.#l(t);return}}unlock(){s.unlock()}setVolume(t){this.#i=f(t),this.#e&&!this.#n&&this.#d(this.#i)}setMuted(t){this.#n=t,this.#e&&this.#d(t?0:this.#i),t||s.unlock()}toggleMuted(){return this.setMuted(!this.#n),this.#n}async play(t){if(this.#o)return;const e=Date.now();if(e-this.#u<this.#a)return;this.#u=e,s.unlock();let n;try{n=t?p(t):this.#f()}catch(i){this.#l(i);return}try{const i=await s.decode(n),r=s.context();if(!r||this.#o)return;r.state!=="running"&&await r.resume().catch(l);const u=this.#m(r),o=r.createBufferSource();o.buffer=i,this.#s>0&&(o.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#s)),o.connect(u),this.#h("play"),await new Promise(d=>{o.onended=()=>{o.disconnect(),d()},o.start(0)}),this.#h("end")}catch(i){this.#l(i)}}on(t,e){const n=i=>e(i.detail);return this.addEventListener(t,n),()=>this.removeEventListener(t,n)}once(t,e){const n=i=>e(i.detail);this.addEventListener(t,n,{once:!0})}destroy(){this.#o||(this.#o=!0,this.#e?.disconnect(),this.#e=null)}#f(){if(this.#t)return this.#t;throw this.#r??new Error("No valid sound source.")}#m(t){return(!this.#e||this.#e.context!==t)&&(this.#e=t.createGain(),this.#e.gain.value=this.#n?0:this.#i,this.#e.connect(t.destination)),this.#e}#d(t){const e=this.#e;if(!e)return;const n=e.context.currentTime;e.gain.cancelScheduledValues(n),e.gain.setValueAtTime(e.gain.value,n),e.gain.linearRampToValueAtTime(t,n+.015)}#h(t,e){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(t,{detail:e}));else if(typeof Event<"u"){const n=new Event(t);n.detail=e,this.dispatchEvent(n)}}#l(t){this.#c,this.#h("error",t)}};a.ClickTone=g});
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
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.0",
3
+ "version": "2.0.0-dev.1",
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",
@@ -54,15 +54,15 @@
54
54
  "LICENSE"
55
55
  ],
56
56
  "devDependencies": {
57
- "@biomejs/biome": "2.4.15",
58
- "@types/node": "25.5.0",
57
+ "@biomejs/biome": "2.4.16",
58
+ "@types/node": "25.9.1",
59
59
  "esbuild": "0.28.0",
60
- "jsdom": "27.0.1",
60
+ "jsdom": "29.1.1",
61
61
  "rimraf": "6.1.3",
62
62
  "typescript": "6.0.3",
63
- "vite": "8.0.14",
64
- "vite-plugin-dts": "5.0.1",
65
- "vitest": "3.2.4"
63
+ "vite": "8.0.16",
64
+ "vite-plugin-dts": "5.0.2",
65
+ "vitest": "4.1.8"
66
66
  },
67
67
  "keywords": [
68
68
  "MP3",