dopaminejs 3.5.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/dist/{DataService-QQBNqJtN.js → DataService-B5noGvMr.js} +228 -254
- package/dist/DataService-DKCk0nOu.cjs +1 -0
- package/dist/SoundManager-C6VdZEFo.js +308 -0
- package/dist/SoundManager-DBGDYIkz.cjs +1 -0
- package/dist/celebrate.cjs +1 -0
- package/dist/celebrate.js +100 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +3 -1
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.global.js +3 -3
- package/dist/dopamine.js +5 -3
- package/dist/host-B-Gn-Zg_.js +537 -0
- package/dist/host-D6suk7Ci.cjs +37 -0
- package/dist/storage-B6z-zaBe.cjs +1 -0
- package/dist/storage-C2s4Da9b.js +26 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +3 -2
- package/package.json +10 -3
- package/src/celebrate.js +208 -0
- package/src/dopamine/effects/ParticleSystem.js +5 -1
- package/src/dopamine/ui/RewardUI.js +10 -6
- package/types/celebrate.d.ts +31 -0
- package/types/index.d.ts +2 -0
- package/dist/DataService-Xk7egYXe.cjs +0 -1
- package/dist/host-1c7QSAKI.cjs +0 -37
- package/dist/host-_essSMef.js +0 -835
package/dist/dopamine.global.js
CHANGED
|
@@ -17,7 +17,7 @@ var Dopamine=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Mod
|
|
|
17
17
|
<span class="streak-number">1</span>
|
|
18
18
|
</div>
|
|
19
19
|
</div>
|
|
20
|
-
`,this.liveRegion=document.createElement(`div`),this.liveRegion.className=`dopamine-live-region`,this.liveRegion.setAttribute(`aria-live`,`polite`),this.liveRegion.setAttribute(`role`,`status`),Object.assign(this.liveRegion.style,{position:`absolute`,width:`1px`,height:`1px`,overflow:`hidden`,clipPath:`inset(50%)`,whiteSpace:`nowrap`}),this.container.appendChild(this.liveRegion),document.body.appendChild(this.container),this.levelBadge=this.container.querySelector(`.level-badge`),this.streakBadge=this.container.querySelector(`.streak-badge`),this.xpBar=this.container.querySelector(`.xp-bar-fill`),this.xpText=this.container.querySelector(`.xp-text`),this.levelDisplay=this.container.querySelector(`.level-number`),this.streakDisplay=this.container.querySelector(`.streak-number`),this._setIcon(this.container.querySelector(`.streak-icon`),this._streakIcon)}_addStyles(){if(document.getElementById(je))return;let e=typeof this._injectCss==`string`?this._injectCss:Oe;this._style=document.createElement(`style`),this._style.id=je,this._style.textContent=e,document.head.appendChild(this._style)}_setIcon(e,t){if(e.textContent=``,typeof Node<`u`&&t instanceof Node)e.appendChild(t);else if(typeof t!=`string`)return;else if(!this.safeIcons)e.innerHTML=t;else{let n=Ke(t);n?e.appendChild(n):e.textContent=t}}_defer(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);return this._timers.add(n),n}_mount(e){return document.body.appendChild(e),this._detached.push(e),e}_announce(e){this.liveRegion&&(this.liveRegion.textContent=e)}_burst(e,t,n){this.parts.particles?.burst?.(e,t,n)}_replayAnimation(e,t){e&&(e.style.animation=`none`,this._defer(()=>{e.style.animation=t},10))}hud(e){if(!this.container||!e)return;let{xp:t,level:n,progress:r,streak:i,next:a}=e,o=Number.isFinite(r)?r:a>0?t/a:0;this.xpBar.style.width=`${Math.max(0,Math.min(100,o*100))}%`,this.xpText.textContent=Number.isFinite(a)?`${t} / ${a} XP`:`${t} XP`,t!==this._xp&&this._replayAnimation(this.xpBar,`xp-pulse 0.3s ease-out`),this._xp=t,this.levelDisplay.textContent=n,n!==this._level&&this._replayAnimation(this.levelBadge,`level-pulse 0.5s ease-out`),this._level=n,this.streakDisplay.textContent=i,i>=7?this.streakBadge.style.background=`linear-gradient(135deg, #ff6b00 0%, #ff4400 100%)`:i>=3?this.streakBadge.style.background=`linear-gradient(135deg, #ff8800 0%, #ff6b00 100%)`:this.streakBadge.style.background=``}popup(e){if(!this.container||!e||typeof e!=`object`)return;let t=Z(e,`kind`);t===`level`?this._levelPopup(e):t===`notice`?this._notice(e):this._card(e,t===`achievement`)}_card(e,t){let{title:n,body:r,meta:i,icon:a}=e;this._cardQueue.push([{title:n,body:r,meta:i,icon:a},t]),this._nextCard()}_nextCard(){if(this._cardActive)return;let e=this._cardQueue.shift();if(e){this._cardActive=!0;try{this._showCard(e[0],e[1])}catch(e){throw this._cardActive=!1,this._nextCard(),e}}}_showCard(e,t){let n=document.createElement(`div`);n.className=`achievement-popup`,n.innerHTML=`
|
|
20
|
+
`,this.liveRegion=document.createElement(`div`),this.liveRegion.className=`dopamine-live-region`,this.liveRegion.setAttribute(`aria-live`,`polite`),this.liveRegion.setAttribute(`role`,`status`),Object.assign(this.liveRegion.style,{position:`absolute`,width:`1px`,height:`1px`,overflow:`hidden`,clipPath:`inset(50%)`,whiteSpace:`nowrap`}),this.container.appendChild(this.liveRegion),document.body.appendChild(this.container),this.levelBadge=this.container.querySelector(`.level-badge`),this.streakBadge=this.container.querySelector(`.streak-badge`),this.xpBar=this.container.querySelector(`.xp-bar-fill`),this.xpText=this.container.querySelector(`.xp-text`),this.levelDisplay=this.container.querySelector(`.level-number`),this.streakDisplay=this.container.querySelector(`.streak-number`),this._setIcon(this.container.querySelector(`.streak-icon`),this._streakIcon)}_addStyles(){if(document.getElementById(je))return;let e=typeof this._injectCss==`string`?this._injectCss:Oe;this._style=document.createElement(`style`),this._style.id=je,this._style.textContent=e,document.head.appendChild(this._style)}_setIcon(e,t){if(e.textContent=``,typeof Node<`u`&&t instanceof Node)e.appendChild(t);else if(typeof t!=`string`)return;else if(!this.safeIcons)e.innerHTML=t;else{let n=Ke(t);n?e.appendChild(n):e.textContent=t}}_defer(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);return this._timers.add(n),n}_mount(e){return document.body.appendChild(e),this._detached.push(e),e}_announce(e){this.liveRegion&&(this.liveRegion.textContent=e)}_burst(e,t,n){this.parts.particles?.burst?.(e,t,n)}_replayAnimation(e,t){e&&(e.style.animation=`none`,this._defer(()=>{e.style.animation=t},10))}hud(e){if(!this.container||!e)return;let{xp:t,level:n,progress:r,streak:i,next:a}=e,o=Number.isFinite(r)?r:a>0?t/a:0;this.xpBar.style.width=`${Math.max(0,Math.min(100,o*100))}%`,this.xpText.textContent=Number.isFinite(a)?`${t} / ${a} XP`:`${t} XP`,t!==this._xp&&this._replayAnimation(this.xpBar,`xp-pulse 0.3s ease-out`),this._xp=t,this.levelDisplay.textContent=n,n!==this._level&&this._replayAnimation(this.levelBadge,`level-pulse 0.5s ease-out`),this._level=n,this.streakDisplay.textContent=i,i>=7?this.streakBadge.style.background=`linear-gradient(135deg, #ff6b00 0%, #ff4400 100%)`:i>=3?this.streakBadge.style.background=`linear-gradient(135deg, #ff8800 0%, #ff6b00 100%)`:this.streakBadge.style.background=``}popup(e){if(!this.container||!e||typeof e!=`object`)return;let t=Z(e,`kind`);t===`level`?this._levelPopup(e):t===`notice`?this._notice(e):this._card(e,t===`achievement`)}_card(e,t){let{title:n,body:r,meta:i,icon:a}=e;this._cardQueue.push([{title:n,body:r,meta:i,icon:a,burst:Z(e,`burst`)},t]),this._nextCard()}_nextCard(){if(this._cardActive)return;let e=this._cardQueue.shift();if(e){this._cardActive=!0;try{this._showCard(e[0],e[1])}catch(e){throw this._cardActive=!1,this._nextCard(),e}}}_showCard(e,t){let n=document.createElement(`div`);n.className=`achievement-popup`,n.innerHTML=`
|
|
21
21
|
<div class="achievement-shine"></div>
|
|
22
22
|
<div class="achievement-content">
|
|
23
23
|
<div class="achievement-icon"></div>
|
|
@@ -28,10 +28,10 @@ var Dopamine=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Mod
|
|
|
28
28
|
<div class="achievement-xp"></div>
|
|
29
29
|
</div>
|
|
30
30
|
</div>
|
|
31
|
-
`;let r=X(e.title);n.querySelector(`.achievement-title`).textContent=t?this.strings.achievementUnlocked:``,this._setIcon(n.querySelector(`.achievement-icon`),e.icon),n.querySelector(`.achievement-name`).textContent=r,n.querySelector(`.achievement-desc`).textContent=X(e.body),n.querySelector(`.achievement-xp`).textContent=X(e.meta),this._mount(n),this._announce(t?`${this.strings.achievementUnlocked}: ${r}`:r),this._defer(()=>{let e=n.getBoundingClientRect();this._burst(`confetti`,{x:e.left+e.width/2,y:e.top+e.height/2},{count:40})},300),this._defer(()=>{n.style.animation=`slideOut 0.3s ease-in forwards`,this._defer(()=>{this._remove(n),this._cardActive=!1,this._nextCard()},300)},4e3)}_levelPopup(e){let t=typeof e.title==`string`&&e.title!==``?e.title:this.strings.levelUp,n=X(e.body),r=document.createElement(`div`);r.className=`level-up-overlay`,r.innerHTML=`
|
|
31
|
+
`;let r=X(e.title);n.querySelector(`.achievement-title`).textContent=t?this.strings.achievementUnlocked:``,this._setIcon(n.querySelector(`.achievement-icon`),e.icon),n.querySelector(`.achievement-name`).textContent=r,n.querySelector(`.achievement-desc`).textContent=X(e.body),n.querySelector(`.achievement-xp`).textContent=X(e.meta),this._mount(n),this._announce(t?`${this.strings.achievementUnlocked}: ${r}`:r),e.burst!==!1&&this._defer(()=>{let e=n.getBoundingClientRect();this._burst(`confetti`,{x:e.left+e.width/2,y:e.top+e.height/2},{count:40})},300),this._defer(()=>{n.style.animation=`slideOut 0.3s ease-in forwards`,this._defer(()=>{this._remove(n),this._cardActive=!1,this._nextCard()},300)},4e3)}_levelPopup(e){let t=typeof e.title==`string`&&e.title!==``?e.title:this.strings.levelUp,n=X(e.body),r=document.createElement(`div`);r.className=`level-up-overlay`,r.innerHTML=`
|
|
32
32
|
<div class="level-up-content">
|
|
33
33
|
<div class="level-up-title"></div>
|
|
34
34
|
<div class="level-up-number"></div>
|
|
35
35
|
<div class="level-up-subtitle">Amazing progress!</div>
|
|
36
36
|
</div>
|
|
37
|
-
`,r.querySelector(`.level-up-title`).textContent=t,r.querySelector(`.level-up-number`).textContent=n,this._mount(r),this._announce(`Level up: ${n}`),this._defer(()=>{for(let e=0;e<5;e++)this._defer(()=>{this._burst(`confetti`,{x:Math.random()*window.innerWidth,y:Math.random()*window.innerHeight*.6},{count:30})},e*200)},300),this._defer(()=>{r.style.opacity=`0`,this._defer(()=>this._remove(r),500)},2500)}_notice(e){let t=window.innerWidth/2,n=window.innerHeight/3,r=X(e.title);e.tier===`legendary`?(this._floatText({text:r,x:t,y:n,color:`#ffd700`,size:`36px`}),this._burst(`stars`,{x:t,y:n},{count:12}),this._burst(`confetti`,{x:t,y:n},{count:25})):e.tier===`rare`?(this._floatText({text:r,x:t,y:n,color:`#ff6b6b`,size:`32px`}),this._burst(`fire`,{x:t,y:n},{count:20})):this._floatText({text:r,x:t,y:n,color:`#fff`,size:`24px`}),this._announce(r)}text(e){this._floatText({...e})}_floatText({text:e,x:t,y:n,color:r=`#ffd700`,size:i=`24px`}){if(!this.container)return;let a=document.createElement(`div`);a.className=`floating-text`,a.textContent=X(e),a.style.left=(Number.isFinite(t)?t:window.innerWidth/2)+`px`,a.style.top=(Number.isFinite(n)?n:window.innerHeight/3)+`px`,a.style.color=r,a.style.fontSize=i,this._mount(a),this._defer(()=>this._remove(a),2e3)}_remove(e){e.remove();let t=this._detached.indexOf(e);t>-1&&this._detached.splice(t,1)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear(),this._cardQueue=[],this._cardActive=!1;for(let e of this._detached)e.remove();this._detached=[],this.container?.remove(),this._style?.remove(),this._style=null,this.container=null,this.liveRegion=null,this.xpBar=null,this.xpText=null,this.levelBadge=null,this.streakBadge=null,this.levelDisplay=null,this.streakDisplay=null,this._streakIcon=null}},Je=Object.freeze({matches:!1});function Ye(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||Je}var Xe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ze={confetti:(e,t,n,r)=>e.confetti(t,n,r),sparkle:(e,t,n,r,i)=>e.sparkle(t,n,r,i),fire:(e,t,n,r)=>e.fire(t,n,r),stars:(e,t,n,r)=>e.starBurst(t,n,r),coins:(e,t,n,r)=>e.coinShower(t,n,r)},Qe=class{constructor(e={}){this.container=e.container?typeof e.container==`string`?document.querySelector(e.container):e.container:document.body,this.container||=(console.warn(`[DopamineJS] Particle container '${e.container}' not found. Using document.body.`),document.body),this.maxParticles=Number.isFinite(e.maxParticles)?Math.max(0,Math.floor(e.maxParticles)):5e3,this._reducedMotion=e.respectReducedMotion===!1?null:Ye(window),this.canvasId=e.canvasId||`dopamine-particle-canvas`,this.canvas=document.createElement(`canvas`),this.canvas.classList.add(`dopamine-particle-canvas`),document.getElementById(this.canvasId)||(this.canvas.id=this.canvasId),this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.zIndex||`9999`,this.container===document.body?(this.canvas.style.position=`fixed`,this.canvas.style.top=`0`,this.canvas.style.left=`0`):(this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,window.getComputedStyle(this.container).position===`static`&&(this.container.style.position=`relative`)),this.container.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.particles=[],this.pool=[],this.sprites=new Map,this.customEffects=new Map,this.isAnimating=!1,this._onResize=()=>this._resize(),this._resizeObserver=null,this._frameHandle=null,this._lastFrameTime=null,this._resize(),window.ResizeObserver&&this.container!==document.body?(this._resizeObserver=new ResizeObserver(this._onResize),this._resizeObserver.observe(this.container)):window.addEventListener(`resize`,this._onResize)}_resize(){let e=this.container===document.body?window.innerWidth:this.container.clientWidth,t=this.container===document.body?window.innerHeight:this.container.clientHeight,n=window.devicePixelRatio||1;this.width=e,this.height=t,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.ctx.setTransform(n,0,0,n,0,0)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){typeof t==`object`&&t&&(r=n===void 0?[]:[n,...r],{x:t,y:n}=t);let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){let{x:t,y:n,count:r=10,speed:i=5,gravity:a=.1,decay:o=.02,life:s=1,color:c=`#ffd700`,sprite:l=null,spread:u=Math.PI*2,angle:d=0,size:f=5,type:p=null}=e,m=this._allowed(r);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;e.x=t,e.y=n,e.vx=Math.cos(r)*m,e.vy=Math.sin(r)*m,e.life=s,e.decay=o*(.8+Math.random()*.4),e.gravity=a,e.color=Array.isArray(c)?c[Math.floor(Math.random()*c.length)]:c,e.size=f*(.8+Math.random()*.4),e.sprite=l,e.type=p,e.rotation=Math.random()*Math.PI*2,e.rotationSpeed=(Math.random()-.5)*.2,this.particles.push(e)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}burst(e,t,n){if(typeof e!=`string`||!Xe(Ze,e))return;let r=Number.isFinite(t?.x)?t.x:this.width/2,i=Number.isFinite(t?.y)?t.y:this.height/2,a=Number.isFinite(n?.count)?n.count:void 0;Ze[e](this,r,i,a,n?.color)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;i.x=e,i.y=t,i.vx=Math.cos(a)*4,i.vy=Math.sin(a)*4,i.life=1,i.decay=.03,i.gravity=0,i.color=`#ffffff`,i.size=15,i.sprite=null,i.type=`star`,i.rotation=a,i.rotationSpeed=0,this.particles.push(i)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];if(n.vy+=n.gravity*t,n.x+=n.vx*t,n.y+=n.vy*t,n.life-=n.decay*t,n.rotationSpeed&&(n.rotation+=n.rotationSpeed*t),n.life<=0){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t)}else{if(this.ctx.save(),this.ctx.globalAlpha=n.life,this.ctx.translate(n.x,n.y),this.ctx.rotate(n.rotation),n.sprite&&this.sprites.has(n.sprite)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}else n.type===`star`?(this.ctx.fillStyle=n.color,this._drawStarPath(0,0,5,n.size,n.size/2),this.ctx.fill()):(this.ctx.fillStyle=n.color,this.ctx.beginPath(),this.ctx.arc(0,0,n.size,0,Math.PI*2),this.ctx.fill());this.ctx.restore()}}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);for(let l=0;l<n;l++)o=e+Math.cos(a)*r,s=t+Math.sin(a)*r,this.ctx.lineTo(o,s),a+=c,o=e+Math.cos(a)*i,s=t+Math.sin(a)*i,this.ctx.lineTo(o,s),a+=c;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){this.clear(),this.isAnimating=!1,this._frameHandle!==null&&(cancelAnimationFrame(this._frameHandle),this._frameHandle=null),this._resizeObserver&&=(this._resizeObserver.disconnect(),null),window.removeEventListener(`resize`,this._onResize),this.canvas.remove(),this.sprites.clear(),this.customEffects.clear(),this.pool=[]}},$e=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),et=class{constructor(e={}){this.audioContext=null,this.storageKey=e.storageKey||`dopamineSoundsMuted`,this.storage=e.storage||Y(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=e.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(e.volume??1),this._loading=new Map,this._timers=new Set,this._synths=new Map,this._unlocks=new Set}unlockOn(e,t=[`pointerup`,`touchend`,`keydown`]){let n=()=>{for(let n of t)e.removeEventListener(n,r);this._unlocks.delete(n)},r=()=>{n(),this.initAudio()};for(let n of t)e.addEventListener(n,r);return this._unlocks.add(n),n}_later(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}initAudio(){if(!this.audioContext){let e=typeof window<`u`?window.AudioContext||window.webkitAudioContext:void 0;if(!e)return!1;this.audioContext=new e,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this._volume,this.masterGain.connect(this.audioContext.destination),this.preloadSounds(this.customSounds)}return this.audioContext.state===`suspended`&&this.audioContext.resume(),!0}setVolume(e){return Number.isFinite(e)&&(this._volume=Math.max(0,Math.min(1,e)),this.masterGain&&(this.masterGain.gain.value=this._volume)),this._volume}getVolume(){return this._volume}_output(){return this.masterGain||this.audioContext.destination}toggleMute(){return this.muted=!this.muted,this.storage.setItem(this.storageKey,this.muted),this.muted}registerSound(e,t){this.customSounds[e]=t,this.audioContext&&this.loadSound(e,t)}register(e,t){return typeof e!=`string`||e===``?()=>{}:typeof t==`string`?(this.registerSound(e,t),()=>{this.customSounds[e]===t&&delete this.customSounds[e],this.assets.delete(e)}):typeof t==`function`?(this._synths.set(e,t),()=>{this._synths.get(e)===t&&this._synths.delete(e)}):()=>{}}async preloadSounds(e){let t=Object.entries(e).map(([e,t])=>(this.customSounds[e]=t,this.loadSound(e,t)));await Promise.allSettled(t)}async loadSound(e,t){if(!this.audioContext)return;if(this._loading.has(e))return this._loading.get(e);let n=this._load(e,t).finally(()=>this._loading.delete(e));return this._loading.set(e,n),n}async _load(e,t){try{let n=this.audioContext,r=await fetch(t);if(r.ok===!1)throw Error(`HTTP ${r.status}`);let i=await r.arrayBuffer(),a=await n.decodeAudioData(i);this.audioContext===n&&this.assets.set(e,a)}catch(t){console.warn(`[DopamineJS] Failed to load sound '${e}':`,t)}}async play(e){if(this.muted||!this.initAudio())return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}if($e(this.customSounds,e)&&!this.assets.has(e)){let t=this.audioContext;if(await this.loadSound(e,this.customSounds[e]),this.audioContext!==t)return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}}let t={xp:()=>this.playXP(!0),level_up:()=>this.playLevelUp(!0),achievement:()=>this.playAchievement(!0),personal_best:()=>this.playPersonalBest(!0),click:()=>this.playClick(!0),error:()=>this.playError(!0)};this._synths.has(e)?this._synths.get(e)(this,(e,t)=>this._later(e,t)):$e(t,e)&&t[e]()}_playBuffer(e){let t=this.audioContext.createBufferSource();t.buffer=e,t.connect(this._output()),t.start(0)}playTone(e,t,n=`sine`,r=.3){if(this.muted||!this.initAudio())return;let i=this.audioContext.createOscillator(),a=this.audioContext.createGain();i.connect(a),a.connect(this._output()),i.frequency.value=e,i.type=n;let o=Math.max(1e-4,r);a.gain.setValueAtTime(o,this.audioContext.currentTime),a.gain.exponentialRampToValueAtTime(.01,this.audioContext.currentTime+t),i.start(this.audioContext.currentTime),i.stop(this.audioContext.currentTime+t)}playClick(e=!1){if(!e&&this.assets.has(`click`))return this.play(`click`);this.playTone(600,.05,`sine`,.1)}playXP(e=!1){if(!e&&this.assets.has(`xp`))return this.play(`xp`);this.playTone(700,.06,`sine`,.12)}playLevelUp(e=!1){if(!e&&this.assets.has(`level_up`))return this.play(`level_up`);this.playTone(500,.12,`sine`,.2),this._later(()=>this.playTone(700,.12,`sine`,.2),110),this._later(()=>this.playTone(900,.25,`sine`,.2),220)}playAchievement(e=!1){if(!e&&this.assets.has(`achievement`))return this.play(`achievement`);this.playTone(660,.1,`triangle`,.2),this._later(()=>this.playTone(990,.25,`triangle`,.2),100)}playPersonalBest(e=!1){if(!e&&this.assets.has(`personal_best`))return this.play(`personal_best`);this.playTone(600,.1,`sine`,.2),this._later(()=>this.playTone(800,.2,`sine`,.2),100)}playError(e=!1){if(!e&&this.assets.has(`error`))return this.play(`error`);this.playTone(200,.2,`sawtooth`,.3)}destroy(){for(let e of[...this._unlocks])e();for(let e of this._timers)clearTimeout(e);this._timers.clear(),this.audioContext&&(this.audioContext.close?.())?.catch?.(()=>{}),this.audioContext=null,this.masterGain=null,this.assets.clear(),this._loading.clear(),this._synths.clear()}};function tt({nav:e=globalThis.navigator,enabled:t=!0}={}){let n=!!t,r=t=>{if(n)try{e.vibrate(t)}catch{}};return{tap:()=>r(10),double:()=>r([10,40,10]),setEnabled(e){n=!!e}}}var nt=3,rt=[`ui`,`particles`,`sound`,`haptics`],it=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,at=(e,t)=>{it(e)&&e.then(void 0,e=>t.error(e))};function ot(){let e=typeof document<`u`&&typeof window<`u`;return{hasDom:e,reducedMotion:e?Ye(window).matches===!0:!1}}function $(e,t,n){if(e===!1)return null;let r=e;return typeof e==`function`&&(r=e(t)),r??n()}function st(e,t){let n=`dopamine_plugin_${t}:`;return{getItem:t=>e.getItem(n+t),setItem:(t,r)=>e.setItem(n+t,r),removeItem:t=>e.removeItem(n+t)}}function ct(e={}){let t=e||{},r=ot(),a={debug:()=>{},info:()=>{},warn:(...e)=>console.warn(...e),error:(...e)=>console.error(...e),...t.log||{}},o=t.storage||Y(),s=t.clock||i,c={ui:null,particles:null,sound:null,haptics:null},l={};for(let e of rt)Object.defineProperty(l,e,{enumerable:!0,get:()=>c[e]});Object.freeze(l);let u={...r,parts:l,storage:o,clock:s},d=$(t.progress,u,()=>new Ee(new De({storage:o}),{clock:s,streakDays:t.streakDays,builtinAchievements:t.builtinAchievements,loadRetryMs:t.loadRetryMs}));if(typeof d?.on!=`function`||typeof d?.off!=`function`)throw new n(`invalid_progress`,`progress needs on() and off()`);c.particles=$(t.particles,u,()=>r.hasDom?new Qe:null),c.sound=$(t.sound,u,()=>new et({storage:o})),c.haptics=$(t.haptics,u,()=>tt());try{c.ui=$(t.ui,u,()=>r.hasDom?new qe(l):null)}catch(e){throw f(),e}function f(){for(let e of rt)try{c[e]?.destroy?.()}catch(e){a.error(e)}}let p=d,m=[],h=!1,g=e=>t=>{try{at(e(t),a)}catch(e){a.error(e)}},_=()=>{let e=c.ui;if(!e||typeof d.snapshot!=`function`||typeof d.getXPForNextLevel!=`function`)return;let t=d.snapshot(),{total:n,progress:r}=d.getXPForNextLevel();e.hud({xp:t.xp,level:t.level,progress:r,streak:t.streak.current,next:n})};m.push(p.on(`xp_gained`,g(e=>{_(),e.leveledUp||c.sound?.play(`xp`)})),p.on(`level_up`,g(e=>{_(),c.ui?.popup({kind:`level`,title:``,body:String(e.newLevel)}),c.sound?.play(`level_up`)})),p.on(`achievement_unlocked`,g(e=>{c.ui?.popup({kind:`achievement`,title:e.name,body:e.description,icon:e.icon,meta:`+${e.xp??0} XP`}),c.sound?.play(`achievement`)})),p.on(`streak_updated`,g(_)),p.on(`player_reset`,g(_)),p.on(`load_recovered`,g(_)),p.on(`personal_best`,g(e=>{c.ui?.popup({kind:`notice`,title:`New High Score: ${e.score}!`,tier:`legendary`}),c.sound?.play(`personal_best`)})));let v=new Map,y=[];function b(e){if(typeof e!=`object`||!e||typeof e.name!=`string`||!/^[a-z0-9-]+$/.test(e.name)||typeof e.install!=`function`)throw new n(`plugin_invalid`,`a plugin needs a name (a-z, 0-9 and -) and an install function`);if(e.api!==3)throw new n(`plugin_api`,`${e.name} was built for api ${e.api}, this host is api 3`);if(v.has(e.name))throw new n(`plugin_duplicate`,`${e.name} is already installed`);for(let t of e.after||[])if(!v.has(t)||!v.get(t).done)throw new n(`plugin_order`,`${e.name} must come after ${t}`);for(let t of e.requires||[])if(!rt.includes(t)||c[t]===null)throw new n(`plugin_requires`,`${e.name} requires the ${t} part, which is not set`)}function ee(e){for(let t of e.offs)t();e.offs.clear(),v.delete(e.name);let t=y.indexOf(e);t>-1&&y.splice(t,1)}function x(e){if(e.removed)return;e.removed=!0;let t=e.disposer;e.disposer=null;try{t?.()}catch(e){a.error(e)}ee(e)}function S(e){let{name:t}=e;return{progress:d,parts:l,events:{on(t,n){let r=p.on(t,n),i=()=>{r(),e.offs.delete(i)};return e.offs.add(i),i},off:(e,t)=>p.off(e,t),emit(e,r){if(typeof e!=`string`||!e.startsWith(`${t}:`))throw new n(`plugin_event`,`${t} may only emit events named ${t}:<event>`);p.emit(e,r)}},storage:st(o,t),clock:s,log:a,env:{hasDom:r.hasDom,reducedMotion:r.reducedMotion},plugin:e=>v.has(e)&&v.get(e).done?v.get(e).handle:null,expose:t=>{e.handle=t}}}function C(e){if(h)throw new n(`disposed`,`the host was disposed`);b(e);let t={name:e.name,done:!1,removed:!1,disposer:null,handle:null,offs:new Set};v.set(e.name,t);let r=e=>(t.done=!0,typeof e==`function`&&(t.disposer=e),t.removed||h?(t.removed=!1,x(t),t):(y.push(t),t)),i=e=>{throw ee(t),e},a;try{a=e.install(S(t))}catch(e){return i(e)}return it(a)?a.then(r,i):r(a)}let w=null;function T(e){if(h)throw new n(`disposed`,`the host was disposed`);if(w===null){let t=C(e);if(it(t)){let e=t.then(e=>e,e=>{throw e});return w=e.then(()=>{w=null},()=>{w=null}),{record:null,done:e}}return{record:t,done:Promise.resolve(t)}}let t=w.then(()=>C(e));return w=t.then(()=>{w=null},()=>{w=null}),{record:null,done:t}}function E(e){let{record:t,done:n}=T(e);if(t)return()=>x(t);let r=null,i=!1;return n.then(e=>{r=e,i&&x(e)},e=>a.error(e)),()=>{r?x(r):i=!0}}let D=Promise.resolve();try{for(let e of t.plugins||[]){let{done:t}=T(e);D=D.then(()=>t)}}catch(e){throw O(),e}D=D.catch(e=>{throw O(),e});function O(){if(!h){h=!0;for(let e of[...y].reverse())x(e);for(let e of[...v.values()])x(e);for(let e of m)e();m.length=0,f(),d.clear?.()}}let k=D.then(()=>typeof d.init==`function`?d.init():void 0).then(()=>(h||_(),A));k.catch(()=>{});let A={progress:d,parts:l,events:p,ready:k,use:E,dispose:O};return A}return e.DataService=De,e.DopamineError=n,e.EventEmitter=t,e.HOST_API=nt,e.ParticleSystem=Qe,e.RewardSystem=Ee,e.RewardUI=qe,e.SoundManager=et,e.createDopamine=ct,e.createHaptics=tt,e.createMemoryStorage=J,e.merge=W,e.prefersReducedMotion=Ye,e.resolveStorage=Y,e.validate=R,e})({});
|
|
37
|
+
`,r.querySelector(`.level-up-title`).textContent=t,r.querySelector(`.level-up-number`).textContent=n,this._mount(r),this._announce(`Level up: ${n}`),this._defer(()=>{for(let e=0;e<5;e++)this._defer(()=>{this._burst(`confetti`,{x:Math.random()*window.innerWidth,y:Math.random()*window.innerHeight*.6},{count:30})},e*200)},300),this._defer(()=>{r.style.opacity=`0`,this._defer(()=>this._remove(r),500)},2500)}_notice(e){let t=window.innerWidth/2,n=window.innerHeight/3,r=X(e.title);e.tier===`legendary`?(this._floatText({text:r,x:t,y:n,color:`#ffd700`,size:`36px`}),this._burst(`stars`,{x:t,y:n},{count:12}),this._burst(`confetti`,{x:t,y:n},{count:25})):e.tier===`rare`?(this._floatText({text:r,x:t,y:n,color:`#ff6b6b`,size:`32px`}),this._burst(`fire`,{x:t,y:n},{count:20})):this._floatText({text:r,x:t,y:n,color:`#fff`,size:`24px`}),this._announce(r)}text(e){this._floatText({...e})}_floatText({text:e,x:t,y:n,color:r=`#ffd700`,size:i=`24px`}){if(!this.container)return;let a=document.createElement(`div`);a.className=`floating-text`,a.textContent=X(e),a.style.left=(Number.isFinite(t)?t:window.innerWidth/2)+`px`,a.style.top=(Number.isFinite(n)?n:window.innerHeight/3)+`px`,a.style.color=r,a.style.fontSize=i,this._mount(a),this._defer(()=>this._remove(a),2e3)}_remove(e){e.remove();let t=this._detached.indexOf(e);t>-1&&this._detached.splice(t,1)}destroy(){for(let e of this._timers)clearTimeout(e);this._timers.clear(),this._cardQueue=[],this._cardActive=!1;for(let e of this._detached)e.remove();this._detached=[],this.container?.remove(),this._style?.remove(),this._style=null,this.container=null,this.liveRegion=null,this.xpBar=null,this.xpText=null,this.levelBadge=null,this.streakBadge=null,this.levelDisplay=null,this.streakDisplay=null,this._streakIcon=null}},Je=Object.freeze({matches:!1});function Ye(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||Je}var Xe=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Ze={confetti:(e,t,n,r)=>e.confetti(t,n,r),sparkle:(e,t,n,r,i)=>e.sparkle(t,n,r,i),fire:(e,t,n,r)=>e.fire(t,n,r),stars:(e,t,n,r)=>e.starBurst(t,n,r),coins:(e,t,n,r)=>e.coinShower(t,n,r)},Qe=class{constructor(e={}){this.container=e.container?typeof e.container==`string`?document.querySelector(e.container):e.container:document.body,this.container||=(console.warn(`[DopamineJS] Particle container '${e.container}' not found. Using document.body.`),document.body),this.maxParticles=Number.isFinite(e.maxParticles)?Math.max(0,Math.floor(e.maxParticles)):5e3,this._reducedMotion=e.respectReducedMotion===!1?null:Ye(window),this.canvasId=e.canvasId||`dopamine-particle-canvas`,this.canvas=document.createElement(`canvas`),this.canvas.classList.add(`dopamine-particle-canvas`),document.getElementById(this.canvasId)||(this.canvas.id=this.canvasId),this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.zIndex||`9999`,this.container===document.body?(this.canvas.style.position=`fixed`,this.canvas.style.top=`0`,this.canvas.style.left=`0`):(this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,window.getComputedStyle(this.container).position===`static`&&(this.container.style.position=`relative`));let t=this.canvas.getContext(`2d`);if(!t)throw Error(`[DopamineJS] This canvas has no 2d context`);this.container.appendChild(this.canvas),this.ctx=t,this.particles=[],this.pool=[],this.sprites=new Map,this.customEffects=new Map,this.isAnimating=!1,this._onResize=()=>this._resize(),this._resizeObserver=null,this._frameHandle=null,this._lastFrameTime=null,this._resize(),window.ResizeObserver&&this.container!==document.body?(this._resizeObserver=new ResizeObserver(this._onResize),this._resizeObserver.observe(this.container)):window.addEventListener(`resize`,this._onResize)}_resize(){let e=this.container===document.body?window.innerWidth:this.container.clientWidth,t=this.container===document.body?window.innerHeight:this.container.clientHeight,n=window.devicePixelRatio||1;this.width=e,this.height=t,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.ctx.setTransform(n,0,0,n,0,0)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){typeof t==`object`&&t&&(r=n===void 0?[]:[n,...r],{x:t,y:n}=t);let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){let{x:t,y:n,count:r=10,speed:i=5,gravity:a=.1,decay:o=.02,life:s=1,color:c=`#ffd700`,sprite:l=null,spread:u=Math.PI*2,angle:d=0,size:f=5,type:p=null}=e,m=this._allowed(r);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;e.x=t,e.y=n,e.vx=Math.cos(r)*m,e.vy=Math.sin(r)*m,e.life=s,e.decay=o*(.8+Math.random()*.4),e.gravity=a,e.color=Array.isArray(c)?c[Math.floor(Math.random()*c.length)]:c,e.size=f*(.8+Math.random()*.4),e.sprite=l,e.type=p,e.rotation=Math.random()*Math.PI*2,e.rotationSpeed=(Math.random()-.5)*.2,this.particles.push(e)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}burst(e,t,n){if(typeof e!=`string`||!Xe(Ze,e))return;let r=Number.isFinite(t?.x)?t.x:this.width/2,i=Number.isFinite(t?.y)?t.y:this.height/2,a=Number.isFinite(n?.count)?n.count:void 0;Ze[e](this,r,i,a,n?.color)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;i.x=e,i.y=t,i.vx=Math.cos(a)*4,i.vy=Math.sin(a)*4,i.life=1,i.decay=.03,i.gravity=0,i.color=`#ffffff`,i.size=15,i.sprite=null,i.type=`star`,i.rotation=a,i.rotationSpeed=0,this.particles.push(i)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];if(n.vy+=n.gravity*t,n.x+=n.vx*t,n.y+=n.vy*t,n.life-=n.decay*t,n.rotationSpeed&&(n.rotation+=n.rotationSpeed*t),n.life<=0){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t)}else{if(this.ctx.save(),this.ctx.globalAlpha=n.life,this.ctx.translate(n.x,n.y),this.ctx.rotate(n.rotation),n.sprite&&this.sprites.has(n.sprite)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}else n.type===`star`?(this.ctx.fillStyle=n.color,this._drawStarPath(0,0,5,n.size,n.size/2),this.ctx.fill()):(this.ctx.fillStyle=n.color,this.ctx.beginPath(),this.ctx.arc(0,0,n.size,0,Math.PI*2),this.ctx.fill());this.ctx.restore()}}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);for(let l=0;l<n;l++)o=e+Math.cos(a)*r,s=t+Math.sin(a)*r,this.ctx.lineTo(o,s),a+=c,o=e+Math.cos(a)*i,s=t+Math.sin(a)*i,this.ctx.lineTo(o,s),a+=c;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){this.clear(),this.isAnimating=!1,this._frameHandle!==null&&(cancelAnimationFrame(this._frameHandle),this._frameHandle=null),this._resizeObserver&&=(this._resizeObserver.disconnect(),null),window.removeEventListener(`resize`,this._onResize),this.canvas.remove(),this.sprites.clear(),this.customEffects.clear(),this.pool=[]}},$e=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),et=class{constructor(e={}){this.audioContext=null,this.storageKey=e.storageKey||`dopamineSoundsMuted`,this.storage=e.storage||Y(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=e.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(e.volume??1),this._loading=new Map,this._timers=new Set,this._synths=new Map,this._unlocks=new Set}unlockOn(e,t=[`pointerup`,`touchend`,`keydown`]){let n=()=>{for(let n of t)e.removeEventListener(n,r);this._unlocks.delete(n)},r=()=>{n(),this.initAudio()};for(let n of t)e.addEventListener(n,r);return this._unlocks.add(n),n}_later(e,t){let n=setTimeout(()=>{this._timers.delete(n),e()},t);this._timers.add(n)}initAudio(){if(!this.audioContext){let e=typeof window<`u`?window.AudioContext||window.webkitAudioContext:void 0;if(!e)return!1;this.audioContext=new e,this.masterGain=this.audioContext.createGain(),this.masterGain.gain.value=this._volume,this.masterGain.connect(this.audioContext.destination),this.preloadSounds(this.customSounds)}return this.audioContext.state===`suspended`&&this.audioContext.resume(),!0}setVolume(e){return Number.isFinite(e)&&(this._volume=Math.max(0,Math.min(1,e)),this.masterGain&&(this.masterGain.gain.value=this._volume)),this._volume}getVolume(){return this._volume}_output(){return this.masterGain||this.audioContext.destination}toggleMute(){return this.muted=!this.muted,this.storage.setItem(this.storageKey,this.muted),this.muted}registerSound(e,t){this.customSounds[e]=t,this.audioContext&&this.loadSound(e,t)}register(e,t){return typeof e!=`string`||e===``?()=>{}:typeof t==`string`?(this.registerSound(e,t),()=>{this.customSounds[e]===t&&delete this.customSounds[e],this.assets.delete(e)}):typeof t==`function`?(this._synths.set(e,t),()=>{this._synths.get(e)===t&&this._synths.delete(e)}):()=>{}}async preloadSounds(e){let t=Object.entries(e).map(([e,t])=>(this.customSounds[e]=t,this.loadSound(e,t)));await Promise.allSettled(t)}async loadSound(e,t){if(!this.audioContext)return;if(this._loading.has(e))return this._loading.get(e);let n=this._load(e,t).finally(()=>this._loading.delete(e));return this._loading.set(e,n),n}async _load(e,t){try{let n=this.audioContext,r=await fetch(t);if(r.ok===!1)throw Error(`HTTP ${r.status}`);let i=await r.arrayBuffer(),a=await n.decodeAudioData(i);this.audioContext===n&&this.assets.set(e,a)}catch(t){console.warn(`[DopamineJS] Failed to load sound '${e}':`,t)}}async play(e){if(this.muted||!this.initAudio())return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}if($e(this.customSounds,e)&&!this.assets.has(e)){let t=this.audioContext;if(await this.loadSound(e,this.customSounds[e]),this.audioContext!==t)return;if(this.assets.has(e)){this._playBuffer(this.assets.get(e));return}}let t={xp:()=>this.playXP(!0),level_up:()=>this.playLevelUp(!0),achievement:()=>this.playAchievement(!0),personal_best:()=>this.playPersonalBest(!0),click:()=>this.playClick(!0),error:()=>this.playError(!0)};this._synths.has(e)?this._synths.get(e)(this,(e,t)=>this._later(e,t)):$e(t,e)&&t[e]()}_playBuffer(e){let t=this.audioContext.createBufferSource();t.buffer=e,t.connect(this._output()),t.start(0)}playTone(e,t,n=`sine`,r=.3){if(this.muted||!this.initAudio())return;let i=this.audioContext.createOscillator(),a=this.audioContext.createGain();i.connect(a),a.connect(this._output()),i.frequency.value=e,i.type=n;let o=Math.max(1e-4,r);a.gain.setValueAtTime(o,this.audioContext.currentTime),a.gain.exponentialRampToValueAtTime(.01,this.audioContext.currentTime+t),i.start(this.audioContext.currentTime),i.stop(this.audioContext.currentTime+t)}playClick(e=!1){if(!e&&this.assets.has(`click`))return this.play(`click`);this.playTone(600,.05,`sine`,.1)}playXP(e=!1){if(!e&&this.assets.has(`xp`))return this.play(`xp`);this.playTone(700,.06,`sine`,.12)}playLevelUp(e=!1){if(!e&&this.assets.has(`level_up`))return this.play(`level_up`);this.playTone(500,.12,`sine`,.2),this._later(()=>this.playTone(700,.12,`sine`,.2),110),this._later(()=>this.playTone(900,.25,`sine`,.2),220)}playAchievement(e=!1){if(!e&&this.assets.has(`achievement`))return this.play(`achievement`);this.playTone(660,.1,`triangle`,.2),this._later(()=>this.playTone(990,.25,`triangle`,.2),100)}playPersonalBest(e=!1){if(!e&&this.assets.has(`personal_best`))return this.play(`personal_best`);this.playTone(600,.1,`sine`,.2),this._later(()=>this.playTone(800,.2,`sine`,.2),100)}playError(e=!1){if(!e&&this.assets.has(`error`))return this.play(`error`);this.playTone(200,.2,`sawtooth`,.3)}destroy(){for(let e of[...this._unlocks])e();for(let e of this._timers)clearTimeout(e);this._timers.clear(),this.audioContext&&(this.audioContext.close?.())?.catch?.(()=>{}),this.audioContext=null,this.masterGain=null,this.assets.clear(),this._loading.clear(),this._synths.clear()}};function tt({nav:e=globalThis.navigator,enabled:t=!0}={}){let n=!!t,r=t=>{if(n)try{e.vibrate(t)}catch{}};return{tap:()=>r(10),double:()=>r([10,40,10]),setEnabled(e){n=!!e}}}var nt=3,rt=[`ui`,`particles`,`sound`,`haptics`],it=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,at=(e,t)=>{it(e)&&e.then(void 0,e=>t.error(e))};function ot(){let e=typeof document<`u`&&typeof window<`u`;return{hasDom:e,reducedMotion:e?Ye(window).matches===!0:!1}}function $(e,t,n){if(e===!1)return null;let r=e;return typeof e==`function`&&(r=e(t)),r??n()}function st(e,t){let n=`dopamine_plugin_${t}:`;return{getItem:t=>e.getItem(n+t),setItem:(t,r)=>e.setItem(n+t,r),removeItem:t=>e.removeItem(n+t)}}function ct(e={}){let t=e||{},r=ot(),a={debug:()=>{},info:()=>{},warn:(...e)=>console.warn(...e),error:(...e)=>console.error(...e),...t.log||{}},o=t.storage||Y(),s=t.clock||i,c={ui:null,particles:null,sound:null,haptics:null},l={};for(let e of rt)Object.defineProperty(l,e,{enumerable:!0,get:()=>c[e]});Object.freeze(l);let u={...r,parts:l,storage:o,clock:s},d=$(t.progress,u,()=>new Ee(new De({storage:o}),{clock:s,streakDays:t.streakDays,builtinAchievements:t.builtinAchievements,loadRetryMs:t.loadRetryMs}));if(typeof d?.on!=`function`||typeof d?.off!=`function`)throw new n(`invalid_progress`,`progress needs on() and off()`);c.particles=$(t.particles,u,()=>r.hasDom?new Qe:null),c.sound=$(t.sound,u,()=>new et({storage:o})),c.haptics=$(t.haptics,u,()=>tt());try{c.ui=$(t.ui,u,()=>r.hasDom?new qe(l):null)}catch(e){throw f(),e}function f(){for(let e of rt)try{c[e]?.destroy?.()}catch(e){a.error(e)}}let p=d,m=[],h=!1,g=e=>t=>{try{at(e(t),a)}catch(e){a.error(e)}},_=()=>{let e=c.ui;if(!e||typeof d.snapshot!=`function`||typeof d.getXPForNextLevel!=`function`)return;let t=d.snapshot(),{total:n,progress:r}=d.getXPForNextLevel();e.hud({xp:t.xp,level:t.level,progress:r,streak:t.streak.current,next:n})};m.push(p.on(`xp_gained`,g(e=>{_(),e.leveledUp||c.sound?.play(`xp`)})),p.on(`level_up`,g(e=>{_(),c.ui?.popup({kind:`level`,title:``,body:String(e.newLevel)}),c.sound?.play(`level_up`)})),p.on(`achievement_unlocked`,g(e=>{c.ui?.popup({kind:`achievement`,title:e.name,body:e.description,icon:e.icon,meta:`+${e.xp??0} XP`}),c.sound?.play(`achievement`)})),p.on(`streak_updated`,g(_)),p.on(`player_reset`,g(_)),p.on(`load_recovered`,g(_)),p.on(`personal_best`,g(e=>{c.ui?.popup({kind:`notice`,title:`New High Score: ${e.score}!`,tier:`legendary`}),c.sound?.play(`personal_best`)})));let v=new Map,y=[];function b(e){if(typeof e!=`object`||!e||typeof e.name!=`string`||!/^[a-z0-9-]+$/.test(e.name)||typeof e.install!=`function`)throw new n(`plugin_invalid`,`a plugin needs a name (a-z, 0-9 and -) and an install function`);if(e.api!==3)throw new n(`plugin_api`,`${e.name} was built for api ${e.api}, this host is api 3`);if(v.has(e.name))throw new n(`plugin_duplicate`,`${e.name} is already installed`);for(let t of e.after||[])if(!v.has(t)||!v.get(t).done)throw new n(`plugin_order`,`${e.name} must come after ${t}`);for(let t of e.requires||[])if(!rt.includes(t)||c[t]===null)throw new n(`plugin_requires`,`${e.name} requires the ${t} part, which is not set`)}function ee(e){for(let t of e.offs)t();e.offs.clear(),v.delete(e.name);let t=y.indexOf(e);t>-1&&y.splice(t,1)}function x(e){if(e.removed)return;e.removed=!0;let t=e.disposer;e.disposer=null;try{t?.()}catch(e){a.error(e)}ee(e)}function S(e){let{name:t}=e;return{progress:d,parts:l,events:{on(t,n){let r=p.on(t,n),i=()=>{r(),e.offs.delete(i)};return e.offs.add(i),i},off:(e,t)=>p.off(e,t),emit(e,r){if(typeof e!=`string`||!e.startsWith(`${t}:`))throw new n(`plugin_event`,`${t} may only emit events named ${t}:<event>`);p.emit(e,r)}},storage:st(o,t),clock:s,log:a,env:{hasDom:r.hasDom,reducedMotion:r.reducedMotion},plugin:e=>v.has(e)&&v.get(e).done?v.get(e).handle:null,expose:t=>{e.handle=t}}}function C(e){if(h)throw new n(`disposed`,`the host was disposed`);b(e);let t={name:e.name,done:!1,removed:!1,disposer:null,handle:null,offs:new Set};v.set(e.name,t);let r=e=>(t.done=!0,typeof e==`function`&&(t.disposer=e),t.removed||h?(t.removed=!1,x(t),t):(y.push(t),t)),i=e=>{throw ee(t),e},a;try{a=e.install(S(t))}catch(e){return i(e)}return it(a)?a.then(r,i):r(a)}let w=null;function T(e){if(h)throw new n(`disposed`,`the host was disposed`);if(w===null){let t=C(e);if(it(t)){let e=t.then(e=>e,e=>{throw e});return w=e.then(()=>{w=null},()=>{w=null}),{record:null,done:e}}return{record:t,done:Promise.resolve(t)}}let t=w.then(()=>C(e));return w=t.then(()=>{w=null},()=>{w=null}),{record:null,done:t}}function E(e){let{record:t,done:n}=T(e);if(t)return()=>x(t);let r=null,i=!1;return n.then(e=>{r=e,i&&x(e)},e=>a.error(e)),()=>{r?x(r):i=!0}}let D=Promise.resolve();try{for(let e of t.plugins||[]){let{done:t}=T(e);D=D.then(()=>t)}}catch(e){throw O(),e}D=D.catch(e=>{throw O(),e});function O(){if(!h){h=!0;for(let e of[...y].reverse())x(e);for(let e of[...v.values()])x(e);for(let e of m)e();m.length=0,f(),d.clear?.()}}let k=D.then(()=>typeof d.init==`function`?d.init():void 0).then(()=>(h||_(),A));k.catch(()=>{});let A={progress:d,parts:l,events:p,ready:k,use:E,dispose:O};return A}return e.DataService=De,e.DopamineError=n,e.EventEmitter=t,e.HOST_API=nt,e.ParticleSystem=Qe,e.RewardSystem=Ee,e.RewardUI=qe,e.SoundManager=et,e.createDopamine=ct,e.createHaptics=tt,e.createMemoryStorage=J,e.merge=W,e.prefersReducedMotion=Ye,e.resolveStorage=Y,e.validate=R,e})({});
|
package/dist/dopamine.js
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
|
|
1
|
+
import { i as e, n as t, r as n, t as r } from "./host-B-Gn-Zg_.js";
|
|
2
|
+
import { i, n as a, o, r as s, s as c, t as l } from "./DataService-B5noGvMr.js";
|
|
3
|
+
import { n as u, r as d, t as f } from "./SoundManager-C6VdZEFo.js";
|
|
4
|
+
import { n as p, t as m } from "./storage-C2s4Da9b.js";
|
|
5
|
+
export { l as DataService, o as DopamineError, c as EventEmitter, r as HOST_API, u as ParticleSystem, a as RewardSystem, e as RewardUI, f as SoundManager, t as createDopamine, n as createHaptics, m as createMemoryStorage, s as merge, d as prefersReducedMotion, p as resolveStorage, i as validate };
|