dopaminejs 3.1.0 → 3.3.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 +30 -0
- package/dist/{DataService-DN6xwvXU.js → DataService-Bd1S-C1N.js} +5 -3
- package/dist/{DataService-D1uL6E8R.cjs → DataService-GRTvq4BS.cjs} +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.js +1 -1
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.js +2 -2
- package/dist/host-Bm0Kq5Th.cjs +37 -0
- package/dist/{host-CdjhXPy-.js → host-CSnyl6nv.js} +28 -5
- package/dist/style.css +13 -12
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +2 -2
- package/package.json +1 -1
- package/spec/README.md +1 -1
- package/spec/fixtures/streaks.json +77 -0
- package/src/dopamine/core/RewardSystem.js +22 -1
- package/src/dopamine/ui/RewardUI.js +43 -2
- package/src/dopamine/ui/dopamine.css +13 -12
- package/types/index.d.ts +8 -1
- package/dist/host-7FzZ-yO7.cjs +0 -37
package/README.md
CHANGED
|
@@ -94,6 +94,36 @@ import { myPlugin } from './my-plugin.js';
|
|
|
94
94
|
const dopamine = createDopamine({ plugins: [myPlugin] });
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
+
## Style the achievement card
|
|
98
|
+
|
|
99
|
+
The achievement card reads CSS variables. Each has a fallback, so the default look stays as it is.
|
|
100
|
+
|
|
101
|
+
| Variable | Sets | Default |
|
|
102
|
+
|---|---|---|
|
|
103
|
+
| `--dopamine-toast-bg` | background | purple gradient |
|
|
104
|
+
| `--dopamine-toast-text` | name colour | `white` |
|
|
105
|
+
| `--dopamine-toast-muted` | title and description colour | translucent white |
|
|
106
|
+
| `--dopamine-toast-accent` | XP chip text | `#ffd700` |
|
|
107
|
+
| `--dopamine-toast-radius` | corner radius | `16px` |
|
|
108
|
+
| `--dopamine-toast-shadow` | box shadow | `0 8px 32px rgba(0, 0, 0, 0.4)` |
|
|
109
|
+
| `--dopamine-toast-top` | distance from the top, plus the safe area inset | `80px` |
|
|
110
|
+
| `--dopamine-toast-right` | distance from the right | `20px` (`12px` on small screens) |
|
|
111
|
+
| `--dopamine-toast-left` | distance from the left | `auto` |
|
|
112
|
+
| `--dopamine-toast-max-width` | max width, never wider than the screen less 24px on small screens | `320px` |
|
|
113
|
+
|
|
114
|
+
```css
|
|
115
|
+
:root {
|
|
116
|
+
--dopamine-toast-bg: #1b1f3a;
|
|
117
|
+
--dopamine-toast-accent: #7cf5c8;
|
|
118
|
+
--dopamine-toast-top: 16px;
|
|
119
|
+
--dopamine-toast-radius: 8px;
|
|
120
|
+
}
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
To put the card on the left, set `--dopamine-toast-right: auto` as well. With both sides set, the card stretches between them up to its max width.
|
|
124
|
+
|
|
125
|
+
Cards show one at a time. A second unlock waits until the first has left, so its announcement and confetti come later too.
|
|
126
|
+
|
|
97
127
|
## Cleanup
|
|
98
128
|
|
|
99
129
|
Everything that touches the DOM can be torn down:
|
|
@@ -480,10 +480,12 @@ var X = "device", Z = () => {
|
|
|
480
480
|
});
|
|
481
481
|
return a;
|
|
482
482
|
}
|
|
483
|
-
async reset() {
|
|
484
|
-
|
|
483
|
+
async reset(e) {
|
|
484
|
+
let t = e?.overwrite;
|
|
485
|
+
if (e !== void 0 && (typeof e != "object" || !e || Array.isArray(e)) || t !== void 0 && typeof t != "boolean") throw TypeError("[DopamineJS] reset expects { overwrite?: boolean }");
|
|
486
|
+
return this._requirePlayer(), t === !1 && this._readFailed ? (this._doc = A(this.clock.now()), this._publish("player_reset", {}), this.snapshot()) : (await this._batch(async () => {
|
|
485
487
|
this._doc = A(this.clock.now()), this._loadFailed = !1, this._readFailed = !1, await this.save();
|
|
486
|
-
}), this._publish("player_reset", {}), this.snapshot();
|
|
488
|
+
}), this._publish("player_reset", {}), this.snapshot());
|
|
487
489
|
}
|
|
488
490
|
use(e) {
|
|
489
491
|
return this._middleware.use(e);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(n=>{try{n(t)}catch(t){console.error(`Error in listener for event '${e}':`,t)}})}clear(){this.listeners.clear()}},t=class extends Error{constructor(e,t){super(t||e),this.name=`DopamineError`,this.code=e}},n=(e,t=2)=>String(e).padStart(t,`0`),r={now:()=>Date.now(),localDate(e=Date.now()){let t=new Date(e);return`${n(t.getFullYear(),4)}-${n(t.getMonth()+1)}-${n(t.getDate())}`}},i=e=>e>0?Math.max(1,Math.floor((1+Math.sqrt(1+4*e/50))/2)):1,a=e=>50*e*(e-1),o=()=>({first_game:{name:`First Steps`,description:`Play your first game`,icon:`🎮`,xp:50,check:e=>e.totalGamesPlayed>=1},level_5:{name:`Rising Star`,description:`Reach level 5`,icon:`⭐`,xp:100,check:e=>e.level>=5},level_10:{name:`Expert Player`,description:`Reach level 10`,icon:`🏆`,xp:250,check:e=>e.level>=10},streak_3:{name:`Dedicated`,description:`Play 3 days in a row`,icon:`🔥`,xp:100,check:e=>e.streak.current>=3},streak_7:{name:`Unstoppable`,description:`Play 7 days in a row`,icon:`💥`,xp:300,check:e=>e.streak.current>=7}}),s={first_game:50,level_5:100,level_10:250,streak_3:100,streak_7:300},c=e=>{let t={};for(let n of Object.keys(e))t[n]=Number.isFinite(e[n]?.xp)&&e[n].xp>0?e[n].xp:0;return t},l=864e5,u=/^\d{4}-\d{2}-\d{2}$/,d=e=>{let t=new Date(0);return t.setUTCFullYear(+e.slice(0,4),e.slice(5,7)-1,+e.slice(8)),t.getTime()/l},f=e=>new Date(e*l).toISOString().slice(0,10),p=e=>typeof e==`string`&&u.test(e)&&f(d(e))===e,m=(e,t)=>f(d(e)+t);function h(e,t){let n=[...new Set(e)].sort();if(!t)return n;let r=d(t)-399,i=d(t)+1;return n.filter(e=>d(e)>=r&&d(e)<=i)}function g(e,t){let n=new Set(e),r=n.has(t)?t:m(t,-1),i=0;for(;n.has(r);)i++,r=m(r,-1);return i}function _(e){let t=0,n=0,r=NaN;for(let i of[...e].sort()){let e=d(i);n=e===r+1?n+1:1,r=e,n>t&&(t=n)}return t}var v=(e,t)=>e.reduce((e,n)=>n<=t&&(!e||n>e)?n:e,void 0),y=`legacy`,b=new Set([`__proto__`,`constructor`,`prototype`]),x=e=>typeof e==`string`&&e.length>0&&!b.has(e),S=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),C=e=>typeof e==`object`&&!!e&&!Array.isArray(e),w=e=>Number.isInteger(e)&&e>=0,T=e=>Number.isFinite(e)&&e>=0,E=e=>Number.isFinite(e),D=e=>Math.min(e,2**53-1),O=(e,t,n=0)=>Number.isInteger(e)&&e>=n?D(e):t,k=(e,t=e=>e)=>Object.keys(e).sort().reduce((n,r)=>D(n+t(e[r])),0),A=(e=0)=>({v:3,name:`Player`,createdAt:e,lastPlayedAt:e,level:1,longest:0,playDates:[],xpBy:{},xpSpentBy:{},gamesBy:{},playsBy:{},best:{},sumsBy:{},achievements:{}});function j(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&t(e[r])&&(n[r]=D(e[r]));return n}function M(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&(n[r]=j(e[r],t));return n}function N(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e)){let i=e[r];x(r)&&C(i)&&(n[r]={unlockedAt:E(i.unlockedAt)?i.unlockedAt:t,seen:i.seen===!0,reward:T(i.reward)?D(i.reward):0})}return n}function P(e){let t=e.sumsBy,n=new Set([...Object.keys(e.playsBy),...Object.keys(e.best),...Object.keys(t)]);for(let r of n)S(e.playsBy,r)||(e.playsBy[r]={}),S(e.best,r)||(e.best[r]=0),S(t,r)||(t[r]={});return e}function F(e,t,n){return P({v:3,name:typeof e.name==`string`?e.name:`Player`,createdAt:E(e.createdAt)?e.createdAt:t,lastPlayedAt:E(e.lastPlayedAt)?e.lastPlayedAt:t,level:O(e.level,1,1),longest:O(e.longest,0),playDates:h(Array.isArray(e.playDates)?e.playDates.filter(p):[],n),xpBy:j(e.xpBy,T),xpSpentBy:j(e.xpSpentBy,T),gamesBy:j(e.gamesBy,w),playsBy:M(e.playsBy,w),best:j(e.best,T),sumsBy:I(e.sumsBy),achievements:N(e.achievements,t)})}function I(e){let t={};if(!C(e))return t;for(let n of Object.keys(e))x(n)&&(t[n]=M(e[n],E));return t}function L(e,t,n,r){let a=A(t);a.name=typeof e.name==`string`?e.name:`Player`,a.createdAt=E(e.createdAt)?e.createdAt:t,a.lastPlayedAt=E(e.lastPlayedAt)?e.lastPlayedAt:t,a.achievements=N(e.achievements,t);let o=0;for(let e of Object.keys(a.achievements)){let t=S(n,e)&&T(n[e])?D(n[e]):0;a.achievements[e].reward=t,o+=t}let s=T(e.xp)?D(e.xp):0,c=Math.max(0,s-o);c>0&&(a.xpBy[y]=c),a.level=Math.max(i(s),O(e.level,1,1));let l=O(e.totalGamesPlayed,0);if(l>0&&(a.gamesBy[y]=l),C(e.stats))for(let t of Object.keys(e.stats)){let n=e.stats[t];if(!x(t)||!C(n))continue;let r=O(n.totalPlays,0);a.playsBy[t]=r>0?{[y]:r}:{},a.best[t]=T(n.highScore)?D(n.highScore):0,a.sumsBy[t]={};for(let e of Object.keys(n))x(e)&&e!==`totalPlays`&&e!==`highScore`&&E(n[e])&&(a.sumsBy[t][e]={[y]:D(n[e])})}let u=C(e.streak)?e.streak:{},d=O(u.current,1,1);if(a.longest=Math.max(d,O(u.longest,0)),p(u.lastPlayDate)){for(let e=0;e<Math.min(d,400);e++)a.playDates.push(m(u.lastPlayDate,-e));a.playDates=h(a.playDates,r)}else a.longest=O(u.longest,0);return P(a)}function R(e){let t=new Set([...Object.keys(e.xpBy),...Object.keys(e.xpSpentBy),...Object.keys(e.gamesBy)]);for(let n of Object.keys(e.playsBy))for(let r of Object.keys(e.playsBy[n]))t.add(r);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))for(let i of Object.keys(e.sumsBy[n][r]))t.add(i);return t}function z(e){if(R(e).size>20)throw new t(`too_many_devices`,`[DopamineJS] a save holds at most 20 devices`)}function B(e,n={}){if(!C(e))throw new t(`invalid_document`,`[DopamineJS] a save must be an object`);if(e.v!==void 0&&e.v!==3)throw new t(`unsupported_version`,`[DopamineJS] save version ${String(e.v)} is not 3`);let r=E(n.now)?n.now:0,i=p(n.today)?n.today:void 0,a=e.v===3?F(e,r,i):L(e,r,C(n.rewards)?n.rewards:s,i);return z(a),a}var V=e=>D(Math.max(0,k(e.xpBy)+k(e.achievements,e=>e.reward)-k(e.xpSpentBy))),H=e=>Math.max(e.level,i(V(e)));function U(e,t){let n={};for(let t of Object.keys(e.playsBy)){let r={plays:k(e.playsBy[t]),best:e.best[t]};for(let n of Object.keys(e.sumsBy[t]))n!==`plays`&&n!==`best`&&(r[n]=k(e.sumsBy[t][n]));n[t]=r}let r={};for(let t of Object.keys(e.achievements))r[t]={...e.achievements[t]};let i={current:g(e.playDates,t),longest:Math.max(e.longest,_(e.playDates))},a=v(e.playDates,t);return a&&(i.lastPlayDate=a),{name:e.name,xp:V(e),level:H(e),totalGamesPlayed:k(e.gamesBy),createdAt:e.createdAt,lastPlayedAt:e.lastPlayedAt,streak:i,achievements:r,stats:n}}var W=e=>JSON.parse(JSON.stringify(e));function G(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))G(e[t])}return e}var K=[`beforeXP`,`afterXP`,`beforeRecord`,`afterRecord`,`beforeUnlock`,`afterUnlock`],q=class{constructor(){this._list=[]}use(e){if(!C(e)||!K.some(t=>typeof e[t]==`function`))throw TypeError(`[DopamineJS] use expects an object with one of: ${K.join(`, `)}`);return this._list.push(e),()=>{let t=this._list.indexOf(e);t>=0&&this._list.splice(t,1)}}async before(e,t,n=()=>!0){for(let r of[...this._list]){if(typeof r[e]!=`function`)continue;let i;try{i=await r[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t);continue}if(i===!1)return!1;if(!C(i))continue;let a={...t};for(let e of Object.keys(t))Object.prototype.hasOwnProperty.call(i,e)&&(a[e]=i[e]);n(a)&&(t=a)}return t}async after(e,t){for(let n of[...this._list])if(typeof n[e]==`function`)try{await n[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t)}}};function J(e,t,n){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=S(e,i)?e[i]:void 0,o=S(t,i)?t[i]:void 0;r[i]=n>0?J(a||{},o||{},n-1):a===void 0?o:o===void 0?a:Math.max(a,o)}return r}function ee(e,t){let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let i=S(e,r)?e[r]:void 0,a=S(t,r)?t[r]:void 0;if(!i||!a){n[r]={...i||a};continue}let o=i.unlockedAt<a.unlockedAt||i.unlockedAt===a.unlockedAt&&i.reward>=a.reward?i:a;n[r]={unlockedAt:o.unlockedAt,seen:i.seen||a.seen,reward:o.reward}}return n}var te=(e,t)=>e>0&&t>0?Math.min(e,t):Math.max(e,t);function Y(e,t,n){let r=B(e,n),i=B(t,n),a={v:3,name:(r.lastPlayedAt===i.lastPlayedAt?r.name>=i.name?r:i:r.lastPlayedAt>i.lastPlayedAt?r:i).name,createdAt:te(r.createdAt,i.createdAt),lastPlayedAt:Math.max(r.lastPlayedAt,i.lastPlayedAt),level:Math.max(r.level,i.level),longest:Math.max(r.longest,i.longest),playDates:h([...r.playDates,...i.playDates],p(n?.today)?n.today:void 0),xpBy:J(r.xpBy,i.xpBy,0),xpSpentBy:J(r.xpSpentBy,i.xpSpentBy,0),gamesBy:J(r.gamesBy,i.gamesBy,0),playsBy:J(r.playsBy,i.playsBy,1),best:J(r.best,i.best,0),sumsBy:J(r.sumsBy,i.sumsBy,2),achievements:ee(r.achievements,i.achievements)};return z(a),a}var X=`device`,Z=()=>{let e=new Uint8Array(8),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)t.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)},ne=e=>x(e)&&e!==`legacy`,re=class extends e{constructor(e,t={}){super(),this.dataService=e,this.clock=t.clock&&typeof t.clock.now==`function`&&typeof t.clock.localDate==`function`?t.clock:r,this.achievements={...t.builtinAchievements===!1?{}:o(),...t.achievements||{}},this.streakDays=t.streakDays===`record`?`record`:`any`,this._doc=null,this._deviceId=null,this._deviceSaved=!1,this._middleware=new q,this._batchDepth=0,this._pendingSave=!1,this._loadFailed=!1,this._readFailed=!1}get loadFailed(){return this._readFailed}_publish(e,t){let n=Object.freeze({...t});this.emit(e,n)}async _batch(e){this._batchDepth++;try{return await e()}finally{this._batchDepth--,this._batchDepth===0&&this._pendingSave&&(this._pendingSave=!1,await this._write())}}_options(){return{now:this.clock.now(),today:this.clock.localDate(),rewards:{...s,...c(this.achievements)}}}async init(){let e=await this._readSaved();return this._loadFailed&&this._doc||(this._doc=this._load(e)),await this._readDevice(),await this.save(),this.snapshot()}async _readSaved(){this._loadFailed=!0;try{let e=await this.dataService.load(`player`,null,{strict:!0});return this._loadFailed=!1,this._readFailed=!1,e}catch(e){if(e?.code===`DOPAMINE_CORRUPT`){let t=await this.dataService.save(`player_corrupt`,e.raw);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}return this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null}}_load(e){if(!C(e))return A(this.clock.now());try{return B(e,this._options())}catch(e){if(!(e instanceof t))throw e;return this._loadFailed=!0,this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:e.code,error:e}),A(this.clock.now())}}async _readDevice(){if(this._deviceId)return;let e=null;try{e=await this.dataService.load(X,null,{strict:!0})}catch{this._deviceId=Z();return}ne(e)?(this._deviceId=e,this._deviceSaved=!0):this._deviceId=Z()}_hasSlot(){let e=R(this._doc);return e.has(this._deviceId)||e.size<20?!0:(this._publish(`load_failed`,{key:`player`,reason:`too_many_devices`}),!1)}_requirePlayer(){if(!this._doc)throw Error(`[DopamineJS] RewardSystem.init() must be awaited before use`)}snapshot(){return this._requirePlayer(),G(U(this._doc,this.clock.localDate()))}export(){return this._requirePlayer(),W(this._doc)}async import(e,{silent:t=!1}={}){this._requirePlayer();let n=this.snapshot(),r=B(e,this._options()),i=Y(this._doc,r,this._options());i.level=H(i),this._doc=i;let a=this.snapshot();if(await this.save(),t)return a;let o=a.xp-n.xp,s=a.level>n.level;o>0&&this._publish(`xp_gained`,{amount:o,reason:`import`,leveledUp:s,newLevel:a.level,total:a.xp}),s&&this._publish(`level_up`,{oldLevel:n.level,newLevel:a.level,totalXP:a.xp});for(let e of Object.keys(a.achievements))!S(n.achievements,e)&&S(this.achievements,e)&&this._publish(`achievement_unlocked`,{...this.achievements[e],id:e});return a}async reset(){return this._requirePlayer(),await this._batch(async()=>{this._doc=A(this.clock.now()),this._loadFailed=!1,this._readFailed=!1,await this.save()}),this._publish(`player_reset`,{}),this.snapshot()}use(e){return this._middleware.use(e)}defineAchievement(e,t){if(!x(e))throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);if(!C(t)||typeof t.check!=`function`)throw TypeError(`[DopamineJS] defineAchievement expects a definition with a check function`);let n=S(this.achievements,e)?this.achievements[e]:void 0;return this.achievements[e]=t,()=>{this.achievements[e]===t&&(n?this.achievements[e]=n:delete this.achievements[e])}}async save(){if(this._doc){if(this._batchDepth>0){this._pendingSave=!0;return}await this._write()}}async _write(){this._loadFailed||(this._doc.lastPlayedAt=this.clock.now(),this._deviceSaved||=await this.dataService.save(X,this._deviceId)!==!1,await this.dataService.save(`player`,this._doc)===!1&&this._publish(`save_failed`,{key:`player`}))}async addXP(e,t=``){if(!Number.isFinite(e))throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);if(this._requirePlayer(),!this._hasSlot())return{leveledUp:!1,newLevel:H(this._doc),xpGained:0};let n=await this._middleware.before(`beforeXP`,{amount:e,reason:t},e=>Number.isFinite(e.amount));if(n===!1)return{leveledUp:!1,newLevel:H(this._doc),xpGained:0};this.streakDays===`any`&&n.amount>0&&this._markDay();let r=await this._applyXP(n.amount,n.reason,(e,t)=>{t>=0?e.xpBy[this._deviceId]=D((S(e.xpBy,this._deviceId)?e.xpBy[this._deviceId]:0)+t):e.xpSpentBy[this._deviceId]=D((S(e.xpSpentBy,this._deviceId)?e.xpSpentBy[this._deviceId]:0)-t)});return await this._middleware.after(`afterXP`,{amount:r.xpGained,reason:n.reason,total:V(this._doc),level:r.newLevel}),r}async _applyXP(e,t,n){let r=this._doc,i=H(r);return e=Math.max(e,-V(r)),n(r,e),this._announceXP(i,e,t)}async _announceXP(e,t,n){let r=this._doc,a=V(r),o=Math.max(e,i(a)),s=o>e;return o>r.level&&(r.level=o),await this.save(),this._publish(`xp_gained`,{amount:t,reason:n,leveledUp:s,newLevel:o,total:a}),s&&this._publish(`level_up`,{oldLevel:e,newLevel:o,totalXP:a}),{leveledUp:s,newLevel:o,xpGained:t}}getXPForNextLevel(){this._requirePlayer();let e=H(this._doc),t=V(this._doc),n=a(e+1),r=a(e),i=n-r,o=i>0?Math.max(0,Math.min(1,(t-r)/i)):0;return{total:n,needed:Math.max(0,n-t),progress:o}}_checkRecord(e,t){if(!x(e))throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);if(!C(t))throw TypeError(`[DopamineJS] record expects a result object`);if(t.score!==void 0&&!Number.isFinite(t.score))throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`)}async record(e,t={}){if(this._requirePlayer(),this._checkRecord(e,t),!this._hasSlot())return!1;let n=await this._middleware.before(`beforeRecord`,{activity:e,result:t},e=>{try{return this._checkRecord(e.activity,e.result),!0}catch{return!1}});if(n===!1)return!1;let r=await this._batch(()=>this._record(n.activity,n.result));return await this._middleware.after(`afterRecord`,{activity:n.activity,result:n.result,xp:r}),!0}_markDay(){let e=this._doc,t=this.clock.localDate();if(e.playDates.includes(t))return;let n=e.playDates.length===0;e.playDates=h([...e.playDates,t],t),e.longest=Math.max(e.longest,_(e.playDates)),n||this._publish(`streak_updated`,{current:g(e.playDates,t),longest:Math.max(e.longest,_(e.playDates))})}async _record(e,t){let n=this._doc,r=this._deviceId,i=(e,t)=>{e[r]=D((S(e,r)?e[r]:0)+t)};this._markDay(),S(n.playsBy,e)||(n.playsBy[e]={},n.best[e]=0,n.sumsBy[e]={}),i(n.playsBy[e],1),i(n.gamesBy,1),t.score!==void 0&&t.score>n.best[e]&&(n.best[e]=t.score,this._publish(`personal_best`,{activity:e,score:t.score}));for(let r of Object.keys(t))r!==`score`&&r!==`plays`&&r!==`best`&&x(r)&&(S(n.sumsBy[e],r)||(n.sumsBy[e][r]={}),i(n.sumsBy[e][r],Number.isFinite(t[r])&&t[r]>0?t[r]:0));let a=10;return t.score&&(a+=Math.max(0,Math.floor(t.score/5))),a=Math.floor(a*this.getStreakMultiplier()),await this.addXP(a,`Played ${e}`),await this.checkAchievements(e,t),await this.save(),a}async checkAchievements(e,t){let n=[];for(let[r,i]of Object.entries(this.achievements)){if(S(this._doc.achievements,r))continue;let a=!1;try{a=i.check(this.snapshot(),e,t)}catch(e){console.error(`[DopamineJS] Achievement "${r}" check threw:`,e);continue}a&&await this.unlockAchievement(r)&&n.push(i)}return n}async unlockAchievement(e){if(this._requirePlayer(),!x(e)||!S(this.achievements,e)||S(this._doc.achievements,e))return!1;let t=this.achievements[e];if(!t)return!1;let{[e]:n}=c(this.achievements),r=await this._middleware.before(`beforeUnlock`,{id:e,reward:n},e=>Number.isFinite(e.reward)&&e.reward>=0);if(r===!1)return!1;let i=this._doc,a=H(i);return i.achievements[e]={unlockedAt:this.clock.now(),seen:!1,reward:r.reward},await this._announceXP(a,r.reward,`Achievement: ${t.name}`),this._publish(`achievement_unlocked`,{...t,id:e}),await this.save(),await this._middleware.after(`afterUnlock`,{id:e,reward:r.reward}),!0}getUnlockedAchievements(){return this._requirePlayer(),Object.entries(this._doc.achievements).map(([e,t])=>({...this.achievements[e],id:e,...t}))}getUnseenAchievements(){return this.getUnlockedAchievements().filter(e=>!e.seen)}async markAchievementsSeen(e){for(let t of e)S(this._doc.achievements,t)&&(this._doc.achievements[t].seen=!0);await this.save()}getStreakMultiplier(){let e=this.snapshot().streak.current;return e>=7?2:e>=5?1.5:e>=3?1.25:1}};function Q(){let e=new Map;return{getItem:t=>e.has(t)?e.get(t):null,setItem:(t,n)=>{e.set(t,String(n))},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()}}}function $(){try{if(typeof localStorage>`u`)return Q();let e=`__dopamine_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return Q()}}var ie=class{constructor(e={}){this.storage=e.storage||$(),this.prefix=e.prefix||`dopamine_`,this._tail=null}_write(e){let t=this._tail?this._tail.then(e):e();if(typeof t?.then==`function`){let e=Promise.resolve(t).catch(()=>{}).then(()=>{this._tail===e&&(this._tail=null)});this._tail=e}return t}async save(e,t){try{let n=JSON.stringify(t);return await this._write(()=>this.storage.setItem(this.prefix+e,n)),!0}catch(e){return console.error(`Error saving data:`,e),!1}}async load(e,t=null,n={}){let r;try{await this._tail,r=await this.storage.getItem(this.prefix+e)}catch(e){if(n.strict)throw e;return console.error(`Error loading data:`,e),t}if(!r)return t;try{return JSON.parse(r)}catch(i){if(n.strict)throw Object.assign(Error(`[DopamineJS] saved "${e}" is not valid JSON`),{code:`DOPAMINE_CORRUPT`,raw:r});return console.error(`Error loading data:`,i),t}}async clear(e){await this._write(()=>this.storage.removeItem(this.prefix+e))}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ie}});
|
|
1
|
+
var e=class{constructor(){this.listeners=new Map}on(e,t){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(t),()=>this.off(e,t)}off(e,t){this.listeners.has(e)&&this.listeners.get(e).delete(t)}emit(e,t){this.listeners.has(e)&&this.listeners.get(e).forEach(n=>{try{n(t)}catch(t){console.error(`Error in listener for event '${e}':`,t)}})}clear(){this.listeners.clear()}},t=class extends Error{constructor(e,t){super(t||e),this.name=`DopamineError`,this.code=e}},n=(e,t=2)=>String(e).padStart(t,`0`),r={now:()=>Date.now(),localDate(e=Date.now()){let t=new Date(e);return`${n(t.getFullYear(),4)}-${n(t.getMonth()+1)}-${n(t.getDate())}`}},i=e=>e>0?Math.max(1,Math.floor((1+Math.sqrt(1+4*e/50))/2)):1,a=e=>50*e*(e-1),o=()=>({first_game:{name:`First Steps`,description:`Play your first game`,icon:`🎮`,xp:50,check:e=>e.totalGamesPlayed>=1},level_5:{name:`Rising Star`,description:`Reach level 5`,icon:`⭐`,xp:100,check:e=>e.level>=5},level_10:{name:`Expert Player`,description:`Reach level 10`,icon:`🏆`,xp:250,check:e=>e.level>=10},streak_3:{name:`Dedicated`,description:`Play 3 days in a row`,icon:`🔥`,xp:100,check:e=>e.streak.current>=3},streak_7:{name:`Unstoppable`,description:`Play 7 days in a row`,icon:`💥`,xp:300,check:e=>e.streak.current>=7}}),s={first_game:50,level_5:100,level_10:250,streak_3:100,streak_7:300},c=e=>{let t={};for(let n of Object.keys(e))t[n]=Number.isFinite(e[n]?.xp)&&e[n].xp>0?e[n].xp:0;return t},l=864e5,u=/^\d{4}-\d{2}-\d{2}$/,d=e=>{let t=new Date(0);return t.setUTCFullYear(+e.slice(0,4),e.slice(5,7)-1,+e.slice(8)),t.getTime()/l},f=e=>new Date(e*l).toISOString().slice(0,10),p=e=>typeof e==`string`&&u.test(e)&&f(d(e))===e,m=(e,t)=>f(d(e)+t);function h(e,t){let n=[...new Set(e)].sort();if(!t)return n;let r=d(t)-399,i=d(t)+1;return n.filter(e=>d(e)>=r&&d(e)<=i)}function g(e,t){let n=new Set(e),r=n.has(t)?t:m(t,-1),i=0;for(;n.has(r);)i++,r=m(r,-1);return i}function _(e){let t=0,n=0,r=NaN;for(let i of[...e].sort()){let e=d(i);n=e===r+1?n+1:1,r=e,n>t&&(t=n)}return t}var v=(e,t)=>e.reduce((e,n)=>n<=t&&(!e||n>e)?n:e,void 0),y=`legacy`,b=new Set([`__proto__`,`constructor`,`prototype`]),x=e=>typeof e==`string`&&e.length>0&&!b.has(e),S=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),C=e=>typeof e==`object`&&!!e&&!Array.isArray(e),w=e=>Number.isInteger(e)&&e>=0,T=e=>Number.isFinite(e)&&e>=0,E=e=>Number.isFinite(e),D=e=>Math.min(e,2**53-1),O=(e,t,n=0)=>Number.isInteger(e)&&e>=n?D(e):t,k=(e,t=e=>e)=>Object.keys(e).sort().reduce((n,r)=>D(n+t(e[r])),0),A=(e=0)=>({v:3,name:`Player`,createdAt:e,lastPlayedAt:e,level:1,longest:0,playDates:[],xpBy:{},xpSpentBy:{},gamesBy:{},playsBy:{},best:{},sumsBy:{},achievements:{}});function j(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&t(e[r])&&(n[r]=D(e[r]));return n}function M(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e))x(r)&&(n[r]=j(e[r],t));return n}function N(e,t){let n={};if(!C(e))return n;for(let r of Object.keys(e)){let i=e[r];x(r)&&C(i)&&(n[r]={unlockedAt:E(i.unlockedAt)?i.unlockedAt:t,seen:i.seen===!0,reward:T(i.reward)?D(i.reward):0})}return n}function P(e){let t=e.sumsBy,n=new Set([...Object.keys(e.playsBy),...Object.keys(e.best),...Object.keys(t)]);for(let r of n)S(e.playsBy,r)||(e.playsBy[r]={}),S(e.best,r)||(e.best[r]=0),S(t,r)||(t[r]={});return e}function F(e,t,n){return P({v:3,name:typeof e.name==`string`?e.name:`Player`,createdAt:E(e.createdAt)?e.createdAt:t,lastPlayedAt:E(e.lastPlayedAt)?e.lastPlayedAt:t,level:O(e.level,1,1),longest:O(e.longest,0),playDates:h(Array.isArray(e.playDates)?e.playDates.filter(p):[],n),xpBy:j(e.xpBy,T),xpSpentBy:j(e.xpSpentBy,T),gamesBy:j(e.gamesBy,w),playsBy:M(e.playsBy,w),best:j(e.best,T),sumsBy:I(e.sumsBy),achievements:N(e.achievements,t)})}function I(e){let t={};if(!C(e))return t;for(let n of Object.keys(e))x(n)&&(t[n]=M(e[n],E));return t}function L(e,t,n,r){let a=A(t);a.name=typeof e.name==`string`?e.name:`Player`,a.createdAt=E(e.createdAt)?e.createdAt:t,a.lastPlayedAt=E(e.lastPlayedAt)?e.lastPlayedAt:t,a.achievements=N(e.achievements,t);let o=0;for(let e of Object.keys(a.achievements)){let t=S(n,e)&&T(n[e])?D(n[e]):0;a.achievements[e].reward=t,o+=t}let s=T(e.xp)?D(e.xp):0,c=Math.max(0,s-o);c>0&&(a.xpBy[y]=c),a.level=Math.max(i(s),O(e.level,1,1));let l=O(e.totalGamesPlayed,0);if(l>0&&(a.gamesBy[y]=l),C(e.stats))for(let t of Object.keys(e.stats)){let n=e.stats[t];if(!x(t)||!C(n))continue;let r=O(n.totalPlays,0);a.playsBy[t]=r>0?{[y]:r}:{},a.best[t]=T(n.highScore)?D(n.highScore):0,a.sumsBy[t]={};for(let e of Object.keys(n))x(e)&&e!==`totalPlays`&&e!==`highScore`&&E(n[e])&&(a.sumsBy[t][e]={[y]:D(n[e])})}let u=C(e.streak)?e.streak:{},d=O(u.current,1,1);if(a.longest=Math.max(d,O(u.longest,0)),p(u.lastPlayDate)){for(let e=0;e<Math.min(d,400);e++)a.playDates.push(m(u.lastPlayDate,-e));a.playDates=h(a.playDates,r)}else a.longest=O(u.longest,0);return P(a)}function R(e){let t=new Set([...Object.keys(e.xpBy),...Object.keys(e.xpSpentBy),...Object.keys(e.gamesBy)]);for(let n of Object.keys(e.playsBy))for(let r of Object.keys(e.playsBy[n]))t.add(r);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))for(let i of Object.keys(e.sumsBy[n][r]))t.add(i);return t}function z(e){if(R(e).size>20)throw new t(`too_many_devices`,`[DopamineJS] a save holds at most 20 devices`)}function B(e,n={}){if(!C(e))throw new t(`invalid_document`,`[DopamineJS] a save must be an object`);if(e.v!==void 0&&e.v!==3)throw new t(`unsupported_version`,`[DopamineJS] save version ${String(e.v)} is not 3`);let r=E(n.now)?n.now:0,i=p(n.today)?n.today:void 0,a=e.v===3?F(e,r,i):L(e,r,C(n.rewards)?n.rewards:s,i);return z(a),a}var V=e=>D(Math.max(0,k(e.xpBy)+k(e.achievements,e=>e.reward)-k(e.xpSpentBy))),H=e=>Math.max(e.level,i(V(e)));function U(e,t){let n={};for(let t of Object.keys(e.playsBy)){let r={plays:k(e.playsBy[t]),best:e.best[t]};for(let n of Object.keys(e.sumsBy[t]))n!==`plays`&&n!==`best`&&(r[n]=k(e.sumsBy[t][n]));n[t]=r}let r={};for(let t of Object.keys(e.achievements))r[t]={...e.achievements[t]};let i={current:g(e.playDates,t),longest:Math.max(e.longest,_(e.playDates))},a=v(e.playDates,t);return a&&(i.lastPlayDate=a),{name:e.name,xp:V(e),level:H(e),totalGamesPlayed:k(e.gamesBy),createdAt:e.createdAt,lastPlayedAt:e.lastPlayedAt,streak:i,achievements:r,stats:n}}var W=e=>JSON.parse(JSON.stringify(e));function G(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))G(e[t])}return e}var K=[`beforeXP`,`afterXP`,`beforeRecord`,`afterRecord`,`beforeUnlock`,`afterUnlock`],q=class{constructor(){this._list=[]}use(e){if(!C(e)||!K.some(t=>typeof e[t]==`function`))throw TypeError(`[DopamineJS] use expects an object with one of: ${K.join(`, `)}`);return this._list.push(e),()=>{let t=this._list.indexOf(e);t>=0&&this._list.splice(t,1)}}async before(e,t,n=()=>!0){for(let r of[...this._list]){if(typeof r[e]!=`function`)continue;let i;try{i=await r[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t);continue}if(i===!1)return!1;if(!C(i))continue;let a={...t};for(let e of Object.keys(t))Object.prototype.hasOwnProperty.call(i,e)&&(a[e]=i[e]);n(a)&&(t=a)}return t}async after(e,t){for(let n of[...this._list])if(typeof n[e]==`function`)try{await n[e](Object.freeze({...t}))}catch(t){console.error(`[DopamineJS] ${e} hook threw:`,t)}}};function J(e,t,n){let r={};for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=S(e,i)?e[i]:void 0,o=S(t,i)?t[i]:void 0;r[i]=n>0?J(a||{},o||{},n-1):a===void 0?o:o===void 0?a:Math.max(a,o)}return r}function ee(e,t){let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let i=S(e,r)?e[r]:void 0,a=S(t,r)?t[r]:void 0;if(!i||!a){n[r]={...i||a};continue}let o=i.unlockedAt<a.unlockedAt||i.unlockedAt===a.unlockedAt&&i.reward>=a.reward?i:a;n[r]={unlockedAt:o.unlockedAt,seen:i.seen||a.seen,reward:o.reward}}return n}var te=(e,t)=>e>0&&t>0?Math.min(e,t):Math.max(e,t);function Y(e,t,n){let r=B(e,n),i=B(t,n),a={v:3,name:(r.lastPlayedAt===i.lastPlayedAt?r.name>=i.name?r:i:r.lastPlayedAt>i.lastPlayedAt?r:i).name,createdAt:te(r.createdAt,i.createdAt),lastPlayedAt:Math.max(r.lastPlayedAt,i.lastPlayedAt),level:Math.max(r.level,i.level),longest:Math.max(r.longest,i.longest),playDates:h([...r.playDates,...i.playDates],p(n?.today)?n.today:void 0),xpBy:J(r.xpBy,i.xpBy,0),xpSpentBy:J(r.xpSpentBy,i.xpSpentBy,0),gamesBy:J(r.gamesBy,i.gamesBy,0),playsBy:J(r.playsBy,i.playsBy,1),best:J(r.best,i.best,0),sumsBy:J(r.sumsBy,i.sumsBy,2),achievements:ee(r.achievements,i.achievements)};return z(a),a}var X=`device`,Z=()=>{let e=new Uint8Array(8),t=globalThis.crypto;if(typeof t?.getRandomValues==`function`)t.getRandomValues(e);else for(let t=0;t<e.length;t++)e[t]=Math.floor(Math.random()*256);return Array.from(e,e=>e.toString(16).padStart(2,`0`)).join(``)},ne=e=>x(e)&&e!==`legacy`,re=class extends e{constructor(e,t={}){super(),this.dataService=e,this.clock=t.clock&&typeof t.clock.now==`function`&&typeof t.clock.localDate==`function`?t.clock:r,this.achievements={...t.builtinAchievements===!1?{}:o(),...t.achievements||{}},this.streakDays=t.streakDays===`record`?`record`:`any`,this._doc=null,this._deviceId=null,this._deviceSaved=!1,this._middleware=new q,this._batchDepth=0,this._pendingSave=!1,this._loadFailed=!1,this._readFailed=!1}get loadFailed(){return this._readFailed}_publish(e,t){let n=Object.freeze({...t});this.emit(e,n)}async _batch(e){this._batchDepth++;try{return await e()}finally{this._batchDepth--,this._batchDepth===0&&this._pendingSave&&(this._pendingSave=!1,await this._write())}}_options(){return{now:this.clock.now(),today:this.clock.localDate(),rewards:{...s,...c(this.achievements)}}}async init(){let e=await this._readSaved();return this._loadFailed&&this._doc||(this._doc=this._load(e)),await this._readDevice(),await this.save(),this.snapshot()}async _readSaved(){this._loadFailed=!0;try{let e=await this.dataService.load(`player`,null,{strict:!0});return this._loadFailed=!1,this._readFailed=!1,e}catch(e){if(e?.code===`DOPAMINE_CORRUPT`){let t=await this.dataService.save(`player_corrupt`,e.raw);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}return this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null}}_load(e){if(!C(e))return A(this.clock.now());try{return B(e,this._options())}catch(e){if(!(e instanceof t))throw e;return this._loadFailed=!0,this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:e.code,error:e}),A(this.clock.now())}}async _readDevice(){if(this._deviceId)return;let e=null;try{e=await this.dataService.load(X,null,{strict:!0})}catch{this._deviceId=Z();return}ne(e)?(this._deviceId=e,this._deviceSaved=!0):this._deviceId=Z()}_hasSlot(){let e=R(this._doc);return e.has(this._deviceId)||e.size<20?!0:(this._publish(`load_failed`,{key:`player`,reason:`too_many_devices`}),!1)}_requirePlayer(){if(!this._doc)throw Error(`[DopamineJS] RewardSystem.init() must be awaited before use`)}snapshot(){return this._requirePlayer(),G(U(this._doc,this.clock.localDate()))}export(){return this._requirePlayer(),W(this._doc)}async import(e,{silent:t=!1}={}){this._requirePlayer();let n=this.snapshot(),r=B(e,this._options()),i=Y(this._doc,r,this._options());i.level=H(i),this._doc=i;let a=this.snapshot();if(await this.save(),t)return a;let o=a.xp-n.xp,s=a.level>n.level;o>0&&this._publish(`xp_gained`,{amount:o,reason:`import`,leveledUp:s,newLevel:a.level,total:a.xp}),s&&this._publish(`level_up`,{oldLevel:n.level,newLevel:a.level,totalXP:a.xp});for(let e of Object.keys(a.achievements))!S(n.achievements,e)&&S(this.achievements,e)&&this._publish(`achievement_unlocked`,{...this.achievements[e],id:e});return a}async reset(e){let t=e?.overwrite;if(e!==void 0&&(typeof e!=`object`||!e||Array.isArray(e))||t!==void 0&&typeof t!=`boolean`)throw TypeError(`[DopamineJS] reset expects { overwrite?: boolean }`);return this._requirePlayer(),t===!1&&this._readFailed?(this._doc=A(this.clock.now()),this._publish(`player_reset`,{}),this.snapshot()):(await this._batch(async()=>{this._doc=A(this.clock.now()),this._loadFailed=!1,this._readFailed=!1,await this.save()}),this._publish(`player_reset`,{}),this.snapshot())}use(e){return this._middleware.use(e)}defineAchievement(e,t){if(!x(e))throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);if(!C(t)||typeof t.check!=`function`)throw TypeError(`[DopamineJS] defineAchievement expects a definition with a check function`);let n=S(this.achievements,e)?this.achievements[e]:void 0;return this.achievements[e]=t,()=>{this.achievements[e]===t&&(n?this.achievements[e]=n:delete this.achievements[e])}}async save(){if(this._doc){if(this._batchDepth>0){this._pendingSave=!0;return}await this._write()}}async _write(){this._loadFailed||(this._doc.lastPlayedAt=this.clock.now(),this._deviceSaved||=await this.dataService.save(X,this._deviceId)!==!1,await this.dataService.save(`player`,this._doc)===!1&&this._publish(`save_failed`,{key:`player`}))}async addXP(e,t=``){if(!Number.isFinite(e))throw TypeError(`[DopamineJS] addXP expects a finite number, received ${e}`);if(this._requirePlayer(),!this._hasSlot())return{leveledUp:!1,newLevel:H(this._doc),xpGained:0};let n=await this._middleware.before(`beforeXP`,{amount:e,reason:t},e=>Number.isFinite(e.amount));if(n===!1)return{leveledUp:!1,newLevel:H(this._doc),xpGained:0};this.streakDays===`any`&&n.amount>0&&this._markDay();let r=await this._applyXP(n.amount,n.reason,(e,t)=>{t>=0?e.xpBy[this._deviceId]=D((S(e.xpBy,this._deviceId)?e.xpBy[this._deviceId]:0)+t):e.xpSpentBy[this._deviceId]=D((S(e.xpSpentBy,this._deviceId)?e.xpSpentBy[this._deviceId]:0)-t)});return await this._middleware.after(`afterXP`,{amount:r.xpGained,reason:n.reason,total:V(this._doc),level:r.newLevel}),r}async _applyXP(e,t,n){let r=this._doc,i=H(r);return e=Math.max(e,-V(r)),n(r,e),this._announceXP(i,e,t)}async _announceXP(e,t,n){let r=this._doc,a=V(r),o=Math.max(e,i(a)),s=o>e;return o>r.level&&(r.level=o),await this.save(),this._publish(`xp_gained`,{amount:t,reason:n,leveledUp:s,newLevel:o,total:a}),s&&this._publish(`level_up`,{oldLevel:e,newLevel:o,totalXP:a}),{leveledUp:s,newLevel:o,xpGained:t}}getXPForNextLevel(){this._requirePlayer();let e=H(this._doc),t=V(this._doc),n=a(e+1),r=a(e),i=n-r,o=i>0?Math.max(0,Math.min(1,(t-r)/i)):0;return{total:n,needed:Math.max(0,n-t),progress:o}}_checkRecord(e,t){if(!x(e))throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);if(!C(t))throw TypeError(`[DopamineJS] record expects a result object`);if(t.score!==void 0&&!Number.isFinite(t.score))throw TypeError(`[DopamineJS] record expects a finite score, received ${String(t.score)}`)}async record(e,t={}){if(this._requirePlayer(),this._checkRecord(e,t),!this._hasSlot())return!1;let n=await this._middleware.before(`beforeRecord`,{activity:e,result:t},e=>{try{return this._checkRecord(e.activity,e.result),!0}catch{return!1}});if(n===!1)return!1;let r=await this._batch(()=>this._record(n.activity,n.result));return await this._middleware.after(`afterRecord`,{activity:n.activity,result:n.result,xp:r}),!0}_markDay(){let e=this._doc,t=this.clock.localDate();if(e.playDates.includes(t))return;let n=e.playDates.length===0;e.playDates=h([...e.playDates,t],t),e.longest=Math.max(e.longest,_(e.playDates)),n||this._publish(`streak_updated`,{current:g(e.playDates,t),longest:Math.max(e.longest,_(e.playDates))})}async _record(e,t){let n=this._doc,r=this._deviceId,i=(e,t)=>{e[r]=D((S(e,r)?e[r]:0)+t)};this._markDay(),S(n.playsBy,e)||(n.playsBy[e]={},n.best[e]=0,n.sumsBy[e]={}),i(n.playsBy[e],1),i(n.gamesBy,1),t.score!==void 0&&t.score>n.best[e]&&(n.best[e]=t.score,this._publish(`personal_best`,{activity:e,score:t.score}));for(let r of Object.keys(t))r!==`score`&&r!==`plays`&&r!==`best`&&x(r)&&(S(n.sumsBy[e],r)||(n.sumsBy[e][r]={}),i(n.sumsBy[e][r],Number.isFinite(t[r])&&t[r]>0?t[r]:0));let a=10;return t.score&&(a+=Math.max(0,Math.floor(t.score/5))),a=Math.floor(a*this.getStreakMultiplier()),await this.addXP(a,`Played ${e}`),await this.checkAchievements(e,t),await this.save(),a}async checkAchievements(e,t){let n=[];for(let[r,i]of Object.entries(this.achievements)){if(S(this._doc.achievements,r))continue;let a=!1;try{a=i.check(this.snapshot(),e,t)}catch(e){console.error(`[DopamineJS] Achievement "${r}" check threw:`,e);continue}a&&await this.unlockAchievement(r)&&n.push(i)}return n}async unlockAchievement(e){if(this._requirePlayer(),!x(e)||!S(this.achievements,e)||S(this._doc.achievements,e))return!1;let t=this.achievements[e];if(!t)return!1;let{[e]:n}=c(this.achievements),r=await this._middleware.before(`beforeUnlock`,{id:e,reward:n},e=>Number.isFinite(e.reward)&&e.reward>=0);if(r===!1)return!1;let i=this._doc,a=H(i);return i.achievements[e]={unlockedAt:this.clock.now(),seen:!1,reward:r.reward},await this._announceXP(a,r.reward,`Achievement: ${t.name}`),this._publish(`achievement_unlocked`,{...t,id:e}),await this.save(),await this._middleware.after(`afterUnlock`,{id:e,reward:r.reward}),!0}getUnlockedAchievements(){return this._requirePlayer(),Object.entries(this._doc.achievements).map(([e,t])=>({...this.achievements[e],id:e,...t}))}getUnseenAchievements(){return this.getUnlockedAchievements().filter(e=>!e.seen)}async markAchievementsSeen(e){for(let t of e)S(this._doc.achievements,t)&&(this._doc.achievements[t].seen=!0);await this.save()}getStreakMultiplier(){let e=this.snapshot().streak.current;return e>=7?2:e>=5?1.5:e>=3?1.25:1}};function Q(){let e=new Map;return{getItem:t=>e.has(t)?e.get(t):null,setItem:(t,n)=>{e.set(t,String(n))},removeItem:t=>{e.delete(t)},clear:()=>{e.clear()}}}function $(){try{if(typeof localStorage>`u`)return Q();let e=`__dopamine_probe__`;return localStorage.setItem(e,`1`),localStorage.removeItem(e),localStorage}catch{return Q()}}var ie=class{constructor(e={}){this.storage=e.storage||$(),this.prefix=e.prefix||`dopamine_`,this._tail=null}_write(e){let t=this._tail?this._tail.then(e):e();if(typeof t?.then==`function`){let e=Promise.resolve(t).catch(()=>{}).then(()=>{this._tail===e&&(this._tail=null)});this._tail=e}return t}async save(e,t){try{let n=JSON.stringify(t);return await this._write(()=>this.storage.setItem(this.prefix+e,n)),!0}catch(e){return console.error(`Error saving data:`,e),!1}}async load(e,t=null,n={}){let r;try{await this._tail,r=await this.storage.getItem(this.prefix+e)}catch(e){if(n.strict)throw e;return console.error(`Error loading data:`,e),t}if(!r)return t;try{return JSON.parse(r)}catch(i){if(n.strict)throw Object.assign(Error(`[DopamineJS] saved "${e}" is not valid JSON`),{code:`DOPAMINE_CORRUPT`,raw:r});return console.error(`Error loading data:`,i),t}}async clear(e){await this._write(()=>this.storage.removeItem(this.prefix+e))}};Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return Y}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return re}}),Object.defineProperty(exports,"l",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Q}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return B}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return $}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return ie}});
|
package/dist/core.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-GRTvq4BS.cjs");exports.DataService=e.t,exports.DopamineError=e.c,exports.EventEmitter=e.l,exports.RewardSystem=e.i,exports.createMemoryStorage=e.n,exports.merge=e.a,exports.resolveStorage=e.r,exports.validate=e.o;
|
package/dist/core.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, t as s } from "./DataService-
|
|
1
|
+
import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, t as s } from "./DataService-Bd1S-C1N.js";
|
|
2
2
|
export { s as DataService, t as DopamineError, r as EventEmitter, n as RewardSystem, i as createMemoryStorage, e as merge, o as resolveStorage, a as validate };
|
package/dist/dopamine.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-GRTvq4BS.cjs"),t=require("./host-Bm0Kq5Th.cjs");exports.DataService=e.t,exports.DopamineError=e.c,exports.EventEmitter=e.l,exports.HOST_API=t.t,exports.ParticleSystem=t.a,exports.RewardSystem=e.i,exports.RewardUI=t.s,exports.SoundManager=t.i,exports.createDopamine=t.n,exports.createHaptics=t.r,exports.createMemoryStorage=e.n,exports.merge=e.a,exports.prefersReducedMotion=t.o,exports.resolveStorage=e.r,exports.validate=e.o;
|
package/dist/dopamine.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, t as s } from "./DataService-
|
|
2
|
-
import { a as c, i as l, n as u, o as d, r as f, s as p, t as m } from "./host-
|
|
1
|
+
import { a as e, c as t, i as n, l as r, n as i, o as a, r as o, t as s } from "./DataService-Bd1S-C1N.js";
|
|
2
|
+
import { a as c, i as l, n as u, o as d, r as f, s as p, t as m } from "./host-CSnyl6nv.js";
|
|
3
3
|
export { s as DataService, t as DopamineError, r as EventEmitter, m as HOST_API, c as ParticleSystem, n as RewardSystem, p as RewardUI, l as SoundManager, u as createDopamine, f as createHaptics, i as createMemoryStorage, e as merge, d as prefersReducedMotion, o as resolveStorage, a as validate };
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
const e=require("./DataService-GRTvq4BS.cjs");var t=`#game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{top:calc(var(--dopamine-toast-top,80px) + env(safe-area-inset-top,0px));right:var(--dopamine-toast-right,20px);left:var(--dopamine-toast-left,auto);background:var(--dopamine-toast-bg,linear-gradient(135deg, #667eea 0%, #764ba2 100%));border-radius:var(--dopamine-toast-radius,16px);box-shadow:var(--dopamine-toast-shadow,0 8px 32px #0006);z-index:10000;max-width:var(--dopamine-toast-max-width,320px);padding:16px;animation:.5s cubic-bezier(.68,-.55,.265,1.55) slideIn;position:fixed;overflow:hidden}.achievement-shine{background:linear-gradient(90deg,#0000,#ffffff4d,#0000);width:100%;height:100%;animation:2s infinite shine;position:absolute;top:0;left:-100%}.achievement-content{align-items:center;gap:12px;display:flex;position:relative}.achievement-icon{font-size:48px;animation:.6s ease-out bounce}.achievement-info{flex:1}.achievement-title{color:var(--dopamine-toast-muted,#ffffffe6);text-transform:uppercase;letter-spacing:.5px;font-size:12px;font-weight:600}.achievement-name{color:var(--dopamine-toast-text,white);margin:2px 0;font-size:18px;font-weight:800}.achievement-desc{color:var(--dopamine-toast-muted,#fffc);margin-bottom:4px;font-size:13px}.achievement-xp{color:var(--dopamine-toast-accent,gold);background:#fff3;border-radius:8px;padding:4px 8px;font-size:12px;font-weight:700;display:inline-block}.level-up-overlay{z-index:10001;background:#000000d9;justify-content:center;align-items:center;width:100%;height:100%;animation:.3s ease-out fadeIn;display:flex;position:fixed;top:0;left:0}.level-up-content{text-align:center;animation:.5s cubic-bezier(.68,-.55,.265,1.55) scaleIn}.level-up-title{background:linear-gradient(135deg,gold 0%,#ffed4e 100%);-webkit-text-fill-color:transparent;text-transform:uppercase;letter-spacing:4px;-webkit-background-clip:text;background-clip:text;margin-bottom:16px;font-size:32px;font-weight:800}.level-up-number{color:#fff;text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066;font-size:120px;font-weight:900;animation:1s ease-in-out infinite alternate glow}.level-up-subtitle{color:#fffc;margin-top:16px;font-size:24px;font-weight:600}.floating-text{text-shadow:2px 2px #000,-1px -1px #000,1px -1px #000,-1px 1px #000;pointer-events:none;z-index:9998;font-weight:800;animation:2s ease-out forwards floatUp;position:fixed}@keyframes slideIn{0%{opacity:0;transform:translate(400px)}to{opacity:1;transform:translate(0)}}@keyframes slideOut{0%{opacity:1;transform:translate(0)}to{opacity:0;transform:translate(400px)}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066}to{text-shadow:0 0 30px gold,0 0 60px #ffd700cc,0 0 90px #ffd70099}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100px)}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media (width<=480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{min-width:50px;padding:6px 10px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{right:var(--dopamine-toast-right,12px);max-width:min(var(--dopamine-toast-max-width,320px), calc(100% - 24px))}.level-up-number{font-size:80px}}@media (prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{transition:none!important;animation:none!important}.floating-text{animation:none!important}}`,n=`game-ui-overlay`,r={levelUp:`LEVEL UP!`,achievementUnlocked:`Achievement Unlocked!`},i=`dopamine-reward-ui-css`,a=`🔥`,o=e=>e==null?``:String(e),s=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),c=(e,t)=>typeof e==`object`&&e&&s(e,t)?e[t]:void 0,l=`http://www.w3.org/2000/svg`,u=new Set([`svg`,`g`,`path`,`circle`,`ellipse`,`rect`,`line`,`polyline`,`polygon`,`text`,`tspan`,`title`,`desc`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`]),d=new Set(`viewBox.width.height.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.d.points.transform.fill.fill-opacity.fill-rule.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-opacity.opacity.offset.stop-color.stop-opacity.gradientUnits.gradientTransform.clip-path.mask.clip-rule.font-size.font-family.font-weight.text-anchor.id.aria-hidden.aria-label.role`.split(`.`)),f=new Set([`fill`,`stroke`,`clip-path`,`mask`]),p=new Set([`transform`,`gradientTransform`]),m=/^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/,h=/^[#a-zA-Z0-9(),.%\s-]+$/,g=/^[a-zA-Z0-9(),.\s-]+$/,_=/^[A-Za-z][\w.:-]*$/,v=0;function y(e,t){if(e.nodeType!==1||e.namespaceURI!==l||!u.has(e.localName))return;let n=e.getAttribute(`id`);n&&_.test(n)&&t.add(n);for(let n of Array.from(e.childNodes))y(n,t)}function b(e,t,n){if(t.includes(`\\`))return null;let r=t.trim();if(e===`id`)return _.test(r)?n.prefix+r:null;if(f.has(e)){let e=m.exec(r);return e?n.ids.has(e[1])?`url(#${n.prefix}${e[1]})`:null:h.test(r)&&!/url/i.test(r)?r:null}return p.has(e)?g.test(r)&&!/url/i.test(r)?r:null:t.includes(`(`)?e===`stop-color`&&h.test(r)&&!/url/i.test(r)?r:null:t}function x(e,t){if(e.nodeType===3||e.nodeType===4)return document.createTextNode(e.data);if(e.nodeType!==1||e.namespaceURI!==l||!u.has(e.localName))return null;let n=document.createElementNS(l,e.localName);for(let r of Array.from(e.attributes)){if(r.namespaceURI!==null||!d.has(r.name))continue;let e=b(r.name,r.value,t);e!==null&&n.setAttribute(r.name,e)}for(let r of Array.from(e.childNodes)){let e=x(r,t);e&&n.appendChild(e)}return n}function S(e){let t,n=/^\s*<svg[\s>]/.test(e)&&!/^\s*<svg\b[^>]*\sxmlns\s*=/.test(e)?e.replace(/^(\s*<svg)/,`$1 xmlns="${l}"`):e;try{t=new DOMParser().parseFromString(n,`image/svg+xml`)}catch{return null}let r=t.documentElement;if(!r||r.localName!==`svg`||t.getElementsByTagName(`parsererror`).length>0)return null;let i=new Set;return y(r,i),x(r,{ids:i,prefix:`dj-icon-${++v}-`})}var C=class{constructor(e={},t={}){this.parts=e||{};let n=c(t,`text`);this.strings={...r};for(let e of Object.keys(r)){let t=c(n,e);typeof t==`string`&&(this.strings[e]=t)}this.safeIcons=c(t,`safeIcons`)!==!1,this._streakIcon=c(c(t,`icons`),`streak`)??a,this._injectCss=c(t,`injectCss`),this.container=null,this.xpBar=null,this.levelDisplay=null,this.streakDisplay=null,this._style=null,this._xp=null,this._level=null,this._timers=new Set,this._detached=[],this._cardQueue=[],this._cardActive=!1,this._build()}get root(){return this.container}_build(){this._injectCss&&this._addStyles(),this.container=document.createElement(`div`),this.container.className=`game-ui-overlay`,document.getElementById(n)||(this.container.id=n),this.container.innerHTML=`
|
|
2
|
+
<div class="game-ui-top-bar">
|
|
3
|
+
<div class="level-badge">
|
|
4
|
+
<span class="level-label">LVL</span>
|
|
5
|
+
<span class="level-number">1</span>
|
|
6
|
+
</div>
|
|
7
|
+
|
|
8
|
+
<div class="xp-container">
|
|
9
|
+
<div class="xp-bar-bg">
|
|
10
|
+
<div class="xp-bar-fill" style="width: 0%"></div>
|
|
11
|
+
</div>
|
|
12
|
+
<div class="xp-text">0 / 100 XP</div>
|
|
13
|
+
</div>
|
|
14
|
+
|
|
15
|
+
<div class="streak-badge">
|
|
16
|
+
<span class="streak-icon"></span>
|
|
17
|
+
<span class="streak-number">1</span>
|
|
18
|
+
</div>
|
|
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(i))return;let e=typeof this._injectCss==`string`?this._injectCss:t;this._style=document.createElement(`style`),this._style.id=i,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=S(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=c(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=`
|
|
21
|
+
<div class="achievement-shine"></div>
|
|
22
|
+
<div class="achievement-content">
|
|
23
|
+
<div class="achievement-icon"></div>
|
|
24
|
+
<div class="achievement-info">
|
|
25
|
+
<div class="achievement-title"></div>
|
|
26
|
+
<div class="achievement-name"></div>
|
|
27
|
+
<div class="achievement-desc"></div>
|
|
28
|
+
<div class="achievement-xp"></div>
|
|
29
|
+
</div>
|
|
30
|
+
</div>
|
|
31
|
+
`;let r=o(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=o(e.body),n.querySelector(`.achievement-xp`).textContent=o(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=o(e.body),r=document.createElement(`div`);r.className=`level-up-overlay`,r.innerHTML=`
|
|
32
|
+
<div class="level-up-content">
|
|
33
|
+
<div class="level-up-title"></div>
|
|
34
|
+
<div class="level-up-number"></div>
|
|
35
|
+
<div class="level-up-subtitle">Amazing progress!</div>
|
|
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=o(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=o(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}},w=Object.freeze({matches:!1});function T(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||w}var E=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),D={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)},O=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:T(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`||!E(D,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;D[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);continue}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=[]}},k=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),A=class{constructor(t={}){this.audioContext=null,this.storageKey=t.storageKey||`dopamineSoundsMuted`,this.storage=t.storage||e.r(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=t.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(t.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):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(k(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)):k(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 j({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 M=3,N=[`ui`,`particles`,`sound`,`haptics`],P=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,F=(e,t)=>{P(e)&&e.then(void 0,e=>t.error(e))};function I(){let e=typeof document<`u`&&typeof window<`u`;return{hasDom:e,reducedMotion:e?T(window).matches===!0:!1}}function L(e,t,n){if(e===!1)return null;let r=e;return typeof e==`function`&&(r=e(t)),r??n()}function R(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 z(t={}){let n=t||{},r=I(),i={debug:()=>{},info:()=>{},warn:(...e)=>console.warn(...e),error:(...e)=>console.error(...e),...n.log||{}},a=n.storage||e.r(),o=n.clock||e.s,s={ui:null,particles:null,sound:null,haptics:null},c={};for(let e of N)Object.defineProperty(c,e,{enumerable:!0,get:()=>s[e]});Object.freeze(c);let l={...r,parts:c,storage:a,clock:o},u=L(n.progress,l,()=>new e.i(new e.t({storage:a}),{clock:o,streakDays:n.streakDays,builtinAchievements:n.builtinAchievements}));if(typeof u?.on!=`function`||typeof u?.off!=`function`)throw new e.c(`invalid_progress`,`progress needs on() and off()`);s.particles=L(n.particles,l,()=>r.hasDom?new O:null),s.sound=L(n.sound,l,()=>new A({storage:a})),s.haptics=L(n.haptics,l,()=>j());try{s.ui=L(n.ui,l,()=>r.hasDom?new C(c):null)}catch(e){throw d(),e}function d(){for(let e of N)try{s[e]?.destroy?.()}catch(e){i.error(e)}}let f=u,p=[],m=!1,h=e=>t=>{try{F(e(t),i)}catch(e){i.error(e)}},g=()=>{let e=s.ui;if(!e||typeof u.snapshot!=`function`||typeof u.getXPForNextLevel!=`function`)return;let t=u.snapshot(),{total:n,progress:r}=u.getXPForNextLevel();e.hud({xp:t.xp,level:t.level,progress:r,streak:t.streak.current,next:n})};p.push(f.on(`xp_gained`,h(e=>{g(),e.leveledUp||s.sound?.play(`xp`)})),f.on(`level_up`,h(e=>{g(),s.ui?.popup({kind:`level`,title:``,body:String(e.newLevel)}),s.sound?.play(`level_up`)})),f.on(`achievement_unlocked`,h(e=>{s.ui?.popup({kind:`achievement`,title:e.name,body:e.description,icon:e.icon,meta:`+${e.xp??0} XP`}),s.sound?.play(`achievement`)})),f.on(`streak_updated`,h(g)),f.on(`player_reset`,h(g)),f.on(`personal_best`,h(e=>{s.ui?.popup({kind:`notice`,title:`New High Score: ${e.score}!`,tier:`legendary`}),s.sound?.play(`personal_best`)})));let _=new Map,v=[];function y(t){if(typeof t!=`object`||!t||typeof t.name!=`string`||!/^[a-z0-9-]+$/.test(t.name)||typeof t.install!=`function`)throw new e.c(`plugin_invalid`,`a plugin needs a name (a-z, 0-9 and -) and an install function`);if(t.api!==3)throw new e.c(`plugin_api`,`${t.name} was built for api ${t.api}, this host is api 3`);if(_.has(t.name))throw new e.c(`plugin_duplicate`,`${t.name} is already installed`);for(let n of t.after||[])if(!_.has(n)||!_.get(n).done)throw new e.c(`plugin_order`,`${t.name} must come after ${n}`);for(let n of t.requires||[])if(!N.includes(n)||s[n]===null)throw new e.c(`plugin_requires`,`${t.name} requires the ${n} part, which is not set`)}function b(e){for(let t of e.offs)t();e.offs.clear(),_.delete(e.name);let t=v.indexOf(e);t>-1&&v.splice(t,1)}function x(e){if(e.removed)return;e.removed=!0;let t=e.disposer;e.disposer=null;try{t?.()}catch(e){i.error(e)}b(e)}function S(t){let{name:n}=t;return{progress:u,parts:c,events:{on(e,n){let r=f.on(e,n),i=()=>{r(),t.offs.delete(i)};return t.offs.add(i),i},off:(e,t)=>f.off(e,t),emit(t,r){if(typeof t!=`string`||!t.startsWith(`${n}:`))throw new e.c(`plugin_event`,`${n} may only emit events named ${n}:<event>`);f.emit(t,r)}},storage:R(a,n),clock:o,log:i,env:{hasDom:r.hasDom,reducedMotion:r.reducedMotion},plugin:e=>_.has(e)&&_.get(e).done?_.get(e).handle:null,expose:e=>{t.handle=e}}}function w(t){if(m)throw new e.c(`disposed`,`the host was disposed`);y(t);let n={name:t.name,done:!1,removed:!1,disposer:null,handle:null,offs:new Set};_.set(t.name,n);let r=e=>(n.done=!0,typeof e==`function`&&(n.disposer=e),n.removed||m?(n.removed=!1,x(n),n):(v.push(n),n)),i=e=>{throw b(n),e},a;try{a=t.install(S(n))}catch(e){return i(e)}return P(a)?a.then(r,i):r(a)}let T=null;function E(t){if(m)throw new e.c(`disposed`,`the host was disposed`);if(T===null){let e=w(t);if(P(e)){let t=e.then(e=>e,e=>{throw e});return T=t.then(()=>{T=null},()=>{T=null}),{record:null,done:t}}return{record:e,done:Promise.resolve(e)}}let n=T.then(()=>w(t));return T=n.then(()=>{T=null},()=>{T=null}),{record:null,done:n}}function D(e){let{record:t,done:n}=E(e);if(t)return()=>x(t);let r=null,a=!1;return n.then(e=>{r=e,a&&x(e)},e=>i.error(e)),()=>{r?x(r):a=!0}}let k=Promise.resolve();try{for(let e of n.plugins||[]){let{done:t}=E(e);k=k.then(()=>t)}}catch(e){throw M(),e}k=k.catch(e=>{throw M(),e});function M(){if(!m){m=!0;for(let e of[...v].reverse())x(e);for(let e of[..._.values()])x(e);for(let e of p)e();p.length=0,d(),u.clear?.()}}let z=k.then(()=>typeof u.init==`function`?u.init():void 0).then(()=>(m||g(),B));z.catch(()=>{});let B={progress:u,parts:c,events:f,ready:z,use:D,dispose:M};return B}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return M}});
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { c as e, i as t, r as n, s as r, t as i } from "./DataService-
|
|
1
|
+
import { c as e, i as t, r as n, s as r, t as i } from "./DataService-Bd1S-C1N.js";
|
|
2
2
|
//#region src/dopamine/ui/dopamine.css?inline
|
|
3
|
-
var a = "#game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{
|
|
3
|
+
var a = "#game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{top:calc(var(--dopamine-toast-top,80px) + env(safe-area-inset-top,0px));right:var(--dopamine-toast-right,20px);left:var(--dopamine-toast-left,auto);background:var(--dopamine-toast-bg,linear-gradient(135deg, #667eea 0%, #764ba2 100%));border-radius:var(--dopamine-toast-radius,16px);box-shadow:var(--dopamine-toast-shadow,0 8px 32px #0006);z-index:10000;max-width:var(--dopamine-toast-max-width,320px);padding:16px;animation:.5s cubic-bezier(.68,-.55,.265,1.55) slideIn;position:fixed;overflow:hidden}.achievement-shine{background:linear-gradient(90deg,#0000,#ffffff4d,#0000);width:100%;height:100%;animation:2s infinite shine;position:absolute;top:0;left:-100%}.achievement-content{align-items:center;gap:12px;display:flex;position:relative}.achievement-icon{font-size:48px;animation:.6s ease-out bounce}.achievement-info{flex:1}.achievement-title{color:var(--dopamine-toast-muted,#ffffffe6);text-transform:uppercase;letter-spacing:.5px;font-size:12px;font-weight:600}.achievement-name{color:var(--dopamine-toast-text,white);margin:2px 0;font-size:18px;font-weight:800}.achievement-desc{color:var(--dopamine-toast-muted,#fffc);margin-bottom:4px;font-size:13px}.achievement-xp{color:var(--dopamine-toast-accent,gold);background:#fff3;border-radius:8px;padding:4px 8px;font-size:12px;font-weight:700;display:inline-block}.level-up-overlay{z-index:10001;background:#000000d9;justify-content:center;align-items:center;width:100%;height:100%;animation:.3s ease-out fadeIn;display:flex;position:fixed;top:0;left:0}.level-up-content{text-align:center;animation:.5s cubic-bezier(.68,-.55,.265,1.55) scaleIn}.level-up-title{background:linear-gradient(135deg,gold 0%,#ffed4e 100%);-webkit-text-fill-color:transparent;text-transform:uppercase;letter-spacing:4px;-webkit-background-clip:text;background-clip:text;margin-bottom:16px;font-size:32px;font-weight:800}.level-up-number{color:#fff;text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066;font-size:120px;font-weight:900;animation:1s ease-in-out infinite alternate glow}.level-up-subtitle{color:#fffc;margin-top:16px;font-size:24px;font-weight:600}.floating-text{text-shadow:2px 2px #000,-1px -1px #000,1px -1px #000,-1px 1px #000;pointer-events:none;z-index:9998;font-weight:800;animation:2s ease-out forwards floatUp;position:fixed}@keyframes slideIn{0%{opacity:0;transform:translate(400px)}to{opacity:1;transform:translate(0)}}@keyframes slideOut{0%{opacity:1;transform:translate(0)}to{opacity:0;transform:translate(400px)}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066}to{text-shadow:0 0 30px gold,0 0 60px #ffd700cc,0 0 90px #ffd70099}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100px)}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media (width<=480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{min-width:50px;padding:6px 10px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{right:var(--dopamine-toast-right,12px);max-width:min(var(--dopamine-toast-max-width,320px), calc(100% - 24px))}.level-up-number{font-size:80px}}@media (prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{transition:none!important;animation:none!important}.floating-text{animation:none!important}}", o = "game-ui-overlay", s = {
|
|
4
4
|
levelUp: "LEVEL UP!",
|
|
5
5
|
achievementUnlocked: "Achievement Unlocked!"
|
|
6
6
|
}, c = "dopamine-reward-ui-css", l = "🔥", u = (e) => e == null ? "" : String(e), d = (e, t) => Object.prototype.hasOwnProperty.call(e, t), f = (e, t) => typeof e == "object" && e && d(e, t) ? e[t] : void 0, p = "http://www.w3.org/2000/svg", m = /* @__PURE__ */ new Set([
|
|
@@ -84,7 +84,7 @@ var D = class {
|
|
|
84
84
|
let t = f(n, e);
|
|
85
85
|
typeof t == "string" && (this.strings[e] = t);
|
|
86
86
|
}
|
|
87
|
-
this.safeIcons = f(t, "safeIcons") !== !1, this._streakIcon = f(f(t, "icons"), "streak") ?? l, this._injectCss = f(t, "injectCss"), this.container = null, this.xpBar = null, this.levelDisplay = null, this.streakDisplay = null, this._style = null, this._xp = null, this._level = null, this._timers = /* @__PURE__ */ new Set(), this._detached = [], this._build();
|
|
87
|
+
this.safeIcons = f(t, "safeIcons") !== !1, this._streakIcon = f(f(t, "icons"), "streak") ?? l, this._injectCss = f(t, "injectCss"), this.container = null, this.xpBar = null, this.levelDisplay = null, this.streakDisplay = null, this._style = null, this._xp = null, this._level = null, this._timers = /* @__PURE__ */ new Set(), this._detached = [], this._cardQueue = [], this._cardActive = !1, this._build();
|
|
88
88
|
}
|
|
89
89
|
get root() {
|
|
90
90
|
return this.container;
|
|
@@ -144,6 +144,27 @@ var D = class {
|
|
|
144
144
|
t === "level" ? this._levelPopup(e) : t === "notice" ? this._notice(e) : this._card(e, t === "achievement");
|
|
145
145
|
}
|
|
146
146
|
_card(e, t) {
|
|
147
|
+
let { title: n, body: r, meta: i, icon: a } = e;
|
|
148
|
+
this._cardQueue.push([{
|
|
149
|
+
title: n,
|
|
150
|
+
body: r,
|
|
151
|
+
meta: i,
|
|
152
|
+
icon: a
|
|
153
|
+
}, t]), this._nextCard();
|
|
154
|
+
}
|
|
155
|
+
_nextCard() {
|
|
156
|
+
if (this._cardActive) return;
|
|
157
|
+
let e = this._cardQueue.shift();
|
|
158
|
+
if (e) {
|
|
159
|
+
this._cardActive = !0;
|
|
160
|
+
try {
|
|
161
|
+
this._showCard(e[0], e[1]);
|
|
162
|
+
} catch (e) {
|
|
163
|
+
throw this._cardActive = !1, this._nextCard(), e;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
_showCard(e, t) {
|
|
147
168
|
let n = document.createElement("div");
|
|
148
169
|
n.className = "achievement-popup", n.innerHTML = "\n <div class=\"achievement-shine\"></div>\n <div class=\"achievement-content\">\n <div class=\"achievement-icon\"></div>\n <div class=\"achievement-info\">\n <div class=\"achievement-title\"></div>\n <div class=\"achievement-name\"></div>\n <div class=\"achievement-desc\"></div>\n <div class=\"achievement-xp\"></div>\n </div>\n </div>\n ";
|
|
149
170
|
let r = u(e.title);
|
|
@@ -154,7 +175,9 @@ var D = class {
|
|
|
154
175
|
y: e.top + e.height / 2
|
|
155
176
|
}, { count: 40 });
|
|
156
177
|
}, 300), this._defer(() => {
|
|
157
|
-
n.style.animation = "slideOut 0.3s ease-in forwards", this._defer(() =>
|
|
178
|
+
n.style.animation = "slideOut 0.3s ease-in forwards", this._defer(() => {
|
|
179
|
+
this._remove(n), this._cardActive = !1, this._nextCard();
|
|
180
|
+
}, 300);
|
|
158
181
|
}, 4e3);
|
|
159
182
|
}
|
|
160
183
|
_levelPopup(e) {
|
|
@@ -216,7 +239,7 @@ var D = class {
|
|
|
216
239
|
}
|
|
217
240
|
destroy() {
|
|
218
241
|
for (let e of this._timers) clearTimeout(e);
|
|
219
|
-
this._timers.clear();
|
|
242
|
+
this._timers.clear(), this._cardQueue = [], this._cardActive = !1;
|
|
220
243
|
for (let e of this._detached) e.remove();
|
|
221
244
|
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;
|
|
222
245
|
}
|
package/dist/style.css
CHANGED
|
@@ -112,15 +112,16 @@
|
|
|
112
112
|
|
|
113
113
|
.achievement-popup {
|
|
114
114
|
position: fixed;
|
|
115
|
-
top: 80px;
|
|
116
|
-
right: 20px;
|
|
117
|
-
|
|
118
|
-
|
|
115
|
+
top: calc(var(--dopamine-toast-top, 80px) + env(safe-area-inset-top, 0px));
|
|
116
|
+
right: var(--dopamine-toast-right, 20px);
|
|
117
|
+
left: var(--dopamine-toast-left, auto);
|
|
118
|
+
background: var(--dopamine-toast-bg, linear-gradient(135deg, #667eea 0%, #764ba2 100%));
|
|
119
|
+
border-radius: var(--dopamine-toast-radius, 16px);
|
|
119
120
|
padding: 16px;
|
|
120
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
|
121
|
+
box-shadow: var(--dopamine-toast-shadow, 0 8px 32px rgba(0, 0, 0, 0.4));
|
|
121
122
|
animation: slideIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
|
|
122
123
|
z-index: 10000;
|
|
123
|
-
max-width: 320px;
|
|
124
|
+
max-width: var(--dopamine-toast-max-width, 320px);
|
|
124
125
|
overflow: hidden;
|
|
125
126
|
}
|
|
126
127
|
|
|
@@ -153,7 +154,7 @@
|
|
|
153
154
|
.achievement-title {
|
|
154
155
|
font-size: 12px;
|
|
155
156
|
font-weight: 600;
|
|
156
|
-
color: rgba(255, 255, 255, 0.9);
|
|
157
|
+
color: var(--dopamine-toast-muted, rgba(255, 255, 255, 0.9));
|
|
157
158
|
text-transform: uppercase;
|
|
158
159
|
letter-spacing: 0.5px;
|
|
159
160
|
}
|
|
@@ -161,13 +162,13 @@
|
|
|
161
162
|
.achievement-name {
|
|
162
163
|
font-size: 18px;
|
|
163
164
|
font-weight: 800;
|
|
164
|
-
color: white;
|
|
165
|
+
color: var(--dopamine-toast-text, white);
|
|
165
166
|
margin: 2px 0;
|
|
166
167
|
}
|
|
167
168
|
|
|
168
169
|
.achievement-desc {
|
|
169
170
|
font-size: 13px;
|
|
170
|
-
color: rgba(255, 255, 255, 0.8);
|
|
171
|
+
color: var(--dopamine-toast-muted, rgba(255, 255, 255, 0.8));
|
|
171
172
|
margin-bottom: 4px;
|
|
172
173
|
}
|
|
173
174
|
|
|
@@ -178,7 +179,7 @@
|
|
|
178
179
|
border-radius: 8px;
|
|
179
180
|
font-size: 12px;
|
|
180
181
|
font-weight: 700;
|
|
181
|
-
color: #ffd700;
|
|
182
|
+
color: var(--dopamine-toast-accent, #ffd700);
|
|
182
183
|
}
|
|
183
184
|
|
|
184
185
|
/* ==================== LEVEL UP OVERLAY ==================== */
|
|
@@ -367,8 +368,8 @@
|
|
|
367
368
|
}
|
|
368
369
|
|
|
369
370
|
.achievement-popup {
|
|
370
|
-
right: 12px;
|
|
371
|
-
max-width: calc(100% - 24px);
|
|
371
|
+
right: var(--dopamine-toast-right, 12px);
|
|
372
|
+
max-width: min(var(--dopamine-toast-max-width, 320px), calc(100% - 24px));
|
|
372
373
|
}
|
|
373
374
|
|
|
374
375
|
.level-up-number {
|
package/dist/testing.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./DataService-GRTvq4BS.cjs"),t=require("./host-Bm0Kq5Th.cjs");let n=require("vitest"),r=require("node:fs"),i=require("node:path"),a=require("node:url");var o={xp_gained:{amount:10,reason:`test`,totalXP:10,leveledUp:!1},level_up:{oldLevel:1,newLevel:2,totalXP:50},achievement_unlocked:{id:`test`,name:`Test`,description:`Test`,icon:``,xp:5},personal_best:{activity:`test`,score:10},streak_updated:{current:1,longest:1},player_reset:{},save_failed:{error:Error(`save failed`)},load_failed:{reason:`corrupt`}},s=[`confetti`,`sparkle`,`fire`,`stars`,`coins`],c=[`xp`,`level_up`,`achievement`,`personal_best`,`click`,`error`],l=[``,`nope`,`__proto__`,`constructor`,`toString`,`hasOwnProperty`,void 0,null,42,{}],u=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/,d=e=>{throw Error(e)},f=(e,t)=>{e||d(t)};function p(t){if(typeof t==`object`&&t)return{clock:t,move:()=>d(`this clock is not a test clock, it cannot advance`)};let n=t===void 0?`2026-01-15T09:00:00`:t;(typeof n!=`string`||!u.test(n))&&d(`clock must be YYYY-MM-DDTHH:MM:SS local time`);let r=new Date(n).getTime();return{clock:{now:()=>r,localDate:(t=r)=>e.s.localDate(t)},move:e=>{r=e(r)}}}function m(n={}){let{clock:r,storage:i,parts:a={},...o}=n||{},{clock:s,move:c}=p(r),l=[],f=[],m=[],h=[],g=[],_=new Set,v=[],y={ui:()=>({root:null,hud:e=>{m.push(e)},popup:e=>{l.push(e)},text:e=>{f.push(e)},destroy(){}}),particles:()=>({burst:(e,t,n)=>{h.push({kind:e,at:t,opts:n})},destroy(){}}),sound:()=>({play:e=>{g.push(e)},register(e){return _.add(e),()=>{_.delete(e)}},destroy(){}}),haptics:()=>({tap:()=>{v.push(`tap`)},double:()=>{v.push(`double`)},setEnabled(){},destroy(){}})},b={};for(let e of Object.keys(y))b[e]=Object.prototype.hasOwnProperty.call(a,e)?a[e]:y[e]();let x=t.n({...o,...b,storage:i||e.n(),clock:s,log:{warn:()=>{},error:()=>{},...o.log||{}}}),S=[],C=x.progress.emit;return x.progress.emit=function(e,t){return S.push({event:e,data:t}),C.call(this,e,t)},{host:x,progress:x.progress,parts:x.parts,ready:x.ready,use:x.use,dispose:()=>{x.dispose(),x.progress.emit=C},clock:s,popups:l,texts:f,huds:m,bursts:h,sounds:g,soundKeys:_,haptics:v,events:{log:S,on:(e,t)=>x.progress.on(e,t),off:(e,t)=>x.progress.off(e,t),emit:(e,t)=>x.progress.emit(e,t)},advance:e=>c(t=>t+e),advanceDays(e){c(t=>{let n=new Date(t);return n.setDate(n.getDate()+e),n.getTime()})},setClock(e){u.test(e)||d(`clock must be YYYY-MM-DDTHH:MM:SS local time`),c(()=>new Date(e).getTime())}}}var h=async e=>{await e},g=()=>typeof document>`u`?null:document.body.innerHTML,_=()=>m().parts,v=e=>[[`draws every burst kind without throwing`,async()=>{let t=e();try{for(let e of s)t.burst(e),t.burst(e,{x:10,y:20}),t.burst(e,{x:10,y:20},{count:3,color:`#fff`})}finally{t.destroy()}}],[`treats an unknown kind as a no-op`,async()=>{let t=e();try{for(let e of l)t.burst(e,{x:1,y:1})}finally{t.destroy()}}],[`has destroy`,async()=>{let t=e();f(typeof t.destroy==`function`,`a particle part needs destroy()`),t.destroy()}]],y=e=>[[`plays every preset key without throwing`,async()=>{let t=e();try{for(let e of c)await h(t.play(e))}finally{t.destroy()}}],[`treats an unknown key as a no-op`,async()=>{let t=e();try{for(let e of l)await h(t.play(e))}finally{t.destroy()}}],[`stops a registered key after its remover runs`,async()=>{let t=e();try{if(typeof t.register!=`function`)return;let e=0,n=t.register(`conformance_key`,()=>{e+=1});f(typeof n==`function`,`register() must return a remover`),n(),await h(t.play(`conformance_key`)),f(e===0,`a removed key still played`)}finally{t.destroy()}}]],b=e=>[[`draws the hud`,async()=>{let t=e(_());try{t.hud({xp:10,level:1,progress:.2,streak:0,next:50}),t.hud({xp:0,level:1,streak:3})}finally{t.destroy()}}],[`shows every popup kind and tier`,async()=>{let t=e(_());try{for(let e of[`achievement`,`level`,`notice`,`custom`])for(let n of[void 0,`common`,`rare`,`legendary`])t.popup({kind:e,title:`T`,body:`B`,icon:`I`,meta:`M`,tier:n})}finally{t.destroy()}}],[`ignores a popup it cannot read`,async()=>{let t=e(_());try{for(let e of[void 0,null,42,`text`,{},{kind:`__proto__`}])t.popup(e)}finally{t.destroy()}}],[`floats text`,async()=>{let t=e(_());try{t.text({text:`hello`,x:5,y:5,color:`#fff`}),t.text({text:`hello`})}finally{t.destroy()}}],[`has a root that is an element or null`,async()=>{let t=e(_());try{let e=t.root;f(e===null||typeof e==`object`&&typeof e.nodeType==`number`,`root must be an element or null`)}finally{t.destroy()}}],[`leaves no DOM behind after destroy`,async()=>{let t=g(),n=e(_());n.hud({xp:1,level:1,streak:1}),n.popup({kind:`achievement`,title:`T`}),n.text({text:`x`}),n.destroy(),f(g()===t,`the page changed after destroy()`)}]],x=`conformance_key`,S=e=>[[`returns null for a missing key`,async()=>{let t=e();for(let e of[x,`__proto__`,`constructor`,`toString`])f(await t.getItem(e)===null,`getItem(${e}) should be null`)}],[`keeps what setItem stores and overwrites it`,async()=>{let t=e();await t.setItem(x,`one`),f(await t.getItem(x)===`one`,`getItem should return the stored value`),await t.setItem(x,`two`),f(await t.getItem(x)===`two`,`setItem should overwrite`)}],[`keeps keys apart`,async()=>{let t=e();await t.setItem(`a`,`1`),await t.setItem(`b`,`2`),f(await t.getItem(`a`)===`1`&&await t.getItem(`b`)===`2`,`keys must not share a value`)}],[`forgets a key after removeItem`,async()=>{let t=e();await t.setItem(x,`one`),await t.removeItem(x),f(await t.getItem(x)===null,`removeItem should clear the key`),await t.removeItem(x)}]];function C(){let e=new Set,t={},n=[`setTimeout`,`setInterval`,`requestAnimationFrame`],r={setTimeout:`clearTimeout`,setInterval:`clearInterval`,requestAnimationFrame:`cancelAnimationFrame`};for(let i of n)t[i]=globalThis[i],t[r[i]]=globalThis[r[i]],typeof t[i]==`function`&&(globalThis[i]=(n,...r)=>{let a=i!==`setInterval`,o;return o=t[i]((...t)=>(a&&e.delete(o),n(...t)),...r),e.add(o),o},typeof t[r[i]]==`function`&&(globalThis[r[i]]=n=>(e.delete(n),t[r[i]](n))));return{live:()=>e.size,stop(){for(let n of e)t.clearTimeout?.(n),t.clearInterval?.(n),t.cancelAnimationFrame?.(n);for(let e of Object.keys(t))typeof t[e]==`function`&&(globalThis[e]=t[e])}}}var w=e=>{let t=0;for(let n of e.listeners.values())t+=n.size;return t};async function T(e,t){let n=C(),r=[],i=console.error;console.error=(...e)=>{r.push(e)};let a=m();try{await a.ready,await t(a,{watch:n,errors:r})}finally{console.error=i,a.dispose(),n.stop()}}var E={particles:v,sound:y,ui:b,storage:S,plugin:e=>[[`has a name, a version and the host api`,async()=>{let t=e();f(typeof t.name==`string`&&t.name!==``,`a plugin needs a name`),f(typeof t.version==`string`&&t.version!==``,`a plugin needs a version`),f(t.api===3,`a plugin needs api 3`),f(typeof t.install==`function`,`a plugin needs install()`)}],[`installs on a host and survives every core event`,async()=>{await T(e,async(t,{errors:n})=>{t.use(e()),await t.ready;for(let e of Object.keys(o))t.progress.emit(e,o[e]);await t.progress.addXP(5,`conformance`),f(n.length===0,`a listener threw: ${String(n[0]?.[1]??n[0]?.[0])}`)})}],[`leaves no listeners, timers or DOM behind once disposed`,async()=>{await T(e,async(t,{watch:n})=>{await t.ready;let r=w(t.progress),i=g(),a=n.live(),s=t.use(e());await t.progress.addXP(1,`conformance`);for(let e of Object.keys(o))t.progress.emit(e,o[e]);await t.ready,s(),f(w(t.progress)===r,`the plugin left listeners on the bus`),f(n.live()<=a,`the plugin left timers running`),f(g()===i,`the plugin left DOM in the page`)})}]]},D=e=>t=>{(0,n.describe)(`conformance.${e}`,()=>{for(let[r,i]of E[e](t))(0,n.it)(r,i)})},O={particles:D(`particles`),sound:D(`sound`),ui:D(`ui`),storage:D(`storage`),plugin:D(`plugin`)};async function k(e,t){Object.prototype.hasOwnProperty.call(E,e)||d(`unknown suite ${String(e)}`);let n=[];for(let[r,i]of E[e](t))try{await i()}catch{n.push(r)}return n}function A(){let e=typeof __dirname==`string`?__dirname:(0,i.dirname)((0,a.fileURLToPath)({}.url));for(let t of[`../spec`,`../../../spec`]){let n=(0,i.resolve)(e,t);if((0,r.existsSync)((0,i.join)(n,`VERSION`)))return n}return d(`spec/ was not found next to this package`)}function j(e){let t=e||A(),n=Number(/contract:\s*(\d+)/.exec((0,r.readFileSync)((0,i.join)(t,`VERSION`),`utf8`))?.[1]),a=JSON.parse((0,r.readFileSync)((0,i.join)(t,`schema.json`),`utf8`)),o={};for(let e of(0,r.readdirSync)((0,i.join)(t,`fixtures`)).sort()){if(!e.endsWith(`.json`))continue;let n=JSON.parse((0,r.readFileSync)((0,i.join)(t,`fixtures`,e),`utf8`));o[n.suite]=n}return{contract:n,schema:a,suites:o}}exports.conformance=O,exports.conformanceFailures=k,exports.createTestHost=m,exports.loadFixtures=j;
|
package/dist/testing.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as e, s as t } from "./DataService-
|
|
2
|
-
import { n } from "./host-
|
|
1
|
+
import { n as e, s as t } from "./DataService-Bd1S-C1N.js";
|
|
2
|
+
import { n } from "./host-CSnyl6nv.js";
|
|
3
3
|
import { describe as r, it as i } from "vitest";
|
|
4
4
|
import { existsSync as a, readFileSync as o, readdirSync as s } from "node:fs";
|
|
5
5
|
import { dirname as c, join as l, resolve as u } from "node:path";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dopaminejs",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.3.0",
|
|
4
4
|
"description": "Progression mechanics for web apps: XP, levels, achievements and timezone-correct daily streaks, with the particles and sound to make them land. Zero dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/dopamine.cjs",
|
package/spec/README.md
CHANGED
|
@@ -99,7 +99,7 @@ except for `setClock`, where it is accepted and checked if present.
|
|
|
99
99
|
| `record` | `activity`, `result?` | `record(activity, result)`. A missing `result` means the default. `null` is passed as `null`. Returns `true`. |
|
|
100
100
|
| `unlockAchievement` | `id` | `unlockAchievement(id)`. |
|
|
101
101
|
| `markAchievementsSeen` | `ids` | `markAchievementsSeen(ids)`. |
|
|
102
|
-
| `reset` |
|
|
102
|
+
| `reset` | `overwrite?` | `reset({ overwrite })`, or `reset()` when `overwrite` is missing. Replaces the player with an empty document, keeps the device id, saves, and returns the new snapshot. Fires `player_reset` after the save. With `overwrite` false and a failed load, nothing is saved: the stored document stays as it was and later writes stay blocked. After a load that worked, `overwrite` false saves like a plain reset. |
|
|
103
103
|
| `getXPForNextLevel` | none | Reads `{ total, needed, progress }`. |
|
|
104
104
|
| `export` | `as` | `export()`. Keeps the document under the name `as`. |
|
|
105
105
|
| `import` | `doc` or `from`, `silent?` | `import(doc, { silent })`. `from` names a kept document. Returns the snapshot. Achievement ids with no definition are kept but fire no event. |
|
|
@@ -962,6 +962,83 @@
|
|
|
962
962
|
}
|
|
963
963
|
}
|
|
964
964
|
]
|
|
965
|
+
},
|
|
966
|
+
{
|
|
967
|
+
"name": "reset with overwrite false after a newer version keeps the saved document",
|
|
968
|
+
"clock": "2026-08-07T09:00:00",
|
|
969
|
+
"note": "Nothing is written and later writes stay blocked. Reloading proves the v 99 document is still in storage.",
|
|
970
|
+
"config": {
|
|
971
|
+
"builtinAchievements": false
|
|
972
|
+
},
|
|
973
|
+
"savedJson": {
|
|
974
|
+
"v": 99,
|
|
975
|
+
"xpBy": {
|
|
976
|
+
"a": 900
|
|
977
|
+
}
|
|
978
|
+
},
|
|
979
|
+
"afterInit": {
|
|
980
|
+
"player": {
|
|
981
|
+
"xp": 0
|
|
982
|
+
},
|
|
983
|
+
"events": [
|
|
984
|
+
{
|
|
985
|
+
"event": "load_failed",
|
|
986
|
+
"reason": "unsupported_version"
|
|
987
|
+
}
|
|
988
|
+
]
|
|
989
|
+
},
|
|
990
|
+
"steps": [
|
|
991
|
+
{
|
|
992
|
+
"op": "addXP",
|
|
993
|
+
"amount": 30,
|
|
994
|
+
"expect": {
|
|
995
|
+
"player": {
|
|
996
|
+
"xp": 30
|
|
997
|
+
}
|
|
998
|
+
}
|
|
999
|
+
},
|
|
1000
|
+
{
|
|
1001
|
+
"op": "reset",
|
|
1002
|
+
"overwrite": false,
|
|
1003
|
+
"expect": {
|
|
1004
|
+
"player": {
|
|
1005
|
+
"xp": 0,
|
|
1006
|
+
"level": 1,
|
|
1007
|
+
"streak": {
|
|
1008
|
+
"current": 0
|
|
1009
|
+
}
|
|
1010
|
+
},
|
|
1011
|
+
"events": [
|
|
1012
|
+
{
|
|
1013
|
+
"event": "player_reset"
|
|
1014
|
+
}
|
|
1015
|
+
]
|
|
1016
|
+
}
|
|
1017
|
+
},
|
|
1018
|
+
{
|
|
1019
|
+
"op": "addXP",
|
|
1020
|
+
"amount": 10,
|
|
1021
|
+
"expect": {
|
|
1022
|
+
"player": {
|
|
1023
|
+
"xp": 10
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
},
|
|
1027
|
+
{
|
|
1028
|
+
"op": "reload",
|
|
1029
|
+
"expect": {
|
|
1030
|
+
"player": {
|
|
1031
|
+
"xp": 0
|
|
1032
|
+
},
|
|
1033
|
+
"events": [
|
|
1034
|
+
{
|
|
1035
|
+
"event": "load_failed",
|
|
1036
|
+
"reason": "unsupported_version"
|
|
1037
|
+
}
|
|
1038
|
+
]
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
]
|
|
965
1042
|
}
|
|
966
1043
|
]
|
|
967
1044
|
}
|
|
@@ -275,15 +275,36 @@ export class RewardSystem extends EventEmitter {
|
|
|
275
275
|
* could not read the saved player: the stored player is replaced, without
|
|
276
276
|
* a backup, and `loadFailed` goes back to false.
|
|
277
277
|
*
|
|
278
|
+
* Pass `{ overwrite: false }` to keep the stored player when the last
|
|
279
|
+
* init() could not read it (an unsupported newer version, or a read that
|
|
280
|
+
* keeps failing). The player in memory is replaced by a new empty one,
|
|
281
|
+
* nothing is written, `loadFailed` stays true so later writes stay
|
|
282
|
+
* blocked, and `player_reset` is still emitted. When the last init() did
|
|
283
|
+
* read the saved player, `overwrite: false` changes nothing: it saves
|
|
284
|
+
* like a plain reset(). A corrupt save that init() backed up to `player_corrupt` counts as loaded, so `overwrite: false` saves like a plain reset().
|
|
285
|
+
* If the backup failed, it counts as a failed load and nothing is written.
|
|
286
|
+
*
|
|
278
287
|
* Timing: call it after init() has resolved, not while init() is pending.
|
|
279
288
|
* A record() already in flight when reset() runs lands in the new player.
|
|
280
289
|
* Called from inside a hook, the write happens when the outer record or
|
|
281
290
|
* unlock finishes.
|
|
282
291
|
*
|
|
292
|
+
* @param {Object} [options]
|
|
293
|
+
* @param {boolean} [options.overwrite=true] - false keeps the stored player after a failed load
|
|
283
294
|
* @returns {Promise<Object>} Frozen snapshot of the new player
|
|
284
295
|
*/
|
|
285
|
-
async reset() {
|
|
296
|
+
async reset(options) {
|
|
297
|
+
const overwrite = options?.overwrite;
|
|
298
|
+
if (options !== undefined && (options === null || typeof options !== 'object' || Array.isArray(options))
|
|
299
|
+
|| overwrite !== undefined && typeof overwrite !== 'boolean') {
|
|
300
|
+
throw new TypeError('[DopamineJS] reset expects { overwrite?: boolean }');
|
|
301
|
+
}
|
|
286
302
|
this._requirePlayer();
|
|
303
|
+
if (overwrite === false && this._readFailed) {
|
|
304
|
+
this._doc = emptyDoc(this.clock.now());
|
|
305
|
+
this._publish('player_reset', {});
|
|
306
|
+
return this.snapshot();
|
|
307
|
+
}
|
|
287
308
|
await this._batch(async () => {
|
|
288
309
|
this._doc = emptyDoc(this.clock.now());
|
|
289
310
|
this._loadFailed = false;
|
|
@@ -187,6 +187,11 @@ export class RewardUI {
|
|
|
187
187
|
this._timers = new Set();
|
|
188
188
|
this._detached = [];
|
|
189
189
|
|
|
190
|
+
// Achievement and custom cards share one spot, so they show one at a
|
|
191
|
+
// time. Each entry is the arguments of a _card call.
|
|
192
|
+
this._cardQueue = [];
|
|
193
|
+
this._cardActive = false;
|
|
194
|
+
|
|
190
195
|
this._build();
|
|
191
196
|
}
|
|
192
197
|
|
|
@@ -411,8 +416,38 @@ export class RewardUI {
|
|
|
411
416
|
}
|
|
412
417
|
}
|
|
413
418
|
|
|
414
|
-
/**
|
|
419
|
+
/**
|
|
420
|
+
* Queue a card. Two unlocks in the same moment would otherwise mount at the
|
|
421
|
+
* same fixed spot and hide each other.
|
|
422
|
+
* @private
|
|
423
|
+
*/
|
|
415
424
|
_card(popup, withHeading) {
|
|
425
|
+
// Copy the fields now, so a caller that reuses its object cannot change
|
|
426
|
+
// a card that is still waiting.
|
|
427
|
+
const { title, body, meta, icon } = popup;
|
|
428
|
+
this._cardQueue.push([{ title, body, meta, icon }, withHeading]);
|
|
429
|
+
this._nextCard();
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
/** @private */
|
|
433
|
+
_nextCard() {
|
|
434
|
+
if (this._cardActive) return;
|
|
435
|
+
const next = this._cardQueue.shift();
|
|
436
|
+
if (!next) return;
|
|
437
|
+
this._cardActive = true;
|
|
438
|
+
try {
|
|
439
|
+
this._showCard(next[0], next[1]);
|
|
440
|
+
} catch (error) {
|
|
441
|
+
// A card that fails to build never schedules its removal, so the
|
|
442
|
+
// flag would stay set and every later card would be lost.
|
|
443
|
+
this._cardActive = false;
|
|
444
|
+
this._nextCard();
|
|
445
|
+
throw error;
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** @private */
|
|
450
|
+
_showCard(popup, withHeading) {
|
|
416
451
|
const card = document.createElement('div');
|
|
417
452
|
card.className = 'achievement-popup';
|
|
418
453
|
card.innerHTML = `
|
|
@@ -445,7 +480,11 @@ export class RewardUI {
|
|
|
445
480
|
|
|
446
481
|
this._defer(() => {
|
|
447
482
|
card.style.animation = 'slideOut 0.3s ease-in forwards';
|
|
448
|
-
this._defer(() =>
|
|
483
|
+
this._defer(() => {
|
|
484
|
+
this._remove(card);
|
|
485
|
+
this._cardActive = false;
|
|
486
|
+
this._nextCard();
|
|
487
|
+
}, 300);
|
|
449
488
|
}, 4000);
|
|
450
489
|
}
|
|
451
490
|
|
|
@@ -547,6 +586,8 @@ export class RewardUI {
|
|
|
547
586
|
clearTimeout(id);
|
|
548
587
|
}
|
|
549
588
|
this._timers.clear();
|
|
589
|
+
this._cardQueue = [];
|
|
590
|
+
this._cardActive = false;
|
|
550
591
|
|
|
551
592
|
for (const el of this._detached) {
|
|
552
593
|
el.remove();
|
|
@@ -112,15 +112,16 @@
|
|
|
112
112
|
|
|
113
113
|
.achievement-popup {
|
|
114
114
|
position: fixed;
|
|
115
|
-
top: 80px;
|
|
116
|
-
right: 20px;
|
|
117
|
-
|
|
118
|
-
|
|
115
|
+
top: calc(var(--dopamine-toast-top, 80px) + env(safe-area-inset-top, 0px));
|
|
116
|
+
right: var(--dopamine-toast-right, 20px);
|
|
117
|
+
left: var(--dopamine-toast-left, auto);
|
|
118
|
+
background: var(--dopamine-toast-bg, linear-gradient(135deg, #667eea 0%, #764ba2 100%));
|
|
119
|
+
border-radius: var(--dopamine-toast-radius, 16px);
|
|
119
120
|
padding: 16px;
|
|
120
|
-
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
|
|
121
|
+
box-shadow: var(--dopamine-toast-shadow, 0 8px 32px rgba(0, 0, 0, 0.4));
|
|
121
122
|
animation: slideIn 0.5s cubic-bezier(0.68, -0.55, 0.265, 1.55);
|
|
122
123
|
z-index: 10000;
|
|
123
|
-
max-width: 320px;
|
|
124
|
+
max-width: var(--dopamine-toast-max-width, 320px);
|
|
124
125
|
overflow: hidden;
|
|
125
126
|
}
|
|
126
127
|
|
|
@@ -153,7 +154,7 @@
|
|
|
153
154
|
.achievement-title {
|
|
154
155
|
font-size: 12px;
|
|
155
156
|
font-weight: 600;
|
|
156
|
-
color: rgba(255, 255, 255, 0.9);
|
|
157
|
+
color: var(--dopamine-toast-muted, rgba(255, 255, 255, 0.9));
|
|
157
158
|
text-transform: uppercase;
|
|
158
159
|
letter-spacing: 0.5px;
|
|
159
160
|
}
|
|
@@ -161,13 +162,13 @@
|
|
|
161
162
|
.achievement-name {
|
|
162
163
|
font-size: 18px;
|
|
163
164
|
font-weight: 800;
|
|
164
|
-
color: white;
|
|
165
|
+
color: var(--dopamine-toast-text, white);
|
|
165
166
|
margin: 2px 0;
|
|
166
167
|
}
|
|
167
168
|
|
|
168
169
|
.achievement-desc {
|
|
169
170
|
font-size: 13px;
|
|
170
|
-
color: rgba(255, 255, 255, 0.8);
|
|
171
|
+
color: var(--dopamine-toast-muted, rgba(255, 255, 255, 0.8));
|
|
171
172
|
margin-bottom: 4px;
|
|
172
173
|
}
|
|
173
174
|
|
|
@@ -178,7 +179,7 @@
|
|
|
178
179
|
border-radius: 8px;
|
|
179
180
|
font-size: 12px;
|
|
180
181
|
font-weight: 700;
|
|
181
|
-
color: #ffd700;
|
|
182
|
+
color: var(--dopamine-toast-accent, #ffd700);
|
|
182
183
|
}
|
|
183
184
|
|
|
184
185
|
/* ==================== LEVEL UP OVERLAY ==================== */
|
|
@@ -367,8 +368,8 @@
|
|
|
367
368
|
}
|
|
368
369
|
|
|
369
370
|
.achievement-popup {
|
|
370
|
-
right: 12px;
|
|
371
|
-
max-width: calc(100% - 24px);
|
|
371
|
+
right: var(--dopamine-toast-right, 12px);
|
|
372
|
+
max-width: min(var(--dopamine-toast-max-width, 320px), calc(100% - 24px));
|
|
372
373
|
}
|
|
373
374
|
|
|
374
375
|
.level-up-number {
|
package/types/index.d.ts
CHANGED
|
@@ -211,8 +211,15 @@ export class RewardSystem extends EventEmitter {
|
|
|
211
211
|
* Call it after `init()` has resolved, not while `init()` is pending. A
|
|
212
212
|
* `record()` already in flight when it runs lands in the new player. Called
|
|
213
213
|
* from inside a hook, the write happens when the outer record or unlock finishes.
|
|
214
|
+
*
|
|
215
|
+
* With `{ overwrite: false }` and a failed load, the stored player is kept:
|
|
216
|
+
* the player in memory is replaced by a new empty one, nothing is written,
|
|
217
|
+
* `loadFailed` stays true and `player_reset` is still emitted. After a load
|
|
218
|
+
* that worked, `overwrite: false` behaves like a plain `reset()` and saves.
|
|
219
|
+
* A corrupt save that init() backed up to `player_corrupt` counts as loaded, so `overwrite: false` saves like a plain reset(). If the backup failed, it counts as a failed load and nothing is written.
|
|
220
|
+
* A non-object `options` or a non-boolean `overwrite` throws a `TypeError`.
|
|
214
221
|
*/
|
|
215
|
-
reset(): Promise<Player>;
|
|
222
|
+
reset(options?: { overwrite?: boolean }): Promise<Player>;
|
|
216
223
|
/** Hooks run in `use` order. Returns a function that removes it. */
|
|
217
224
|
use(middleware: Middleware): () => void;
|
|
218
225
|
/** Adds a rule at runtime. Returns a function that removes it. */
|
package/dist/host-7FzZ-yO7.cjs
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
const e=require("./DataService-D1uL6E8R.cjs");var t=`#game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{z-index:10000;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:16px;max-width:320px;padding:16px;animation:.5s cubic-bezier(.68,-.55,.265,1.55) slideIn;position:fixed;top:80px;right:20px;overflow:hidden;box-shadow:0 8px 32px #0006}.achievement-shine{background:linear-gradient(90deg,#0000,#ffffff4d,#0000);width:100%;height:100%;animation:2s infinite shine;position:absolute;top:0;left:-100%}.achievement-content{align-items:center;gap:12px;display:flex;position:relative}.achievement-icon{font-size:48px;animation:.6s ease-out bounce}.achievement-info{flex:1}.achievement-title{color:#ffffffe6;text-transform:uppercase;letter-spacing:.5px;font-size:12px;font-weight:600}.achievement-name{color:#fff;margin:2px 0;font-size:18px;font-weight:800}.achievement-desc{color:#fffc;margin-bottom:4px;font-size:13px}.achievement-xp{color:gold;background:#fff3;border-radius:8px;padding:4px 8px;font-size:12px;font-weight:700;display:inline-block}.level-up-overlay{z-index:10001;background:#000000d9;justify-content:center;align-items:center;width:100%;height:100%;animation:.3s ease-out fadeIn;display:flex;position:fixed;top:0;left:0}.level-up-content{text-align:center;animation:.5s cubic-bezier(.68,-.55,.265,1.55) scaleIn}.level-up-title{background:linear-gradient(135deg,gold 0%,#ffed4e 100%);-webkit-text-fill-color:transparent;text-transform:uppercase;letter-spacing:4px;-webkit-background-clip:text;background-clip:text;margin-bottom:16px;font-size:32px;font-weight:800}.level-up-number{color:#fff;text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066;font-size:120px;font-weight:900;animation:1s ease-in-out infinite alternate glow}.level-up-subtitle{color:#fffc;margin-top:16px;font-size:24px;font-weight:600}.floating-text{text-shadow:2px 2px #000,-1px -1px #000,1px -1px #000,-1px 1px #000;pointer-events:none;z-index:9998;font-weight:800;animation:2s ease-out forwards floatUp;position:fixed}@keyframes slideIn{0%{opacity:0;transform:translate(400px)}to{opacity:1;transform:translate(0)}}@keyframes slideOut{0%{opacity:1;transform:translate(0)}to{opacity:0;transform:translate(400px)}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066}to{text-shadow:0 0 30px gold,0 0 60px #ffd700cc,0 0 90px #ffd70099}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100px)}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media (width<=480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{min-width:50px;padding:6px 10px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{max-width:calc(100% - 24px);right:12px}.level-up-number{font-size:80px}}@media (prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{transition:none!important;animation:none!important}.floating-text{animation:none!important}}`,n=`game-ui-overlay`,r={levelUp:`LEVEL UP!`,achievementUnlocked:`Achievement Unlocked!`},i=`dopamine-reward-ui-css`,a=`🔥`,o=e=>e==null?``:String(e),s=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),c=(e,t)=>typeof e==`object`&&e&&s(e,t)?e[t]:void 0,l=`http://www.w3.org/2000/svg`,u=new Set([`svg`,`g`,`path`,`circle`,`ellipse`,`rect`,`line`,`polyline`,`polygon`,`text`,`tspan`,`title`,`desc`,`defs`,`linearGradient`,`radialGradient`,`stop`,`clipPath`,`mask`]),d=new Set(`viewBox.width.height.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.d.points.transform.fill.fill-opacity.fill-rule.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-opacity.opacity.offset.stop-color.stop-opacity.gradientUnits.gradientTransform.clip-path.mask.clip-rule.font-size.font-family.font-weight.text-anchor.id.aria-hidden.aria-label.role`.split(`.`)),f=new Set([`fill`,`stroke`,`clip-path`,`mask`]),p=new Set([`transform`,`gradientTransform`]),m=/^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/,h=/^[#a-zA-Z0-9(),.%\s-]+$/,g=/^[a-zA-Z0-9(),.\s-]+$/,_=/^[A-Za-z][\w.:-]*$/,v=0;function y(e,t){if(e.nodeType!==1||e.namespaceURI!==l||!u.has(e.localName))return;let n=e.getAttribute(`id`);n&&_.test(n)&&t.add(n);for(let n of Array.from(e.childNodes))y(n,t)}function b(e,t,n){if(t.includes(`\\`))return null;let r=t.trim();if(e===`id`)return _.test(r)?n.prefix+r:null;if(f.has(e)){let e=m.exec(r);return e?n.ids.has(e[1])?`url(#${n.prefix}${e[1]})`:null:h.test(r)&&!/url/i.test(r)?r:null}return p.has(e)?g.test(r)&&!/url/i.test(r)?r:null:t.includes(`(`)?e===`stop-color`&&h.test(r)&&!/url/i.test(r)?r:null:t}function x(e,t){if(e.nodeType===3||e.nodeType===4)return document.createTextNode(e.data);if(e.nodeType!==1||e.namespaceURI!==l||!u.has(e.localName))return null;let n=document.createElementNS(l,e.localName);for(let r of Array.from(e.attributes)){if(r.namespaceURI!==null||!d.has(r.name))continue;let e=b(r.name,r.value,t);e!==null&&n.setAttribute(r.name,e)}for(let r of Array.from(e.childNodes)){let e=x(r,t);e&&n.appendChild(e)}return n}function S(e){let t,n=/^\s*<svg[\s>]/.test(e)&&!/^\s*<svg\b[^>]*\sxmlns\s*=/.test(e)?e.replace(/^(\s*<svg)/,`$1 xmlns="${l}"`):e;try{t=new DOMParser().parseFromString(n,`image/svg+xml`)}catch{return null}let r=t.documentElement;if(!r||r.localName!==`svg`||t.getElementsByTagName(`parsererror`).length>0)return null;let i=new Set;return y(r,i),x(r,{ids:i,prefix:`dj-icon-${++v}-`})}var C=class{constructor(e={},t={}){this.parts=e||{};let n=c(t,`text`);this.strings={...r};for(let e of Object.keys(r)){let t=c(n,e);typeof t==`string`&&(this.strings[e]=t)}this.safeIcons=c(t,`safeIcons`)!==!1,this._streakIcon=c(c(t,`icons`),`streak`)??a,this._injectCss=c(t,`injectCss`),this.container=null,this.xpBar=null,this.levelDisplay=null,this.streakDisplay=null,this._style=null,this._xp=null,this._level=null,this._timers=new Set,this._detached=[],this._build()}get root(){return this.container}_build(){this._injectCss&&this._addStyles(),this.container=document.createElement(`div`),this.container.className=`game-ui-overlay`,document.getElementById(n)||(this.container.id=n),this.container.innerHTML=`
|
|
2
|
-
<div class="game-ui-top-bar">
|
|
3
|
-
<div class="level-badge">
|
|
4
|
-
<span class="level-label">LVL</span>
|
|
5
|
-
<span class="level-number">1</span>
|
|
6
|
-
</div>
|
|
7
|
-
|
|
8
|
-
<div class="xp-container">
|
|
9
|
-
<div class="xp-bar-bg">
|
|
10
|
-
<div class="xp-bar-fill" style="width: 0%"></div>
|
|
11
|
-
</div>
|
|
12
|
-
<div class="xp-text">0 / 100 XP</div>
|
|
13
|
-
</div>
|
|
14
|
-
|
|
15
|
-
<div class="streak-badge">
|
|
16
|
-
<span class="streak-icon"></span>
|
|
17
|
-
<span class="streak-number">1</span>
|
|
18
|
-
</div>
|
|
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(i))return;let e=typeof this._injectCss==`string`?this._injectCss:t;this._style=document.createElement(`style`),this._style.id=i,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=S(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=c(e,`kind`);t===`level`?this._levelPopup(e):t===`notice`?this._notice(e):this._card(e,t===`achievement`)}_card(e,t){let n=document.createElement(`div`);n.className=`achievement-popup`,n.innerHTML=`
|
|
21
|
-
<div class="achievement-shine"></div>
|
|
22
|
-
<div class="achievement-content">
|
|
23
|
-
<div class="achievement-icon"></div>
|
|
24
|
-
<div class="achievement-info">
|
|
25
|
-
<div class="achievement-title"></div>
|
|
26
|
-
<div class="achievement-name"></div>
|
|
27
|
-
<div class="achievement-desc"></div>
|
|
28
|
-
<div class="achievement-xp"></div>
|
|
29
|
-
</div>
|
|
30
|
-
</div>
|
|
31
|
-
`;let r=o(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=o(e.body),n.querySelector(`.achievement-xp`).textContent=o(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),300)},4e3)}_levelPopup(e){let t=typeof e.title==`string`&&e.title!==``?e.title:this.strings.levelUp,n=o(e.body),r=document.createElement(`div`);r.className=`level-up-overlay`,r.innerHTML=`
|
|
32
|
-
<div class="level-up-content">
|
|
33
|
-
<div class="level-up-title"></div>
|
|
34
|
-
<div class="level-up-number"></div>
|
|
35
|
-
<div class="level-up-subtitle">Amazing progress!</div>
|
|
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=o(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=o(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();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}},w=Object.freeze({matches:!1});function T(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||w}var E=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),D={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)},O=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:T(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`||!E(D,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;D[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);continue}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=[]}},k=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),A=class{constructor(t={}){this.audioContext=null,this.storageKey=t.storageKey||`dopamineSoundsMuted`,this.storage=t.storage||e.r(),this.muted=this.storage.getItem(this.storageKey)===`true`,this.assets=new Map,this.customSounds=t.customSounds||{},this.masterGain=null,this._volume=1,this.setVolume(t.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):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(k(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)):k(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 j({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 M=3,N=[`ui`,`particles`,`sound`,`haptics`],P=e=>typeof e==`object`&&!!e&&typeof e.then==`function`,F=(e,t)=>{P(e)&&e.then(void 0,e=>t.error(e))};function I(){let e=typeof document<`u`&&typeof window<`u`;return{hasDom:e,reducedMotion:e?T(window).matches===!0:!1}}function L(e,t,n){if(e===!1)return null;let r=e;return typeof e==`function`&&(r=e(t)),r??n()}function R(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 z(t={}){let n=t||{},r=I(),i={debug:()=>{},info:()=>{},warn:(...e)=>console.warn(...e),error:(...e)=>console.error(...e),...n.log||{}},a=n.storage||e.r(),o=n.clock||e.s,s={ui:null,particles:null,sound:null,haptics:null},c={};for(let e of N)Object.defineProperty(c,e,{enumerable:!0,get:()=>s[e]});Object.freeze(c);let l={...r,parts:c,storage:a,clock:o},u=L(n.progress,l,()=>new e.i(new e.t({storage:a}),{clock:o,streakDays:n.streakDays,builtinAchievements:n.builtinAchievements}));if(typeof u?.on!=`function`||typeof u?.off!=`function`)throw new e.c(`invalid_progress`,`progress needs on() and off()`);s.particles=L(n.particles,l,()=>r.hasDom?new O:null),s.sound=L(n.sound,l,()=>new A({storage:a})),s.haptics=L(n.haptics,l,()=>j());try{s.ui=L(n.ui,l,()=>r.hasDom?new C(c):null)}catch(e){throw d(),e}function d(){for(let e of N)try{s[e]?.destroy?.()}catch(e){i.error(e)}}let f=u,p=[],m=!1,h=e=>t=>{try{F(e(t),i)}catch(e){i.error(e)}},g=()=>{let e=s.ui;if(!e||typeof u.snapshot!=`function`||typeof u.getXPForNextLevel!=`function`)return;let t=u.snapshot(),{total:n,progress:r}=u.getXPForNextLevel();e.hud({xp:t.xp,level:t.level,progress:r,streak:t.streak.current,next:n})};p.push(f.on(`xp_gained`,h(e=>{g(),e.leveledUp||s.sound?.play(`xp`)})),f.on(`level_up`,h(e=>{g(),s.ui?.popup({kind:`level`,title:``,body:String(e.newLevel)}),s.sound?.play(`level_up`)})),f.on(`achievement_unlocked`,h(e=>{s.ui?.popup({kind:`achievement`,title:e.name,body:e.description,icon:e.icon,meta:`+${e.xp??0} XP`}),s.sound?.play(`achievement`)})),f.on(`streak_updated`,h(g)),f.on(`player_reset`,h(g)),f.on(`personal_best`,h(e=>{s.ui?.popup({kind:`notice`,title:`New High Score: ${e.score}!`,tier:`legendary`}),s.sound?.play(`personal_best`)})));let _=new Map,v=[];function y(t){if(typeof t!=`object`||!t||typeof t.name!=`string`||!/^[a-z0-9-]+$/.test(t.name)||typeof t.install!=`function`)throw new e.c(`plugin_invalid`,`a plugin needs a name (a-z, 0-9 and -) and an install function`);if(t.api!==3)throw new e.c(`plugin_api`,`${t.name} was built for api ${t.api}, this host is api 3`);if(_.has(t.name))throw new e.c(`plugin_duplicate`,`${t.name} is already installed`);for(let n of t.after||[])if(!_.has(n)||!_.get(n).done)throw new e.c(`plugin_order`,`${t.name} must come after ${n}`);for(let n of t.requires||[])if(!N.includes(n)||s[n]===null)throw new e.c(`plugin_requires`,`${t.name} requires the ${n} part, which is not set`)}function b(e){for(let t of e.offs)t();e.offs.clear(),_.delete(e.name);let t=v.indexOf(e);t>-1&&v.splice(t,1)}function x(e){if(e.removed)return;e.removed=!0;let t=e.disposer;e.disposer=null;try{t?.()}catch(e){i.error(e)}b(e)}function S(t){let{name:n}=t;return{progress:u,parts:c,events:{on(e,n){let r=f.on(e,n),i=()=>{r(),t.offs.delete(i)};return t.offs.add(i),i},off:(e,t)=>f.off(e,t),emit(t,r){if(typeof t!=`string`||!t.startsWith(`${n}:`))throw new e.c(`plugin_event`,`${n} may only emit events named ${n}:<event>`);f.emit(t,r)}},storage:R(a,n),clock:o,log:i,env:{hasDom:r.hasDom,reducedMotion:r.reducedMotion},plugin:e=>_.has(e)&&_.get(e).done?_.get(e).handle:null,expose:e=>{t.handle=e}}}function w(t){if(m)throw new e.c(`disposed`,`the host was disposed`);y(t);let n={name:t.name,done:!1,removed:!1,disposer:null,handle:null,offs:new Set};_.set(t.name,n);let r=e=>(n.done=!0,typeof e==`function`&&(n.disposer=e),n.removed||m?(n.removed=!1,x(n),n):(v.push(n),n)),i=e=>{throw b(n),e},a;try{a=t.install(S(n))}catch(e){return i(e)}return P(a)?a.then(r,i):r(a)}let T=null;function E(t){if(m)throw new e.c(`disposed`,`the host was disposed`);if(T===null){let e=w(t);if(P(e)){let t=e.then(e=>e,e=>{throw e});return T=t.then(()=>{T=null},()=>{T=null}),{record:null,done:t}}return{record:e,done:Promise.resolve(e)}}let n=T.then(()=>w(t));return T=n.then(()=>{T=null},()=>{T=null}),{record:null,done:n}}function D(e){let{record:t,done:n}=E(e);if(t)return()=>x(t);let r=null,a=!1;return n.then(e=>{r=e,a&&x(e)},e=>i.error(e)),()=>{r?x(r):a=!0}}let k=Promise.resolve();try{for(let e of n.plugins||[]){let{done:t}=E(e);k=k.then(()=>t)}}catch(e){throw M(),e}k=k.catch(e=>{throw M(),e});function M(){if(!m){m=!0;for(let e of[...v].reverse())x(e);for(let e of[..._.values()])x(e);for(let e of p)e();p.length=0,d(),u.clear?.()}}let z=k.then(()=>typeof u.init==`function`?u.init():void 0).then(()=>(m||g(),B));z.catch(()=>{});let B={progress:u,parts:c,events:f,ready:z,use:D,dispose:M};return B}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return O}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return A}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return z}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return T}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return j}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return C}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return M}});
|