dopaminejs 3.5.0 → 3.7.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 +52 -2
- package/dist/{DataService-QQBNqJtN.js → DataService-B5noGvMr.js} +228 -254
- package/dist/DataService-DKCk0nOu.cjs +1 -0
- package/dist/SoundManager-C6VdZEFo.js +308 -0
- package/dist/SoundManager-DBGDYIkz.cjs +1 -0
- package/dist/celebrate.cjs +1 -0
- package/dist/celebrate.js +103 -0
- package/dist/certificate.cjs +1 -0
- package/dist/certificate.js +234 -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-BWKiYtjY.cjs +37 -0
- package/dist/host-Bhf9EqSk.js +457 -0
- package/dist/icon-BakWSiz_.js +89 -0
- package/dist/icon-gkpxMw48.cjs +1 -0
- package/dist/storage-B6z-zaBe.cjs +1 -0
- package/dist/storage-C2s4Da9b.js +26 -0
- package/dist/testing.cjs +1 -1
- package/dist/testing.js +3 -2
- package/package.json +15 -3
- package/src/celebrate.js +213 -0
- package/src/certificate.js +391 -0
- package/src/dopamine/effects/ParticleSystem.js +5 -1
- package/src/dopamine/ui/RewardUI.js +13 -154
- package/src/dopamine/ui/icon.js +157 -0
- package/types/celebrate.d.ts +39 -0
- package/types/certificate.d.ts +30 -0
- package/types/index.d.ts +2 -0
- package/dist/DataService-Xk7egYXe.cjs +0 -1
- package/dist/host-1c7QSAKI.cjs +0 -37
- package/dist/host-_essSMef.js +0 -835
package/dist/testing.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-BWKiYtjY.cjs"),t=require("./storage-B6z-zaBe.cjs"),n=require("./DataService-DKCk0nOu.cjs");let r=require("vitest"),i=require("node:fs"),a=require("node:path"),o=require("node:url");var s={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`},load_recovered:{key:`player`}},c=[`confetti`,`sparkle`,`fire`,`stars`,`coins`],l=[`xp`,`level_up`,`achievement`,`personal_best`,`click`,`error`],u=[``,`nope`,`__proto__`,`constructor`,`toString`,`hasOwnProperty`,void 0,null,42,{}],d=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/,f=e=>{throw Error(e)},p=(e,t)=>{e||f(t)};function m(e){if(typeof e==`object`&&e)return{clock:e,move:()=>f(`this clock is not a test clock, it cannot advance`)};let t=e===void 0?`2026-01-15T09:00:00`:e;typeof t==`string`&&d.test(t)||f(`clock must be YYYY-MM-DDTHH:MM:SS local time`);let r=new Date(t).getTime();return{clock:{now:()=>r,localDate:(e=r)=>n.a.localDate(e)},move:e=>{r=e(r)}}}function h(n={}){let{clock:r,storage:i,parts:a={},...o}=n||{},{clock:s,move:c}=m(r),l=[],u=[],p=[],h=[],g=[],_=new Set,v=[],y={ui:()=>({root:null,hud:e=>{p.push(e)},popup:e=>{l.push(e)},text:e=>{u.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=e.n({...o,...b,storage:i||t.t(),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:u,huds:p,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){d.test(e)||f(`clock must be YYYY-MM-DDTHH:MM:SS local time`),c(()=>new Date(e).getTime())}}}var g=async e=>{await e},_=()=>typeof document>`u`?null:document.body.innerHTML,v=()=>h().parts,y=e=>[[`draws every burst kind without throwing`,async()=>{let t=e();try{for(let e of c)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 u)t.burst(e,{x:1,y:1})}finally{t.destroy()}}],[`has destroy`,async()=>{let t=e();p(typeof t.destroy==`function`,`a particle part needs destroy()`),t.destroy()}]],b=e=>[[`plays every preset key without throwing`,async()=>{let t=e();try{for(let e of l)await g(t.play(e))}finally{t.destroy()}}],[`treats an unknown key as a no-op`,async()=>{let t=e();try{for(let e of u)await g(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});p(typeof n==`function`,`register() must return a remover`),n(),await g(t.play(`conformance_key`)),p(e===0,`a removed key still played`)}finally{t.destroy()}}]],x=e=>[[`draws the hud`,async()=>{let t=e(v());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(v());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(v());try{for(let e of[void 0,null,42,`text`,{},{kind:`__proto__`}])t.popup(e)}finally{t.destroy()}}],[`floats text`,async()=>{let t=e(v());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(v());try{let e=t.root;p(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=_(),n=e(v());n.hud({xp:1,level:1,streak:1}),n.popup({kind:`achievement`,title:`T`}),n.text({text:`x`}),n.destroy(),p(_()===t,`the page changed after destroy()`)}]],S=`conformance_key`,C=e=>[[`returns null for a missing key`,async()=>{let t=e();for(let e of[S,`__proto__`,`constructor`,`toString`])p(await t.getItem(e)===null,`getItem(${e}) should be null`)}],[`keeps what setItem stores and overwrites it`,async()=>{let t=e();await t.setItem(S,`one`),p(await t.getItem(S)===`one`,`getItem should return the stored value`),await t.setItem(S,`two`),p(await t.getItem(S)===`two`,`setItem should overwrite`)}],[`keeps keys apart`,async()=>{let t=e();await t.setItem(`a`,`1`),await t.setItem(`b`,`2`),p(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(S,`one`),await t.removeItem(S),p(await t.getItem(S)===null,`removeItem should clear the key`),await t.removeItem(S)}]];function w(){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 T=e=>{let t=0;for(let n of e.listeners.values())t+=n.size;return t};async function E(e,t){let n=w(),r=[],i=console.error;console.error=(...e)=>{r.push(e)};let a=h();try{await a.ready,await t(a,{watch:n,errors:r})}finally{console.error=i,a.dispose(),n.stop()}}var D={particles:y,sound:b,ui:x,storage:C,plugin:e=>[[`has a name, a version and the host api`,async()=>{let t=e();p(typeof t.name==`string`&&t.name!==``,`a plugin needs a name`),p(typeof t.version==`string`&&t.version!==``,`a plugin needs a version`),p(t.api===3,`a plugin needs api 3`),p(typeof t.install==`function`,`a plugin needs install()`)}],[`installs on a host and survives every core event`,async()=>{await E(e,async(t,{errors:n})=>{t.use(e()),await t.ready;for(let e of Object.keys(s))t.progress.emit(e,s[e]);await t.progress.addXP(5,`conformance`),p(n.length===0,`a listener threw: ${String(n[0]?.[1]??n[0]?.[0])}`)})}],[`leaves no listeners, timers or DOM behind once disposed`,async()=>{await E(e,async(t,{watch:n})=>{await t.ready;let r=T(t.progress),i=_(),a=n.live(),o=t.use(e());await t.progress.addXP(1,`conformance`);for(let e of Object.keys(s))t.progress.emit(e,s[e]);await t.ready,o(),p(T(t.progress)===r,`the plugin left listeners on the bus`),p(n.live()<=a,`the plugin left timers running`),p(_()===i,`the plugin left DOM in the page`)})}]]},O=e=>t=>{(0,r.describe)(`conformance.${e}`,()=>{for(let[n,i]of D[e](t))(0,r.it)(n,i)})},k={particles:O(`particles`),sound:O(`sound`),ui:O(`ui`),storage:O(`storage`),plugin:O(`plugin`)};async function A(e,t){Object.prototype.hasOwnProperty.call(D,e)||f(`unknown suite ${String(e)}`);let n=[];for(let[r,i]of D[e](t))try{await i()}catch{n.push(r)}return n}function j(){let e=typeof __dirname==`string`?__dirname:(0,a.dirname)((0,o.fileURLToPath)({}.url));for(let t of[`../spec`,`../../../spec`]){let n=(0,a.resolve)(e,t);if((0,i.existsSync)((0,a.join)(n,`VERSION`)))return n}return f(`spec/ was not found next to this package`)}function M(e){let t=e||j(),n=Number(/contract:\s*(\d+)/.exec((0,i.readFileSync)((0,a.join)(t,`VERSION`),`utf8`))?.[1]),r=JSON.parse((0,i.readFileSync)((0,a.join)(t,`schema.json`),`utf8`)),o={};for(let e of(0,i.readdirSync)((0,a.join)(t,`fixtures`)).sort()){if(!e.endsWith(`.json`))continue;let n=JSON.parse((0,i.readFileSync)((0,a.join)(t,`fixtures`,e),`utf8`));o[n.suite]=n}return{contract:n,schema:r,suites:o}}exports.conformance=k,exports.conformanceFailures=A,exports.createTestHost=h,exports.loadFixtures=M;
|
package/dist/testing.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { n as e } from "./host-
|
|
2
|
-
import {
|
|
1
|
+
import { n as e } from "./host-Bhf9EqSk.js";
|
|
2
|
+
import { t } from "./storage-C2s4Da9b.js";
|
|
3
|
+
import { a as n } from "./DataService-B5noGvMr.js";
|
|
3
4
|
import { describe as r, it as i } from "vitest";
|
|
4
5
|
import { existsSync as a, readFileSync as o, readdirSync as s } from "node:fs";
|
|
5
6
|
import { dirname as c, join as l, resolve as u } from "node:path";
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dopaminejs",
|
|
3
|
-
"version": "3.
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "3.7.0",
|
|
4
|
+
"description": "Gamification for any website: XP, levels, achievements and timezone-correct daily streaks, with confetti, particles and sound. One script tag or one import. Zero dependencies.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/dopamine.cjs",
|
|
7
7
|
"module": "./dist/dopamine.js",
|
|
@@ -23,6 +23,16 @@
|
|
|
23
23
|
"import": "./dist/games.js",
|
|
24
24
|
"require": "./dist/games.cjs"
|
|
25
25
|
},
|
|
26
|
+
"./celebrate": {
|
|
27
|
+
"types": "./types/celebrate.d.ts",
|
|
28
|
+
"import": "./dist/celebrate.js",
|
|
29
|
+
"require": "./dist/celebrate.cjs"
|
|
30
|
+
},
|
|
31
|
+
"./certificate": {
|
|
32
|
+
"types": "./types/certificate.d.ts",
|
|
33
|
+
"import": "./dist/certificate.js",
|
|
34
|
+
"require": "./dist/certificate.cjs"
|
|
35
|
+
},
|
|
26
36
|
"./testing": {
|
|
27
37
|
"types": "./types/testing.d.ts",
|
|
28
38
|
"import": "./dist/testing.js",
|
|
@@ -59,7 +69,9 @@
|
|
|
59
69
|
"juice",
|
|
60
70
|
"particles",
|
|
61
71
|
"confetti",
|
|
62
|
-
"feedback"
|
|
72
|
+
"feedback",
|
|
73
|
+
"no-build",
|
|
74
|
+
"script-tag"
|
|
63
75
|
],
|
|
64
76
|
"author": "BaryoDev",
|
|
65
77
|
"license": "MPL-2.0",
|
package/src/celebrate.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `dopaminejs/celebrate` subpath: one call shows a toast, fires confetti
|
|
3
|
+
* and plays a sound. It works without createDopamine(). Pass `parts` to send
|
|
4
|
+
* the three through a host instead. Nothing in the main entry imports it.
|
|
5
|
+
* `celebrate('certificate', { certificate })` loads ./certificate.js on demand.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { ParticleSystem } from './dopamine/effects/ParticleSystem.js';
|
|
9
|
+
import { SoundManager } from './dopamine/audio/SoundManager.js';
|
|
10
|
+
import { prefersReducedMotion } from './dopamine/feel/motion.js';
|
|
11
|
+
|
|
12
|
+
const preset = (title, icon, sound, count) => Object.freeze({ title, icon, sound, count });
|
|
13
|
+
|
|
14
|
+
const PRESETS = Object.freeze(Object.assign(Object.create(null), {
|
|
15
|
+
complete: preset('Complete!', '\u{2705}', 'achievement', 40),
|
|
16
|
+
milestone: preset('Milestone reached', '\u{1F3C1}', 'level_up', 60),
|
|
17
|
+
streak: preset('Streak kept', '\u{1F525}', 'achievement', 40),
|
|
18
|
+
certificate: preset('Certificate earned', '\u{1F393}', 'level_up', 80)
|
|
19
|
+
}));
|
|
20
|
+
|
|
21
|
+
const TOAST_MS = 3000;
|
|
22
|
+
const TOAST_STYLE = 'position:fixed;top:16px;left:50%;transform:translateX(-50%);z-index:10000;'
|
|
23
|
+
+ 'display:flex;align-items:center;gap:12px;max-width:min(90vw,420px);padding:12px 18px;'
|
|
24
|
+
+ 'border-radius:10px;background:#1f2937;color:#fff;border:1px solid rgba(255,255,255,0.25);'
|
|
25
|
+
+ 'box-shadow:0 6px 24px rgba(0,0,0,0.35);font:16px/1.3 system-ui,sans-serif;pointer-events:none';
|
|
26
|
+
|
|
27
|
+
const hasBody = (body) => body !== undefined && body !== null && body !== '';
|
|
28
|
+
|
|
29
|
+
const REGION_STYLE = 'position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap';
|
|
30
|
+
|
|
31
|
+
// Options come from callers, so an inherited property must not count. A local
|
|
32
|
+
// copy: importing hasOwn from core/store.js splits a shared chunk and grows the main CJS bundle.
|
|
33
|
+
const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
|
|
34
|
+
const ownValue = (object, key) =>
|
|
35
|
+
(object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
|
|
36
|
+
|
|
37
|
+
// What the standalone route made, until destroyCelebrations().
|
|
38
|
+
let particles = null;
|
|
39
|
+
let sound = null;
|
|
40
|
+
let toast = null;
|
|
41
|
+
let timer = null;
|
|
42
|
+
let region = null;
|
|
43
|
+
let regionTimer = null;
|
|
44
|
+
|
|
45
|
+
// A part that throws or rejects is logged, so the other two still run.
|
|
46
|
+
const attempt = (fn) => {
|
|
47
|
+
try {
|
|
48
|
+
const result = fn();
|
|
49
|
+
if (result !== null && typeof result === 'object' && typeof result.then === 'function') {
|
|
50
|
+
result.then(undefined, (error) => console.error(error));
|
|
51
|
+
}
|
|
52
|
+
} catch (error) {
|
|
53
|
+
console.error(error);
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
// Where the confetti goes: the middle of the target, else the viewport.
|
|
58
|
+
function centreOf(target) {
|
|
59
|
+
if (typeof target?.getBoundingClientRect === 'function') {
|
|
60
|
+
const { left, top, width, height } = target.getBoundingClientRect();
|
|
61
|
+
if ((width !== 0 || height !== 0) && Number.isFinite(left + top + width + height)) {
|
|
62
|
+
return { x: left + width / 2, y: top + height / 2 };
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { x: window.innerWidth / 2, y: window.innerHeight / 2 };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function removeToast() {
|
|
69
|
+
clearTimeout(timer);
|
|
70
|
+
timer = null;
|
|
71
|
+
toast?.remove();
|
|
72
|
+
toast = null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// A live region that arrives with its text is often skipped, so one hidden
|
|
76
|
+
// region is put in the page empty and its text is always set a tick later.
|
|
77
|
+
// A page that replaces its body leaves the old region detached, so that one
|
|
78
|
+
// counts as missing.
|
|
79
|
+
function announce(message) {
|
|
80
|
+
clearTimeout(regionTimer);
|
|
81
|
+
if (region && !region.isConnected) region = null;
|
|
82
|
+
// The same text set again may send no live-region event, so empty it first.
|
|
83
|
+
if (region) region.textContent = '';
|
|
84
|
+
if (!region) {
|
|
85
|
+
region = document.createElement('div');
|
|
86
|
+
region.className = 'dopamine-celebrate-live';
|
|
87
|
+
region.setAttribute('role', 'status');
|
|
88
|
+
region.setAttribute('aria-live', 'polite');
|
|
89
|
+
region.style.cssText = REGION_STYLE;
|
|
90
|
+
document.body.appendChild(region);
|
|
91
|
+
}
|
|
92
|
+
regionTimer = setTimeout(() => {
|
|
93
|
+
regionTimer = null;
|
|
94
|
+
if (region) region.textContent = message;
|
|
95
|
+
}, 0);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function showToast(title, body, icon) {
|
|
99
|
+
removeToast();
|
|
100
|
+
const el = document.createElement('div');
|
|
101
|
+
el.className = 'dopamine-celebrate-toast';
|
|
102
|
+
el.setAttribute('aria-hidden', 'true');
|
|
103
|
+
el.style.cssText = TOAST_STYLE;
|
|
104
|
+
|
|
105
|
+
const add = (text) => {
|
|
106
|
+
const child = document.createElement('div');
|
|
107
|
+
child.textContent = text;
|
|
108
|
+
return child;
|
|
109
|
+
};
|
|
110
|
+
if (typeof Node !== 'undefined' && icon instanceof Node) {
|
|
111
|
+
const holder = document.createElement('div');
|
|
112
|
+
holder.appendChild(icon);
|
|
113
|
+
el.appendChild(holder);
|
|
114
|
+
} else if (typeof icon === 'string' && icon !== '') {
|
|
115
|
+
const holder = add(icon);
|
|
116
|
+
holder.style.fontSize = '28px';
|
|
117
|
+
el.appendChild(holder);
|
|
118
|
+
}
|
|
119
|
+
const text = document.createElement('div');
|
|
120
|
+
const name = add(title);
|
|
121
|
+
name.style.fontWeight = '600';
|
|
122
|
+
text.appendChild(name);
|
|
123
|
+
if (hasBody(body)) text.appendChild(add(body));
|
|
124
|
+
el.appendChild(text);
|
|
125
|
+
|
|
126
|
+
document.body.appendChild(el);
|
|
127
|
+
toast = el;
|
|
128
|
+
timer = setTimeout(removeToast, TOAST_MS);
|
|
129
|
+
announce(hasBody(body) ? `${title}. ${body}` : String(title));
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Show a toast, fire confetti and play a sound. Presets: complete, milestone,
|
|
134
|
+
* streak, certificate. An unknown preset does nothing. Never throws.
|
|
135
|
+
*
|
|
136
|
+
* @param {'complete'|'milestone'|'streak'|'certificate'} name
|
|
137
|
+
* @param {{ title?: string, body?: string, icon?: string|Node, target?: Element,
|
|
138
|
+
* sound?: string|false, parts?: Object, certificate?: Object }} [options] - `parts`
|
|
139
|
+
* sends the toast, confetti and sound through a host's parts. `certificate`
|
|
140
|
+
* opens that certificate after the confetti; destroyCertificate() closes it.
|
|
141
|
+
* A part the host does not have is skipped, with no standalone fallback.
|
|
142
|
+
* @returns {undefined}
|
|
143
|
+
*/
|
|
144
|
+
export function celebrate(name, options) {
|
|
145
|
+
if (typeof name !== 'string' || !hasOwn(PRESETS, name)) return;
|
|
146
|
+
const { title, icon, sound: presetSound, count } = PRESETS[name];
|
|
147
|
+
let shownTitle, body, shownIcon, key, given, target;
|
|
148
|
+
try {
|
|
149
|
+
// A getter on the options can throw, so the reads sit inside the guard.
|
|
150
|
+
shownTitle = ownValue(options, 'title') ?? title;
|
|
151
|
+
body = ownValue(options, 'body');
|
|
152
|
+
shownIcon = ownValue(options, 'icon') ?? icon;
|
|
153
|
+
const soundOption = ownValue(options, 'sound');
|
|
154
|
+
key = soundOption === false ? null : (typeof soundOption === 'string' ? soundOption : presetSound);
|
|
155
|
+
given = ownValue(options, 'parts');
|
|
156
|
+
target = ownValue(options, 'target');
|
|
157
|
+
} catch (error) {
|
|
158
|
+
console.error(error);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
const routed = given !== null && typeof given === 'object';
|
|
162
|
+
|
|
163
|
+
const hasDom = typeof document !== 'undefined' && typeof window !== 'undefined';
|
|
164
|
+
// No DOM: only a host's parts can still do something.
|
|
165
|
+
if (!hasDom && !routed) return;
|
|
166
|
+
const motionAllowed = () => prefersReducedMotion(window).matches !== true;
|
|
167
|
+
|
|
168
|
+
attempt(() => {
|
|
169
|
+
if (routed) {
|
|
170
|
+
return given.ui?.popup({ kind: 'custom', title: shownTitle, body, icon: shownIcon, burst: false });
|
|
171
|
+
}
|
|
172
|
+
showToast(shownTitle, body, shownIcon);
|
|
173
|
+
});
|
|
174
|
+
attempt(() => {
|
|
175
|
+
if (!hasDom || !motionAllowed()) return;
|
|
176
|
+
const at = centreOf(target);
|
|
177
|
+
if (routed) return given.particles?.burst?.('confetti', at, { count });
|
|
178
|
+
// A body replace detaches the canvas, so confetti would draw where nobody sees it.
|
|
179
|
+
if (particles && !particles.canvas.isConnected) {
|
|
180
|
+
const old = particles;
|
|
181
|
+
particles = null;
|
|
182
|
+
attempt(() => old.destroy());
|
|
183
|
+
}
|
|
184
|
+
particles ??= new ParticleSystem({ canvasId: 'dopamine-celebrate-canvas' });
|
|
185
|
+
particles.burst('confetti', at, { count });
|
|
186
|
+
});
|
|
187
|
+
// Loaded on demand so the certificate code is not in this entry.
|
|
188
|
+
attempt(() => {
|
|
189
|
+
const fields = ownValue(options, 'certificate');
|
|
190
|
+
return fields && import('./certificate.js').then((m) => m.showCertificate(fields));
|
|
191
|
+
});
|
|
192
|
+
if (key === null) return;
|
|
193
|
+
attempt(() => {
|
|
194
|
+
if (routed) return given.sound?.play?.(key);
|
|
195
|
+
sound ??= new SoundManager();
|
|
196
|
+
// The manager reads the mute flag once, so take a mute made elsewhere.
|
|
197
|
+
sound.muted = sound.storage.getItem(sound.storageKey) === 'true';
|
|
198
|
+
return sound.play(key);
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Remove the toast, the live region, the timers, and the particle system and sound manager the standalone route made. */
|
|
203
|
+
export function destroyCelebrations() {
|
|
204
|
+
removeToast();
|
|
205
|
+
clearTimeout(regionTimer);
|
|
206
|
+
regionTimer = null;
|
|
207
|
+
region?.remove();
|
|
208
|
+
region = null;
|
|
209
|
+
const made = [particles, sound];
|
|
210
|
+
particles = null;
|
|
211
|
+
sound = null;
|
|
212
|
+
for (const part of made) attempt(() => part?.destroy());
|
|
213
|
+
}
|