dopaminejs 2.3.1 → 2.5.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/style.css CHANGED
@@ -1 +1,2 @@
1
- #game-ui-overlay,.game-ui-overlay{position:fixed;top:0;left:0;width:100%;pointer-events:none;z-index:1000;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif}.game-ui-top-bar{display:flex;align-items:center;gap:12px;padding:12px 16px;background:#0000004d;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px)}.level-badge{display:flex;flex-direction:column;align-items:center;background:linear-gradient(135deg,#667eea,#764ba2);padding:8px 12px;border-radius:12px;box-shadow:0 4px 12px #667eea66;min-width:60px}.level-label{font-size:10px;font-weight:600;color:#fffc;letter-spacing:.5px}.level-number{font-size:24px;font-weight:800;color:#fff;line-height:1}.xp-container{flex:1;display:flex;flex-direction:column;gap:4px}.xp-bar-bg{height:12px;background:#fff3;border-radius:6px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{height:100%;background:linear-gradient(90deg,#4facfe,#00f2fe);border-radius:6px;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{font-size:11px;color:#fff;font-weight:600;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.5)}.streak-badge{display:flex;align-items:center;gap:6px;background:linear-gradient(135deg,#f80,#f40);padding:8px 12px;border-radius:12px;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:flicker 2s infinite}.streak-number{font-size:18px;font-weight:800;color:#fff}.achievement-popup{position:fixed;top:80px;right:20px;background:linear-gradient(135deg,#667eea,#764ba2);border-radius:16px;padding:16px;box-shadow:0 8px 32px #0006;animation:slideIn .5s cubic-bezier(.68,-.55,.265,1.55);z-index:10000;max-width:320px;overflow:hidden}.achievement-shine{position:absolute;top:0;left:-100%;width:100%;height:100%;background:linear-gradient(90deg,transparent,rgba(255,255,255,.3),transparent);animation:shine 2s infinite}.achievement-content{position:relative;display:flex;gap:12px;align-items:center}.achievement-icon{font-size:48px;animation:bounce .6s ease-out}.achievement-info{flex:1}.achievement-title{font-size:12px;font-weight:600;color:#ffffffe6;text-transform:uppercase;letter-spacing:.5px}.achievement-name{font-size:18px;font-weight:800;color:#fff;margin:2px 0}.achievement-desc{font-size:13px;color:#fffc;margin-bottom:4px}.achievement-xp{display:inline-block;background:#fff3;padding:4px 8px;border-radius:8px;font-size:12px;font-weight:700;color:gold}.level-up-overlay{position:fixed;top:0;left:0;width:100%;height:100%;background:#000000d9;display:flex;align-items:center;justify-content:center;z-index:10001;animation:fadeIn .3s ease-out}.level-up-content{text-align:center;animation:scaleIn .5s cubic-bezier(.68,-.55,.265,1.55)}.level-up-title{font-size:32px;font-weight:800;background:linear-gradient(135deg,gold,#ffed4e);-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;text-transform:uppercase;letter-spacing:4px;margin-bottom:16px}.level-up-number{font-size:120px;font-weight:900;color:#fff;text-shadow:0 0 20px rgba(255,215,0,.8),0 0 40px rgba(255,215,0,.6),0 0 60px rgba(255,215,0,.4);animation:glow 1s ease-in-out infinite alternate}.level-up-subtitle{font-size:24px;color:#fffc;font-weight:600;margin-top:16px}.floating-text{position:fixed;font-weight:800;text-shadow:2px 2px 0 #000,-1px -1px 0 #000,1px -1px 0 #000,-1px 1px 0 #000;pointer-events:none;z-index:9998;animation:floatUp 2s ease-out forwards}@keyframes slideIn{0%{transform:translate(400px);opacity:0}to{transform:translate(0);opacity:1}}@keyframes slideOut{0%{transform:translate(0);opacity:1}to{transform:translate(400px);opacity:0}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{transform:scale(.5);opacity:0}to{transform:scale(1);opacity:1}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px rgba(255,215,0,.8),0 0 40px rgba(255,215,0,.6),0 0 60px rgba(255,215,0,.4)}to{text-shadow:0 0 30px rgba(255,215,0,1),0 0 60px rgba(255,215,0,.8),0 0 90px rgba(255,215,0,.6)}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{transform:translateY(0);opacity:1}to{transform:translateY(-100px);opacity:0}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media(max-width:480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{padding:6px 10px;min-width:50px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{right:12px;max-width:calc(100% - 24px)}.level-up-number{font-size:80px}}@media(prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{animation:none!important;transition:none!important}.floating-text{animation:none!important}}
1
+ #game-ui-overlay,.game-ui-overlay{pointer-events:none;z-index:1000;width:100%;font-family:Inter,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;position:fixed;top:0;left:0}.game-ui-top-bar{-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);background:#0000004d;align-items:center;gap:12px;padding:12px 16px;display:flex}.level-badge{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:12px;flex-direction:column;align-items:center;min-width:60px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #667eea66}.level-label{color:#fffc;letter-spacing:.5px;font-size:10px;font-weight:600}.level-number{color:#fff;font-size:24px;font-weight:800;line-height:1}.xp-container{flex-direction:column;flex:1;gap:4px;display:flex}.xp-bar-bg{background:#fff3;border-radius:6px;height:12px;overflow:hidden;box-shadow:inset 0 2px 4px #0003}.xp-bar-fill{background:linear-gradient(90deg,#4facfe 0%,#00f2fe 100%);border-radius:6px;height:100%;transition:width .5s ease-out;box-shadow:0 0 10px #4facfe99}.xp-text{color:#fff;text-align:center;text-shadow:0 1px 2px #00000080;font-size:11px;font-weight:600}.streak-badge{background:linear-gradient(135deg,#f80 0%,#f40 100%);border-radius:12px;align-items:center;gap:6px;padding:8px 12px;display:flex;box-shadow:0 4px 12px #f806}.streak-icon{font-size:20px;animation:2s infinite flicker}.streak-number{color:#fff;font-size:18px;font-weight:800}.achievement-popup{z-index:10000;background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);border-radius:16px;max-width:320px;padding:16px;animation:.5s cubic-bezier(.68,-.55,.265,1.55) slideIn;position:fixed;top:80px;right:20px;overflow:hidden;box-shadow:0 8px 32px #0006}.achievement-shine{background:linear-gradient(90deg,#0000,#ffffff4d,#0000);width:100%;height:100%;animation:2s infinite shine;position:absolute;top:0;left:-100%}.achievement-content{align-items:center;gap:12px;display:flex;position:relative}.achievement-icon{font-size:48px;animation:.6s ease-out bounce}.achievement-info{flex:1}.achievement-title{color:#ffffffe6;text-transform:uppercase;letter-spacing:.5px;font-size:12px;font-weight:600}.achievement-name{color:#fff;margin:2px 0;font-size:18px;font-weight:800}.achievement-desc{color:#fffc;margin-bottom:4px;font-size:13px}.achievement-xp{color:gold;background:#fff3;border-radius:8px;padding:4px 8px;font-size:12px;font-weight:700;display:inline-block}.level-up-overlay{z-index:10001;background:#000000d9;justify-content:center;align-items:center;width:100%;height:100%;animation:.3s ease-out fadeIn;display:flex;position:fixed;top:0;left:0}.level-up-content{text-align:center;animation:.5s cubic-bezier(.68,-.55,.265,1.55) scaleIn}.level-up-title{background:linear-gradient(135deg,gold 0%,#ffed4e 100%);-webkit-text-fill-color:transparent;text-transform:uppercase;letter-spacing:4px;-webkit-background-clip:text;background-clip:text;margin-bottom:16px;font-size:32px;font-weight:800}.level-up-number{color:#fff;text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066;font-size:120px;font-weight:900;animation:1s ease-in-out infinite alternate glow}.level-up-subtitle{color:#fffc;margin-top:16px;font-size:24px;font-weight:600}.floating-text{text-shadow:2px 2px #000,-1px -1px #000,1px -1px #000,-1px 1px #000;pointer-events:none;z-index:9998;font-weight:800;animation:2s ease-out forwards floatUp;position:fixed}@keyframes slideIn{0%{opacity:0;transform:translate(400px)}to{opacity:1;transform:translate(0)}}@keyframes slideOut{0%{opacity:1;transform:translate(0)}to{opacity:0;transform:translate(400px)}}@keyframes fadeIn{0%{opacity:0}to{opacity:1}}@keyframes scaleIn{0%{opacity:0;transform:scale(.5)}to{opacity:1;transform:scale(1)}}@keyframes bounce{0%,to{transform:translateY(0)}50%{transform:translateY(-10px)}}@keyframes glow{0%{text-shadow:0 0 20px #ffd700cc,0 0 40px #ffd70099,0 0 60px #ffd70066}to{text-shadow:0 0 30px gold,0 0 60px #ffd700cc,0 0 90px #ffd70099}}@keyframes shine{0%{left:-100%}30%{left:100%}to{left:100%}}@keyframes flicker{0%,to{opacity:1}50%{opacity:.8}}@keyframes floatUp{0%{opacity:1;transform:translateY(0)}to{opacity:0;transform:translateY(-100px)}}@keyframes xp-pulse{0%{transform:scaleY(1)}50%{transform:scaleY(1.2)}to{transform:scaleY(1)}}@keyframes level-pulse{0%{transform:scale(1)}50%{transform:scale(1.1)}to{transform:scale(1)}}@media (width<=480px){.game-ui-top-bar{gap:8px;padding:10px 12px}.level-badge{min-width:50px;padding:6px 10px}.level-number{font-size:20px}.xp-bar-bg{height:10px}.xp-text{font-size:10px}.achievement-popup{max-width:calc(100% - 24px);right:12px}.level-up-number{font-size:80px}}@media (prefers-reduced-motion:reduce){.game-ui-overlay *,.achievement-popup,.achievement-popup *,.level-up-overlay,.level-up-overlay *{transition:none!important;animation:none!important}.floating-text{animation:none!important}}
2
+ /*$vite$:1*/
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dopaminejs",
3
- "version": "2.3.1",
3
+ "version": "2.5.0",
4
4
  "description": "Progression mechanics for web apps: XP, levels, achievements and timezone-correct daily streaks, with the particles and sound to make them land. Zero dependencies.",
