dopaminejs 2.4.0 → 3.0.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.
Files changed (83) hide show
  1. package/README.md +40 -50
  2. package/dist/DataService-E4pGQ1V3.cjs +1 -0
  3. package/dist/DataService-MfmvkqXR.js +737 -0
  4. package/dist/core.cjs +1 -0
  5. package/dist/core.js +2 -0
  6. package/dist/dopamine.cjs +1 -37
  7. package/dist/dopamine.js +3 -858
  8. package/dist/games.cjs +1 -0
  9. package/dist/games.js +82 -0
  10. package/dist/host-CkRL74ck.js +814 -0
  11. package/dist/host-Pzb-QBPU.cjs +37 -0
  12. package/dist/style.css +395 -2
  13. package/dist/testing.cjs +1 -0
  14. package/dist/testing.js +474 -0
  15. package/package.json +28 -8
  16. package/spec/README.md +227 -0
  17. package/spec/VERSION +1 -0
  18. package/spec/fixtures/achievements.json +611 -0
  19. package/spec/fixtures/levels.json +421 -0
  20. package/spec/fixtures/merge.json +1739 -0
  21. package/spec/fixtures/migrate.json +916 -0
  22. package/spec/fixtures/scores.json +755 -0
  23. package/spec/fixtures/streaks.json +924 -0
  24. package/spec/schema.json +61 -0
  25. package/src/dopamine/audio/SoundManager.js +78 -24
  26. package/src/dopamine/core/DataService.js +25 -5
  27. package/src/dopamine/core/DopamineError.js +7 -0
  28. package/src/dopamine/core/RewardSystem.js +366 -368
  29. package/src/dopamine/core/achievements.js +49 -0
  30. package/src/dopamine/core/clock.js +11 -0
  31. package/src/dopamine/core/levels.js +4 -0
  32. package/src/dopamine/core/merge.js +68 -0
  33. package/src/dopamine/core/middleware.js +58 -0
  34. package/src/dopamine/core/store.js +261 -0
  35. package/src/dopamine/core/streaks.js +55 -0
  36. package/src/dopamine/effects/ParticleSystem.js +33 -3
  37. package/src/dopamine/feel/haptics.js +21 -0
  38. package/src/dopamine/feel/motion.js +9 -0
  39. package/src/dopamine/host.js +358 -0
  40. package/src/dopamine/ui/RewardUI.js +569 -0
  41. package/src/games.js +138 -0
  42. package/src/index.js +14 -33
  43. package/src/progression.js +16 -0
  44. package/src/testing.js +489 -0
  45. package/types/core.d.ts +35 -0
  46. package/types/games.d.ts +46 -0
  47. package/types/index.d.ts +348 -373
  48. package/types/testing.d.ts +96 -0
  49. package/dist/ScreenShake-9jgNXPS6.cjs +0 -1
  50. package/dist/ScreenShake-CLvO1wx4.js +0 -827
  51. package/dist/engine.cjs +0 -1
  52. package/dist/engine.js +0 -2
  53. package/src/core/Animator.js +0 -62
  54. package/src/core/Collider.js +0 -86
  55. package/src/core/Component.js +0 -38
  56. package/src/core/DopamineKernel.js +0 -170
  57. package/src/core/EventBus.js +0 -206
  58. package/src/core/Game.js +0 -90
  59. package/src/core/GameObject.js +0 -99
  60. package/src/core/PluginRegistry.js +0 -359
  61. package/src/core/Scene.js +0 -107
  62. package/src/core/Sprite.js +0 -51
  63. package/src/core/SystemRegistry.js +0 -263
  64. package/src/core/Vector2.js +0 -50
  65. package/src/dopamine/components/ParticleEmitter.js +0 -50
  66. package/src/dopamine/components/ScreenShake.js +0 -50
  67. package/src/dopamine/components/index.js +0 -2
  68. package/src/dopamine/index.js +0 -93
  69. package/src/dopamine/ui/GameUI.js +0 -420
  70. package/src/dopamine/utils/TextureGenerator.js +0 -90
  71. package/src/engine.js +0 -38
  72. package/src/interfaces/IAudioSystem.js +0 -58
  73. package/src/interfaces/IParticleSystem.js +0 -51
  74. package/src/interfaces/IPhysicsSystem.js +0 -52
  75. package/src/interfaces/ISystem.js +0 -48
  76. package/src/interfaces/index.js +0 -7
  77. package/src/renderer/Renderer.js +0 -45
  78. package/src/systems/Director.js +0 -34
  79. package/src/systems/Input.js +0 -81
  80. package/src/systems/Loader.js +0 -48
  81. package/src/systems/Physics.js +0 -210
  82. package/src/systems/Ticker.js +0 -91
  83. package/src/systems/deprecate.js +0 -38
