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
|
@@ -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
|
+
}
|
|
@@ -60,9 +60,13 @@ export class ParticleSystem {
|
|
|
60
60
|
}
|
|
61
61
|
}
|
|
62
62
|
|
|
63
|
+
// Ask for the context before the canvas goes into the page, so a
|
|
64
|
+
// constructor that fails leaves no node and no listener behind.
|
|
65
|
+
const ctx = this.canvas.getContext('2d');
|
|
66
|
+
if (!ctx) throw new Error('[DopamineJS] This canvas has no 2d context');
|
|
63
67
|
this.container.appendChild(this.canvas);
|
|
64
68
|
|
|
65
|
-
this.ctx =
|
|
69
|
+
this.ctx = ctx;
|
|
66
70
|
this.particles = [];
|
|
67
71
|
this.pool = []; // Object pool
|
|
68
72
|
this.sprites = new Map(); // key -> Image
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
6
|
import DEFAULT_CSS from './dopamine.css?inline';
|
|
7
|
+
import { setIcon } from './icon.js';
|
|
7
8
|
|
|
8
9
|
const OVERLAY_ID = 'game-ui-overlay';
|
|
9
10
|
|
|
@@ -24,128 +25,6 @@ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key
|
|
|
24
25
|
const ownValue = (object, key) =>
|
|
25
26
|
(object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
|
|
26
27
|
|
|
27
|
-
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
28
|
-
|
|
29
|
-
const SVG_ELEMENTS = new Set([
|
|
30
|
-
'svg', 'g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline',
|
|
31
|
-
'polygon', 'text', 'tspan', 'title', 'desc', 'defs', 'linearGradient',
|
|
32
|
-
'radialGradient', 'stop', 'clipPath', 'mask'
|
|
33
|
-
]);
|
|
34
|
-
|
|
35
|
-
// No style, no href, no event handlers: only geometry and paint.
|
|
36
|
-
const SVG_ATTRIBUTES = new Set([
|
|
37
|
-
'viewBox', 'width', 'height', 'x', 'y', 'x1', 'y1', 'x2', 'y2', 'cx', 'cy',
|
|
38
|
-
'r', 'rx', 'ry', 'd', 'points', 'transform', 'fill', 'fill-opacity',
|
|
39
|
-
'fill-rule', 'stroke', 'stroke-width', 'stroke-linecap', 'stroke-linejoin',
|
|
40
|
-
'stroke-opacity', 'opacity', 'offset', 'stop-color', 'stop-opacity',
|
|
41
|
-
'gradientUnits', 'gradientTransform', 'clip-path', 'mask', 'clip-rule',
|
|
42
|
-
'font-size', 'font-family', 'font-weight', 'text-anchor', 'id',
|
|
43
|
-
'aria-hidden', 'aria-label', 'role'
|
|
44
|
-
]);
|
|
45
|
-
|
|
46
|
-
// Attributes that may point at a gradient, clip path or mask in the same icon.
|
|
47
|
-
const REFERENCE_ATTRIBUTES = new Set(['fill', 'stroke', 'clip-path', 'mask']);
|
|
48
|
-
const TRANSFORM_ATTRIBUTES = new Set(['transform', 'gradientTransform']);
|
|
49
|
-
|
|
50
|
-
const SINGLE_FRAGMENT_URL = /^url\(\s*#([A-Za-z][\w.:-]*)\s*\)$/;
|
|
51
|
-
const PLAIN_COLOUR = /^[#a-zA-Z0-9(),.%\s-]+$/;
|
|
52
|
-
const PLAIN_TRANSFORM = /^[a-zA-Z0-9(),.\s-]+$/;
|
|
53
|
-
const SAFE_ID = /^[A-Za-z][\w.:-]*$/;
|
|
54
|
-
|
|
55
|
-
// Ids inside an icon are page-global (window.<id>, getElementById), so every
|
|
56
|
-
// render gets its own prefix.
|
|
57
|
-
let iconCounter = 0;
|
|
58
|
-
|
|
59
|
-
function collectIds(node, ids) {
|
|
60
|
-
if (node.nodeType !== 1 || node.namespaceURI !== SVG_NS || !SVG_ELEMENTS.has(node.localName)) {
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
const id = node.getAttribute('id');
|
|
64
|
-
if (id && SAFE_ID.test(id)) ids.add(id);
|
|
65
|
-
for (const child of Array.from(node.childNodes)) collectIds(child, ids);
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
/**
|
|
69
|
-
* Returns the value to write, or null to drop the attribute.
|
|
70
|
-
*/
|
|
71
|
-
function cleanValue(name, value, ctx) {
|
|
72
|
-
if (value.includes('\\')) return null;
|
|
73
|
-
const trimmed = value.trim();
|
|
74
|
-
|
|
75
|
-
if (name === 'id') {
|
|
76
|
-
return SAFE_ID.test(trimmed) ? ctx.prefix + trimmed : null;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
if (REFERENCE_ATTRIBUTES.has(name)) {
|
|
80
|
-
const ref = SINGLE_FRAGMENT_URL.exec(trimmed);
|
|
81
|
-
if (ref) {
|
|
82
|
-
return ctx.ids.has(ref[1]) ? `url(#${ctx.prefix}${ref[1]})` : null;
|
|
83
|
-
}
|
|
84
|
-
return PLAIN_COLOUR.test(trimmed) && !/url/i.test(trimmed) ? trimmed : null;
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
if (TRANSFORM_ATTRIBUTES.has(name)) {
|
|
88
|
-
return PLAIN_TRANSFORM.test(trimmed) && !/url/i.test(trimmed) ? trimmed : null;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
if (value.includes('(')) {
|
|
92
|
-
// Only a plain colour such as rgb() or hsl() is acceptable here.
|
|
93
|
-
return name === 'stop-color' && PLAIN_COLOUR.test(trimmed) && !/url/i.test(trimmed)
|
|
94
|
-
? trimmed
|
|
95
|
-
: null;
|
|
96
|
-
}
|
|
97
|
-
return value;
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
function cleanNode(source, ctx) {
|
|
101
|
-
// 3 is text, 4 is CDATA.
|
|
102
|
-
if (source.nodeType === 3 || source.nodeType === 4) {
|
|
103
|
-
return document.createTextNode(source.data);
|
|
104
|
-
}
|
|
105
|
-
if (source.nodeType !== 1
|
|
106
|
-
|| source.namespaceURI !== SVG_NS
|
|
107
|
-
|| !SVG_ELEMENTS.has(source.localName)) {
|
|
108
|
-
return null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
const clean = document.createElementNS(SVG_NS, source.localName);
|
|
112
|
-
for (const attr of Array.from(source.attributes)) {
|
|
113
|
-
if (attr.namespaceURI !== null || !SVG_ATTRIBUTES.has(attr.name)) continue;
|
|
114
|
-
const value = cleanValue(attr.name, attr.value, ctx);
|
|
115
|
-
if (value !== null) clean.setAttribute(attr.name, value);
|
|
116
|
-
}
|
|
117
|
-
for (const child of Array.from(source.childNodes)) {
|
|
118
|
-
const kept = cleanNode(child, ctx);
|
|
119
|
-
if (kept) clean.appendChild(kept);
|
|
120
|
-
}
|
|
121
|
-
return clean;
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* Parse a string as SVG and rebuild it from an allowlist of elements and
|
|
126
|
-
* attributes, so nothing that can run script or load a resource survives.
|
|
127
|
-
* Returns null unless the whole string is one valid <svg> document.
|
|
128
|
-
*/
|
|
129
|
-
function parseSafeSvg(markup) {
|
|
130
|
-
let doc;
|
|
131
|
-
// Inline HTML SVG usually has no xmlns, which the XML parser rejects.
|
|
132
|
-
const source = /^\s*<svg[\s>]/.test(markup) && !/^\s*<svg\b[^>]*\sxmlns\s*=/.test(markup)
|
|
133
|
-
? markup.replace(/^(\s*<svg)/, `$1 xmlns="${SVG_NS}"`)
|
|
134
|
-
: markup;
|
|
135
|
-
try {
|
|
136
|
-
doc = new DOMParser().parseFromString(source,'image/svg+xml');
|
|
137
|
-
} catch {
|
|
138
|
-
return null;
|
|
139
|
-
}
|
|
140
|
-
const root = doc.documentElement;
|
|
141
|
-
if (!root || root.localName !== 'svg' || doc.getElementsByTagName('parsererror').length > 0) {
|
|
142
|
-
return null;
|
|
143
|
-
}
|
|
144
|
-
const ids = new Set();
|
|
145
|
-
collectIds(root, ids);
|
|
146
|
-
return cleanNode(root, { ids, prefix: `dj-icon-${++iconCounter}-` });
|
|
147
|
-
}
|
|
148
|
-
|
|
149
28
|
export class RewardUI {
|
|
150
29
|
/**
|
|
151
30
|
* @param {{ particles?: Object|null }} [parts] - Read at call time, so a
|
|
@@ -263,7 +142,7 @@ export class RewardUI {
|
|
|
263
142
|
this.xpText = this.container.querySelector('.xp-text');
|
|
264
143
|
this.levelDisplay = this.container.querySelector('.level-number');
|
|
265
144
|
this.streakDisplay = this.container.querySelector('.streak-number');
|
|
266
|
-
|
|
145
|
+
setIcon(this.container.querySelector('.streak-icon'), this._streakIcon, this.safeIcons);
|
|
267
146
|
}
|
|
268
147
|
|
|
269
148
|
/**
|
|
@@ -280,30 +159,6 @@ export class RewardUI {
|
|
|
280
159
|
document.head.appendChild(this._style);
|
|
281
160
|
}
|
|
282
161
|
|
|
283
|
-
/**
|
|
284
|
-
* Single place where icons reach the DOM. A Node is appended. A string is
|
|
285
|
-
* a sanitised SVG or plain text unless safeIcons is off; then it is HTML
|
|
286
|
-
* (see SECURITY.md).
|
|
287
|
-
* @private
|
|
288
|
-
*/
|
|
289
|
-
_setIcon(el, icon) {
|
|
290
|
-
el.textContent = '';
|
|
291
|
-
if (typeof Node !== 'undefined' && icon instanceof Node) {
|
|
292
|
-
el.appendChild(icon);
|
|
293
|
-
} else if (typeof icon !== 'string') {
|
|
294
|
-
return;
|
|
295
|
-
} else if (!this.safeIcons) {
|
|
296
|
-
el.innerHTML = icon;
|
|
297
|
-
} else {
|
|
298
|
-
const svg = parseSafeSvg(icon);
|
|
299
|
-
if (svg) {
|
|
300
|
-
el.appendChild(svg);
|
|
301
|
-
} else {
|
|
302
|
-
el.textContent = icon;
|
|
303
|
-
}
|
|
304
|
-
}
|
|
305
|
-
}
|
|
306
|
-
|
|
307
162
|
/**
|
|
308
163
|
* setTimeout that destroy() can cancel.
|
|
309
164
|
* @private
|
|
@@ -402,7 +257,9 @@ export class RewardUI {
|
|
|
402
257
|
* - `custom` (and any other kind): the achievement layout without the heading.
|
|
403
258
|
*
|
|
404
259
|
* @param {{ kind: string, title?: string, body?: string, icon?: string|Node,
|
|
405
|
-
* meta?: string, tier?: 'common'|'rare'|'legendary' }} popup
|
|
260
|
+
* meta?: string, tier?: 'common'|'rare'|'legendary', burst?: boolean }} popup
|
|
261
|
+
* `burst: false` on a card skips the confetti it fires after 300 ms. Any
|
|
262
|
+
* other value keeps it.
|
|
406
263
|
*/
|
|
407
264
|
popup(popup) {
|
|
408
265
|
if (!this.container || !popup || typeof popup !== 'object') return;
|
|
@@ -425,7 +282,7 @@ export class RewardUI {
|
|
|
425
282
|
// Copy the fields now, so a caller that reuses its object cannot change
|
|
426
283
|
// a card that is still waiting.
|
|
427
284
|
const { title, body, meta, icon } = popup;
|
|
428
|
-
this._cardQueue.push([{ title, body, meta, icon }, withHeading]);
|
|
285
|
+
this._cardQueue.push([{ title, body, meta, icon, burst: ownValue(popup, 'burst') }, withHeading]);
|
|
429
286
|
this._nextCard();
|
|
430
287
|
}
|
|
431
288
|
|
|
@@ -465,7 +322,7 @@ export class RewardUI {
|
|
|
465
322
|
|
|
466
323
|
const title = textOf(popup.title);
|
|
467
324
|
card.querySelector('.achievement-title').textContent = withHeading ? this.strings.achievementUnlocked : '';
|
|
468
|
-
|
|
325
|
+
setIcon(card.querySelector('.achievement-icon'), popup.icon, this.safeIcons);
|
|
469
326
|
card.querySelector('.achievement-name').textContent = title;
|
|
470
327
|
card.querySelector('.achievement-desc').textContent = textOf(popup.body);
|
|
471
328
|
card.querySelector('.achievement-xp').textContent = textOf(popup.meta);
|
|
@@ -473,10 +330,12 @@ export class RewardUI {
|
|
|
473
330
|
this._mount(card);
|
|
474
331
|
this._announce(withHeading ? `${this.strings.achievementUnlocked}: ${title}` : title);
|
|
475
332
|
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
333
|
+
if (popup.burst !== false) {
|
|
334
|
+
this._defer(() => {
|
|
335
|
+
const rect = card.getBoundingClientRect();
|
|
336
|
+
this._burst('confetti', { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }, { count: 40 });
|
|
337
|
+
}, 300);
|
|
338
|
+
}
|
|
480
339
|
|
|
481
340
|
this._defer(() => {
|
|
482
341
|
card.style.animation = 'slideOut 0.3s ease-in forwards';
|