5
5
  "type": "module",
6
6
  "main": "./dist/dopamine.cjs",
@@ -16,6 +16,11 @@
16
16
  "import": "./dist/engine.js",
17
17
  "require": "./dist/engine.cjs"
18
18
  },
19
+ "./core": {
20
+ "types": "./types/core.d.ts",
21
+ "import": "./dist/core.js",
22
+ "require": "./dist/core.cjs"
23
+ },
19
24
  "./style.css": "./dist/style.css"
20
25
  },
21
26
  "sideEffects": false,
@@ -20,6 +20,19 @@ export class PluginRegistry {
20
20
  // Async inits in flight. Each notes the systems other plugins added
21
21
  // meanwhile, so a failed one removes only its own.
22
22
  this._inFlight = new Set();
23
+
24
+ // Map<pluginName, Map<systemName, system>>: what each plugin
25
+ // registered during init, so remove() can unregister it.
26
+ this._owned = new Map();
27
+ }
28
+
29
+ /**
30
+ * Every registered system by name.
31
+ * @private
32
+ */
33
+ _snapshot() {
34
+ const systems = this.kernel.systems;
35
+ return new Map(systems.getSystemNames().map((name) => [name, systems.get(name)]));
23
36
  }
24
37
 
25
38
  /**
@@ -29,6 +42,57 @@ export class PluginRegistry {
29
42
  return this.kernel.systems.getSystemNames().filter((name) => !before.has(name));
30
43
  }
31
44
 
45
+ /**
46
+ * Names of the systems added or replaced since a snapshot. A plugin that
47
+ * swaps in its own 'audio' adds no new name, so names alone miss it.
48
+ * @private
49
+ */
50
+ _changedSince(before) {
51
+ const systems = this.kernel.systems;
52
+ return systems.getSystemNames().filter((name) => systems.get(name) !== before.get(name));
53
+ }
54
+
55
+ /**
56
+ * Remember the systems a plugin registered during init.
57
+ * @private
58
+ */
59
+ _own(pluginName, names) {
60
+ const systems = this.kernel.systems;
61
+ const owned = new Map();
62
+
63
+ for (const name of names) {
64
+ const system = systems.get(name);
65
+
66
+ // A plugin loaded from inside this one's init() already owns it.
67
+ const taken = [...this._owned.values()].some((other) => other.get(name) === system);
68
+ if (!taken) owned.set(name, system);
69
+ }
70
+
71
+ this._owned.set(pluginName, owned);
72
+ }
73
+
74
+ /**
75
+ * Unregister the systems a removed plugin registered during init.
76
+ * @private
77
+ */
78
+ _release(pluginName) {
79
+ const owned = this._owned.get(pluginName);
80
+ if (!owned) return;
81
+
82
+ this._owned.delete(pluginName);
83
+
84
+ for (const [name, system] of owned) {
85
+ // Replaced or unregistered since. It is no longer this plugin's.
86
+ if (this.kernel.systems.get(name) !== system) continue;
87
+
88
+ try {
89
+ this.kernel.systems.unregister(name);
90
+ } catch (error) {
91
+ console.error(`[PluginRegistry] Error removing system "${name}":`, error);
92
+ }
93
+ }
94
+ }
95
+
32
96
  /**
33
97
  * Mark systems as belonging to a plugin that loaded.
34
98
  * @private
@@ -107,18 +171,20 @@ export class PluginRegistry {
107
171
  this._loadOrder.push(plugin.name);
108
172
 
109
173
  // Initialize plugin
110
- const systemsBefore = new Set(this.kernel.systems.getSystemNames());
174
+ const systemsBefore = this._snapshot();
111
175
 
112
176
  try {
113
177
  plugin.init(this.kernel);
114
178
 
179
+ const mine = this._changedSince(systemsBefore);
180
+ this._own(plugin.name, mine);
181
+ this._claim(mine);
182
+
115
183
  // Emit event
116
184
  this.kernel.events.emit('plugin_loaded', {
117
185
  name: plugin.name,
118
186
  version: plugin.version
119
187
  });
120
-
121
- this._claim(this._systemsSince(systemsBefore));
122
188
  } catch (error) {
123
189
  console.error(`[PluginRegistry] Failed to initialize plugin "${plugin.name}":`, error);
124
190
  this._forget(plugin.name);
@@ -156,7 +222,7 @@ export class PluginRegistry {
156
222
  this._loadOrder.push(plugin.name);
157
223
 
158
224
  const pending = {
159
- before: new Set(this.kernel.systems.getSystemNames()),
225
+ before: this._snapshot(),
160
226
  foreign: new Set()
161
227
  };
162
228
  const own = () => this._systemsSince(pending.before).filter((name) => !pending.foreign.has(name));
@@ -167,7 +233,18 @@ export class PluginRegistry {
167
233
  await plugin.init(this.kernel);
168
234
 
169
235
  this._inFlight.delete(pending);
170
- this._claim(own());
236
+
237
+ const systems = this.kernel.systems;
238
+ const mine = this._changedSince(pending.before).filter((name) => !pending.foreign.has(name));
239
+
240
+ // With another init still running, a system that appeared after
241
+ // that one began could be its work. Nobody owns those, so they
242
+ // stay registered when either plugin is removed.
243
+ const others = [...this._inFlight];
244
+ this._own(plugin.name, mine.filter(
245
+ (name) => others.every((other) => other.before.get(name) === systems.get(name))
246
+ ));
247
+ this._claim(mine);
171
248
 
172
249
  // Emit event
173
250
  this.kernel.events.emit('plugin_loaded', {
@@ -196,6 +273,12 @@ export class PluginRegistry {
196
273
 
197
274
  /**
198
275
  * Remove a plugin
276
+ *
277
+ * Calls the plugin's destroy(), then unregisters the systems it
278
+ * registered during init() that are still in place. Not tracked, and so
279
+ * the plugin's to unregister in destroy(): a system it registers after
280
+ * init(), and one registered while two useAsync() inits overlapped.
281
+ *
199
282
  * @param {string} name - Plugin name
200
283
  * @returns {boolean} - True if plugin was found and removed
201
284
  */