@@ -0,0 +1,569 @@
1
+ /**
2
+ * The default reward UI: a progress bar, achievement and level-up popups and
3
+ * floating text. Nothing here runs at import time.
4
+ */
5
+
6
+ import DEFAULT_CSS from './dopamine.css?inline';
7
+
8
+ const OVERLAY_ID = 'game-ui-overlay';
9
+
10
+ const DEFAULT_TEXT = {
11
+ levelUp: 'LEVEL UP!',
12
+ achievementUnlocked: 'Achievement Unlocked!'
13
+ };
14
+
15
+ const STYLE_ID = 'dopamine-reward-ui-css';
16
+
17
+ const DEFAULT_STREAK_ICON = '🔥';
18
+
19
+ // Config comes from callers, so an inherited property (a polluted prototype)
20
+ // must not count.
21
+ const textOf = (value) => (value === undefined || value === null ? '' : String(value));
22
+
23
+ const hasOwn = (object, key) => Object.prototype.hasOwnProperty.call(object, key);
24
+ const ownValue = (object, key) =>
25
+ (object !== null && typeof object === 'object' && hasOwn(object, key) ? object[key] : undefined);
26
+
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
+ export class RewardUI {
150
+ /**
151
+ * @param {{ particles?: Object|null }} [parts] - Read at call time, so a
152
+ * different particle renderer is picked up without rebuilding the UI.
153
+ * @param {Object} [config]
154
+ * @param {{levelUp?: string, achievementUnlocked?: string}} [config.text]
155
+ * Replaces the built-in popup strings.
156
+ * @param {{streak?: string|Node}} [config.icons]
157
+ * @param {boolean} [config.safeIcons] - Render string icons as sanitised
158
+ * SVG or plain text. Default true. False renders them as HTML.
159
+ * @param {boolean|string} [config.injectCss] - Add the stylesheet from
160
+ * code. A string is the CSS text. Default false: import
161
+ * `dopaminejs/style.css` instead.
162
+ */
163
+ constructor(parts = {}, config = {}) {
164
+ this.parts = parts || {};
165
+
166
+ // Only strings override a default, so a non-string cannot break a
167
+ // popup. An empty string is allowed and hides that text.
168
+ const textConfig = ownValue(config, 'text');
169
+ this.strings = { ...DEFAULT_TEXT };
170
+ for (const key of Object.keys(DEFAULT_TEXT)) {
171
+ const value = ownValue(textConfig, key);
172
+ if (typeof value === 'string') this.strings[key] = value;
173
+ }
174
+ this.safeIcons = ownValue(config, 'safeIcons') !== false;
175
+ this._streakIcon = ownValue(ownValue(config, 'icons'), 'streak') ?? DEFAULT_STREAK_ICON;
176
+ this._injectCss = ownValue(config, 'injectCss');
177
+ this.container = null;
178
+ this.xpBar = null;
179
+ this.levelDisplay = null;
180
+ this.streakDisplay = null;
181
+ this._style = null;
182
+ this._xp = null;
183
+ this._level = null;
184
+
185
+ // Everything this instance put in the DOM or scheduled, so destroy()
186
+ // can take it all back out again.
187
+ this._timers = new Set();
188
+ this._detached = [];
189
+
190
+ this._build();
191
+ }
192
+
193
+ /**
194
+ * The overlay element, for themes. Null after destroy().
195
+ * @returns {HTMLElement|null}
196
+ */
197
+ get root() {
198
+ return this.container;
199
+ }
200
+
201
+ /** @private */
202
+ _build() {
203
+ if (this._injectCss) this._addStyles();
204
+
205
+ this.container = document.createElement('div');
206
+ this.container.className = 'game-ui-overlay';
207
+
208
+ // The stylesheet targets #game-ui-overlay. Claim the id only if it is
209
+ // free, so a second instance cannot produce a duplicate id.
210
+ if (!document.getElementById(OVERLAY_ID)) {
211
+ this.container.id = OVERLAY_ID;
212
+ }
213
+
214
+ this.container.innerHTML = `
215
+ <div class="game-ui-top-bar">
216
+ <div class="level-badge">
217
+ <span class="level-label">LVL</span>
218
+ <span class="level-number">1</span>
219
+ </div>
220
+
221
+ <div class="xp-container">
222
+ <div class="xp-bar-bg">
223
+ <div class="xp-bar-fill" style="width: 0%"></div>
224
+ </div>
225
+ <div class="xp-text">0 / 100 XP</div>
226
+ </div>
227
+
228
+ <div class="streak-badge">
229
+ <span class="streak-icon"></span>
230
+ <span class="streak-number">1</span>
231
+ </div>
232
+ </div>
233
+ `;
234
+
235
+ // Popups are decorative and short-lived, so a screen reader would
236
+ // miss them. This region repeats them as plain text.
237
+ this.liveRegion = document.createElement('div');
238
+ this.liveRegion.className = 'dopamine-live-region';
239
+ this.liveRegion.setAttribute('aria-live', 'polite');
240
+ this.liveRegion.setAttribute('role', 'status');
241
+ Object.assign(this.liveRegion.style, {
242
+ position: 'absolute',
243
+ width: '1px',
244
+ height: '1px',
245
+ overflow: 'hidden',
246
+ clipPath: 'inset(50%)',
247
+ whiteSpace: 'nowrap'
248
+ });
249
+ this.container.appendChild(this.liveRegion);
250
+
251
+ document.body.appendChild(this.container);
252
+
253
+ // Scoped to this instance. Document-wide getElementById would make a
254
+ // second RewardUI silently rebind every element to the first one's DOM.
255
+ this.levelBadge = this.container.querySelector('.level-badge');
256
+ this.streakBadge = this.container.querySelector('.streak-badge');
257
+ this.xpBar = this.container.querySelector('.xp-bar-fill');
258
+ this.xpText = this.container.querySelector('.xp-text');
259
+ this.levelDisplay = this.container.querySelector('.level-number');
260
+ this.streakDisplay = this.container.querySelector('.streak-number');
261
+ this._setIcon(this.container.querySelector('.streak-icon'), this._streakIcon);
262
+ }
263
+
264
+ /**
265
+ * Add the stylesheet once per page. The first instance owns the element
266
+ * and removes it on destroy; later ones share it.
267
+ * @private
268
+ */
269
+ _addStyles() {
270
+ if (document.getElementById(STYLE_ID)) return;
271
+ const css = typeof this._injectCss === 'string' ? this._injectCss : DEFAULT_CSS;
272
+ this._style = document.createElement('style');
273
+ this._style.id = STYLE_ID;
274
+ this._style.textContent = css;
275
+ document.head.appendChild(this._style);
276
+ }
277
+
278
+ /**
279
+ * Single place where icons reach the DOM. A Node is appended. A string is
280
+ * a sanitised SVG or plain text unless safeIcons is off; then it is HTML
281
+ * (see SECURITY.md).
282
+ * @private
283
+ */
284
+ _setIcon(el, icon) {
285
+ el.textContent = '';
286
+ if (typeof Node !== 'undefined' && icon instanceof Node) {
287
+ el.appendChild(icon);
288
+ } else if (typeof icon !== 'string') {
289
+ return;
290
+ } else if (!this.safeIcons) {
291
+ el.innerHTML = icon;
292
+ } else {
293
+ const svg = parseSafeSvg(icon);
294
+ if (svg) {
295
+ el.appendChild(svg);
296
+ } else {
297
+ el.textContent = icon;
298
+ }
299
+ }
300
+ }
301
+
302
+ /**
303
+ * setTimeout that destroy() can cancel.
304
+ * @private
305
+ */
306
+ _defer(fn, delay) {
307
+ const id = setTimeout(() => {
308
+ this._timers.delete(id);
309
+ fn();
310
+ }, delay);
311
+ this._timers.add(id);
312
+ return id;
313
+ }
314
+
315
+ /**
316
+ * Append a transient element and remember it for cleanup.
317
+ * @private
318
+ */
319
+ _mount(el) {
320
+ document.body.appendChild(el);
321
+ this._detached.push(el);
322
+ return el;
323
+ }
324
+
325
+ /**
326
+ * Repeat a popup as text for assistive technology.
327
+ * @private
328
+ */
329
+ _announce(message) {
330
+ if (this.liveRegion) {
331
+ this.liveRegion.textContent = message;
332
+ }
333
+ }
334
+
335
+ /**
336
+ * Ask the particle part for a burst, if there is one. The part is looked
337
+ * up on every call.
338
+ * @private
339
+ */
340
+ _burst(kind, at, opts) {
341
+ this.parts.particles?.burst?.(kind, at, opts);
342
+ }
343
+
344
+ /**
345
+ * Replay a CSS animation by clearing it for one tick.
346
+ * @private
347
+ */
348
+ _replayAnimation(el, animation) {
349
+ if (!el) return;
350
+ el.style.animation = 'none';
351
+ this._defer(() => { el.style.animation = animation; }, 10);
352
+ }
353
+
354
+ /**
355
+ * Draw the bar, the level and the streak.
356
+ * @param {{ xp: number, level: number, progress?: number, streak: number, next?: number }} state
357
+ * `progress` is the position within the current level, 0 to 1. `next` is
358
+ * the XP total that marks the next level. Without `progress` the bar
359
+ * falls back to xp / next.
360
+ */
361
+ hud(state) {
362
+ if (!this.container || !state) return;
363
+ const { xp, level, progress, streak, next } = state;
364
+
365
+ const fraction = Number.isFinite(progress)
366
+ ? progress
367
+ : (next > 0 ? xp / next : 0);
368
+ this.xpBar.style.width = `${Math.max(0, Math.min(100, fraction * 100))}%`;
369
+ this.xpText.textContent = Number.isFinite(next) ? `${xp} / ${next} XP` : `${xp} XP`;
370
+ if (xp !== this._xp) this._replayAnimation(this.xpBar, 'xp-pulse 0.3s ease-out');
371
+ this._xp = xp;
372
+
373
+ this.levelDisplay.textContent = level;
374
+ if (level !== this._level) this._replayAnimation(this.levelBadge, 'level-pulse 0.5s ease-out');
375
+ this._level = level;
376
+
377
+ this.streakDisplay.textContent = streak;
378
+ if (streak >= 7) {
379
+ this.streakBadge.style.background = 'linear-gradient(135deg, #ff6b00 0%, #ff4400 100%)';
380
+ } else if (streak >= 3) {
381
+ this.streakBadge.style.background = 'linear-gradient(135deg, #ff8800 0%, #ff6b00 100%)';
382
+ } else {
383
+ this.streakBadge.style.background = '';
384
+ }
385
+ }
386
+
387
+ /**
388
+ * Show a popup. Every field is set as text. Only `icon` can carry markup,
389
+ * and only when safeIcons is off; a Node is appended as is.
390
+ *
391
+ * - `achievement`: `title` is the name, `body` the description, `meta`
392
+ * an extra line such as "+50 XP".
393
+ * - `level`: `body` is the new level. `title` replaces the heading and
394
+ * falls back to the configured level-up text.
395
+ * - `notice`: `title` is a message floated over the page. `tier` picks
396
+ * the colour and the burst.
397
+ * - `custom` (and any other kind): the achievement layout without the heading.
398
+ *
399
+ * @param {{ kind: string, title?: string, body?: string, icon?: string|Node,
400
+ * meta?: string, tier?: 'common'|'rare'|'legendary' }} popup
401
+ */
402
+ popup(popup) {
403
+ if (!this.container || !popup || typeof popup !== 'object') return;
404
+ const kind = ownValue(popup, 'kind');
405
+ if (kind === 'level') {
406
+ this._levelPopup(popup);
407
+ } else if (kind === 'notice') {
408
+ this._notice(popup);
409
+ } else {
410
+ this._card(popup, kind === 'achievement');
411
+ }
412
+ }
413
+
414
+ /** @private */
415
+ _card(popup, withHeading) {
416
+ const card = document.createElement('div');
417
+ card.className = 'achievement-popup';
418
+ card.innerHTML = `
419
+ <div class="achievement-shine"></div>
420
+ <div class="achievement-content">
421
+ <div class="achievement-icon"></div>
422
+ <div class="achievement-info">
423
+ <div class="achievement-title"></div>
424
+ <div class="achievement-name"></div>
425
+ <div class="achievement-desc"></div>
426
+ <div class="achievement-xp"></div>
427
+ </div>
428
+ </div>
429
+ `;
430
+
431
+ const title = textOf(popup.title);
432
+ card.querySelector('.achievement-title').textContent = withHeading ? this.strings.achievementUnlocked : '';
433
+ this._setIcon(card.querySelector('.achievement-icon'), popup.icon);
434
+ card.querySelector('.achievement-name').textContent = title;
435
+ card.querySelector('.achievement-desc').textContent = textOf(popup.body);
436
+ card.querySelector('.achievement-xp').textContent = textOf(popup.meta);
437
+
438
+ this._mount(card);
439
+ this._announce(withHeading ? `${this.strings.achievementUnlocked}: ${title}` : title);
440
+
441
+ this._defer(() => {
442
+ const rect = card.getBoundingClientRect();
443
+ this._burst('confetti', { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }, { count: 40 });
444
+ }, 300);
445
+
446
+ this._defer(() => {
447
+ card.style.animation = 'slideOut 0.3s ease-in forwards';
448
+ this._defer(() => this._remove(card), 300);
449
+ }, 4000);
450
+ }
451
+
452
+ /** @private */
453
+ _levelPopup(popup) {
454
+ const heading = typeof popup.title === 'string' && popup.title !== '' ? popup.title : this.strings.levelUp;
455
+ const level = textOf(popup.body);
456
+
457
+ const overlay = document.createElement('div');
458
+ overlay.className = 'level-up-overlay';
459
+ overlay.innerHTML = `
460
+ <div class="level-up-content">
461
+ <div class="level-up-title"></div>
462
+ <div class="level-up-number"></div>
463
+ <div class="level-up-subtitle">Amazing progress!</div>
464
+ </div>
465
+ `;
466
+ overlay.querySelector('.level-up-title').textContent = heading;
467
+ overlay.querySelector('.level-up-number').textContent = level;
468
+
469
+ this._mount(overlay);
470
+ this._announce(`Level up: ${level}`);
471
+
472
+ this._defer(() => {
473
+ for (let i = 0; i < 5; i++) {
474
+ this._defer(() => {
475
+ this._burst('confetti', {
476
+ x: Math.random() * window.innerWidth,
477
+ y: Math.random() * window.innerHeight * 0.6
478
+ }, { count: 30 });
479
+ }, i * 200);
480
+ }
481
+ }, 300);
482
+
483
+ this._defer(() => {
484
+ overlay.style.opacity = '0';
485
+ this._defer(() => this._remove(overlay), 500);
486
+ }, 2500);
487
+ }
488
+
489
+ /** @private */
490
+ _notice(popup) {
491
+ const x = window.innerWidth / 2;
492
+ const y = window.innerHeight / 3;
493
+ const message = textOf(popup.title);
494
+
495
+ if (popup.tier === 'legendary') {
496
+ this._floatText({ text: message, x, y, color: '#ffd700', size: '36px' });
497
+ this._burst('stars', { x, y }, { count: 12 });
498
+ this._burst('confetti', { x, y }, { count: 25 });
499
+ } else if (popup.tier === 'rare') {
500
+ this._floatText({ text: message, x, y, color: '#ff6b6b', size: '32px' });
501
+ this._burst('fire', { x, y }, { count: 20 });
502
+ } else {
503
+ this._floatText({ text: message, x, y, color: '#fff', size: '24px' });
504
+ }
505
+
506
+ this._announce(message);
507
+ }
508
+
509
+ /**
510
+ * Float a short text over the page, then remove it.
511
+ * @param {{ text: string, x?: number, y?: number, color?: string }} options
512
+ */
513
+ text(options) {
514
+ this._floatText({ ...options });
515
+ }
516
+
517
+ /** @private */
518
+ _floatText({ text, x, y, color = '#ffd700', size = '24px' }) {
519
+ if (!this.container) return;
520
+ const floater = document.createElement('div');
521
+ floater.className = 'floating-text';
522
+ floater.textContent = textOf(text);
523
+ floater.style.left = (Number.isFinite(x) ? x : window.innerWidth / 2) + 'px';
524
+ floater.style.top = (Number.isFinite(y) ? y : window.innerHeight / 3) + 'px';
525
+ floater.style.color = color;
526
+ floater.style.fontSize = size;
527
+
528
+ this._mount(floater);
529
+
530
+ this._defer(() => this._remove(floater), 2000);
531
+ }
532
+
533
+ /**
534
+ * @private
535
+ */
536
+ _remove(el) {
537
+ el.remove();
538
+ const i = this._detached.indexOf(el);
539
+ if (i > -1) this._detached.splice(i, 1);
540
+ }
541
+
542
+ /**
543
+ * Tear down the overlay, any transient popups, and all pending timers.
544
+ */
545
+ destroy() {
546
+ for (const id of this._timers) {
547
+ clearTimeout(id);
548
+ }
549
+ this._timers.clear();
550
+
551
+ for (const el of this._detached) {
552
+ el.remove();
553
+ }
554
+ this._detached = [];
555
+
556
+ this.container?.remove();
557
+ this._style?.remove();
558
+ this._style = null;
559
+ this.container = null;
560
+ this.liveRegion = null;
561
+ this.xpBar = null;
562
+ this.xpText = null;
563
+ this.levelBadge = null;
564
+ this.streakBadge = null;
565
+ this.levelDisplay = null;
566
+ this.streakDisplay = null;
567
+ this._streakIcon = null;
568
+ }
569
+ }