dopaminejs 3.6.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/dist/testing.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-D6suk7Ci.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;
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,4 +1,4 @@
1
- import { n as e } from "./host-B-Gn-Zg_.js";
1
+ import { n as e } from "./host-Bhf9EqSk.js";
2
2
  import { t } from "./storage-C2s4Da9b.js";
3
3
  import { a as n } from "./DataService-B5noGvMr.js";
4
4
  import { describe as r, it as i } from "vitest";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dopaminejs",
3
- "version": "3.6.0",
3
+ "version": "3.7.0",
4
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",
@@ -28,6 +28,11 @@
28
28
  "import": "./dist/celebrate.js",
29
29
  "require": "./dist/celebrate.cjs"
30
30
  },
31
+ "./certificate": {
32
+ "types": "./types/certificate.d.ts",
33
+ "import": "./dist/certificate.js",
34
+ "require": "./dist/certificate.cjs"
35
+ },
31
36
  "./testing": {
32
37
  "types": "./types/testing.d.ts",
33
38
  "import": "./dist/testing.js",
package/src/celebrate.js CHANGED
@@ -2,6 +2,7 @@
2
2
  * The `dopaminejs/celebrate` subpath: one call shows a toast, fires confetti
3
3
  * and plays a sound. It works without createDopamine(). Pass `parts` to send
4
4
  * the three through a host instead. Nothing in the main entry imports it.
5
+ * `celebrate('certificate', { certificate })` loads ./certificate.js on demand.
5
6
  */
6
7
 
7
8
  import { ParticleSystem } from './dopamine/effects/ParticleSystem.js';
@@ -134,8 +135,9 @@ function showToast(title, body, icon) {
134
135
  *
135
136
  * @param {'complete'|'milestone'|'streak'|'certificate'} name
136
137
  * @param {{ title?: string, body?: string, icon?: string|Node, target?: Element,
137
- * sound?: string|false, parts?: Object }} [options] - `parts` sends the toast,
138
- * confetti and sound through a host's parts.
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.
139
141
  * A part the host does not have is skipped, with no standalone fallback.
140
142
  * @returns {undefined}
141
143
  */
@@ -158,11 +160,9 @@ export function celebrate(name, options) {
158
160
  }
159
161
  const routed = given !== null && typeof given === 'object';
160
162
 
161
- if (typeof document === 'undefined' || typeof window === 'undefined') {
162
- // No DOM: only a host's parts can still do something.
163
- if (!routed) return;
164
- }
165
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
166
  const motionAllowed = () => prefersReducedMotion(window).matches !== true;
167
167
 
168
168
  attempt(() => {
@@ -184,6 +184,11 @@ export function celebrate(name, options) {
184
184
  particles ??= new ParticleSystem({ canvasId: 'dopamine-celebrate-canvas' });
185
185
  particles.burst('confetti', at, { count });
186
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
+ });
187
192
  if (key === null) return;
188
193
  attempt(() => {
189
194
  if (routed) return given.sound?.play?.(key);
@@ -0,0 +1,391 @@
1
+ /**
2
+ * The `dopaminejs/certificate` subpath: a modal completion card the visitor can
3
+ * download as a PNG or print. `celebrate('certificate', { certificate })` loads
4
+ * it on demand. Nothing in the main entry imports it.
5
+ */
6
+
7
+ import { isNode, setIcon } from './dopamine/ui/icon.js';
8
+
9
+ const WIDTH = 1200;
10
+ const HEIGHT = 850;
11
+ const TEXT_WIDTH = WIDTH - 240;
12
+ const LOGO_SIZE = 110;
13
+ const FALLBACK_BG = ['#667eea', '#764ba2'];
14
+
15
+ const FIELD_CSS = {
16
+ title: 'margin:16px 0 0;font-size:32px;font-weight:700;line-height:1.2',
17
+ recipient: 'margin:20px 0 0;font-size:26px;line-height:1.3;color:var(--dopamine-toast-accent,#ffd700)',
18
+ date: 'margin:20px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))',
19
+ issuer: 'margin:8px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))'
20
+ };
21
+ const CLAMP = 'display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden;';
22
+ const LINES = { title: 2, recipient: 3, date: 1, issuer: 2 };
23
+
24
+ const OVERLAY_CSS = 'position:fixed;top:0;right:0;bottom:0;left:0;z-index:10001;display:flex;'
25
+ + 'align-items:center;justify-content:center;padding:16px;overflow:auto;background:rgba(0,0,0,0.6)';
26
+ const CARD_CSS = 'box-sizing:border-box;width:min(100%,720px);padding:36px 32px 24px;text-align:center;'
27
+ + 'overflow-wrap:anywhere;border-radius:var(--dopamine-toast-radius,16px);'
28
+ + 'background:var(--dopamine-toast-bg,linear-gradient(135deg,#667eea 0%,#764ba2 100%));'
29
+ + 'color:var(--dopamine-toast-text,#fff);border:4px double var(--dopamine-toast-accent,#ffd700);'
30
+ + 'box-shadow:var(--dopamine-toast-shadow,0 8px 32px rgba(0,0,0,0.4));font:16px/1.4 system-ui,sans-serif';
31
+ const BUTTON_CSS = 'margin:0 6px;padding:8px 16px;border-radius:8px;font:inherit;cursor:pointer;color:inherit;'
32
+ + 'background:rgba(255,255,255,0.15);border:1px solid var(--dopamine-toast-accent,#ffd700)';
33
+ const PRINT_CSS = '@media print{body>*:not(.dopamine-certificate-overlay){display:none!important}'
34
+ + '.dopamine-certificate-overlay{position:static!important;display:block!important;padding:0!important;'
35
+ + 'background:none!important}.dopamine-certificate-card{margin:0 auto;box-shadow:none!important;'
36
+ + '-webkit-print-color-adjust:exact;print-color-adjust:exact}'
37
+ + '.dopamine-certificate-actions{display:none!important}}';
38
+
39
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
40
+ const ownValue = (object, key) =>
41
+ (object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
42
+ const textOf = (value) => (value === undefined || value === null ? '' : String(value));
43
+
44
+ // What is open now, until close() or destroyCertificate().
45
+ let current = null;
46
+ // Counts calls, so a call that a nested one overtook can tell.
47
+ let invocation = 0;
48
+
49
+ function make(tag, css, text) {
50
+ const node = document.createElement(tag);
51
+ if (css) node.style.cssText = css;
52
+ if (text !== undefined) node.textContent = text;
53
+ return node;
54
+ }
55
+
56
+ // Greedy wrap that breaks a long word by characters. Past `max` lines it stops
57
+ // measuring and ends the last line with an ellipsis, so 5,000 characters cost
58
+ // a few lines of work.
59
+ function wrap(ctx, text, max) {
60
+ const fits = (s) => ctx.measureText(s).width <= TEXT_WIDTH;
61
+ const lines = [];
62
+ let line = '';
63
+ let cut = false;
64
+ const flush = () => {
65
+ if (lines.length === max) {
66
+ cut = true;
67
+ return false;
68
+ }
69
+ lines.push(line);
70
+ line = '';
71
+ return true;
72
+ };
73
+ scan: for (const word of text.split(/\s+/)) {
74
+ if (word === '') continue;
75
+ const joined = line === '' ? word : `${line} ${word}`;
76
+ if (fits(joined)) {
77
+ line = joined;
78
+ continue;
79
+ }
80
+ if (line !== '' && !flush()) break;
81
+ for (const char of word) {
82
+ if (line !== '' && !fits(line + char)) {
83
+ if (!flush()) break scan;
84
+ }
85
+ line += char;
86
+ }
87
+ }
88
+ if (!cut && line !== '') cut = !flush();
89
+ if (cut) {
90
+ let last = lines[max - 1];
91
+ while (last !== '' && !fits(`${last}\u2026`)) {
92
+ last = Array.from(last).slice(0, -1).join('');
93
+ }
94
+ lines[max - 1] = `${last}\u2026`;
95
+ }
96
+ return lines;
97
+ }
98
+
99
+ function paint(ctx, state, logo) {
100
+ const { fields, look } = state;
101
+ // The canvas keeps its old fillStyle when it cannot parse a colour, so a value is
102
+ // taken when setting it after a known one changed it. Two probes cover black and white.
103
+ const accepts = (colour) => {
104
+ for (const probe of ['#000000', '#ffffff']) {
105
+ ctx.fillStyle = probe;
106
+ ctx.fillStyle = colour;
107
+ if (ctx.fillStyle !== probe) return true;
108
+ }
109
+ return false;
110
+ };
111
+ let fill = look.bg && accepts(look.bg) ? look.bg : null;
112
+ if (!fill) {
113
+ fill = ctx.createLinearGradient?.(0, 0, WIDTH, HEIGHT);
114
+ fill?.addColorStop(0, FALLBACK_BG[0]);
115
+ fill?.addColorStop(1, FALLBACK_BG[1]);
116
+ }
117
+ ctx.fillStyle = fill ?? FALLBACK_BG[0];
118
+ ctx.fillRect(0, 0, WIDTH, HEIGHT);
119
+ ctx.strokeStyle = look.accent;
120
+ ctx.lineWidth = 8;
121
+ ctx.strokeRect(24, 24, WIDTH - 48, HEIGHT - 48);
122
+
123
+ ctx.textAlign = 'center';
124
+ ctx.textBaseline = 'top';
125
+ const x = WIDTH / 2;
126
+ let y = 90;
127
+
128
+ if (logo) {
129
+ if (typeof logo === 'string') {
130
+ ctx.fillStyle = look.text;
131
+ ctx.font = `${LOGO_SIZE / 2}px system-ui, sans-serif`;
132
+ ctx.fillText(logo, x, y, TEXT_WIDTH);
133
+ } else {
134
+ const w = logo.naturalWidth || logo.width || LOGO_SIZE;
135
+ const h = logo.naturalHeight || logo.height || LOGO_SIZE;
136
+ const scale = Math.min(TEXT_WIDTH / w, LOGO_SIZE / h);
137
+ const dw = Math.min(TEXT_WIDTH, w * scale);
138
+ const dh = Math.min(LOGO_SIZE, h * scale);
139
+ ctx.drawImage(logo, x - dw / 2, y, dw, dh);
140
+ }
141
+ y += LOGO_SIZE + 30;
142
+ }
143
+
144
+ const rows = [
145
+ ['title', 56, 'bold', look.text, 40],
146
+ ['recipient', 44, '', look.accent, 40],
147
+ ['date', 28, '', look.muted, 30],
148
+ ['issuer', 28, '', look.muted, 0]
149
+ ];
150
+ for (const [name, size, weight, colour, gap] of rows) {
151
+ ctx.fillStyle = colour;
152
+ ctx.font = `${weight} ${size}px system-ui, sans-serif`.trim();
153
+ for (const line of wrap(ctx, fields[name], LINES[name])) {
154
+ ctx.fillText(line, x, y, TEXT_WIDTH);
155
+ y += size * 1.25;
156
+ }
157
+ y += gap;
158
+ }
159
+ }
160
+
161
+ // The logo as something drawImage takes, text, or null. Always drawn from the
162
+ // copy already in the card, so the same sanitising rules apply.
163
+ function loadLogo(holder) {
164
+ const dropped = () => {
165
+ console.warn('[DopamineJS] The certificate logo had not loaded, so the PNG has no logo.');
166
+ return null;
167
+ };
168
+ const img = holder.querySelector('img');
169
+ if (img) return Promise.resolve(img.naturalWidth > 0 ? img : dropped());
170
+ const svg = holder.querySelector('svg');
171
+ if (!svg) return Promise.resolve(holder.textContent.trim() || null);
172
+ return new Promise((resolve) => {
173
+ const image = new Image();
174
+ image.onload = () => resolve(image);
175
+ image.onerror = () => resolve(dropped());
176
+ image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(svg))}`;
177
+ });
178
+ }
179
+
180
+ function toBlob(canvas) {
181
+ return new Promise((resolve) => canvas.toBlob(resolve, 'image/png'));
182
+ }
183
+
184
+ async function download(state) {
185
+ const logo = state.logoHolder ? await loadLogo(state.logoHolder) : null;
186
+ const render = async (withLogo) => {
187
+ const canvas = document.createElement('canvas');
188
+ canvas.width = WIDTH;
189
+ canvas.height = HEIGHT;
190
+ const ctx = canvas.getContext('2d');
191
+ if (!ctx) throw new Error('[DopamineJS] This canvas has no 2d context');
192
+ paint(ctx, state, withLogo);
193
+ return toBlob(canvas);
194
+ };
195
+ let blob;
196
+ try {
197
+ blob = await render(logo);
198
+ } catch (error) {
199
+ // A cross-origin logo taints the canvas, and export then throws.
200
+ if (!logo || error?.name !== 'SecurityError') throw error;
201
+ console.warn('[DopamineJS] The certificate logo could not be saved (cross-origin), so the PNG has no logo.');
202
+ blob = await render(null);
203
+ }
204
+ if (!blob) {
205
+ console.error(new Error('[DopamineJS] The canvas gave no PNG'));
206
+ return;
207
+ }
208
+ const url = URL.createObjectURL(blob);
209
+ const link = document.createElement('a');
210
+ link.href = url;
211
+ link.download = 'certificate.png';
212
+ link.click();
213
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
214
+ }
215
+
216
+ function close() {
217
+ const open = current;
218
+ if (!open) return;
219
+ current = null;
220
+ for (const undo of open.undo) undo();
221
+ open.overlay.remove();
222
+ open.style.remove();
223
+ const back = open.previous;
224
+ // A logo put back above can open a newer certificate. That one keeps the focus and takes this one's opener.
225
+ if (current) {
226
+ if (open.overlay.contains(current.previous)) current.previous = back;
227
+ } else if (back && back.isConnected && typeof back.focus === 'function') back.focus();
228
+ }
229
+
230
+ /**
231
+ * Open a completion certificate in a modal with Download (PNG), Print and
232
+ * Close. Every field is set as text. A second call closes the first. Never
233
+ * throws.
234
+ *
235
+ * @param {{ title?: string, recipient?: string, date?: string, issuer?: string,
236
+ * logo?: string|HTMLImageElement|Node }} fields
237
+ * @param {{ safeIcons?: boolean }} [options] - A string `logo` follows
238
+ * `safeIcons` as an achievement icon does. Default true.
239
+ * @returns {undefined}
240
+ */
241
+ export function showCertificate(fields, options) {
242
+ if (typeof document === 'undefined') return;
243
+ if (fields === null || typeof fields !== 'object' || Array.isArray(fields)) {
244
+ console.warn('[DopamineJS] showCertificate needs an object of fields.');
245
+ return;
246
+ }
247
+ const token = ++invocation;
248
+ close();
249
+ const previous = document.activeElement;
250
+ let restoreLogo = null;
251
+ try {
252
+ const value = (name) => textOf(ownValue(fields, name));
253
+ const given = { title: value('title'), recipient: value('recipient'), date: value('date'), issuer: value('issuer') };
254
+ const logo = ownValue(fields, 'logo');
255
+ const safeIcons = ownValue(options, 'safeIcons') !== false;
256
+
257
+ const overlay = make('div', OVERLAY_CSS);
258
+ overlay.className = 'dopamine-certificate-overlay';
259
+ const card = make('div', CARD_CSS);
260
+ card.className = 'dopamine-certificate-card';
261
+ card.setAttribute('role', 'dialog');
262
+ card.setAttribute('aria-modal', 'true');
263
+ if (given.title.trim()) card.setAttribute('aria-labelledby', 'dopamine-certificate-title');
264
+ else card.setAttribute('aria-label', 'Completion certificate');
265
+ card.tabIndex = -1;
266
+
267
+ let logoHolder = null;
268
+ if (logo !== undefined && logo !== null && logo !== '') {
269
+ logoHolder = make('div', `height:${LOGO_SIZE}px;font-size:56px;line-height:${LOGO_SIZE}px`);
270
+ logoHolder.className = 'dopamine-certificate-logo';
271
+ // A node taken from the page goes back where it was, with its style, when the certificate closes. One with no parent is left out.
272
+ const node = isNode(logo);
273
+ const parent = node ? logo.parentNode : null;
274
+ const next = parent ? logo.nextSibling : null;
275
+ // A fragment is emptied by the move, so its children go back into it.
276
+ const kids = node && logo.nodeType === 11 ? [...logo.childNodes] : null;
277
+ const styled = [];
278
+ setIcon(logoHolder, logo, safeIcons);
279
+ for (const child of logoHolder.querySelectorAll('img,svg')) {
280
+ styled.push([child, child.getAttribute('style')]);
281
+ child.style.maxWidth = '100%';
282
+ child.style.maxHeight = `${LOGO_SIZE}px`;
283
+ }
284
+ if (node) {
285
+ restoreLogo = () => {
286
+ restoreLogo = null;
287
+ for (const [child, text] of styled) {
288
+ if (text === null) child.removeAttribute('style');
289
+ else child.setAttribute('style', text);
290
+ }
291
+ if (kids) {
292
+ logo.append(...kids);
293
+ return;
294
+ }
295
+ logo.parentNode?.removeChild(logo);
296
+ parent?.insertBefore(logo, next && next.parentNode === parent ? next : null);
297
+ };
298
+ }
299
+ if (logoHolder.firstChild) card.appendChild(logoHolder);
300
+ else logoHolder = null;
301
+ }
302
+ for (const name of ['title', 'recipient', 'date', 'issuer']) {
303
+ const node = make(name === 'title' ? 'h2' : 'p', `${CLAMP}-webkit-line-clamp:${LINES[name]};${FIELD_CSS[name]}`, given[name]);
304
+ node.className = `dopamine-certificate-${name}`;
305
+ if (name === 'title') node.id = 'dopamine-certificate-title';
306
+ card.appendChild(node);
307
+ }
308
+
309
+ const actions = make('div', 'margin-top:28px');
310
+ actions.className = 'dopamine-certificate-actions';
311
+ const buttons = {};
312
+ for (const [name, label] of [['download', 'Download'], ['print', 'Print'], ['close', 'Close']]) {
313
+ buttons[name] = make('button', BUTTON_CSS, label);
314
+ buttons[name].type = 'button';
315
+ buttons[name].className = `dopamine-certificate-${name}`;
316
+ actions.appendChild(buttons[name]);
317
+ }
318
+ card.appendChild(actions);
319
+ overlay.appendChild(card);
320
+
321
+ const style = document.createElement('style');
322
+ style.textContent = PRINT_CSS;
323
+ const state = { fields: given, logoHolder, look: null, overlay, style, undo: [], previous };
324
+ // A focus listener that ran during close() can have opened a newer certificate.
325
+ if (token !== invocation) {
326
+ restoreLogo?.();
327
+ return;
328
+ }
329
+ current = state;
330
+ if (restoreLogo) state.undo.push(restoreLogo);
331
+ const read = (name, fallback) => getComputedStyle(card).getPropertyValue(name).trim() || fallback;
332
+ const refreshLook = () => {
333
+ state.look = {
334
+ bg: read('--dopamine-toast-bg', ''),
335
+ text: read('--dopamine-toast-text', '#fff'),
336
+ muted: read('--dopamine-toast-muted', 'rgba(255,255,255,0.85)'),
337
+ accent: read('--dopamine-toast-accent', '#ffd700')
338
+ };
339
+ };
340
+
341
+ const on = (target, type, handler) => {
342
+ target.addEventListener(type, handler);
343
+ state.undo.push(() => target.removeEventListener(type, handler));
344
+ };
345
+ on(document, 'keydown', (event) => {
346
+ if (event.key === 'Escape') {
347
+ if (event.defaultPrevented) return;
348
+ event.preventDefault();
349
+ close();
350
+ } else if (event.key === 'Tab' && !event.ctrlKey && !event.altKey && !event.metaKey) {
351
+ const order = [buttons.download, buttons.print, buttons.close];
352
+ const at = order.indexOf(document.activeElement);
353
+ const step = event.shiftKey ? order.length - 1 : 1;
354
+ const next = at === -1 ? (event.shiftKey ? order.length - 1 : 0) : (at + step) % order.length;
355
+ event.preventDefault();
356
+ order[next].focus();
357
+ }
358
+ });
359
+ // aria-modal does not stop a script from focusing the page behind. A closing certificate's trap can still be
360
+ // installed when its logo goes back, so it stands down once it no longer owns the certificate.
361
+ on(document, 'focusin', (event) => {
362
+ if (current === state && !overlay.contains(event.target)) card.focus();
363
+ });
364
+ on(overlay, 'click', (event) => {
365
+ const target = event.target;
366
+ if (target === overlay || target === buttons.close) {
367
+ close();
368
+ } else if (target === buttons.print) {
369
+ window.print();
370
+ } else if (target === buttons.download && !state.saving) {
371
+ state.saving = true;
372
+ refreshLook();
373
+ download(state).catch((error) => console.error(error)).finally(() => { state.saving = false; });
374
+ }
375
+ });
376
+
377
+ document.head.appendChild(style);
378
+ document.body.appendChild(overlay);
379
+ card.focus();
380
+ } catch (error) {
381
+ console.error(error);
382
+ // A newer call owns the certificate now.
383
+ if (token === invocation) close();
384
+ restoreLogo?.();
385
+ }
386
+ }
387
+
388
+ /** Close the open certificate and remove its DOM, print style and listeners. */
389
+ export function destroyCertificate() {
390
+ close();
391
+ }