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/README.md CHANGED
@@ -135,6 +135,45 @@ celebrate('certificate', { parts: dopamine.parts }); // through a host
135
135
 
136
136
  Shows a toast, fires confetti and plays a sound, with or without `createDopamine()`. Presets: `complete`, `milestone`, `streak`, `certificate`. Options: `title`, `body`, `icon`, `target` (confetti starts at its centre), `sound` (a key, or `false`) and `parts`. With reduced motion on there is no confetti. A part the host does not have is skipped, with no standalone fallback. `destroyCelebrations()` removes what the standalone route made. Not in the script tag build.
137
137
 
138
+ ## Completion certificate
139
+
140
+ A modal card the visitor can download as a PNG or print. This one opens when a video ends:
141
+
142
+ ```javascript
143
+ import { showCertificate } from 'dopaminejs/certificate';
144
+
145
+ const logo = new Image();
146
+ logo.src = '/img/acme.png';
147
+
148
+ video.addEventListener('ended', () => {
149
+ showCertificate({
150
+ title: 'Intro to Gardening',
151
+ recipient: 'Ana Reyes',
152
+ date: 'Nov 25, 2026',
153
+ issuer: 'Acme Academy',
154
+ logo
155
+ });
156
+ });
157
+ ```
158
+
159
+ `celebrate` can open it after the confetti. The certificate code loads on demand, so a page that never shows one does not download it:
160
+
161
+ ```javascript
162
+ import { celebrate } from 'dopaminejs/celebrate';
163
+
164
+ celebrate('certificate', { certificate: { title: 'Intro to Gardening', recipient: 'Ana Reyes' } });
165
+ ```
166
+
167
+ - `title`, `recipient`, `date` and `issuer` are set as text, so a name from a CMS cannot inject HTML. Long text wraps, and past a few lines it ends with an ellipsis, in the card and in the PNG.
168
+ - `logo` is a string or an image. A string follows `safeIcons` as an achievement icon does: text or allowlisted SVG by default, HTML only with `showCertificate(fields, { safeIcons: false })`. An `HTMLImageElement` is moved in, never parsed, and goes back to its place in the page, with its own style, when the certificate closes.
169
+ - Download draws the card on a canvas and saves `certificate.png`. If the logo is from another origin the canvas cannot be exported, so the PNG is saved without the logo and `console.warn` says so once. A logo that has not loaded is dropped from the PNG the same way.
170
+ - The PNG takes a plain colour from `--dopamine-toast-bg` (anything the canvas accepts as a colour) and draws a gradient as its default purple background.
171
+ - `fields` must be an object; anything else logs a warning and opens nothing.
172
+ - Print calls `window.print()` with a print style that shows only the certificate.
173
+ - It is a dialog (`role="dialog"`, `aria-modal`, labelled by the title) with focus kept inside. Escape, Close or a click outside closes it and focus goes back to where it was. One certificate is open at a time. `destroyCertificate()` closes it and removes its DOM, print style and listeners. `destroyCelebrations()` does not.
174
+ - Colours come from the `--dopamine-toast-*` variables (`bg`, `text`, `muted`, `accent`, `radius`, `shadow`). The PNG reads them too; a gradient `bg` is drawn as the default purple gradient.
175
+ - Not in the script tag build.
176
+
138
177
  ## Cleanup
139
178
 
140
179
  Everything that touches the DOM can be torn down:
