@wasm-gaming/blastem-wasm 0.1.2 → 0.2.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/src/app/app.js CHANGED
@@ -8,13 +8,103 @@
8
8
  // - Coming back with any suspend point shows them: the unsaved one, four slots, and
9
9
  // "from the beginning". Y saves the unsaved point into a slot; Y on a saved one
10
10
  // locks / unlocks or deletes it.
11
- // - In game, Select+Start or Escape opens the pause menu.
11
+ // - In game, Select+Start or Escape opens the pause menu, with the four slots in it: an
12
+ // empty one saves the moment at once; a saved one opens Cargar (focused) · Guardar aquí ·
13
+ // Bloquear · Borrar.
14
+ // - By touch: the hints are buttons (A, B, Y), and a long press on a card is Y.
12
15
  //
13
16
  // Plain JS and DOM: it ships next to the SDK and imports nothing else.
14
17
 
15
- import BlastemSDK, { AUTO_STATE_SLOT, STATE_SLOTS } from '../blastem.sdk.js';
18
+ import BlastemSDK, { AUTO_STATE_SLOT, BLASTEM_CONTROLS, STATE_SLOTS } from '../blastem.sdk.js';
19
+ import {
20
+ SHARED_SETTINGS,
21
+ controlsModel,
22
+ createFullscreenToggle,
23
+ createPerfCounter,
24
+ createSettingsScreen,
25
+ createWakeLock,
26
+ loadSettings,
27
+ resolveLocale,
28
+ saveSettings,
29
+ settingsDefaults,
30
+ settingsModel,
31
+ } from '../engine-specs.js';
16
32
 
17
33
  const OWNER = 'app';
34
+ const ENGINE_ID = 'blastem';
35
+
36
+ /** The app's words, in English and Spanish (engine-specs UX.md, "Languages"). */
37
+ const STRINGS = {
38
+ booting: { en: 'Starting the engine…', es: 'Arrancando el motor…' },
39
+ today: { en: 'Today · {time}', es: 'Hoy · {time}' },
40
+ yesterday: { en: 'Yesterday · {time}', es: 'Ayer · {time}' },
41
+ slot: { en: 'slot', es: 'hueco' },
42
+ saveHere: { en: 'save here', es: 'guardar aquí' },
43
+ cancelHint: { en: 'cancel', es: 'cancelar' },
44
+ choose: { en: 'choose', es: 'elegir' },
45
+ playHint: { en: 'play', es: 'jugar' },
46
+ saveToSlot: { en: 'save to a slot', es: 'guardar en un hueco' },
47
+ options: { en: 'options', es: 'opciones' },
48
+ backHint: { en: 'back', es: 'volver' },
49
+ quitHint: { en: 'quit', es: 'salir' },
50
+ saveHereOrOptions: { en: 'options', es: 'opciones' },
51
+ continueHint: { en: 'continue', es: 'continuar' },
52
+ fromStart: { en: 'From the beginning', es: 'Desde el principio' },
53
+ unsaved: { en: 'Unsaved', es: 'Sin guardar' },
54
+ empty: { en: 'Empty', es: 'Vacío' },
55
+ bootFailed: { en: 'Could not start', es: 'No se pudo arrancar' },
56
+ back: { en: 'Back', es: 'Volver' },
57
+ whichSlot: { en: 'Which slot does it go in?', es: '¿En qué hueco lo guardas?' },
58
+ points: { en: 'Suspend points', es: 'Puntos de suspensión' },
59
+ paused: { en: 'Paused', es: 'Pausa' },
60
+ point: { en: 'Point {n}', es: 'Punto {n}' },
61
+ continue: { en: 'Continue', es: 'Continuar' },
62
+ restart: { en: 'Restart', es: 'Reiniciar' },
63
+ restartHint: { en: 'console reset', es: 'reset de la consola' },
64
+ settings: { en: 'Settings', es: 'Ajustes' },
65
+ fullscreen: { en: 'Fullscreen', es: 'Pantalla completa' },
66
+ fullscreenHint: { en: 'Alt+Enter · Select + Y', es: 'Alt+Enter · Select + Y' },
67
+ fullscreenHintMac: { en: 'Cmd+Enter · Select + Y', es: 'Cmd+Enter · Select + Y' },
68
+ exit: { en: 'Back to the launcher', es: 'Volver al lanzador' },
69
+ exitHint: { en: 'a suspend point is kept', es: 'se queda un punto de suspensión' },
70
+ savedIn: { en: 'Saved in slot {n}', es: 'Guardado en el hueco {n}' },
71
+ loadFailed: { en: 'Could not load that point', es: 'No se pudo cargar ese punto' },
72
+ slotLocked: { en: 'That slot is locked', es: 'Ese hueco está bloqueado' },
73
+ allLocked: { en: 'The four slots are locked', es: 'Los cuatro huecos están bloqueados' },
74
+ load: { en: 'Load', es: 'Cargar' },
75
+ saveHereItem: { en: 'Save here', es: 'Guardar aquí' },
76
+ unlockFirst: { en: 'unlock it first', es: 'desbloquéalo antes' },
77
+ replaces: { en: 'replaces what is there', es: 'sustituye lo que hay' },
78
+ overwriteAsk: { en: 'Overwrite point {n}?', es: '¿Sobrescribir el punto {n}?' },
79
+ overwrite: { en: 'Overwrite', es: 'Sobrescribir' },
80
+ cancel: { en: 'Cancel', es: 'Cancelar' },
81
+ unlock: { en: 'Unlock', es: 'Desbloquear' },
82
+ lock: { en: 'Lock', es: 'Bloquear' },
83
+ unlockHint: { en: 'it can be overwritten and deleted', es: 'se podrá sobrescribir y borrar' },
84
+ lockHint: { en: 'so it is not overwritten or deleted', es: 'que no se sobrescriba ni se borre' },
85
+ delete: { en: 'Delete', es: 'Borrar' },
86
+ deleteAsk: { en: 'Delete point {n}?', es: '¿Borrar el punto {n}?' },
87
+ noUndo: { en: 'This cannot be undone.', es: 'No se puede deshacer.' },
88
+ saving: { en: 'Saving the suspend point…', es: 'Guardando el punto de suspensión…' },
89
+ leaveAsk: { en: 'Back to the launcher?', es: '¿Volver al lanzador?' },
90
+ leave: { en: 'Leave', es: 'Salir' },
91
+ stay: { en: 'Stay', es: 'Seguir' },
92
+ };
93
+
94
+ const DIRECTIONS = {
95
+ up: { en: 'Up', es: 'Arriba' },
96
+ down: { en: 'Down', es: 'Abajo' },
97
+ left: { en: 'Left', es: 'Izquierda' },
98
+ right: { en: 'Right', es: 'Derecha' },
99
+ };
100
+ /** The Mega Drive pad's buttons, for Ajustes → Controles. */
101
+ const BUTTONS = BLASTEM_CONTROLS.map((c) => ({ id: c.id, label: DIRECTIONS[c.id] ?? c.label }));
102
+ const DEFAULT_CONTROLS = Object.fromEntries(BLASTEM_CONTROLS.map((c) => [c.id, { code: c.code, button: c.button }]));
103
+ /** Bindings (engine-specs) → what `play.setControls()` takes. */
104
+ const toBlastemControls = (bindings) => ({
105
+ keys: Object.fromEntries(Object.entries(bindings).filter(([, b]) => b.code).map(([id, b]) => [id, b.code])),
106
+ buttons: Object.fromEntries(Object.entries(bindings).filter(([, b]) => Number.isInteger(b.button)).map(([id, b]) => [id, b.button])),
107
+ });
18
108
  const esc = (text) => String(text ?? '').replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