@@ -222,6 +305,8 @@ export class PluginRegistry {
222
305
  this._loadOrder.splice(index, 1);
223
306
  }
224
307
 
308
+ this._release(name);
309
+
225
310
  // Emit event
226
311
  this.kernel.events.emit('plugin_unloaded', { name });
227
312
 
@@ -29,6 +29,28 @@ export class SoundManager {
29
29
 
30
30
  // Queued follow-up tones, so destroy() can cancel them.
31
31
  this._timers = new Set();
32
+
33
+ // unlockOn removers, so destroy() takes listeners that never fired off too.
34
+ this._unlocks = new Set();
35
+ }
36
+
37
+ /**
38
+ * Start audio on the first gesture on `target`. Browsers keep an
39
+ * AudioContext silent until the page gets one, and a touch pointerdown
40
+ * is not one, so the default waits for pointerup. Returns a remover.
41
+ */
42
+ unlockOn(target, events = ['pointerup', 'touchend', 'keydown']) {
43
+ const remove = () => {
44
+ for (const type of events) target.removeEventListener(type, unlock);
45
+ this._unlocks.delete(remove);
46
+ };
47
+ const unlock = () => {
48
+ remove();
49
+ this.initAudio();
50
+ };
51
+ for (const type of events) target.addEventListener(type, unlock);
52
+ this._unlocks.add(remove);
53
+ return remove;
32
54
  }