@@ -1 +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;
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,S=typeof document<`u`&&typeof window<`u`;if(!S&&!x)return;let 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})}),h(()=>{let e=c(r,`certificate`);return e&&Promise.resolve().then(()=>require("./certificate.cjs")).then(t=>t.showCertificate(e))}),_!==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;
package/dist/celebrate.js CHANGED
@@ -68,9 +68,9 @@ function S(r, a) {
68
68
  console.error(e);
69
69
  return;
70
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;
71
+ let C = typeof b == "object" && !!b, w = typeof document < "u" && typeof window < "u";
72
+ if (!w && !C) return;
73
+ let T = () => t(window).matches !== !0;
74
74
  _(() => {
75
75
  if (C) return b.ui?.popup({
76
76
  kind: "custom",
@@ -89,6 +89,9 @@ function S(r, a) {
89
89
  d = null, _(() => e.destroy());
90
90
  }
91
91
  d ??= new e({ canvasId: "dopamine-celebrate-canvas" }), d.burst("confetti", t, { count: p });
92
+ }), _(() => {
93
+ let e = u(a, "certificate");
94
+ return e && import("./certificate.js").then((t) => t.showCertificate(e));
92
95
  }), y !== null && _(() => C ? b.sound?.play?.(y) : (f ??= new n(), f.muted = f.storage.getItem(f.storageKey) === "true", f.play(y)));
93
96
  }
94
97
  function C() {
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./icon-gkpxMw48.cjs");var t=1200,n=850,r=960,i=110,a=[`#667eea`,`#764ba2`],o={title:`margin:16px 0 0;font-size:32px;font-weight:700;line-height:1.2`,recipient:`margin:20px 0 0;font-size:26px;line-height:1.3;color:var(--dopamine-toast-accent,#ffd700)`,date:`margin:20px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))`,issuer:`margin:8px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))`},s=`display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden;`,c={title:2,recipient:3,date:1,issuer:2},l=`position:fixed;top:0;right:0;bottom:0;left:0;z-index:10001;display:flex;align-items:center;justify-content:center;padding:16px;overflow:auto;background:rgba(0,0,0,0.6)`,u=`box-sizing:border-box;width:min(100%,720px);padding:36px 32px 24px;text-align:center;overflow-wrap:anywhere;border-radius:var(--dopamine-toast-radius,16px);background:var(--dopamine-toast-bg,linear-gradient(135deg,#667eea 0%,#764ba2 100%));color:var(--dopamine-toast-text,#fff);border:4px double var(--dopamine-toast-accent,#ffd700);box-shadow:var(--dopamine-toast-shadow,0 8px 32px rgba(0,0,0,0.4));font:16px/1.4 system-ui,sans-serif`,d=`margin:0 6px;padding:8px 16px;border-radius:8px;font:inherit;cursor:pointer;color:inherit;background:rgba(255,255,255,0.15);border:1px solid var(--dopamine-toast-accent,#ffd700)`,f=`@media print{body>*:not(.dopamine-certificate-overlay){display:none!important}.dopamine-certificate-overlay{position:static!important;display:block!important;padding:0!important;background:none!important}.dopamine-certificate-card{margin:0 auto;box-shadow:none!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}.dopamine-certificate-actions{display:none!important}}`,p=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),m=(e,t)=>typeof e==`object`&&e&&p(e,t)?e[t]:void 0,h=e=>e==null?``:String(e),g=null,_=0;function v(e,t,n){let r=document.createElement(e);return t&&(r.style.cssText=t),n!==void 0&&(r.textContent=n),r}function y(e,t,n){let i=t=>e.measureText(t).width<=r,a=[],o=``,s=!1,c=()=>a.length===n?(s=!0,!1):(a.push(o),o=``,!0);scan:for(let e of t.split(/\s+/)){if(e===``)continue;let t=o===``?e:`${o} ${e}`;if(i(t))o=t;else{if(o!==``&&!c())break;for(let t of e){if(o!==``&&!i(o+t)&&!c())break scan;o+=t}}}if(!s&&o!==``&&(s=!c()),s){let e=a[n-1];for(;e!==``&&!i(`${e}\u2026`);)e=Array.from(e).slice(0,-1).join(``);a[n-1]=`${e}\u2026`}return a}function b(e,o,s){let{fields:l,look:u}=o,d=u.bg&&(t=>{for(let n of[`#000000`,`#ffffff`])if(e.fillStyle=n,e.fillStyle=t,e.fillStyle!==n)return!0;return!1})(u.bg)?u.bg:null;d||(d=e.createLinearGradient?.(0,0,t,n),d?.addColorStop(0,a[0]),d?.addColorStop(1,a[1])),e.fillStyle=d??a[0],e.fillRect(0,0,t,n),e.strokeStyle=u.accent,e.lineWidth=8,e.strokeRect(24,24,1152,802),e.textAlign=`center`,e.textBaseline=`top`;let f=t/2,p=90;if(s){if(typeof s==`string`)e.fillStyle=u.text,e.font=`${i/2}px system-ui, sans-serif`,e.fillText(s,f,p,r);else{let t=s.naturalWidth||s.width||i,n=s.naturalHeight||s.height||i,a=Math.min(r/t,i/n),o=Math.min(r,t*a),c=Math.min(i,n*a);e.drawImage(s,f-o/2,p,o,c)}p+=140}let m=[[`title`,56,`bold`,u.text,40],[`recipient`,44,``,u.accent,40],[`date`,28,``,u.muted,30],[`issuer`,28,``,u.muted,0]];for(let[t,n,i,a,o]of m){e.fillStyle=a,e.font=`${i} ${n}px system-ui, sans-serif`.trim();for(let i of y(e,l[t],c[t]))e.fillText(i,f,p,r),p+=n*1.25;p+=o}}function x(e){let t=()=>(console.warn(`[DopamineJS] The certificate logo had not loaded, so the PNG has no logo.`),null),n=e.querySelector(`img`);if(n)return Promise.resolve(n.naturalWidth>0?n:t());let r=e.querySelector(`svg`);return r?new Promise(e=>{let n=new Image;n.onload=()=>e(n),n.onerror=()=>e(t()),n.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(r))}`}):Promise.resolve(e.textContent.trim()||null)}function S(e){return new Promise(t=>e.toBlob(t,`image/png`))}async function C(e){let r=e.logoHolder?await x(e.logoHolder):null,i=async r=>{let i=document.createElement(`canvas`);i.width=t,i.height=n;let a=i.getContext(`2d`);if(!a)throw Error(`[DopamineJS] This canvas has no 2d context`);return b(a,e,r),S(i)},a;try{a=await i(r)}catch(e){if(!r||e?.name!==`SecurityError`)throw e;console.warn(`[DopamineJS] The certificate logo could not be saved (cross-origin), so the PNG has no logo.`),a=await i(null)}if(!a){console.error(Error(`[DopamineJS] The canvas gave no PNG`));return}let o=URL.createObjectURL(a),s=document.createElement(`a`);s.href=o,s.download=`certificate.png`,s.click(),setTimeout(()=>URL.revokeObjectURL(o),1e3)}function w(){let e=g;if(!e)return;g=null;for(let t of e.undo)t();e.overlay.remove(),e.style.remove();let t=e.previous;g?e.overlay.contains(g.previous)&&(g.previous=t):t&&t.isConnected&&typeof t.focus==`function`&&t.focus()}function T(t,n){if(typeof document>`u`)return;if(typeof t!=`object`||!t||Array.isArray(t)){console.warn(`[DopamineJS] showCertificate needs an object of fields.`);return}let r=++_;w();let a=document.activeElement,p=null;try{let y=e=>h(m(t,e)),b={title:y(`title`),recipient:y(`recipient`),date:y(`date`),issuer:y(`issuer`)},x=m(t,`logo`),S=m(n,`safeIcons`)!==!1,T=v(`div`,l);T.className=`dopamine-certificate-overlay`;let E=v(`div`,u);E.className=`dopamine-certificate-card`,E.setAttribute(`role`,`dialog`),E.setAttribute(`aria-modal`,`true`),b.title.trim()?E.setAttribute(`aria-labelledby`,`dopamine-certificate-title`):E.setAttribute(`aria-label`,`Completion certificate`),E.tabIndex=-1;let D=null;if(x!=null&&x!==``){D=v(`div`,`height:${i}px;font-size:56px;line-height:${i}px`),D.className=`dopamine-certificate-logo`;let t=e.t(x),n=t?x.parentNode:null,r=n?x.nextSibling:null,a=t&&x.nodeType===11?[...x.childNodes]:null,o=[];e.n(D,x,S);for(let e of D.querySelectorAll(`img,svg`))o.push([e,e.getAttribute(`style`)]),e.style.maxWidth=`100%`,e.style.maxHeight=`${i}px`;t&&(p=()=>{p=null;for(let[e,t]of o)t===null?e.removeAttribute(`style`):e.setAttribute(`style`,t);a?x.append(...a):(x.parentNode?.removeChild(x),n?.insertBefore(x,r&&r.parentNode===n?r:null))}),D.firstChild?E.appendChild(D):D=null}for(let e of[`title`,`recipient`,`date`,`issuer`]){let t=v(e===`title`?`h2`:`p`,`${s}-webkit-line-clamp:${c[e]};${o[e]}`,b[e]);t.className=`dopamine-certificate-${e}`,e===`title`&&(t.id=`dopamine-certificate-title`),E.appendChild(t)}let O=v(`div`,`margin-top:28px`);O.className=`dopamine-certificate-actions`;let k={};for(let[e,t]of[[`download`,`Download`],[`print`,`Print`],[`close`,`Close`]])k[e]=v(`button`,d,t),k[e].type=`button`,k[e].className=`dopamine-certificate-${e}`,O.appendChild(k[e]);E.appendChild(O),T.appendChild(E);let A=document.createElement(`style`);A.textContent=f;let j={fields:b,logoHolder:D,look:null,overlay:T,style:A,undo:[],previous:a};if(r!==_){p?.();return}g=j,p&&j.undo.push(p);let M=(e,t)=>getComputedStyle(E).getPropertyValue(e).trim()||t,N=()=>{j.look={bg:M(`--dopamine-toast-bg`,``),text:M(`--dopamine-toast-text`,`#fff`),muted:M(`--dopamine-toast-muted`,`rgba(255,255,255,0.85)`),accent:M(`--dopamine-toast-accent`,`#ffd700`)}},P=(e,t,n)=>{e.addEventListener(t,n),j.undo.push(()=>e.removeEventListener(t,n))};P(document,`keydown`,e=>{if(e.key===`Escape`){if(e.defaultPrevented)return;e.preventDefault(),w()}else if(e.key===`Tab`&&!e.ctrlKey&&!e.altKey&&!e.metaKey){let t=[k.download,k.print,k.close],n=t.indexOf(document.activeElement),r=e.shiftKey?t.length-1:1,i=n===-1?e.shiftKey?t.length-1:0:(n+r)%t.length;e.preventDefault(),t[i].focus()}}),P(document,`focusin`,e=>{g===j&&!T.contains(e.target)&&E.focus()}),P(T,`click`,e=>{let t=e.target;t===T||t===k.close?w():t===k.print?window.print():t===k.download&&!j.saving&&(j.saving=!0,N(),C(j).catch(e=>console.error(e)).finally(()=>{j.saving=!1}))}),document.head.appendChild(A),document.body.appendChild(T),E.focus()}catch(e){console.error(e),r===_&&w(),p?.()}}function E(){w()}exports.destroyCertificate=E,exports.showCertificate=T;
@@ -0,0 +1,234 @@
1
+ import { n as e, t } from "./icon-BakWSiz_.js";
2
+ // src/certificate.js
3
+ var n = 1200, r = 850, i = 960, a = 110, o = ["#667eea", "#764ba2"], s = {
4
+ title: "margin:16px 0 0;font-size:32px;font-weight:700;line-height:1.2",
5
+ recipient: "margin:20px 0 0;font-size:26px;line-height:1.3;color:var(--dopamine-toast-accent,#ffd700)",
6
+ date: "margin:20px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))",
7
+ issuer: "margin:8px 0 0;font-size:16px;color:var(--dopamine-toast-muted,rgba(255,255,255,0.85))"
8
+ }, c = "display:-webkit-box;-webkit-box-orient:vertical;overflow:hidden;", l = {
9
+ title: 2,
10
+ recipient: 3,
11
+ date: 1,
12
+ issuer: 2
13
+ }, u = "position:fixed;top:0;right:0;bottom:0;left:0;z-index:10001;display:flex;align-items:center;justify-content:center;padding:16px;overflow:auto;background:rgba(0,0,0,0.6)", d = "box-sizing:border-box;width:min(100%,720px);padding:36px 32px 24px;text-align:center;overflow-wrap:anywhere;border-radius:var(--dopamine-toast-radius,16px);background:var(--dopamine-toast-bg,linear-gradient(135deg,#667eea 0%,#764ba2 100%));color:var(--dopamine-toast-text,#fff);border:4px double var(--dopamine-toast-accent,#ffd700);box-shadow:var(--dopamine-toast-shadow,0 8px 32px rgba(0,0,0,0.4));font:16px/1.4 system-ui,sans-serif", f = "margin:0 6px;padding:8px 16px;border-radius:8px;font:inherit;cursor:pointer;color:inherit;background:rgba(255,255,255,0.15);border:1px solid var(--dopamine-toast-accent,#ffd700)", p = "@media print{body>*:not(.dopamine-certificate-overlay){display:none!important}.dopamine-certificate-overlay{position:static!important;display:block!important;padding:0!important;background:none!important}.dopamine-certificate-card{margin:0 auto;box-shadow:none!important;-webkit-print-color-adjust:exact;print-color-adjust:exact}.dopamine-certificate-actions{display:none!important}}", m = (e, t) => Object.prototype.hasOwnProperty.call(e, t), h = (e, t) => typeof e == "object" && e && m(e, t) ? e[t] : void 0, g = (e) => e == null ? "" : String(e), _ = null, v = 0;
14
+ function y(e, t, n) {
15
+ let r = document.createElement(e);
16
+ return t && (r.style.cssText = t), n !== void 0 && (r.textContent = n), r;
17
+ }
18
+ function b(e, t, n) {
19
+ let r = (t) => e.measureText(t).width <= i, a = [], o = "", s = !1, c = () => a.length === n ? (s = !0, !1) : (a.push(o), o = "", !0);
20
+ scan: for (let e of t.split(/\s+/)) {
21
+ if (e === "") continue;
22
+ let t = o === "" ? e : `${o} ${e}`;
23
+ if (r(t)) o = t;
24
+ else {
25
+ if (o !== "" && !c()) break;
26
+ for (let t of e) {
27
+ if (o !== "" && !r(o + t) && !c()) break scan;
28
+ o += t;
29
+ }
30
+ }
31
+ }
32
+ if (!s && o !== "" && (s = !c()), s) {
33
+ let e = a[n - 1];
34
+ for (; e !== "" && !r(`${e}\u2026`);) e = Array.from(e).slice(0, -1).join("");
35
+ a[n - 1] = `${e}\u2026`;
36
+ }
37
+ return a;
38
+ }
39
+ function x(e, t, s) {
40
+ let { fields: c, look: u } = t, d = u.bg && ((t) => {
41
+ for (let n of ["#000000", "#ffffff"]) if (e.fillStyle = n, e.fillStyle = t, e.fillStyle !== n) return !0;
42
+ return !1;
43
+ })(u.bg) ? u.bg : null;
44
+ d || (d = e.createLinearGradient?.(0, 0, n, r), d?.addColorStop(0, o[0]), d?.addColorStop(1, o[1])), e.fillStyle = d ?? o[0], e.fillRect(0, 0, n, r), e.strokeStyle = u.accent, e.lineWidth = 8, e.strokeRect(24, 24, 1152, 802), e.textAlign = "center", e.textBaseline = "top";
45
+ let f = n / 2, p = 90;
46
+ if (s) {
47
+ if (typeof s == "string") e.fillStyle = u.text, e.font = `${a / 2}px system-ui, sans-serif`, e.fillText(s, f, p, i);
48
+ else {
49
+ let t = s.naturalWidth || s.width || a, n = s.naturalHeight || s.height || a, r = Math.min(i / t, a / n), o = Math.min(i, t * r), c = Math.min(a, n * r);
50
+ e.drawImage(s, f - o / 2, p, o, c);
51
+ }
52
+ p += 140;
53
+ }
54
+ let m = [
55
+ [
56
+ "title",
57
+ 56,
58
+ "bold",
59
+ u.text,
60
+ 40
61
+ ],
62
+ [
63
+ "recipient",
64
+ 44,
65
+ "",
66
+ u.accent,
67
+ 40
68
+ ],
69
+ [
70
+ "date",
71
+ 28,
72
+ "",
73
+ u.muted,
74
+ 30
75
+ ],
76
+ [
77
+ "issuer",
78
+ 28,
79
+ "",
80
+ u.muted,
81
+ 0
82
+ ]
83
+ ];
84
+ for (let [t, n, r, a, o] of m) {
85
+ e.fillStyle = a, e.font = `${r} ${n}px system-ui, sans-serif`.trim();
86
+ for (let r of b(e, c[t], l[t])) e.fillText(r, f, p, i), p += n * 1.25;
87
+ p += o;
88
+ }
89
+ }
90
+ function S(e) {
91
+ let t = () => (console.warn("[DopamineJS] The certificate logo had not loaded, so the PNG has no logo."), null), n = e.querySelector("img");
92
+ if (n) return Promise.resolve(n.naturalWidth > 0 ? n : t());
93
+ let r = e.querySelector("svg");
94
+ return r ? new Promise((e) => {
95
+ let n = new Image();
96
+ n.onload = () => e(n), n.onerror = () => e(t()), n.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(r))}`;
97
+ }) : Promise.resolve(e.textContent.trim() || null);
98
+ }
99
+ function C(e) {
100
+ return new Promise((t) => e.toBlob(t, "image/png"));
101
+ }
102
+ async function w(e) {
103
+ let t = e.logoHolder ? await S(e.logoHolder) : null, i = async (t) => {
104
+ let i = document.createElement("canvas");
105
+ i.width = n, i.height = r;
106
+ let a = i.getContext("2d");
107
+ if (!a) throw Error("[DopamineJS] This canvas has no 2d context");
108
+ return x(a, e, t), C(i);
109
+ }, a;
110
+ try {
111
+ a = await i(t);
112
+ } catch (e) {
113
+ if (!t || e?.name !== "SecurityError") throw e;
114
+ console.warn("[DopamineJS] The certificate logo could not be saved (cross-origin), so the PNG has no logo."), a = await i(null);
115
+ }
116
+ if (!a) {
117
+ console.error(/* @__PURE__ */ Error("[DopamineJS] The canvas gave no PNG"));
118
+ return;
119
+ }
120
+ let o = URL.createObjectURL(a), s = document.createElement("a");
121
+ s.href = o, s.download = "certificate.png", s.click(), setTimeout(() => URL.revokeObjectURL(o), 1e3);
122
+ }
123
+ function T() {
124
+ let e = _;
125
+ if (!e) return;
126
+ _ = null;
127
+ for (let t of e.undo) t();
128
+ e.overlay.remove(), e.style.remove();
129
+ let t = e.previous;
130
+ _ ? e.overlay.contains(_.previous) && (_.previous = t) : t && t.isConnected && typeof t.focus == "function" && t.focus();
131
+ }
132
+ function E(n, r) {
133
+ if (typeof document > "u") return;
134
+ if (typeof n != "object" || !n || Array.isArray(n)) {
135
+ console.warn("[DopamineJS] showCertificate needs an object of fields.");
136
+ return;
137
+ }
138
+ let i = ++v;
139
+ T();
140
+ let o = document.activeElement, m = null;
141
+ try {
142
+ let b = (e) => g(h(n, e)), x = {
143
+ title: b("title"),
144
+ recipient: b("recipient"),
145
+ date: b("date"),
146
+ issuer: b("issuer")
147
+ }, S = h(n, "logo"), C = h(r, "safeIcons") !== !1, E = y("div", u);
148
+ E.className = "dopamine-certificate-overlay";
149
+ let D = y("div", d);
150
+ D.className = "dopamine-certificate-card", D.setAttribute("role", "dialog"), D.setAttribute("aria-modal", "true"), x.title.trim() ? D.setAttribute("aria-labelledby", "dopamine-certificate-title") : D.setAttribute("aria-label", "Completion certificate"), D.tabIndex = -1;
151
+ let O = null;
152
+ if (S != null && S !== "") {
153
+ O = y("div", `height:${a}px;font-size:56px;line-height:${a}px`), O.className = "dopamine-certificate-logo";
154
+ let n = t(S), r = n ? S.parentNode : null, i = r ? S.nextSibling : null, o = n && S.nodeType === 11 ? [...S.childNodes] : null, s = [];
155
+ e(O, S, C);
156
+ for (let e of O.querySelectorAll("img,svg")) s.push([e, e.getAttribute("style")]), e.style.maxWidth = "100%", e.style.maxHeight = `${a}px`;
157
+ n && (m = () => {
158
+ m = null;
159
+ for (let [e, t] of s) t === null ? e.removeAttribute("style") : e.setAttribute("style", t);
160
+ o ? S.append(...o) : (S.parentNode?.removeChild(S), r?.insertBefore(S, i && i.parentNode === r ? i : null));
161
+ }), O.firstChild ? D.appendChild(O) : O = null;
162
+ }
163
+ for (let e of [
164
+ "title",
165
+ "recipient",
166
+ "date",
167
+ "issuer"
168
+ ]) {
169
+ let t = y(e === "title" ? "h2" : "p", `${c}-webkit-line-clamp:${l[e]};${s[e]}`, x[e]);
170
+ t.className = `dopamine-certificate-${e}`, e === "title" && (t.id = "dopamine-certificate-title"), D.appendChild(t);
171
+ }
172
+ let k = y("div", "margin-top:28px");
173
+ k.className = "dopamine-certificate-actions";
174
+ let A = {};
175
+ for (let [e, t] of [
176
+ ["download", "Download"],
177
+ ["print", "Print"],
178
+ ["close", "Close"]
179
+ ]) A[e] = y("button", f, t), A[e].type = "button", A[e].className = `dopamine-certificate-${e}`, k.appendChild(A[e]);
180
+ D.appendChild(k), E.appendChild(D);
181
+ let j = document.createElement("style");
182
+ j.textContent = p;
183
+ let M = {
184
+ fields: x,
185
+ logoHolder: O,
186
+ look: null,
187
+ overlay: E,
188
+ style: j,
189
+ undo: [],
190
+ previous: o
191
+ };
192
+ if (i !== v) {
193
+ m?.();
194
+ return;
195
+ }
196
+ _ = M, m && M.undo.push(m);
197
+ let N = (e, t) => getComputedStyle(D).getPropertyValue(e).trim() || t, P = () => {
198
+ M.look = {
199
+ bg: N("--dopamine-toast-bg", ""),
200
+ text: N("--dopamine-toast-text", "#fff"),
201
+ muted: N("--dopamine-toast-muted", "rgba(255,255,255,0.85)"),
202
+ accent: N("--dopamine-toast-accent", "#ffd700")
203
+ };
204
+ }, F = (e, t, n) => {
205
+ e.addEventListener(t, n), M.undo.push(() => e.removeEventListener(t, n));
206
+ };
207
+ F(document, "keydown", (e) => {
208
+ if (e.key === "Escape") {
209
+ if (e.defaultPrevented) return;
210
+ e.preventDefault(), T();
211
+ } else if (e.key === "Tab" && !e.ctrlKey && !e.altKey && !e.metaKey) {
212
+ let t = [
213
+ A.download,
214
+ A.print,
215
+ A.close
216
+ ], n = t.indexOf(document.activeElement), r = e.shiftKey ? t.length - 1 : 1, i = n === -1 ? e.shiftKey ? t.length - 1 : 0 : (n + r) % t.length;
217
+ e.preventDefault(), t[i].focus();
218
+ }
219
+ }), F(document, "focusin", (e) => {
220
+ _ === M && !E.contains(e.target) && D.focus();
221
+ }), F(E, "click", (e) => {
222
+ let t = e.target;
223
+ t === E || t === A.close ? T() : t === A.print ? window.print() : t === A.download && !M.saving && (M.saving = !0, P(), w(M).catch((e) => console.error(e)).finally(() => {
224
+ M.saving = !1;
225
+ }));
226
+ }), document.head.appendChild(j), document.body.appendChild(E), D.focus();
227
+ } catch (e) {
228
+ console.error(e), i === v && T(), m?.();
229
+ }
230
+ }
231
+ function D() {
232
+ T();
233
+ }
234
+ export { D as destroyCertificate, E as showCertificate };
package/dist/dopamine.cjs CHANGED
@@ -1 +1 @@
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;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./host-BWKiYtjY.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;