dopaminejs 3.4.0 → 3.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -2
- package/dist/DataService-B5noGvMr.js +894 -0
- package/dist/DataService-DKCk0nOu.cjs +1 -0
- package/dist/SoundManager-C6VdZEFo.js +308 -0
- package/dist/SoundManager-DBGDYIkz.cjs +1 -0
- package/dist/celebrate.cjs +1 -0
- package/dist/celebrate.js +100 -0
- package/dist/core.cjs +1 -1
- package/dist/core.js +3 -1
- package/dist/dopamine.cjs +1 -1
- package/dist/dopamine.global.js +4 -4
- package/dist/dopamine.js +5 -3
- package/dist/host-B-Gn-Zg_.js +537 -0
- package/dist/host-D6suk7Ci.cjs +37 -0
- package/dist/storage-B6z-zaBe.cjs +1 -0
- package/dist/storage-C2s4Da9b.js +26 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +5 -3
- package/package.json +10 -3
- package/spec/README.md +113 -14
- package/spec/fixtures/merge.json +345 -0
- package/spec/fixtures/migrate.json +345 -22
- package/spec/fixtures/recovery.json +1861 -0
- package/spec/schema.json +2 -2
- package/src/celebrate.js +208 -0
- package/src/dopamine/core/RewardSystem.js +150 -11
- package/src/dopamine/core/merge.js +116 -1
- package/src/dopamine/core/store.js +90 -32
- package/src/dopamine/effects/ParticleSystem.js +5 -1
- package/src/dopamine/host.js +3 -1
- package/src/dopamine/ui/RewardUI.js +10 -6
- package/src/testing.js +2 -1
- package/types/celebrate.d.ts +31 -0
- package/types/index.d.ts +27 -4
- package/dist/DataService-CydwGT_D.js +0 -744
- package/dist/DataService-EJeOPnbo.cjs +0 -1
- package/dist/host-DOvdGHZL.js +0 -834
- package/dist/host-MPzunSej.cjs +0 -37
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./storage-B6z-zaBe.cjs");var t=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()}},n=class extends Error{constructor(e,t){super(t||e),this.name=`DopamineError`,this.code=e}},r=(e,t=2)=>String(e).padStart(t,`0`),i={now:()=>Date.now(),localDate(e=Date.now()){let t=new Date(e);return`${r(t.getFullYear(),4)}-${r(t.getMonth()+1)}-${r(t.getDate())}`}},a=e=>e>0?Math.max(1,Math.floor((1+Math.sqrt(1+4*e/50))/2)):1,o=e=>50*e*(e-1),s=()=>({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}}),c={first_game:50,level_5:100,level_10:250,streak_3:100,streak_7:300},l=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},u=864e5,d=/^\d{4}-\d{2}-\d{2}$/,f=e=>{let t=new Date(0);return t.setUTCFullYear(+e.slice(0,4),e.slice(5,7)-1,+e.slice(8)),t.getTime()/u},p=e=>new Date(e*u).toISOString().slice(0,10),m=e=>typeof e==`string`&&d.test(e)&&p(f(e))===e,h=(e,t)=>p(f(e)+t);function g(e,t){let n=[...new Set(e)].sort();if(!t)return n;let r=f(t)-399,i=f(t)+1;return n.filter(e=>f(e)>=r&&f(e)<=i)}function _(e,t){let n=new Set(e),r=n.has(t)?t:h(t,-1),i=0;for(;n.has(r);)i++,r=h(r,-1);return i}function v(e){let t=0,n=0,r=NaN;for(let i of[...e].sort()){let e=f(i);n=e===r+1?n+1:1,r=e,n>t&&(t=n)}return t}var ee=(e,t)=>e.reduce((e,n)=>n<=t&&(!e||n>e)?n:e,void 0),y=`legacy`,te=new Set([`__proto__`,`constructor`,`prototype`]),b=e=>typeof e==`string`&&e.length>0&&!te.has(e),x=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),S=e=>typeof e==`object`&&!!e&&!Array.isArray(e),ne=/^\s*-?\d+(\.\d+)?\s*$/;function C(e){return typeof e==`string`&&(e=ne.test(e)?Number(e):void 0),typeof e==`number`&&Number.isFinite(e)?e:void 0}var w=e=>Math.min(e,2**53-1),re=C,T=e=>{let t=C(e);return t!==void 0&&t>=0?t:void 0},E=e=>{let t=C(e);return Number.isInteger(t)&&t>=0?t:void 0},D=(e,t)=>re(e)??t,O=(e,t)=>T(e)??t,k=(e,t,n=0)=>{let r=C(e);return Number.isInteger(r)&&r>=n?w(r):t},A=(e,t=e=>e)=>Object.keys(e).sort().reduce((n,r)=>w(n+t(e[r])),0),j=(e=0)=>({v:3,name:`Player`,createdAt:e,lastPlayedAt:e,level:1,longest:0,playDates:[],xpBy:{},xpSpentBy:{},gamesBy:{},playsBy:{},best:{},sumsBy:{},achievements:{}});function M(e,t){let n={};if(!S(e))return n;for(let r of Object.keys(e)){let i=b(r)?t(e[r]):void 0;i!==void 0&&(n[r]=w(i))}return n}function N(e,t){let n={};if(!S(e))return n;for(let r of Object.keys(e))b(r)&&(n[r]=M(e[r],t));return n}function P(e,t){let n={};if(!S(e))return n;for(let r of Object.keys(e)){let i=e[r];b(r)&&S(i)&&(n[r]={unlockedAt:D(i.unlockedAt,t),seen:i.seen===!0,reward:w(O(i.reward,0))})}return n}var F=new Set([`v`,`name`,`createdAt`,`lastPlayedAt`,`level`,`longest`,`playDates`,`xpBy`,`xpSpentBy`,`gamesBy`,`playsBy`,`best`,`sumsBy`,`achievements`]),ie=new Set([...F,`xp`,`totalGamesPlayed`,`stats`,`streak`]);function I(e,t=0){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(t>=32)return;if(Array.isArray(e))return e.map(e=>I(e,t+1)??null);if(!S(e))return;let n={};for(let r of Object.keys(e)){let i=b(r)?I(e[r],t+1):void 0;i!==void 0&&(n[r]=i)}return n}function L(e,t){for(let n of Object.keys(e)){if(ie.has(n)||!b(n))continue;let r=I(e[n]);r!==void 0&&(t[n]=r)}return t}var R=e=>Object.keys(e).filter(e=>!F.has(e));function z(e){let t=e.sumsBy,n=new Set([...Object.keys(e.playsBy),...Object.keys(e.best),...Object.keys(t)]);for(let r of n)x(e.playsBy,r)||(e.playsBy[r]={}),x(e.best,r)||(e.best[r]=0),x(t,r)||(t[r]={});return e}function ae(e,t,n){return L(e,z({v:3,name:typeof e.name==`string`?e.name:`Player`,createdAt:D(e.createdAt,t),lastPlayedAt:D(e.lastPlayedAt,t),level:k(e.level,1,1),longest:k(e.longest,0),playDates:g(Array.isArray(e.playDates)?e.playDates.filter(m):[],n),xpBy:M(e.xpBy,T),xpSpentBy:M(e.xpSpentBy,T),gamesBy:M(e.gamesBy,E),playsBy:N(e.playsBy,E),best:M(e.best,T),sumsBy:oe(e.sumsBy),achievements:P(e.achievements,t)}))}function oe(e){let t={};if(!S(e))return t;for(let n of Object.keys(e))b(n)&&(t[n]=N(e[n],T));return t}function se(e,t,n,r){let i=j(t);i.name=typeof e.name==`string`?e.name:`Player`,i.createdAt=D(e.createdAt,t),i.lastPlayedAt=D(e.lastPlayedAt,t),i.achievements=P(e.achievements,t);let o=0;for(let e of Object.keys(i.achievements)){let t=x(n,e)?w(O(n[e],0)):0;i.achievements[e].reward=t,o+=t}let s=w(O(e.xp,0)),c=Math.max(0,s-o);c>0&&(i.xpBy[y]=c),i.level=Math.max(a(s),k(e.level,1,1));let l=k(e.totalGamesPlayed,0);if(l>0&&(i.gamesBy[y]=l),S(e.stats))for(let t of Object.keys(e.stats)){let n=e.stats[t];if(!b(t)||!S(n))continue;let r=k(n.totalPlays,0);i.playsBy[t]=r>0?{[y]:r}:{},i.best[t]=w(O(n.highScore,0)),i.sumsBy[t]={};for(let e of Object.keys(n)){if(!b(e)||e===`totalPlays`||e===`highScore`)continue;let r=T(n[e]);r!==void 0&&(i.sumsBy[t][e]={[y]:w(r)})}}let u=S(e.streak)?e.streak:{},d=k(u.current,1,1);if(i.longest=Math.max(d,k(u.longest,0)),m(u.lastPlayDate)){let e=r&&u.lastPlayDate>r?r:u.lastPlayDate;for(let t=0;t<Math.min(d,400);t++)i.playDates.push(h(e,-t));i.playDates=g(i.playDates,r)}else i.longest=Math.max(k(u.current,0),k(u.longest,0));return L(e,z(i))}function B(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 V(e){if(B(e).size>20)throw new n(`too_many_devices`,`[DopamineJS] a save holds at most 20 devices`)}function H(e,t={}){if(!S(e))throw new n(`invalid_document`,`[DopamineJS] a save must be an object`);if(e.v!==void 0&&e.v!==3)throw new n(`unsupported_version`,`[DopamineJS] save version ${String(e.v)} is not 3`);let r=Number.isFinite(t.now)?t.now:0,i=m(t.today)?t.today:void 0,a=e.v===3?ae(e,r,i):se(e,r,S(t.rewards)?t.rewards:c,i);return V(a),a}var U=e=>w(Math.max(0,A(e.xpBy)+A(e.achievements,e=>e.reward)-A(e.xpSpentBy))),W=e=>Math.max(e.level,a(U(e)));function ce(e,t){let n={};for(let t of Object.keys(e.playsBy)){let r={plays:A(e.playsBy[t]),best:e.best[t]};for(let n of Object.keys(e.sumsBy[t]))n!==`plays`&&n!==`best`&&(r[n]=A(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:_(e.playDates,t),longest:Math.max(e.longest,v(e.playDates))},a=ee(e.playDates,t);return a&&(i.lastPlayDate=a),{name:e.name,xp:U(e),level:W(e),totalGamesPlayed:A(e.gamesBy),createdAt:e.createdAt,lastPlayedAt:e.lastPlayedAt,streak:i,achievements:r,stats:n}}var G=e=>JSON.parse(JSON.stringify(e));function K(e){if(typeof e==`object`&&e&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))K(e[t])}return e}var q=[`beforeXP`,`afterXP`,`beforeRecord`,`afterRecord`,`beforeUnlock`,`afterUnlock`],le=class{constructor(){this._list=[]}use(e){if(!S(e)||!q.some(t=>typeof e[t]==`function`))throw TypeError(`[DopamineJS] use expects an object with one of: ${q.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(!S(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=x(e,i)?e[i]:void 0,o=x(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 ue(e,t){let n={};for(let r of new Set([...Object.keys(e),...Object.keys(t)])){let i=x(e,r)?e[r]:void 0,a=x(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 Y=e=>Array.isArray(e)?`[${e.map(Y).join(`,`)}]`:typeof e==`object`&&e?`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${Y(e[t])}`).join(`,`)}}`:JSON.stringify(e),de=(e,t)=>(Number.isFinite(e)&&Number.isFinite(t)&&e!==t?e>t:Y(e)>=Y(t))?e:t;function fe(e,t,n){for(let r of new Set([...R(e),...R(t)])){let i=x(e,r)?e[r]:void 0,a=x(t,r)?t[r]:void 0;n[r]=i===void 0?a:a===void 0?i:de(i,a)}}var pe=(e,t)=>e>0&&t>0?Math.min(e,t):Math.max(e,t);function X(e,t,n){let r=H(e,n),i=H(t,n),a={v:3,name:(r.lastPlayedAt===i.lastPlayedAt?r.name>=i.name?r:i:r.lastPlayedAt>i.lastPlayedAt?r:i).name,createdAt:pe(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:g([...r.playDates,...i.playDates],m(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:ue(r.achievements,i.achievements)};return fe(r,i,a),V(a),a}function Z(e){let t=new Map([[JSON.stringify([`xpBy`]),e.xpBy],[JSON.stringify([`xpSpentBy`]),e.xpSpentBy],[JSON.stringify([`gamesBy`]),e.gamesBy]]);for(let n of Object.keys(e.playsBy))t.set(JSON.stringify([`playsBy`,n]),e.playsBy[n]);for(let n of Object.keys(e.sumsBy))for(let r of Object.keys(e.sumsBy[n]))t.set(JSON.stringify([`sumsBy`,n,r]),e.sumsBy[n][r]);return t}function me(e){let t=new Set;for(let n of Z(e).values())for(let e in n)n[e]>0&&t.add(e);return t}function Q(e,t){let n=new Map;for(let[r,i]of Z(e))x(i,t)&&n.set(r,i[t]);return n}function he(e,t,n){for(let[r,i]of n){let n=e;for(let e of JSON.parse(r))x(n,e)||(n[e]={}),n=n[e];n[t]=w((x(n,t)?n[t]:0)+i)}}function ge(e,t,n,r,i=new Map){let a=H(e,r),o=H(t,r),s=X(a,o,r);s.name=a.name;for(let e of R(a))s[e]=a[e];let c=Z(s),l=Z(a);for(let[e,t]of Z(o)){if(!x(t,n))continue;let r=Math.min(i.get(e)??0,t[n]),a=l.has(e)&&x(l.get(e),n)?l.get(e)[n]:0;c.get(e)[n]=w(Math.max(a,r)+(t[n]-r))}return s}function _e(e,t,n){let r=G(e),i=e=>{x(e,t)&&(e[n]=x(e,n)?Math.max(e[n],e[t]):e[t],delete e[t])};for(let e of[r.xpBy,r.xpSpentBy,r.gamesBy])i(e);for(let e of Object.keys(r.playsBy))i(r.playsBy[e]);for(let e of Object.keys(r.sumsBy))for(let t of Object.keys(r.sumsBy[e]))i(r.sumsBy[e][t]);return r}var $=`device`,ve=()=>{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(``)},ye=e=>b(e)&&e!==`legacy`,be=class extends t{constructor(e,t={}){super(),this.dataService=e,this.clock=t.clock&&typeof t.clock.now==`function`&&typeof t.clock.localDate==`function`?t.clock:i,this.achievements={...t.builtinAchievements===!1?{}:s(),...t.achievements||{}},this.streakDays=t.streakDays===`record`?`record`:`any`,this._doc=null,this._deviceId=null,this._deviceSaved=!1,this._middleware=new le,this._unlocking=new Set,this._batchDepth=0,this._pendingSave=!1,this._loadFailed=!1,this._readFailed=!1,this.loadRetryMs=Number.isFinite(t.loadRetryMs)&&t.loadRetryMs>=0?t.loadRetryMs:3e4,this._lastRead=0,this._reading=!1,this._recovering=null,this._epoch=0,this._forgetImports(),this._recoveries=0}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:{...c,...l(this.achievements)}}}async init(){let e=this._doc&&!this._loadFailed&&Q(this._doc,this._deviceId),t=await this._readSaved();return this._loadFailed&&this._doc?e&&e.forEach((e,t)=>this._base.set(t,Math.max(this._base.get(t)??0,e))):(this._doc=this._load(t),this._forgetImports()),await this._readDevice(),await this.save(),this.snapshot()}async _readSaved(){this._loadFailed=!0,this._reading=!0,this._epoch++,this._recovering=null,this._lastRead=this.clock.now();try{let e=await this.dataService.load(`player`,null,{strict:!0});return e!==null&&!S(e)?await this._keepCorrupt(e):(this._loadFailed=!1,this._readFailed=!1,e)}catch(e){return e?.code===`DOPAMINE_CORRUPT`?this._keepCorrupt(e.raw):(this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:`read`,error:e}),null)}finally{this._reading=!1}}_recover(){if(this._recovering||!this._readFailed||this._reading)return Promise.resolve(!1);let e=this.clock.now()-this._lastRead;if(e>=0&&e<this.loadRetryMs)return Promise.resolve(!1);this._lastRead=this.clock.now();let t=this._retryRead(this._epoch).finally(()=>{this._recovering===t&&(this._recovering=null)});return this._recovering=t,t}async _retryRead(e){let t,n=null;try{if(t=await this.dataService.load(`player`,null,{strict:!0}),t!==null&&!S(t))return!1;if(!this._deviceSaved){let e=await this.dataService.load($,null,{strict:!0});ye(e)&&e!==this._deviceId&&(n=e)}}catch{return!1}if(e!==this._epoch||!this._loadFailed||me(this._doc).has(n))return!1;let r;try{let e=this._options(),i=n??this._deviceId,a=n?_e(this._doc,this._deviceId,n):this._doc;r=t===null?G(a):ge(t,a,i,e,this._base),V(r),r.level=W(r)}catch{return!1}return n&&(this._deviceId=n,this._deviceSaved=!0),this._doc=r,this._recoveries++,this._savedLevel=Number(t?.level)||0,this._loadFailed=!1,this._readFailed=!1,this._forgetImports(),await this._write(),this._publish(`load_recovered`,{key:`player`}),!0}_forgetImports(){this._base=new Map}async _keepCorrupt(e){this._loadFailed=!0;let t=await this.dataService.save(`player_corrupt`,e);return t&&(this._loadFailed=!1),this._readFailed=!t,this._publish(`load_failed`,{key:`player`,reason:`corrupt`,backedUp:t}),null}_load(e){if(!S(e))return j(this.clock.now());try{return H(e,this._options())}catch(e){if(!(e instanceof n))throw e;return this._loadFailed=!0,this._readFailed=!0,this._publish(`load_failed`,{key:`player`,reason:e.code,error:e}),j(this.clock.now())}}async _readDevice(){if(this._deviceId)return;let e=null;try{e=await this.dataService.load($,null,{strict:!0})}catch{this._deviceId=ve();return}ye(e)?(this._deviceId=e,this._deviceSaved=!0):this._deviceId=ve()}_hasSlot(){let e=B(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(),K(ce(this._doc,this.clock.localDate()))}export(){return this._requirePlayer(),G(this._doc)}async import(e,{silent:t=!1}={}){this._requirePlayer();let n=this.snapshot(),r=H(e,this._options()),i=this._doc,a=null;if(this._readFailed){a=new Map(this._base);let e=new Map,t=Q(this._doc,this._deviceId);Q(r,this._deviceId).forEach((n,r)=>{n>(t.get(r)??0)&&(e.set(r,n-(a.get(r)??0)),a.set(r,n))}),i=G(this._doc),he(i,this._deviceId,e)}let o=X(i,r,this._options());o.level=W(o),this._doc=o,a&&(this._base=a);let s=this.snapshot();if(await this.save(),t)return s;let c=s.xp-n.xp,l=s.level>n.level;c>0&&this._publish(`xp_gained`,{amount:c,reason:`import`,leveledUp:l,newLevel:s.level,total:s.xp}),l&&this._publish(`level_up`,{oldLevel:n.level,newLevel:s.level,totalXP:s.xp});for(let e of Object.keys(s.achievements))!x(n.achievements,e)&&x(this.achievements,e)&&this._publish(`achievement_unlocked`,{...this.achievements[e],id:e});return s}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=j(this.clock.now()),this._forgetImports(),this._publish(`player_reset`,{}),this.snapshot()):(await this._batch(async()=>{this._doc=j(this.clock.now()),this._loadFailed=!1,this._readFailed=!1,this._forgetImports(),await this.save()}),this._publish(`player_reset`,{}),this.snapshot())}use(e){return this._middleware.use(e)}defineAchievement(e,t){if(!b(e))throw TypeError(`[DopamineJS] defineAchievement expects an id, received ${String(e)}`);if(!S(t)||typeof t.check!=`function`)throw TypeError(`[DopamineJS] defineAchievement expects a definition with a check function`);let n=x(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(){this._doc&&(this._batchDepth>0?this._pendingSave=!0:await this._write())}async _write(){this._loadFailed?await this._recover():(this._doc.lastPlayedAt=this.clock.now(),this._deviceSaved||=await this.dataService.save($,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:W(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:W(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]=w((x(e.xpBy,this._deviceId)?e.xpBy[this._deviceId]:0)+t):e.xpSpentBy[this._deviceId]=w((x(e.xpSpentBy,this._deviceId)?e.xpSpentBy[this._deviceId]:0)-t)});return await this._middleware.after(`afterXP`,{amount:r.xpGained,reason:n.reason,total:U(this._doc),level:r.newLevel}),r}async _applyXP(e,t,n){let r=this._doc,i=W(r);return e=Math.max(e,-U(r)),n(r,e),this._announceXP(i,e,t)}async _announceXP(e,t,n){let r=this._doc,i=U(r),o=Math.max(e,a(i));o>r.level&&(r.level=o);let s=this._recoveries;await this.save(),this._recoveries!==s&&(i=U(this._doc),o=Math.max(o,W(this._doc)),e=Math.max(e,this._savedLevel,a(i-t)));let c=o>e;return this._publish(`xp_gained`,{amount:t,reason:n,leveledUp:c,newLevel:o,total:i}),c&&this._publish(`level_up`,{oldLevel:e,newLevel:o,totalXP:i}),{leveledUp:c,newLevel:o,xpGained:t}}getXPForNextLevel(){this._requirePlayer();let e=W(this._doc),t=U(this._doc),n=o(e+1),r=o(e),i=n-r,a=i>0?Math.max(0,Math.min(1,(t-r)/i)):0;return{total:n,needed:Math.max(0,n-t),progress:a}}_checkRecord(e,t){if(!b(e))throw TypeError(`[DopamineJS] record expects an activity name, received ${String(e)}`);if(!S(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=g([...e.playDates,t],t),e.longest=Math.max(e.longest,v(e.playDates)),n||this._publish(`streak_updated`,{current:_(e.playDates,t),longest:Math.max(e.longest,v(e.playDates))})}async _record(e,t){let n=this._doc,r=this._deviceId,i=(e,t)=>{e[r]=w((x(e,r)?e[r]:0)+t)};this._markDay(),x(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`&&b(r)&&(x(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(x(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(),!b(e)||!x(this.achievements,e)||x(this._doc.achievements,e)||this._unlocking.has(e))return!1;let t=this.achievements[e];if(!t)return!1;let{[e]:n}=l(this.achievements);this._unlocking.add(e);let r;try{r=await this._middleware.before(`beforeUnlock`,{id:e,reward:n},e=>Number.isFinite(e.reward)&&e.reward>=0)}finally{this._unlocking.delete(e)}if(r===!1||x(this._doc.achievements,e))return!1;let i=this._doc,a=W(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){this._requirePlayer();for(let t of e)x(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}},xe=class{constructor(t={}){this.storage=t.storage||e.n(),this.prefix=t.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 i}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return H}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return be}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return X}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return xe}});
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { n as e } from "./storage-C2s4Da9b.js";
|
|
2
|
+
// src/dopamine/feel/motion.js
|
|
3
|
+
var t = Object.freeze({ matches: !1 });
|
|
4
|
+
function n(e = globalThis.window) {
|
|
5
|
+
return typeof e?.matchMedia == "function" && e.matchMedia("(prefers-reduced-motion: reduce)") || t;
|
|
6
|
+
}
|
|
7
|
+
// src/dopamine/effects/ParticleSystem.js
|
|
8
|
+
var r = (e, t) => Object.prototype.hasOwnProperty.call(e, t), i = {
|
|
9
|
+
confetti: (e, t, n, r) => e.confetti(t, n, r),
|
|
10
|
+
sparkle: (e, t, n, r, i) => e.sparkle(t, n, r, i),
|
|
11
|
+
fire: (e, t, n, r) => e.fire(t, n, r),
|
|
12
|
+
stars: (e, t, n, r) => e.starBurst(t, n, r),
|
|
13
|
+
coins: (e, t, n, r) => e.coinShower(t, n, r)
|
|
14
|
+
}, a = class {
|
|
15
|
+
constructor(e = {}) {
|
|
16
|
+
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 : n(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"));
|
|
17
|
+
let t = this.canvas.getContext("2d");
|
|
18
|
+
if (!t) throw Error("[DopamineJS] This canvas has no 2d context");
|
|
19
|
+
this.container.appendChild(this.canvas), this.ctx = t, this.particles = [], this.pool = [], this.sprites = /* @__PURE__ */ new Map(), this.customEffects = /* @__PURE__ */ 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);
|
|
20
|
+
}
|
|
21
|
+
_resize() {
|
|
22
|
+
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;
|
|
23
|
+
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);
|
|
24
|
+
}
|
|
25
|
+
registerSprite(e, t) {
|
|
26
|
+
let n = new Image();
|
|
27
|
+
n.src = t, this.sprites.set(e, n);
|
|
28
|
+
}
|
|
29
|
+
registerEffect(e, t) {
|
|
30
|
+
this.customEffects.set(e, t);
|
|
31
|
+
}
|
|
32
|
+
play(e, t, n, ...r) {
|
|
33
|
+
typeof t == "object" && t && (r = n === void 0 ? [] : [n, ...r], {x: t, y: n} = t);
|
|
34
|
+
let i = this.customEffects.get(e);
|
|
35
|
+
i ? i(t, n, ...r) : console.warn(`[DopamineJS] Effect '${e}' not found.`);
|
|
36
|
+
}
|
|
37
|
+
emit(e) {
|
|
38
|
+
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);
|
|
39
|
+
for (let e = 0; e < m; e++) {
|
|
40
|
+
let e = this._getParticle(), r = d + (Math.random() - .5) * u, m = Math.random() * i;
|
|
41
|
+
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);
|
|
42
|
+
}
|
|
43
|
+
m > 0 && this._startAnimation();
|
|
44
|
+
}
|
|
45
|
+
_allowed(e) {
|
|
46
|
+
if (this._reducedMotion?.matches || !Number.isFinite(e)) return 0;
|
|
47
|
+
let t = this.maxParticles - this.particles.length;
|
|
48
|
+
return Math.max(0, Math.min(Math.floor(e), t));
|
|
49
|
+
}
|
|
50
|
+
_getParticle() {
|
|
51
|
+
return this.pool.length > 0 ? this.pool.pop() : {};
|
|
52
|
+
}
|
|
53
|
+
_recycleParticle(e) {
|
|
54
|
+
this.pool.push(e);
|
|
55
|
+
}
|
|
56
|
+
burst(e, t, n) {
|
|
57
|
+
if (typeof e != "string" || !r(i, e)) return;
|
|
58
|
+
let a = Number.isFinite(t?.x) ? t.x : this.width / 2, o = Number.isFinite(t?.y) ? t.y : this.height / 2, s = Number.isFinite(n?.count) ? n.count : void 0;
|
|
59
|
+
i[e](this, a, o, s, n?.color);
|
|
60
|
+
}
|
|
61
|
+
confetti(e, t, n = 50) {
|
|
62
|
+
this.emit({
|
|
63
|
+
x: e,
|
|
64
|
+
y: t,
|
|
65
|
+
count: n,
|
|
66
|
+
color: [
|
|
67
|
+
"#ff6b6b",
|
|
68
|
+
"#4ecdc4",
|
|
69
|
+
"#45b7d1",
|
|
70
|
+
"#f7dc6f",
|
|
71
|
+
"#c06c84",
|
|
72
|
+
"#6c5ce7"
|
|
73
|
+
],
|
|
74
|
+
speed: 10,
|
|
75
|
+
gravity: .3,
|
|
76
|
+
decay: .015,
|
|
77
|
+
size: 8,
|
|
78
|
+
spread: Math.PI * 2
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
coinShower(e, t, n = 10) {
|
|
82
|
+
this.emit({
|
|
83
|
+
x: e,
|
|
84
|
+
y: t,
|
|
85
|
+
count: n,
|
|
86
|
+
color: "#ffd700",
|
|
87
|
+
speed: 4,
|
|
88
|
+
gravity: .4,
|
|
89
|
+
decay: .012,
|
|
90
|
+
size: 12,
|
|
91
|
+
angle: -Math.PI / 2,
|
|
92
|
+
spread: Math.PI / 2
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
sparkle(e, t, n = 20, r = "#ffd700") {
|
|
96
|
+
this.emit({
|
|
97
|
+
x: e,
|
|
98
|
+
y: t,
|
|
99
|
+
count: n,
|
|
100
|
+
color: r,
|
|
101
|
+
speed: 3,
|
|
102
|
+
gravity: -.05,
|
|
103
|
+
decay: .03,
|
|
104
|
+
size: 3
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
fire(e, t, n = 15) {
|
|
108
|
+
this.emit({
|
|
109
|
+
x: e,
|
|
110
|
+
y: t,
|
|
111
|
+
count: n,
|
|
112
|
+
color: [
|
|
113
|
+
"#ff6b00",
|
|
114
|
+
"#ff8800",
|
|
115
|
+
"#ffaa00",
|
|
116
|
+
"#ff4400"
|
|
117
|
+
],
|
|
118
|
+
speed: 3,
|
|
119
|
+
gravity: -.2,
|
|
120
|
+
decay: .04,
|
|
121
|
+
size: 5,
|
|
122
|
+
angle: -Math.PI / 2,
|
|
123
|
+
spread: Math.PI / 4
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
starBurst(e, t, n = 8) {
|
|
127
|
+
let r = this._allowed(n);
|
|
128
|
+
for (let n = 0; n < r; n++) {
|
|
129
|
+
let i = this._getParticle(), a = Math.PI * 2 / r * n;
|
|
130
|
+
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);
|
|
131
|
+
}
|
|
132
|
+
r > 0 && this._startAnimation();
|
|
133
|
+
}
|
|
134
|
+
_startAnimation() {
|
|
135
|
+
this.isAnimating || (this.isAnimating = !0, this._lastFrameTime = null, this._animate());
|
|
136
|
+
}
|
|
137
|
+
_animate(e) {
|
|
138
|
+
this._frameHandle = null, this.ctx.clearRect(0, 0, this.width, this.height);
|
|
139
|
+
let t = 1;
|
|
140
|
+
Number.isFinite(e) && (this._lastFrameTime !== null && (t = Math.max(0, Math.min(3, (e - this._lastFrameTime) / (1e3 / 60)))), this._lastFrameTime = e);
|
|
141
|
+
for (let e = this.particles.length - 1; e >= 0; e--) {
|
|
142
|
+
let n = this.particles[e];
|
|
143
|
+
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) {
|
|
144
|
+
this._recycleParticle(n);
|
|
145
|
+
let t = this.particles.pop();
|
|
146
|
+
e < this.particles.length && (this.particles[e] = t);
|
|
147
|
+
} else {
|
|
148
|
+
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)) {
|
|
149
|
+
let e = this.sprites.get(n.sprite);
|
|
150
|
+
e.complete && this.ctx.drawImage(e, -n.size / 2, -n.size / 2, n.size, n.size);
|
|
151
|
+
} 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());
|
|
152
|
+
this.ctx.restore();
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
this.particles.length > 0 ? this._frameHandle = requestAnimationFrame((e) => this._animate(e)) : this.isAnimating = !1;
|
|
156
|
+
}
|
|
157
|
+
_drawStarPath(e, t, n, r, i) {
|
|
158
|
+
let a = Math.PI / 2 * 3, o = e, s = t, c = Math.PI / n;
|
|
159
|
+
this.ctx.beginPath(), this.ctx.moveTo(e, t - r);
|
|
160
|
+
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;
|
|
161
|
+
this.ctx.lineTo(e, t - r), this.ctx.closePath();
|
|
162
|
+
}
|
|
163
|
+
clear() {
|
|
164
|
+
this.particles.forEach((e) => this._recycleParticle(e)), this.particles = [], this.ctx.clearRect(0, 0, this.width, this.height);
|
|
165
|
+
}
|
|
166
|
+
destroy() {
|
|
167
|
+
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 = [];
|
|
168
|
+
}
|
|
169
|
+
}, o = (e, t) => Object.prototype.hasOwnProperty.call(e, t), s = class {
|
|
170
|
+
constructor(t = {}) {
|
|
171
|
+
this.audioContext = null, this.storageKey = t.storageKey || "dopamineSoundsMuted", this.storage = t.storage || e(), this.muted = this.storage.getItem(this.storageKey) === "true", this.assets = /* @__PURE__ */ new Map(), this.customSounds = t.customSounds || {}, this.masterGain = null, this._volume = 1, this.setVolume(t.volume ?? 1), this._loading = /* @__PURE__ */ new Map(), this._timers = /* @__PURE__ */ new Set(), this._synths = /* @__PURE__ */ new Map(), this._unlocks = /* @__PURE__ */ new Set();
|
|
172
|
+
}
|
|
173
|
+
unlockOn(e, t = [
|
|
174
|
+
"pointerup",
|
|
175
|
+
"touchend",
|
|
176
|
+
"keydown"
|
|
177
|
+
]) {
|
|
178
|
+
let n = () => {
|
|
179
|
+
for (let n of t) e.removeEventListener(n, r);
|
|
180
|
+
this._unlocks.delete(n);
|
|
181
|
+
}, r = () => {
|
|
182
|
+
n(), this.initAudio();
|
|
183
|
+
};
|
|
184
|
+
for (let n of t) e.addEventListener(n, r);
|
|
185
|
+
return this._unlocks.add(n), n;
|
|
186
|
+
}
|
|
187
|
+
_later(e, t) {
|
|
188
|
+
let n = setTimeout(() => {
|
|
189
|
+
this._timers.delete(n), e();
|
|
190
|
+
}, t);
|
|
191
|
+
this._timers.add(n);
|
|
192
|
+
}
|
|
193
|
+
initAudio() {
|
|
194
|
+
if (!this.audioContext) {
|
|
195
|
+
let e = typeof window < "u" ? window.AudioContext || window.webkitAudioContext : void 0;
|
|
196
|
+
if (!e) return !1;
|
|
197
|
+
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);
|
|
198
|
+
}
|
|
199
|
+
return this.audioContext.state === "suspended" && this.audioContext.resume(), !0;
|
|
200
|
+
}
|
|
201
|
+
setVolume(e) {
|
|
202
|
+
return Number.isFinite(e) && (this._volume = Math.max(0, Math.min(1, e)), this.masterGain && (this.masterGain.gain.value = this._volume)), this._volume;
|
|
203
|
+
}
|
|
204
|
+
getVolume() {
|
|
205
|
+
return this._volume;
|
|
206
|
+
}
|
|
207
|
+
_output() {
|
|
208
|
+
return this.masterGain || this.audioContext.destination;
|
|
209
|
+
}
|
|
210
|
+
toggleMute() {
|
|
211
|
+
return this.muted = !this.muted, this.storage.setItem(this.storageKey, this.muted), this.muted;
|
|
212
|
+
}
|
|
213
|
+
registerSound(e, t) {
|
|
214
|
+
this.customSounds[e] = t, this.audioContext && this.loadSound(e, t);
|
|
215
|
+
}
|
|
216
|
+
register(e, t) {
|
|
217
|
+
return typeof e != "string" || e === "" ? () => {} : typeof t == "string" ? (this.registerSound(e, t), () => {
|
|
218
|
+
this.customSounds[e] === t && delete this.customSounds[e], this.assets.delete(e);
|
|
219
|
+
}) : typeof t == "function" ? (this._synths.set(e, t), () => {
|
|
220
|
+
this._synths.get(e) === t && this._synths.delete(e);
|
|
221
|
+
}) : () => {};
|
|
222
|
+
}
|
|
223
|
+
async preloadSounds(e) {
|
|
224
|
+
let t = Object.entries(e).map(([e, t]) => (this.customSounds[e] = t, this.loadSound(e, t)));
|
|
225
|
+
await Promise.allSettled(t);
|
|
226
|
+
}
|
|
227
|
+
async loadSound(e, t) {
|
|
228
|
+
if (!this.audioContext) return;
|
|
229
|
+
if (this._loading.has(e)) return this._loading.get(e);
|
|
230
|
+
let n = this._load(e, t).finally(() => this._loading.delete(e));
|
|
231
|
+
return this._loading.set(e, n), n;
|
|
232
|
+
}
|
|
233
|
+
async _load(e, t) {
|
|
234
|
+
try {
|
|
235
|
+
let n = this.audioContext, r = await fetch(t);
|
|
236
|
+
if (r.ok === !1) throw Error(`HTTP ${r.status}`);
|
|
237
|
+
let i = await r.arrayBuffer(), a = await n.decodeAudioData(i);
|
|
238
|
+
this.audioContext === n && this.assets.set(e, a);
|
|
239
|
+
} catch (t) {
|
|
240
|
+
console.warn(`[DopamineJS] Failed to load sound '${e}':`, t);
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
async play(e) {
|
|
244
|
+
if (this.muted || !this.initAudio()) return;
|
|
245
|
+
if (this.assets.has(e)) {
|
|
246
|
+
this._playBuffer(this.assets.get(e));
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
if (o(this.customSounds, e) && !this.assets.has(e)) {
|
|
250
|
+
let t = this.audioContext;
|
|
251
|
+
if (await this.loadSound(e, this.customSounds[e]), this.audioContext !== t) return;
|
|
252
|
+
if (this.assets.has(e)) {
|
|
253
|
+
this._playBuffer(this.assets.get(e));
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
let t = {
|
|
258
|
+
xp: () => this.playXP(!0),
|
|
259
|
+
level_up: () => this.playLevelUp(!0),
|
|
260
|
+
achievement: () => this.playAchievement(!0),
|
|
261
|
+
personal_best: () => this.playPersonalBest(!0),
|
|
262
|
+
click: () => this.playClick(!0),
|
|
263
|
+
error: () => this.playError(!0)
|
|
264
|
+
};
|
|
265
|
+
this._synths.has(e) ? this._synths.get(e)(this, (e, t) => this._later(e, t)) : o(t, e) && t[e]();
|
|
266
|
+
}
|
|
267
|
+
_playBuffer(e) {
|
|
268
|
+
let t = this.audioContext.createBufferSource();
|
|
269
|
+
t.buffer = e, t.connect(this._output()), t.start(0);
|
|
270
|
+
}
|
|
271
|
+
playTone(e, t, n = "sine", r = .3) {
|
|
272
|
+
if (this.muted || !this.initAudio()) return;
|
|
273
|
+
let i = this.audioContext.createOscillator(), a = this.audioContext.createGain();
|
|
274
|
+
i.connect(a), a.connect(this._output()), i.frequency.value = e, i.type = n;
|
|
275
|
+
let o = Math.max(1e-4, r);
|
|
276
|
+
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);
|
|
277
|
+
}
|
|
278
|
+
playClick(e = !1) {
|
|
279
|
+
if (!e && this.assets.has("click")) return this.play("click");
|
|
280
|
+
this.playTone(600, .05, "sine", .1);
|
|
281
|
+
}
|
|
282
|
+
playXP(e = !1) {
|
|
283
|
+
if (!e && this.assets.has("xp")) return this.play("xp");
|
|
284
|
+
this.playTone(700, .06, "sine", .12);
|
|
285
|
+
}
|
|
286
|
+
playLevelUp(e = !1) {
|
|
287
|
+
if (!e && this.assets.has("level_up")) return this.play("level_up");
|
|
288
|
+
this.playTone(500, .12, "sine", .2), this._later(() => this.playTone(700, .12, "sine", .2), 110), this._later(() => this.playTone(900, .25, "sine", .2), 220);
|
|
289
|
+
}
|
|
290
|
+
playAchievement(e = !1) {
|
|
291
|
+
if (!e && this.assets.has("achievement")) return this.play("achievement");
|
|
292
|
+
this.playTone(660, .1, "triangle", .2), this._later(() => this.playTone(990, .25, "triangle", .2), 100);
|
|
293
|
+
}
|
|
294
|
+
playPersonalBest(e = !1) {
|
|
295
|
+
if (!e && this.assets.has("personal_best")) return this.play("personal_best");
|
|
296
|
+
this.playTone(600, .1, "sine", .2), this._later(() => this.playTone(800, .2, "sine", .2), 100);
|
|
297
|
+
}
|
|
298
|
+
playError(e = !1) {
|
|
299
|
+
if (!e && this.assets.has("error")) return this.play("error");
|
|
300
|
+
this.playTone(200, .2, "sawtooth", .3);
|
|
301
|
+
}
|
|
302
|
+
destroy() {
|
|
303
|
+
for (let e of [...this._unlocks]) e();
|
|
304
|
+
for (let e of this._timers) clearTimeout(e);
|
|
305
|
+
this._timers.clear(), this.audioContext && (this.audioContext.close?.())?.catch?.(() => {}), this.audioContext = null, this.masterGain = null, this.assets.clear(), this._loading.clear(), this._synths.clear();
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
export { a as n, n as r, s as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=require("./storage-B6z-zaBe.cjs");var t=Object.freeze({matches:!1});function n(e=globalThis.window){return typeof e?.matchMedia==`function`&&e.matchMedia(`(prefers-reduced-motion: reduce)`)||t}var r=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),i={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)},a=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:n(window),this.canvasId=e.canvasId||`dopamine-particle-canvas`,this.canvas=document.createElement(`canvas`),this.canvas.classList.add(`dopamine-particle-canvas`),document.getElementById(this.canvasId)||(this.canvas.id=this.canvasId),this.canvas.style.pointerEvents=`none`,this.canvas.style.zIndex=e.zIndex||`9999`,this.container===document.body?(this.canvas.style.position=`fixed`,this.canvas.style.top=`0`,this.canvas.style.left=`0`):(this.canvas.style.position=`absolute`,this.canvas.style.top=`0`,this.canvas.style.left=`0`,window.getComputedStyle(this.container).position===`static`&&(this.container.style.position=`relative`));let t=this.canvas.getContext(`2d`);if(!t)throw Error(`[DopamineJS] This canvas has no 2d context`);this.container.appendChild(this.canvas),this.ctx=t,this.particles=[],this.pool=[],this.sprites=new Map,this.customEffects=new Map,this.isAnimating=!1,this._onResize=()=>this._resize(),this._resizeObserver=null,this._frameHandle=null,this._lastFrameTime=null,this._resize(),window.ResizeObserver&&this.container!==document.body?(this._resizeObserver=new ResizeObserver(this._onResize),this._resizeObserver.observe(this.container)):window.addEventListener(`resize`,this._onResize)}_resize(){let e=this.container===document.body?window.innerWidth:this.container.clientWidth,t=this.container===document.body?window.innerHeight:this.container.clientHeight,n=window.devicePixelRatio||1;this.width=e,this.height=t,this.canvas.width=Math.round(e*n),this.canvas.height=Math.round(t*n),this.canvas.style.width=`${e}px`,this.canvas.style.height=`${t}px`,this.ctx.setTransform(n,0,0,n,0,0)}registerSprite(e,t){let n=new Image;n.src=t,this.sprites.set(e,n)}registerEffect(e,t){this.customEffects.set(e,t)}play(e,t,n,...r){typeof t==`object`&&t&&(r=n===void 0?[]:[n,...r],{x:t,y:n}=t);let i=this.customEffects.get(e);i?i(t,n,...r):console.warn(`[DopamineJS] Effect '${e}' not found.`)}emit(e){let{x:t,y:n,count:r=10,speed:i=5,gravity:a=.1,decay:o=.02,life:s=1,color:c=`#ffd700`,sprite:l=null,spread:u=Math.PI*2,angle:d=0,size:f=5,type:p=null}=e,m=this._allowed(r);for(let e=0;e<m;e++){let e=this._getParticle(),r=d+(Math.random()-.5)*u,m=Math.random()*i;e.x=t,e.y=n,e.vx=Math.cos(r)*m,e.vy=Math.sin(r)*m,e.life=s,e.decay=o*(.8+Math.random()*.4),e.gravity=a,e.color=Array.isArray(c)?c[Math.floor(Math.random()*c.length)]:c,e.size=f*(.8+Math.random()*.4),e.sprite=l,e.type=p,e.rotation=Math.random()*Math.PI*2,e.rotationSpeed=(Math.random()-.5)*.2,this.particles.push(e)}m>0&&this._startAnimation()}_allowed(e){if(this._reducedMotion?.matches||!Number.isFinite(e))return 0;let t=this.maxParticles-this.particles.length;return Math.max(0,Math.min(Math.floor(e),t))}_getParticle(){return this.pool.length>0?this.pool.pop():{}}_recycleParticle(e){this.pool.push(e)}burst(e,t,n){if(typeof e!=`string`||!r(i,e))return;let a=Number.isFinite(t?.x)?t.x:this.width/2,o=Number.isFinite(t?.y)?t.y:this.height/2,s=Number.isFinite(n?.count)?n.count:void 0;i[e](this,a,o,s,n?.color)}confetti(e,t,n=50){this.emit({x:e,y:t,count:n,color:[`#ff6b6b`,`#4ecdc4`,`#45b7d1`,`#f7dc6f`,`#c06c84`,`#6c5ce7`],speed:10,gravity:.3,decay:.015,size:8,spread:Math.PI*2})}coinShower(e,t,n=10){this.emit({x:e,y:t,count:n,color:`#ffd700`,speed:4,gravity:.4,decay:.012,size:12,angle:-Math.PI/2,spread:Math.PI/2})}sparkle(e,t,n=20,r=`#ffd700`){this.emit({x:e,y:t,count:n,color:r,speed:3,gravity:-.05,decay:.03,size:3})}fire(e,t,n=15){this.emit({x:e,y:t,count:n,color:[`#ff6b00`,`#ff8800`,`#ffaa00`,`#ff4400`],speed:3,gravity:-.2,decay:.04,size:5,angle:-Math.PI/2,spread:Math.PI/4})}starBurst(e,t,n=8){let r=this._allowed(n);for(let n=0;n<r;n++){let i=this._getParticle(),a=Math.PI*2/r*n;i.x=e,i.y=t,i.vx=Math.cos(a)*4,i.vy=Math.sin(a)*4,i.life=1,i.decay=.03,i.gravity=0,i.color=`#ffffff`,i.size=15,i.sprite=null,i.type=`star`,i.rotation=a,i.rotationSpeed=0,this.particles.push(i)}r>0&&this._startAnimation()}_startAnimation(){this.isAnimating||(this.isAnimating=!0,this._lastFrameTime=null,this._animate())}_animate(e){this._frameHandle=null,this.ctx.clearRect(0,0,this.width,this.height);let t=1;Number.isFinite(e)&&(this._lastFrameTime!==null&&(t=Math.max(0,Math.min(3,(e-this._lastFrameTime)/(1e3/60)))),this._lastFrameTime=e);for(let e=this.particles.length-1;e>=0;e--){let n=this.particles[e];if(n.vy+=n.gravity*t,n.x+=n.vx*t,n.y+=n.vy*t,n.life-=n.decay*t,n.rotationSpeed&&(n.rotation+=n.rotationSpeed*t),n.life<=0){this._recycleParticle(n);let t=this.particles.pop();e<this.particles.length&&(this.particles[e]=t)}else{if(this.ctx.save(),this.ctx.globalAlpha=n.life,this.ctx.translate(n.x,n.y),this.ctx.rotate(n.rotation),n.sprite&&this.sprites.has(n.sprite)){let e=this.sprites.get(n.sprite);e.complete&&this.ctx.drawImage(e,-n.size/2,-n.size/2,n.size,n.size)}else n.type===`star`?(this.ctx.fillStyle=n.color,this._drawStarPath(0,0,5,n.size,n.size/2),this.ctx.fill()):(this.ctx.fillStyle=n.color,this.ctx.beginPath(),this.ctx.arc(0,0,n.size,0,Math.PI*2),this.ctx.fill());this.ctx.restore()}}this.particles.length>0?this._frameHandle=requestAnimationFrame(e=>this._animate(e)):this.isAnimating=!1}_drawStarPath(e,t,n,r,i){let a=Math.PI/2*3,o=e,s=t,c=Math.PI/n;this.ctx.beginPath(),this.ctx.moveTo(e,t-r);for(let l=0;l<n;l++)o=e+Math.cos(a)*r,s=t+Math.sin(a)*r,this.ctx.lineTo(o,s),a+=c,o=e+Math.cos(a)*i,s=t+Math.sin(a)*i,this.ctx.lineTo(o,s),a+=c;this.ctx.lineTo(e,t-r),this.ctx.closePath()}clear(){this.particles.forEach(e=>this._recycleParticle(e)),this.particles=[],this.ctx.clearRect(0,0,this.width,this.height)}destroy(){this.clear(),this.isAnimating=!1,this._frameHandle!==null&&(cancelAnimationFrame(this._frameHandle),this._frameHandle=null),this._resizeObserver&&=(this._resizeObserver.disconnect(),null),window.removeEventListener(`resize`,this._onResize),this.canvas.remove(),this.sprites.clear(),this.customEffects.clear(),this.pool=[]}},o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),s=class{constructor(t={}){this.audioContext=null,this.storageKey=t.storageKey||`dopamineSoundsMuted`,this.storage=t.storage||e.n(),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}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(o(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)):o(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()}};Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return s}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./SoundManager-DBGDYIkz.cjs");var t=(e,t,n,r)=>Object.freeze({title:e,icon:t,sound:n,count:r}),n=Object.freeze(Object.assign(Object.create(null),{complete:t(`Complete!`,`✅`,`achievement`,40),milestone:t(`Milestone reached`,`🏁`,`level_up`,60),streak:t(`Streak kept`,`🔥`,`achievement`,40),certificate:t(`Certificate earned`,`🎓`,`level_up`,80)})),r=3e3,i=`position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:10000;display:flex;align-items:center;gap:12px;max-width:min(90vw,420px);padding:12px 18px;border-radius:10px;background:#1f2937;color:#fff;border:1px solid rgba(255,255,255,0.25);box-shadow:0 6px 24px rgba(0,0,0,0.35);font:16px/1.3 system-ui,sans-serif;pointer-events:none`,a=e=>e!=null&&e!==``,o=`position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap`,s=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),c=(e,t)=>typeof e==`object`&&e&&s(e,t)?e[t]:void 0,l=null,u=null,d=null,f=null,p=null,m=null,h=e=>{try{let t=e();typeof t==`object`&&t&&typeof t.then==`function`&&t.then(void 0,e=>console.error(e))}catch(e){console.error(e)}};function g(e){if(typeof e?.getBoundingClientRect==`function`){let{left:t,top:n,width:r,height:i}=e.getBoundingClientRect();if((r!==0||i!==0)&&Number.isFinite(t+n+r+i))return{x:t+r/2,y:n+i/2}}return{x:window.innerWidth/2,y:window.innerHeight/2}}function _(){clearTimeout(f),f=null,d?.remove(),d=null}function v(e){clearTimeout(m),p&&!p.isConnected&&(p=null),p&&(p.textContent=``),p||(p=document.createElement(`div`),p.className=`dopamine-celebrate-live`,p.setAttribute(`role`,`status`),p.setAttribute(`aria-live`,`polite`),p.style.cssText=o,document.body.appendChild(p)),m=setTimeout(()=>{m=null,p&&(p.textContent=e)},0)}function y(e,t,n){_();let o=document.createElement(`div`);o.className=`dopamine-celebrate-toast`,o.setAttribute(`aria-hidden`,`true`),o.style.cssText=i;let s=e=>{let t=document.createElement(`div`);return t.textContent=e,t};if(typeof Node<`u`&&n instanceof Node){let e=document.createElement(`div`);e.appendChild(n),o.appendChild(e)}else if(typeof n==`string`&&n!==``){let e=s(n);e.style.fontSize=`28px`,o.appendChild(e)}let c=document.createElement(`div`),l=s(e);l.style.fontWeight=`600`,c.appendChild(l),a(t)&&c.appendChild(s(t)),o.appendChild(c),document.body.appendChild(o),d=o,f=setTimeout(_,r),v(a(t)?`${e}. ${t}`:String(e))}function b(t,r){if(typeof t!=`string`||!s(n,t))return;let{title:i,icon:a,sound:o,count:d}=n[t],f,p,m,_,v,b;try{f=c(r,`title`)??i,p=c(r,`body`),m=c(r,`icon`)??a;let e=c(r,`sound`);_=e===!1?null:typeof e==`string`?e:o,v=c(r,`parts`),b=c(r,`target`)}catch(e){console.error(e);return}let x=typeof v==`object`&&!!v;if((typeof document>`u`||typeof window>`u`)&&!x)return;let S=typeof document<`u`&&typeof window<`u`,C=()=>e.r(window).matches!==!0;h(()=>{if(x)return v.ui?.popup({kind:`custom`,title:f,body:p,icon:m,burst:!1});y(f,p,m)}),h(()=>{if(!S||!C())return;let t=g(b);if(x)return v.particles?.burst?.(`confetti`,t,{count:d});if(l&&!l.canvas.isConnected){let e=l;l=null,h(()=>e.destroy())}l??=new e.n({canvasId:`dopamine-celebrate-canvas`}),l.burst(`confetti`,t,{count:d})}),_!==null&&h(()=>x?v.sound?.play?.(_):(u??=new e.t,u.muted=u.storage.getItem(u.storageKey)===`true`,u.play(_)))}function x(){_(),clearTimeout(m),m=null,p?.remove(),p=null;let e=[l,u];l=null,u=null;for(let t of e)h(()=>t?.destroy())}exports.celebrate=b,exports.destroyCelebrations=x;
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { n as e, r as t, t as n } from "./SoundManager-C6VdZEFo.js";
|
|
2
|
+
// src/celebrate.js
|
|
3
|
+
var r = (e, t, n, r) => Object.freeze({
|
|
4
|
+
title: e,
|
|
5
|
+
icon: t,
|
|
6
|
+
sound: n,
|
|
7
|
+
count: r
|
|
8
|
+
}), i = Object.freeze(Object.assign(Object.create(null), {
|
|
9
|
+
complete: r("Complete!", "✅", "achievement", 40),
|
|
10
|
+
milestone: r("Milestone reached", "🏁", "level_up", 60),
|
|
11
|
+
streak: r("Streak kept", "🔥", "achievement", 40),
|
|
12
|
+
certificate: r("Certificate earned", "🎓", "level_up", 80)
|
|
13
|
+
})), a = 3e3, o = "position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:10000;display:flex;align-items:center;gap:12px;max-width:min(90vw,420px);padding:12px 18px;border-radius:10px;background:#1f2937;color:#fff;border:1px solid rgba(255,255,255,0.25);box-shadow:0 6px 24px rgba(0,0,0,0.35);font:16px/1.3 system-ui,sans-serif;pointer-events:none", s = (e) => e != null && e !== "", c = "position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap", l = (e, t) => Object.prototype.hasOwnProperty.call(e, t), u = (e, t) => typeof e == "object" && e && l(e, t) ? e[t] : void 0, d = null, f = null, p = null, m = null, h = null, g = null, _ = (e) => {
|
|
14
|
+
try {
|
|
15
|
+
let t = e();
|
|
16
|
+
typeof t == "object" && t && typeof t.then == "function" && t.then(void 0, (e) => console.error(e));
|
|
17
|
+
} catch (e) {
|
|
18
|
+
console.error(e);
|
|
19
|
+
}
|
|
20
|
+
};
|
|
21
|
+
function v(e) {
|
|
22
|
+
if (typeof e?.getBoundingClientRect == "function") {
|
|
23
|
+
let { left: t, top: n, width: r, height: i } = e.getBoundingClientRect();
|
|
24
|
+
if ((r !== 0 || i !== 0) && Number.isFinite(t + n + r + i)) return {
|
|
25
|
+
x: t + r / 2,
|
|
26
|
+
y: n + i / 2
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
return {
|
|
30
|
+
x: window.innerWidth / 2,
|
|
31
|
+
y: window.innerHeight / 2
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
function y() {
|
|
35
|
+
clearTimeout(m), m = null, p?.remove(), p = null;
|
|
36
|
+
}
|
|
37
|
+
function b(e) {
|
|
38
|
+
clearTimeout(g), h && !h.isConnected && (h = null), h && (h.textContent = ""), h || (h = document.createElement("div"), h.className = "dopamine-celebrate-live", h.setAttribute("role", "status"), h.setAttribute("aria-live", "polite"), h.style.cssText = c, document.body.appendChild(h)), g = setTimeout(() => {
|
|
39
|
+
g = null, h && (h.textContent = e);
|
|
40
|
+
}, 0);
|
|
41
|
+
}
|
|
42
|
+
function x(e, t, n) {
|
|
43
|
+
y();
|
|
44
|
+
let r = document.createElement("div");
|
|
45
|
+
r.className = "dopamine-celebrate-toast", r.setAttribute("aria-hidden", "true"), r.style.cssText = o;
|
|
46
|
+
let i = (e) => {
|
|
47
|
+
let t = document.createElement("div");
|
|
48
|
+
return t.textContent = e, t;
|
|
49
|
+
};
|
|
50
|
+
if (typeof Node < "u" && n instanceof Node) {
|
|
51
|
+
let e = document.createElement("div");
|
|
52
|
+
e.appendChild(n), r.appendChild(e);
|
|
53
|
+
} else if (typeof n == "string" && n !== "") {
|
|
54
|
+
let e = i(n);
|
|
55
|
+
e.style.fontSize = "28px", r.appendChild(e);
|
|
56
|
+
}
|
|
57
|
+
let c = document.createElement("div"), l = i(e);
|
|
58
|
+
l.style.fontWeight = "600", c.appendChild(l), s(t) && c.appendChild(i(t)), r.appendChild(c), document.body.appendChild(r), p = r, m = setTimeout(y, a), b(s(t) ? `${e}. ${t}` : String(e));
|
|
59
|
+
}
|
|
60
|
+
function S(r, a) {
|
|
61
|
+
if (typeof r != "string" || !l(i, r)) return;
|
|
62
|
+
let { title: o, icon: s, sound: c, count: p } = i[r], m, h, g, y, b, S;
|
|
63
|
+
try {
|
|
64
|
+
m = u(a, "title") ?? o, h = u(a, "body"), g = u(a, "icon") ?? s;
|
|
65
|
+
let e = u(a, "sound");
|
|
66
|
+
y = e === !1 ? null : typeof e == "string" ? e : c, b = u(a, "parts"), S = u(a, "target");
|
|
67
|
+
} catch (e) {
|
|
68
|
+
console.error(e);
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
let C = typeof b == "object" && !!b;
|
|
72
|
+
if ((typeof document > "u" || typeof window > "u") && !C) return;
|
|
73
|
+
let w = typeof document < "u" && typeof window < "u", T = () => t(window).matches !== !0;
|
|
74
|
+
_(() => {
|
|
75
|
+
if (C) return b.ui?.popup({
|
|
76
|
+
kind: "custom",
|
|
77
|
+
title: m,
|
|
78
|
+
body: h,
|
|
79
|
+
icon: g,
|
|
80
|
+
burst: !1
|
|
81
|
+
});
|
|
82
|
+
x(m, h, g);
|
|
83
|
+
}), _(() => {
|
|
84
|
+
if (!w || !T()) return;
|
|
85
|
+
let t = v(S);
|
|
86
|
+
if (C) return b.particles?.burst?.("confetti", t, { count: p });
|
|
87
|
+
if (d && !d.canvas.isConnected) {
|
|
88
|
+
let e = d;
|
|
89
|
+
d = null, _(() => e.destroy());
|
|
90
|
+
}
|
|
91
|
+
d ??= new e({ canvasId: "dopamine-celebrate-canvas" }), d.burst("confetti", t, { count: p });
|
|
92
|
+
}), y !== null && _(() => C ? b.sound?.play?.(y) : (f ??= new n(), f.muted = f.storage.getItem(f.storageKey) === "true", f.play(y)));
|
|
93
|
+
}
|
|
94
|
+
function C() {
|
|
95
|
+
y(), clearTimeout(g), g = null, h?.remove(), h = null;
|
|
96
|
+
let e = [d, f];
|
|
97
|
+
d = null, f = null;
|
|
98
|
+
for (let t of e) _(() => t?.destroy());
|
|
99
|
+
}
|
|
100
|
+
export { S as celebrate, C as destroyCelebrations };
|
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-DKCk0nOu.cjs"),t=require("./storage-B6z-zaBe.cjs");exports.DataService=e.t,exports.DopamineError=e.o,exports.EventEmitter=e.s,exports.RewardSystem=e.n,exports.createMemoryStorage=t.t,exports.merge=e.r,exports.resolveStorage=t.n,exports.validate=e.i;
|
package/dist/core.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
|
|
1
|
+
import { i as e, n as t, o as n, r, s as i, t as a } from "./DataService-B5noGvMr.js";
|
|
2
|
+
import { n as o, t as s } from "./storage-C2s4Da9b.js";
|
|
3
|
+
export { a as DataService, n as DopamineError, i as EventEmitter, t as RewardSystem, s as createMemoryStorage, r as merge, o as resolveStorage, e as validate };
|
package/dist/dopamine.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-D6suk7Ci.cjs"),t=require("./DataService-DKCk0nOu.cjs"),n=require("./SoundManager-DBGDYIkz.cjs"),r=require("./storage-B6z-zaBe.cjs");exports.DataService=t.t,exports.DopamineError=t.o,exports.EventEmitter=t.s,exports.HOST_API=e.t,exports.ParticleSystem=n.n,exports.RewardSystem=t.n,exports.RewardUI=e.i,exports.SoundManager=n.t,exports.createDopamine=e.n,exports.createHaptics=e.r,exports.createMemoryStorage=r.t,exports.merge=t.r,exports.prefersReducedMotion=n.r,exports.resolveStorage=r.n,exports.validate=t.i;
|