33
55
 
34
56
  /**
@@ -128,11 +150,16 @@ export class SoundManager {
128
150
  }
129
151
 
130
152
  /**
131
- * Preload multiple sounds
153
+ * Register and load multiple sounds. Before the audio context exists the
154
+ * files cannot be decoded, so they load when initAudio() creates it.
132
155
  * @param {Object} soundMap - { key: url }
133
156
  */
134
157
  async preloadSounds(soundMap) {
135
- const promises = Object.entries(soundMap).map(([key, url]) => this.loadSound(key, url));
158
+ const promises = Object.entries(soundMap).map(([key, url]) => {
159
+ // play() only loads keys it finds here.
160
+ this.customSounds[key] = url;
161
+ return this.loadSound(key, url);
162
+ });
136
163
  await Promise.allSettled(promises);
137
164
  }
138
165
 
@@ -295,6 +322,8 @@ export class SoundManager {
295
322
  * Browsers cap the number of live AudioContexts per page.
296
323
  */
297
324
  destroy() {
325
+ for (const remove of [...this._unlocks]) remove();
326
+
298
327
  for (const id of this._timers) {
299
328
  clearTimeout(id);
300
329
  }
@@ -56,15 +56,35 @@ export class DataService {
56
56
 
57
57
  /**
58
58
  * Load data from local storage
59
- * @param {string} key
60
- * @param {any} defaultValue
59
+ *
60
+ * A failed read returns `defaultValue`, so a caller cannot tell "nothing
61
+ * saved" from "could not read". Pass `{ strict: true }` to get the error
62
+ * instead; unparseable data then rejects with `code: 'DOPAMINE_CORRUPT'`
63
+ * and the raw string on `raw`.
64
+ * @param {string} key
65
+ * @param {any} defaultValue
66
+ * @param {{ strict?: boolean }} [options]
61
67
  */
62
- async load(key, defaultValue = null) {
68
+ async load(key, defaultValue = null, options = {}) {
69
+ let data;
63
70
  try {
64
71
  await this._tail;
65
- const data = await this.storage.getItem(this.prefix + key);
66
- return data ? JSON.parse(data) : defaultValue;
72
+ data = await this.storage.getItem(this.prefix + key);
73
+ } catch (e) {
74
+ if (options.strict) throw e;
75
+ console.error('Error loading data:', e);
76
+ return defaultValue;
77
+ }
78
+ if (!data) return defaultValue;
79
+ try {
80
+ return JSON.parse(data);
67
81
  } catch (e) {
82
+ if (options.strict) {
83
+ throw Object.assign(new Error(`[DopamineJS] saved "${key}" is not valid JSON`), {
84
+ code: 'DOPAMINE_CORRUPT',
85
+ raw: data,
86
+ });
87
+ }
68
88
  console.error('Error loading data:', e);
69
89
  return defaultValue;
70
90
  }
@@ -42,6 +42,20 @@ export class RewardSystem extends EventEmitter {
42
42
  // recordGame produced four full serializations of the player object.
43
43
  this._batchDepth = 0;
44
44
  this._pendingSave = false;
45
+
46
+ // Set when init() could not read storage. Saving stays off until a
47
+ // later init() reads it, so the saved player is never replaced.
48
+ this._loadFailed = false;
49
+ this._readFailed = false;
50
+ }
51
+
52
+ /**
53
+ * True when the last init() could not read the saved player, so nothing
54
+ * is saved until init() is called again and the read works.
55
+ * @returns {boolean}
56
+ */
57
+ get loadFailed() {
58
+ return this._readFailed;
45
59
  }
46
60
 
47
61
  /**
@@ -82,8 +96,9 @@ export class RewardSystem extends EventEmitter {
82
96
  * @returns {Promise<Object>} Player data
83
97
  */
84
98
  async init() {
85
- const saved = await this.dataService.load('player', null);
86
- this.player = this._migrate(saved);
99
+ const saved = await this._readSaved();
100
+ // A failed retry keeps the progress made since the first init.
101
+ if (!(this._loadFailed && this.player)) this.player = this._migrate(saved);
87
102
 
88
103
  // Check daily streak
89
104
  const streakChanged = this._updateDailyStreak();
@@ -98,6 +113,38 @@ export class RewardSystem extends EventEmitter {
98
113
  return this.player;
99
114
  }
100
115
 
116
+ /**
117
+ * Read the saved player. A failed read turns off saving for this
118
+ * session, so the new player built from the default never overwrites
119
+ * the real one. Calling init() again retries the read.
120
+ * @private
121
+ */
122
+ async _readSaved() {
123
+ // Stay blocked until the read succeeds, so a write made while a
124
+ // retry is in flight cannot land.
125
+ this._loadFailed = true;
126
+ try {
127
+ // A custom data service that ignores the option still works,
128
+ // without this protection.
129
+ const saved = await this.dataService.load('player', null, { strict: true });
130
+ this._loadFailed = false;
131
+ this._readFailed = false;
132
+ return saved;
133
+ } catch (error) {
134
+ if (error?.code === 'DOPAMINE_CORRUPT') {
135
+ // Keep the unreadable value instead of losing it on the next save.
136
+ const kept = await this.dataService.save('player_corrupt', error.raw);
137
+ if (kept) this._loadFailed = false;
138
+ this._readFailed = !kept;
139
+ this._publish('load_failed', { key: 'player', reason: 'corrupt', backedUp: kept });
140
+ return null;
141
+ }
142
+ this._readFailed = true;
143
+ this._publish('load_failed', { key: 'player', reason: 'read', error });
144
+ return null;
145
+ }
146
+ }
147
+
101
148
  /**
102
149
  * @private
103
150
  */
@@ -257,6 +304,7 @@ export class RewardSystem extends EventEmitter {
257
304
  * @private
258
305
  */
259
306
  async _write() {
307
+ if (this._loadFailed) return;
260
308
  this.player.lastPlayedAt = Date.now();
261
309
  const saved = await this.dataService.save('player', this.player);
262
310
 
@@ -3,6 +3,8 @@
3
3
  * Creates satisfying visual feedback for achievements and rewards
4
4
  */
5
5
 
6
+ import { prefersReducedMotion } from '../feel/motion.js';
7
+
6
8
  export class ParticleSystem {
7
9
  constructor(config = {}) {
8
10
  this.container = config.container ?
@@ -19,9 +21,7 @@ export class ParticleSystem {
19
21
  this.maxParticles = Number.isFinite(config.maxParticles) ? Math.max(0, Math.floor(config.maxParticles)) : 5000;
20
22
 
21
23
  // Effects are skipped for users who asked the OS for less motion.
22
- this._reducedMotion = config.respectReducedMotion !== false && typeof window.matchMedia === 'function'
23
- ? window.matchMedia('(prefers-reduced-motion: reduce)')
24
- : null;
24
+ this._reducedMotion = config.respectReducedMotion !== false ? prefersReducedMotion(window) : null;
25
25
 
26
26
  this.canvasId = config.canvasId || 'dopamine-particle-canvas';
27
27
 
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Short vibrations for hits and wins. A browser without the Vibration API
3
+ * (iOS Safari) or one that blocks it is silent, never an error.
4
+ */
5
+ export function createHaptics({ nav = globalThis.navigator, enabled = true } = {}) {
6
+ let on = Boolean(enabled);
7
+ const buzz = (pattern) => {
8
+ if (!on) return;
9
+ // A missing or non-function vibrate throws here too.
10
+ try {
11
+ nav.vibrate(pattern);
12
+ } catch {}
13
+ };
14
+ return {
15
+ tap: () => buzz(10),
16
+ double: () => buzz([10, 40, 10]),
17
+ setEnabled(value) {
18
+ on = Boolean(value);
19
+ },
20
+ };
21
+ }
@@ -0,0 +1,9 @@
1
+ const NO_PREFERENCE = Object.freeze({ matches: false });
2
+
3
+ /**
4
+ * The reduced-motion media query, or `{ matches: false }` where there is no
5
+ * matchMedia (SSR, tests). The live query updates when the user changes it.
6
+ */
7
+ export function prefersReducedMotion(win = globalThis.window) {
8
+ return (typeof win?.matchMedia === 'function' && win.matchMedia('(prefers-reduced-motion: reduce)')) || NO_PREFERENCE;
9
+ }