19
109
 
20
110
  let cssLoaded = null;
@@ -27,15 +117,15 @@ const loadCss = () =>
27
117
  document.head.append(link);
28
118
  }));
29
119
 
30
- const when = (date) => {
120
+ const whenIn = (t, locale) => (date) => {
31
121
  if (!date) return '';
32
122
  const now = new Date();
33
- const time = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
34
- if (date.toDateString() === now.toDateString()) return `Hoy · ${time}`;
123
+ const time = date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit' });
124
+ if (date.toDateString() === now.toDateString()) return t('today', { time });
35
125
  const yesterday = new Date(now);
36
126
  yesterday.setDate(now.getDate() - 1);
37
- if (date.toDateString() === yesterday.toDateString()) return `Ayer · ${time}`;
38
- return `${date.toLocaleDateString(undefined, { day: 'numeric', month: 'short' })} · ${time}`;
127
+ if (date.toDateString() === yesterday.toDateString()) return t('yesterday', { time });
128
+ return `${date.toLocaleDateString(locale, { day: 'numeric', month: 'short' })} · ${time}`;
39
129
  };
40
130
 
41
131
  const LOCK = '<svg viewBox="0 0 16 16" aria-hidden="true"><path fill="currentColor" d="M4.5 7V5a3.5 3.5 0 0 1 7 0v2h.5a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1zm1.6 0h3.8V5a1.9 1.9 0 0 0-3.8 0z"/></svg>';
@@ -44,6 +134,11 @@ const RESTART = '<svg viewBox="0 0 24 24" aria-hidden="true"><path fill="none" s
44
134
  export async function mount(target, host) {
45
135
  await loadCss();
46
136
 
137
+ const locale = host.locale ?? resolveLocale();
138
+ const t = (key, params = {}) =>
139
+ (STRINGS[key]?.[locale] ?? STRINGS[key]?.en ?? key).replace(/\{(\w+)\}/g, (m, name) => (name in params ? String(params[name]) : m));
140
+ const when = whenIn(t, locale);
141
+
47
142
  const root = document.createElement('div');
48
143
  root.className = 'bem-app';
49
144
  root.style.setProperty('--accent', host.game?.accent ?? '#9f1239');
@@ -61,13 +156,16 @@ export async function mount(target, host) {
61
156
  */
62
157
  const state = {
63
158
  screen: 'boot',
64
- status: 'Arrancando el motor…',
159
+ status: t('booting'),
65
160
  error: null,
66
161
  cards: [], // [{ kind: 'start' | 'auto' | 'slot', slot, info }]
67
162
  focus: 0,
68
163
  from: 'boot',
69
164
  picking: false,
70
- pause: { items: [], focus: 0 },
165
+ // The pause menu: Continuar, the four slots (a row), Reiniciar, Ajustes, Pantalla completa,
166
+ // Volver al lanzador.
167
+ // focus: { kind: 'item' | 'slot', i }; col: the slot the row comes back to.
168
+ pause: { items: [], slots: [], focus: { kind: 'item', i: 0 }, col: 0 },
71
169
  sheet: null, // { slot, items, focus }
72
170
  confirm: null, // { title, text, yes, no, onYes, under, focus }
73
171
  toast: null,
@@ -108,8 +206,16 @@ export async function mount(target, host) {
108
206
 
109
207
  // ---- render ---------------------------------------------------------------------
110
208
 
209
+ // A hint with an action is also a button: tapping it does what the gamepad button
210
+ // would (on a phone the menus are tapped). One without is the gamepad's only.
111
211
  const hints = (pairs) =>
112
- `<footer class="bem-hints">${pairs.map(([k, t]) => `<span><kbd>${k}</kbd>${t}</span>`).join('')}</footer>`;
212
+ `<footer class="bem-hints">${pairs
213
+ .map(([k, t, act]) =>
214
+ act
215
+ ? `<button class="hint" data-act="${act}"><kbd>${k}</kbd>${t}</button>`
216
+ : `<span class="is-pad"><kbd>${k}</kbd>${t}</span>`,
217
+ )
218
+ .join('')}</footer>`;
113
219
 
114
220
  const pointCard = (card, i) => {
115
221
  const focused = state.focus === i ? ' is-focused' : '';
@@ -118,34 +224,55 @@ export async function mount(target, host) {
118
224
  if (card.kind === 'start') {
119
225
  return `<button class="point is-start${focused}${dim}" data-card="${i}">
120
226
  <span class="point-frame">${RESTART}</span>
121
- <span class="point-label">Desde el principio</span>
227
+ <span class="point-label">${esc(t('fromStart'))}</span>
122
228
  <span class="point-date">&nbsp;</span>
123
229
  </button>`;
124
230
  }
125
231
  const { info } = card;
126
232
  const empty = !info.savedAt;
127
- const label = card.kind === 'auto' ? 'Sin guardar' : `${card.slot + 1}`;
233
+ const label = card.kind === 'auto' ? t('unsaved') : `${card.slot + 1}`;
128
234
  return `<button class="point${card.kind === 'auto' ? ' is-auto' : ''}${empty ? ' is-empty' : ''}${info.locked ? ' is-locked' : ''}${focused}${target}${dim}" data-card="${i}">
129
235
  <span class="point-frame">${card.img ? `<img src="${card.img}" alt="">` : ''}${info.locked ? `<i class="point-lock">${LOCK}</i>` : ''}</span>
130
236
  <span class="point-label">${esc(label)}</span>
131
- <span class="point-date">${empty ? 'Vacío' : esc(when(info.savedAt))}</span>
237
+ <span class="point-date">${empty ? esc(t('empty')) : esc(when(info.savedAt))}</span>
132
238
  </button>`;
133
239
  };
134
240
 
135
241
  const pointsHints = () => {
136
- if (state.picking) return hints([['←→', 'hueco'], ['A', 'guardar aquí'], ['B', 'cancelar']]);
242
+ if (state.picking) return hints([['←→', t('slot')], ['A', t('saveHere'), 'accept'], ['B', t('cancelHint'), 'back']]);
137
243
  const card = cardAt(state.focus);
138
- const pairs = [['←→', 'elegir']];
139
- if (card?.kind === 'start' || card?.info?.savedAt) pairs.push(['A', 'jugar']);
140
- if (card?.kind === 'auto') pairs.push(['Y', 'guardar en un hueco']);
141
- if (card?.kind === 'slot' && card.info.savedAt) pairs.push(['Y', 'opciones']);
142
- pairs.push(['B', state.from === 'pause' ? 'volver' : 'salir']);
244
+ const pairs = [['←→', t('choose')]];
245
+ if (card?.kind === 'start' || card?.info?.savedAt) pairs.push(['A', t('playHint'), 'accept']);
246
+ if (card?.kind === 'auto') pairs.push(['Y', t('saveToSlot'), 'more']);
247
+ if (card?.kind === 'slot' && card.info.savedAt) pairs.push(['Y', t('options'), 'more']);
248
+ pairs.push(['B', state.from === 'pause' ? t('backHint') : t('quitHint'), 'back']);
143
249
  return hints(pairs);
144
250
  };
145
251
 
252
+ const slotCard = ({ info, img }, i, focused) => {
253
+ const empty = !info.savedAt;
254
+ return `<button class="slot${focused ? ' is-focused' : ''}${empty ? ' is-empty' : ''}${info.locked ? ' is-locked' : ''}" data-slot="${i}">
255
+ <span class="point-frame">${img ? `<img src="${img}" alt="">` : ''}${info.locked ? `<i class="point-lock">${LOCK}</i>` : ''}</span>
256
+ <span class="slot-label">${info.slot + 1}</span>
257
+ <span class="slot-date">${empty ? esc(t('empty')) : esc(when(info.savedAt))}</span>
258
+ </button>`;
259
+ };
260
+
261
+ const pauseHints = () => {
262
+ const f = state.pause.focus;
263
+ if (f.kind === 'slot') {
264
+ const saved = !!state.pause.slots[f.i]?.info.savedAt;
265
+ return hints([['←→', t('slot')], ['A', saved ? t('options') : t('saveHere')], ['B', t('continueHint')]]);
266
+ }
267
+ // Gamepad-only: by touch, "Continuar" is the first item already.
268
+ return hints([['A', t('choose')], ['B', t('continueHint')]]);
269
+ };
270
+
146
271
  const render = () => {
147
272
  if (destroyed) return;
148
273
  const s = state.screen;
274
+ wake.setActive(s === 'game' && setting('keepScreenOn') !== false);
275
+ if (s === 'settings') return;
149
276
  const base = s === 'confirm' || s === 'sheet' ? (state.confirm?.under ?? state.sheet?.under) : s;
150
277
  root.dataset.screen = base;
151
278
  if (s === 'game') {
@@ -162,9 +289,9 @@ export async function mount(target, host) {
162
289
  if (s === 'error') {
163
290
  overlay.innerHTML = `<section class="bem-panel">
164
291
  <p class="kicker">${esc(host.game?.title ?? 'BlastEm')}</p>
165
- <h2>No se pudo arrancar</h2>
292
+ <h2>${esc(t('bootFailed'))}</h2>
166
293
  <p class="text">${esc(state.error)}</p>
167
- <button class="item is-focused" data-exit>Volver</button>
294
+ <button class="item is-focused" data-exit>${esc(t('back'))}</button>
168
295
  </section>`;
169
296
  return;
170
297
  }
@@ -173,24 +300,34 @@ export async function mount(target, host) {
173
300
  html += `<section class="bem-points">
174
301
  <header>
175
302
  <p class="kicker">${esc(host.game?.title ?? '')}</p>
176
- <h2>${state.picking ? '¿En qué hueco lo guardas?' : 'Puntos de suspensión'}</h2>
303
+ <h2>${esc(state.picking ? t('whichSlot') : t('points'))}</h2>
177
304
  </header>
178
305
  <div class="points">${state.cards.map(pointCard).join('')}</div>
179
306
  ${pointsHints()}
180
307
  </section>`;
181
308
  } else if (base === 'pause') {
182
- html += `<section class="bem-panel">
309
+ const P = state.pause;
310
+ const on = (kind, i) => s === 'pause' && P.focus.kind === kind && P.focus.i === i;
311
+ const item = (i) => {
312
+ const it = P.items[i];
313
+ return `<button class="item${on('item', i) ? ' is-focused' : ''}" data-item="${i}">${esc(it.label)}${it.hint ? `<small>${esc(it.hint)}</small>` : ''}</button>`;
314
+ };
315
+ html += `<section class="bem-panel is-pause">
183
316
  <p class="kicker">${esc(host.game?.title ?? '')}</p>
184
- <h2>Pausa</h2>
185
- ${state.pause.items.map((item, i) => `<button class="item${i === state.pause.focus && s === 'pause' ? ' is-focused' : ''}" data-item="${i}">${esc(item.label)}${item.hint ? `<small>${esc(item.hint)}</small>` : ''}</button>`).join('')}
186
- ${hints([['A', 'elegir'], ['B', 'continuar']])}
317
+ <h2>${esc(t('paused'))}</h2>
318
+ ${item(0)}
319
+ <p class="slots-label">${esc(t('points'))}</p>
320
+ <div class="slots">${P.slots.map((slot, i) => slotCard(slot, i, on('slot', i))).join('')}</div>
321
+ ${P.items.slice(1).map((_, i) => item(i + 1)).join('')}
322
+ ${pauseHints()}
187
323
  </section>`;
188
324
  }
189
325
  if (s === 'sheet') {
190
326
  const sh = state.sheet;
191
327
  html += `<div class="bem-layer"><section class="bem-panel is-small">
192
- <h2>Punto ${sh.slot + 1}</h2>
328
+ <h2>${esc(t('point', { n: sh.slot + 1 }))}</h2>
193
329
  ${sh.items.map((item, i) => `<button class="item${item.danger ? ' is-danger' : ''}${i === sh.focus ? ' is-focused' : ''}" data-sheet="${i}" ${item.disabled ? 'disabled' : ''}>${esc(item.label)}${item.hint ? `<small>${esc(item.hint)}</small>` : ''}</button>`).join('')}
330
+ ${hints([['B', t('backHint')]])}
194
331
  </section></div>`;
195
332
  }
196
333
  if (s === 'confirm') {
@@ -267,21 +404,22 @@ export async function mount(target, host) {
267
404
  if (capture) frame = await play.snapshot().catch(() => null);
268
405
  play.pause(OWNER);
269
406
  state.pause = {
270
- focus: 0,
407
+ focus: { kind: 'item', i: 0 },
408
+ col: state.pause.col ?? 0,
409
+ slots: [],
271
410
  items: [
272
- { label: 'Continuar', run: enterGame },
411
+ { label: t('continue'), run: enterGame },
412
+ { label: t('restart'), hint: t('restartHint'), run: restart },
413
+ { label: t('settings'), run: openSettings },
273
414
  {
274
- label: 'Puntos de suspensión',
275
- hint: 'guarda este momento y elige dónde dejarlo',
276
- run: async () => {
277
- await suspend();
278
- showPoints('pause');
279
- },
415
+ label: t('fullscreen'),
416
+ hint: /mac|iphone|ipad/i.test(navigator.userAgentData?.platform || navigator.platform || '') ? t('fullscreenHintMac') : t('fullscreenHint'),
417
+ run: () => fullscreen.toggle(),
280
418
  },
281
- { label: 'Reiniciar', hint: 'reset de la consola', run: restart },
282
- { label: 'Volver al lanzador', hint: 'se queda un punto de suspensión', run: leave },
419
+ { label: t('exit'), hint: t('exitHint'), run: leave },
283
420
  ],
284
421
  };
422
+ readPauseSlots();
285
423
  state.screen = 'pause';
286
424
  host.input.resume();
287
425
  render();
@@ -292,13 +430,134 @@ export async function mount(target, host) {
292
430
  await play.restart();
293
431
  };
294
432
 
433
+ // ---- save states in the pause menu ---------------------------------------------
434
+
435
+ const readPauseSlots = () => {
436
+ dropUrls();
437
+ state.pause.slots = play.states.list().map((info) => ({ info, img: blobUrl(info.thumbnail) }));
438
+ };
439
+
440
+ /** The moment the menu opened (its frame was taken then) into slot row position `i`. */
441
+ const saveIntoSlot = async (i) => {
442
+ const { info } = state.pause.slots[i];
443
+ await play.states.save(info.slot, { thumbnail: frame });
444
+ readPauseSlots();
445
+ toast(t('savedIn', { n: info.slot + 1 }));
446
+ };
447
+
448
+ const loadSlot = (slot) => {
449
+ state.sheet = null;
450
+ if (!play.states.load(slot)) {
451
+ state.screen = 'pause';
452
+ return toast(t('loadFailed'));
453
+ }
454
+ enterGame();
455
+ };
456
+
457
+ /** A saved slot's sheet, from the pause menu: Cargar first and focused. */
458
+ const openSlotSheet = (i) => {
459
+ const { info } = state.pause.slots[i];
460
+ const n = info.slot + 1;
461
+ const locked = info.locked;
462
+ state.sheet = {
463
+ under: 'pause',
464
+ slot: info.slot,
465
+ focus: 0,
466
+ items: [
467
+ { label: t('load'), hint: when(info.savedAt), run: () => loadSlot(info.slot) },
468
+ {
469
+ label: t('saveHereItem'),
470
+ disabled: locked,
471
+ hint: locked ? t('unlockFirst') : t('replaces'),
472
+ run: () => {
473
+ closeSheet();
474
+ ask({
475
+ title: t('overwriteAsk', { n }),
476
+ text: when(info.savedAt),
477
+ yes: t('overwrite'),
478
+ no: t('cancel'),
479
+ onYes: () => saveIntoSlot(i),
480
+ });
481
+ },
482
+ },
483
+ {
484
+ label: locked ? t('unlock') : t('lock'),
485
+ hint: locked ? t('unlockHint') : t('lockHint'),
486
+ run: async () => {
487
+ await play.states.lock(info.slot, !locked);
488
+ closeSheet();
489
+ readPauseSlots();
490
+ render();
491
+ },
492
+ },
493
+ {
494
+ label: t('delete'),
495
+ danger: true,
496
+ disabled: locked,
497
+ hint: locked ? t('unlockFirst') : null,
498
+ run: () => {
499
+ closeSheet();
500
+ ask({
501
+ title: t('deleteAsk', { n }),
502
+ text: t('noUndo'),
503
+ yes: t('delete'),
504
+ no: t('cancel'),
505
+ onYes: async () => {
506
+ await play.states.remove(info.slot);
507
+ readPauseSlots();
508
+ render();
509
+ },
510
+ });
511
+ },
512
+ },
513
+ { label: t('cancel'), run: () => closeSheet() },
514
+ ],
515
+ };
516
+ state.screen = 'sheet';
517
+ render();
518
+ };
519
+
520
+ /** A slot chosen in the pause menu: an empty one saves at once, a saved one opens its sheet. */
521
+ const onSlot = async (i) => {
522
+ const slot = state.pause.slots[i];
523
+ if (!slot) return;
524
+ state.pause.focus = { kind: 'slot', i };
525
+ state.pause.col = i;
526
+ if (slot.info.savedAt) return openSlotSheet(i);
527
+ if (slot.info.locked) return toast(t('slotLocked'));
528
+ await saveIntoSlot(i);
529
+ };
530
+
531
+ /** Up / down between the rows, left / right along the slots. */
532
+ const onPause = async (action) => {
533
+ const P = state.pause;
534
+ // Rows: the first item, the slots, then the other items.
535
+ const PAUSE_ROWS = P.items.length + 1;
536
+ const row = P.focus.kind === 'slot' ? 1 : P.focus.i === 0 ? 0 : P.focus.i + 1;
537
+ const at = (r) => (r === 1 ? { kind: 'slot', i: P.col } : { kind: 'item', i: r === 0 ? 0 : r - 1 });
538
+ if (action === 'up') P.focus = at((row + PAUSE_ROWS - 1) % PAUSE_ROWS);
539
+ else if (action === 'down') P.focus = at((row + 1) % PAUSE_ROWS);
540
+ else if ((action === 'left' || action === 'right') && P.focus.kind === 'slot') {
541
+ P.col = Math.max(0, Math.min(P.slots.length - 1, P.focus.i + (action === 'left' ? -1 : 1)));
542
+ P.focus = { kind: 'slot', i: P.col };
543
+ } else if (action === 'accept') {
544
+ if (P.focus.kind === 'slot') return onSlot(P.focus.i);
545
+ return P.items[P.focus.i].run();
546
+ } else if (action === 'more' && P.focus.kind === 'slot') {
547
+ if (P.slots[P.focus.i]?.info.savedAt) return openSlotSheet(P.focus.i);
548
+ return;
549
+ } else if (action === 'back' || action === 'menu') return enterGame();
550
+ else return;
551
+ render();
552
+ };
553
+
295
554
  const playCard = async (card) => {
296
555
  if (card.kind === 'start') {
297
556
  if (state.started) return restart();
298
557
  return enterGame();
299
558
  }
300
559
  if (!card.info.savedAt) return;
301
- if (!play.states.load(card.slot)) return toast('No se pudo cargar ese punto');
560
+ if (!play.states.load(card.slot)) return toast(t('loadFailed'));
302
561
  enterGame();
303
562
  };
304
563
 
@@ -310,14 +569,14 @@ export async function mount(target, host) {
310
569
  readPoints();
311
570
  state.picking = false;
312
571
  state.focus = state.cards.findIndex((c) => c.kind === 'slot' && c.slot === card.slot);
313
- toast(`Guardado en el hueco ${card.slot + 1}`);
572
+ toast(t('savedIn', { n: card.slot + 1 }));
314
573
  };
315
574
 
316
575
  const saveAuto = async () => {
317
576
  const free = freeSlot();
318
577
  if (free >= 0) return saveAutoInto(free);
319
578
  const target = state.cards.findIndex((c) => c.kind === 'slot' && !c.info.locked);
320
- if (target < 0) return toast('Los cuatro huecos están bloqueados');
579
+ if (target < 0) return toast(t('allLocked'));
321
580
  state.picking = true;
322
581
  state.focus = target;
323
582
  render();
@@ -331,8 +590,8 @@ export async function mount(target, host) {
331
590
  focus: 0,
332
591
  items: [
333
592
  {
334
- label: locked ? 'Desbloquear' : 'Bloquear',
335
- hint: locked ? 'se podrá sobrescribir y borrar' : 'que no se sobrescriba ni se borre',
593
+ label: locked ? t('unlock') : t('lock'),
594
+ hint: locked ? t('unlockHint') : t('lockHint'),
336
595
  run: async () => {
337
596
  await play.states.lock(card.slot, !locked);
338
597
  closeSheet();
@@ -341,17 +600,17 @@ export async function mount(target, host) {
341
600
  },
342
601
  },
343
602
  {
344
- label: 'Borrar',
603
+ label: t('delete'),
345
604
  danger: true,
346
605
  disabled: locked,
347
- hint: locked ? 'desbloquéalo antes' : null,
606
+ hint: locked ? t('unlockFirst') : null,
348
607
  run: () => {
349
608
  closeSheet();
350
609
  ask({
351
- title: `¿Borrar el punto ${card.slot + 1}?`,
352
- text: 'No se puede deshacer.',
353
- yes: 'Borrar',
354
- no: 'Cancelar',
610
+ title: t('deleteAsk', { n: card.slot + 1 }),
611
+ text: t('noUndo'),
612
+ yes: t('delete'),
613
+ no: t('cancel'),
355
614
  onYes: async () => {
356
615
  await play.states.remove(card.slot);
357
616
  readPoints();
@@ -360,7 +619,7 @@ export async function mount(target, host) {
360
619
  });
361
620
  },
362
621
  },
363
- { label: 'Cancelar', run: () => closeSheet() },
622
+ { label: t('cancel'), run: () => closeSheet() },
364
623
  ],
365
624
  };
366
625
  state.screen = 'sheet';
@@ -400,13 +659,92 @@ export async function mount(target, host) {
400
659
  /** Leaving from a running game keeps it as the unsaved suspend point. */
401
660
  const leave = async () => {
402
661
  if (leaving) return;
403
- state.status = 'Guardando el punto de suspensión…';
662
+ state.status = t('saving');
404
663
  state.screen = 'boot';
405
664
  render();
406
665
  await suspend();
407
666
  await exit();
408
667
  };
409
668
 
669
+ // ---- settings, fullscreen, performance (engine-specs 0.6) -----------------------
670
+
671
+ // The player's choices, per engine (OPFS settings/mgba.json): BlastEm's options, the shared
672
+ // ones (keep the screen on, show performance) and the controls.
673
+ let saved = { version: 1, values: {}, controls: {} };
674
+ const setting = (key) => (key in saved.values ? saved.values[key] : SHARED_SETTINGS[key]?.default);
675
+ const store = () => saveSettings(ENGINE_ID, saved).catch((error) => console.warn('[blastem app] settings not saved', error));
676
+ const engineValues = () =>
677
+ Object.fromEntries(Object.entries(saved.values).filter(([key]) => !(key in SHARED_SETTINGS)));
678
+
679
+ const fullscreen = createFullscreenToggle(root);
680
+ const wake = createWakeLock();
681
+ const perf = createPerfCounter(root, { locale });
682
+ let offFrames = () => {};
683
+ const applyShared = () => {
684
+ if (setting('showPerformance')) perf.show();
685
+ else perf.hide();
686
+ wake.setActive(state.screen === 'game' && setting('keepScreenOn') !== false);
687
+ };
688
+
689
+ let screen = null;
690
+ // BlastEm's settings are in its config (smoothing, region), not its options.
691
+ let configKeys = new Set();
692
+ const described = async () => {
693
+ const config = await play.config();
694
+ configKeys = new Set(Object.keys(config));
695
+ return { ...config, ...(await play.options()), ...SHARED_SETTINGS };
696
+ };
697
+ const write = (values) => {
698
+ const config = Object.fromEntries(Object.entries(values).filter(([key]) => configKeys.has(key)));
699
+ const options = Object.fromEntries(Object.entries(values).filter(([key]) => !configKeys.has(key)));
700
+ if (Object.keys(config).length) play.config(config);
701
+ if (Object.keys(options).length) play.options(options);
702
+ };
703
+ const controlRows = () => controlsModel(BUTTONS, DEFAULT_CONTROLS, saved.controls, locale);
704
+
705
+ const openSettings = async () => {
706
+ const all = await described();
707
+ const model = () => settingsModel(all, saved.values, locale);
708
+ state.screen = 'settings';
709
+ render();
710
+ overlay.innerHTML = '';
711
+ const layer = document.createElement('div');
712
+ layer.className = 'bem-layer bem-settings';
713
+ overlay.append(layer);
714
+ screen = createSettingsScreen(layer, {
715
+ sections: model(),
716
+ controls: controlRows(),
717
+ input: host.input,
718
+ locale,
719
+ onChange(key, value) {
720
+ saved.values = { ...saved.values, [key]: value };
721
+ // BlastEm's own options go to the engine: a live one applies now, the rest on Reiniciar.
722
+ if (key in SHARED_SETTINGS) applyShared();
723
+ else write({ [key]: value });
724
+ void store();
725
+ },
726
+ onControl(_id, _binding, bindings) {
727
+ saved.controls = bindings;
728
+ play.setControls(toBlastemControls(bindings));
729
+ void store();
730
+ },
731
+ onReset() {
732
+ const defaults = settingsDefaults(all);
733
+ saved = { version: 1, values: {}, controls: {} };
734
+ write(Object.fromEntries(Object.entries(defaults).filter(([key]) => !(key in SHARED_SETTINGS))));
735
+ play.setControls({});
736
+ applyShared();
737
+ void store();
738
+ screen.update(settingsModel(all, defaults, locale), controlRows());
739
+ },
740
+ onClose: () => {
741
+ screen?.destroy();
742
+ screen = null;
743
+ void openPause();
744
+ },
745
+ });
746
+ };
747
+
410
748
  // ---- input ----------------------------------------------------------------------
411
749
 
412
750
  const onPoints = (action) => {
@@ -424,10 +762,10 @@ export async function mount(target, host) {
424
762
  if (!state.picking) return playCard(card);
425
763
  if (!card.info.savedAt) return saveAutoInto(state.focus);
426
764
  return ask({
427
- title: `¿Sobrescribir el punto ${card.slot + 1}?`,
765
+ title: t('overwriteAsk', { n: card.slot + 1 }),
428
766
  text: when(card.info.savedAt),
429
- yes: 'Sobrescribir',
430
- no: 'Cancelar',
767
+ yes: t('overwrite'),
768
+ no: t('cancel'),
431
769
  onYes: () => saveAutoInto(state.focus),
432
770
  });
433
771
  } else if (action === 'more' && !state.picking) {
@@ -440,7 +778,7 @@ export async function mount(target, host) {
440
778
  state.focus = state.cards.findIndex((c) => c.kind === 'auto');
441
779
  } else if (state.from === 'pause') return openPause();
442
780
  else
443
- return ask({ title: '¿Volver al lanzador?', yes: 'Salir', no: 'Seguir', onYes: exit });
781
+ return ask({ title: t('leaveAsk'), yes: t('leave'), no: t('stay'), onYes: exit });
444
782
  } else return;
445
783
  render();
446
784
  };
@@ -469,15 +807,16 @@ export async function mount(target, host) {
469
807
  };
470
808
 
471
809
  let busy = false;
472
- const off = host.input.on(async (action) => {
810
+ const onAction = async (action) => {
473
811
  if (leaving || busy) return;
474
812
  busy = true;
475
813
  try {
476
814
  const s = state.screen;
815
+ if (s === 'settings') return;
477
816
  if (s === 'game') {
478
817
  if (action === 'menu') await openPause({ capture: true });
479
818
  } else if (s === 'points') await onPoints(action);
480
- else if (s === 'pause') await onList(state.pause, action, enterGame);
819
+ else if (s === 'pause') await onPause(action);
481
820
  else if (s === 'sheet') await onList(state.sheet, action, closeSheet);
482
821
  else if (s === 'confirm') await onConfirm(action);
483
822
  else if (s === 'error' && (action === 'accept' || action === 'back')) await exit();
@@ -487,18 +826,38 @@ export async function mount(target, host) {
487
826
  } finally {
488
827
  busy = false;
489
828
  }
490
- });
829
+ };
830
+ const off = host.input.on(onAction);
491
831
 
492
832
  // Pointer: hover (real movement only — a render replaces what is under a resting
493
833
  // cursor) focuses, click activates; the same paths as the pad.
494
834
  let lastPointer = '';
495
835
  const onPointer = async (event) => {
496
- const el = event.target.closest('[data-card],[data-item],[data-sheet],[data-confirm],[data-exit]');
836
+ if (event.type === 'click' && longPressed) {
837
+ // The lift after a long press: the press already did its job.
838
+ longPressed = false;
839
+ return;
840
+ }
841
+ const el = event.target.closest('[data-card],[data-item],[data-slot],[data-sheet],[data-confirm],[data-exit],[data-act]');
497
842
  if (!el || leaving || busy) return;
843
+ if (el.dataset.act != null) {
844
+ if (event.type === 'click') await onAction(el.dataset.act);
845
+ return;
846
+ }
498
847
  if (event.type === 'pointermove') {
499
848
  const at = `${event.clientX},${event.clientY}`;
500
849
  if (at === lastPointer) return;
501
850
  lastPointer = at;
851
+ if (state.screen === 'pause' && (el.dataset.item != null || el.dataset.slot != null)) {
852
+ const focus = el.dataset.slot != null ? { kind: 'slot', i: +el.dataset.slot } : { kind: 'item', i: +el.dataset.item };
853
+ const P = state.pause;
854
+ if (P.focus.kind !== focus.kind || P.focus.i !== focus.i) {
855
+ P.focus = focus;
856
+ if (focus.kind === 'slot') P.col = focus.i;
857
+ render();
858
+ }
859
+ return;
860
+ }
502
861
  const key = el.dataset.card ?? el.dataset.item ?? el.dataset.sheet;
503
862
  if (key == null) return;
504
863
  const list = el.dataset.card != null ? state : el.dataset.item != null ? state.pause : state.sheet;
@@ -516,6 +875,7 @@ export async function mount(target, host) {
516
875
  return onPoints('accept');
517
876
  }
518
877
  if (el.dataset.item != null) await state.pause.items[+el.dataset.item].run();
878
+ else if (el.dataset.slot != null) await onSlot(+el.dataset.slot);
519
879
  else if (el.dataset.sheet != null) {
520
880
  const item = state.sheet.items[+el.dataset.sheet];
521
881
  if (!item.disabled) await item.run();
@@ -528,6 +888,45 @@ export async function mount(target, host) {
528
888
  overlay.addEventListener('click', onPointer);
529
889
  overlay.addEventListener('pointermove', onPointer);
530
890
 
891
+ // Touch: a long press on a card focuses it and does what Y does (save the unsaved point
892
+ // into a slot; a saved point's options) — a tap would play it.
893
+ const LONG_PRESS_MS = 500;
894
+ let longPressed = false;
895
+ let press = null;
896
+ const cancelPress = () => {
897
+ if (press) clearTimeout(press.timer);
898
+ press = null;
899
+ };
900
+ const onPressDown = (event) => {
901
+ cancelPress();
902
+ longPressed = false;
903
+ if (event.pointerType === 'mouse') return;
904
+ const el = event.target.closest('[data-card]');
905
+ if (!el || state.screen !== 'points') return;
906
+ const index = +el.dataset.card;
907
+ press = {
908
+ x: event.clientX,
909
+ y: event.clientY,
910
+ timer: setTimeout(async () => {
911
+ press = null;
912
+ longPressed = true;
913
+ if (leaving || busy || state.screen !== 'points') return;
914
+ state.focus = index;
915
+ render();
916
+ await onAction('more');
917
+ }, LONG_PRESS_MS),
918
+ };
919
+ };
920
+ const onPressMove = (event) => {
921
+ if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) > 12) cancelPress();
922
+ };
923
+ const noMenu = (event) => event.preventDefault();
924
+ overlay.addEventListener('pointerdown', onPressDown);
925
+ overlay.addEventListener('pointermove', onPressMove);
926
+ overlay.addEventListener('pointerup', cancelPress);
927
+ overlay.addEventListener('pointercancel', cancelPress);
928
+ overlay.addEventListener('contextmenu', noMenu);
929
+
531
930
  const handle = {
532
931
  async unmount() {
533
932
  destroyed = true;
@@ -536,6 +935,12 @@ export async function mount(target, host) {
536
935
  clearTimeout(toastTimer);
537
936
  overlay.removeEventListener('click', onPointer);
538
937
  overlay.removeEventListener('pointermove', onPointer);
938
+ cancelPress();
939
+ overlay.removeEventListener('pointerdown', onPressDown);
940
+ overlay.removeEventListener('pointermove', onPressMove);
941
+ overlay.removeEventListener('pointerup', cancelPress);
942
+ overlay.removeEventListener('pointercancel', cancelPress);
943
+ overlay.removeEventListener('contextmenu', noMenu);
539
944
  try {
540
945
  await play?.destroy();
541
946
  } catch {
@@ -543,6 +948,11 @@ export async function mount(target, host) {
543
948
  }
544
949
  play = null;
545
950
  dropUrls();
951
+ screen?.destroy();
952
+ offFrames();
953
+ fullscreen.destroy();
954
+ wake.destroy();
955
+ perf.destroy();
546
956
  root.remove();
547
957
  },
548
958
  };
@@ -552,10 +962,13 @@ export async function mount(target, host) {
552
962
  render();
553
963
  host.input.resume();
554
964
  try {
965
+ saved = await loadSettings(ENGINE_ID);
555
966
  play = await new BlastemSDK()
556
967
  .mount(stage)
557
968
  .assets(host.assets)
558
969
  .storage(host.storage)
970
+ // The saved smoothing and region: BlastEm's config.
971
+ .config(engineValues())
559
972
  .on('error', ({ detail }) => console.error('[blastem app]', detail))
560
973
  .on('exit', () => exit())
561
974
  .start();
@@ -564,6 +977,9 @@ export async function mount(target, host) {
564
977
  play = null;
565
978
  return handle;
566
979
  }
980
+ play.setControls(toBlastemControls({ ...DEFAULT_CONTROLS, ...saved.controls }));
981
+ // BlastEm's loop runs inside the WASM and reports no frames: the counter counts the display's.
982
+ applyShared();
567
983
  readPoints();
568
984
  if (hasPoints()) showPoints('boot');
569
985
  else enterGame();