@textadventures/quest-viva-wasmplayer 6.0.4 → 6.1.0-beta.2

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 (156) hide show
  1. package/_framework/Common.wasm +0 -0
  2. package/_framework/Engine.wasm +0 -0
  3. package/_framework/ExtendedNumerics.BigDecimal.wasm +0 -0
  4. package/_framework/Legacy.wasm +0 -0
  5. package/_framework/Microsoft.Extensions.Logging.Abstractions.wasm +0 -0
  6. package/_framework/Microsoft.VisualBasic.Core.wasm +0 -0
  7. package/_framework/NCalc.Core.wasm +0 -0
  8. package/_framework/NCalc.Domain.wasm +0 -0
  9. package/_framework/NCalc.Parser.wasm +0 -0
  10. package/_framework/Parlot.wasm +0 -0
  11. package/_framework/PlayerCore.wasm +0 -0
  12. package/_framework/System.Collections.Immutable.wasm +0 -0
  13. package/_framework/System.Collections.NonGeneric.wasm +0 -0
  14. package/_framework/System.Collections.Specialized.wasm +0 -0
  15. package/_framework/System.Collections.wasm +0 -0
  16. package/_framework/System.ComponentModel.Annotations.wasm +0 -0
  17. package/_framework/System.ComponentModel.Primitives.wasm +0 -0
  18. package/_framework/System.ComponentModel.TypeConverter.wasm +0 -0
  19. package/_framework/System.ComponentModel.wasm +0 -0
  20. package/_framework/System.IO.Compression.wasm +0 -0
  21. package/_framework/System.IO.Pipelines.wasm +0 -0
  22. package/_framework/System.Linq.Expressions.wasm +0 -0
  23. package/_framework/System.Linq.wasm +0 -0
  24. package/_framework/System.Memory.wasm +0 -0
  25. package/_framework/System.Net.Http.wasm +0 -0
  26. package/_framework/System.Net.Primitives.wasm +0 -0
  27. package/_framework/System.ObjectModel.wasm +0 -0
  28. package/_framework/System.Private.CoreLib.wasm +0 -0
  29. package/_framework/System.Private.Uri.wasm +0 -0
  30. package/_framework/System.Private.Xml.Linq.wasm +0 -0
  31. package/_framework/System.Private.Xml.wasm +0 -0
  32. package/_framework/System.Runtime.InteropServices.JavaScript.wasm +0 -0
  33. package/_framework/System.Runtime.Numerics.wasm +0 -0
  34. package/_framework/System.Security.Cryptography.wasm +0 -0
  35. package/_framework/System.Text.Encoding.CodePages.wasm +0 -0
  36. package/_framework/System.Text.Encodings.Web.wasm +0 -0
  37. package/_framework/System.Text.Json.wasm +0 -0
  38. package/_framework/System.Text.RegularExpressions.wasm +0 -0
  39. package/_framework/System.Xml.Linq.wasm +0 -0
  40. package/_framework/System.wasm +0 -0
  41. package/_framework/WasmPlayer.wasm +0 -0
  42. package/_framework/dotnet.js +328 -2
  43. package/_framework/dotnet.native.js +1919 -2049
  44. package/_framework/dotnet.native.wasm +0 -0
  45. package/_framework/dotnet.runtime.js +1 -1
  46. package/_framework/icudt_CJK.dat +0 -0
  47. package/_framework/icudt_EFIGS.dat +0 -0
  48. package/_framework/icudt_no_CJK.dat +0 -0
  49. package/chrome.css +20 -2
  50. package/export-manifest.json +1 -1
  51. package/fonts/courier-prime/LICENSE.txt +93 -0
  52. package/fonts/courier-prime/latin-400-italic.woff2 +0 -0
  53. package/fonts/courier-prime/latin-400-normal.woff2 +0 -0
  54. package/fonts/courier-prime/latin-700-italic.woff2 +0 -0
  55. package/fonts/courier-prime/latin-700-normal.woff2 +0 -0
  56. package/fonts/courier-prime/latin-ext-400-italic.woff2 +0 -0
  57. package/fonts/courier-prime/latin-ext-400-normal.woff2 +0 -0
  58. package/fonts/courier-prime/latin-ext-700-italic.woff2 +0 -0
  59. package/fonts/courier-prime/latin-ext-700-normal.woff2 +0 -0
  60. package/fonts/fonts.css +500 -0
  61. package/fonts/literata/LICENSE.txt +93 -0
  62. package/fonts/literata/cyrillic-400-italic.woff2 +0 -0
  63. package/fonts/literata/cyrillic-400-normal.woff2 +0 -0
  64. package/fonts/literata/cyrillic-700-italic.woff2 +0 -0
  65. package/fonts/literata/cyrillic-700-normal.woff2 +0 -0
  66. package/fonts/literata/cyrillic-ext-400-italic.woff2 +0 -0
  67. package/fonts/literata/cyrillic-ext-400-normal.woff2 +0 -0
  68. package/fonts/literata/cyrillic-ext-700-italic.woff2 +0 -0
  69. package/fonts/literata/cyrillic-ext-700-normal.woff2 +0 -0
  70. package/fonts/literata/greek-400-italic.woff2 +0 -0
  71. package/fonts/literata/greek-400-normal.woff2 +0 -0
  72. package/fonts/literata/greek-700-italic.woff2 +0 -0
  73. package/fonts/literata/greek-700-normal.woff2 +0 -0
  74. package/fonts/literata/greek-ext-400-italic.woff2 +0 -0
  75. package/fonts/literata/greek-ext-400-normal.woff2 +0 -0
  76. package/fonts/literata/greek-ext-700-italic.woff2 +0 -0
  77. package/fonts/literata/greek-ext-700-normal.woff2 +0 -0
  78. package/fonts/literata/latin-400-italic.woff2 +0 -0
  79. package/fonts/literata/latin-400-normal.woff2 +0 -0
  80. package/fonts/literata/latin-700-italic.woff2 +0 -0
  81. package/fonts/literata/latin-700-normal.woff2 +0 -0
  82. package/fonts/literata/latin-ext-400-italic.woff2 +0 -0
  83. package/fonts/literata/latin-ext-400-normal.woff2 +0 -0
  84. package/fonts/literata/latin-ext-700-italic.woff2 +0 -0
  85. package/fonts/literata/latin-ext-700-normal.woff2 +0 -0
  86. package/fonts/literata/vietnamese-400-italic.woff2 +0 -0
  87. package/fonts/literata/vietnamese-400-normal.woff2 +0 -0
  88. package/fonts/literata/vietnamese-700-italic.woff2 +0 -0
  89. package/fonts/literata/vietnamese-700-normal.woff2 +0 -0
  90. package/fonts/nunito/LICENSE.txt +93 -0
  91. package/fonts/nunito/cyrillic-400-italic.woff2 +0 -0
  92. package/fonts/nunito/cyrillic-400-normal.woff2 +0 -0
  93. package/fonts/nunito/cyrillic-700-italic.woff2 +0 -0
  94. package/fonts/nunito/cyrillic-700-normal.woff2 +0 -0
  95. package/fonts/nunito/cyrillic-ext-400-italic.woff2 +0 -0
  96. package/fonts/nunito/cyrillic-ext-400-normal.woff2 +0 -0
  97. package/fonts/nunito/cyrillic-ext-700-italic.woff2 +0 -0
  98. package/fonts/nunito/cyrillic-ext-700-normal.woff2 +0 -0
  99. package/fonts/nunito/latin-400-italic.woff2 +0 -0
  100. package/fonts/nunito/latin-400-normal.woff2 +0 -0
  101. package/fonts/nunito/latin-700-italic.woff2 +0 -0
  102. package/fonts/nunito/latin-700-normal.woff2 +0 -0
  103. package/fonts/nunito/latin-ext-400-italic.woff2 +0 -0
  104. package/fonts/nunito/latin-ext-400-normal.woff2 +0 -0
  105. package/fonts/nunito/latin-ext-700-italic.woff2 +0 -0
  106. package/fonts/nunito/latin-ext-700-normal.woff2 +0 -0
  107. package/fonts/nunito/vietnamese-400-italic.woff2 +0 -0
  108. package/fonts/nunito/vietnamese-400-normal.woff2 +0 -0
  109. package/fonts/nunito/vietnamese-700-italic.woff2 +0 -0
  110. package/fonts/nunito/vietnamese-700-normal.woff2 +0 -0
  111. package/fonts/special-elite/LICENSE.txt +201 -0
  112. package/fonts/special-elite/latin-400-normal.woff2 +0 -0
  113. package/fonts/special-elite/latin-ext-400-normal.woff2 +0 -0
  114. package/fonts/vt323/LICENSE.txt +93 -0
  115. package/fonts/vt323/latin-400-normal.woff2 +0 -0
  116. package/fonts/vt323/latin-ext-400-normal.woff2 +0 -0
  117. package/fonts/vt323/vietnamese-400-normal.woff2 +0 -0
  118. package/game-saver.js +211 -0
  119. package/index.html +140 -52
  120. package/legacy/adapter.js +107 -0
  121. package/{grid.js → legacy/grid.js} +3 -0
  122. package/{player.js → legacy/player.js} +37 -62
  123. package/{playercore.css → legacy/playercore.css} +115 -0
  124. package/{playercore.htm → legacy/playercore.htm} +14 -13
  125. package/{playercore.js → legacy/playercore.js} +188 -252
  126. package/legacy/questui.js +515 -0
  127. package/package.json +1 -1
  128. package/v2/map.js +1 -0
  129. package/v2/player.htm +59 -0
  130. package/v2/v2.css +1 -0
  131. package/v2/v2.js +1 -0
  132. package/wasm-player.js +1359 -284
  133. package/.stamp +0 -0
  134. package/WasmPlayer.runtimeconfig.json +0 -46
  135. package/_framework/System.Collections.Concurrent.wasm +0 -0
  136. package/_framework/dotnet.boot.js +0 -284
  137. /package/{lib → legacy/lib}/images/ui-bg_flat_0_aaaaaa_40x100.png +0 -0
  138. /package/{lib → legacy/lib}/images/ui-bg_flat_55_fbec88_40x100.png +0 -0
  139. /package/{lib → legacy/lib}/images/ui-bg_glass_75_d0e5f5_1x400.png +0 -0
  140. /package/{lib → legacy/lib}/images/ui-bg_glass_85_dfeffc_1x400.png +0 -0
  141. /package/{lib → legacy/lib}/images/ui-bg_glass_95_fef1ec_1x400.png +0 -0
  142. /package/{lib → legacy/lib}/images/ui-bg_gloss-wave_55_5c9ccc_500x100.png +0 -0
  143. /package/{lib → legacy/lib}/images/ui-bg_inset-hard_100_f5f8f9_1x100.png +0 -0
  144. /package/{lib → legacy/lib}/images/ui-bg_inset-hard_100_fcfdfd_1x100.png +0 -0
  145. /package/{lib → legacy/lib}/images/ui-icons_217bc0_256x240.png +0 -0
  146. /package/{lib → legacy/lib}/images/ui-icons_2e83ff_256x240.png +0 -0
  147. /package/{lib → legacy/lib}/images/ui-icons_469bdd_256x240.png +0 -0
  148. /package/{lib → legacy/lib}/images/ui-icons_6da8d5_256x240.png +0 -0
  149. /package/{lib → legacy/lib}/images/ui-icons_cd0a0a_256x240.png +0 -0
  150. /package/{lib → legacy/lib}/images/ui-icons_d8e7f3_256x240.png +0 -0
  151. /package/{lib → legacy/lib}/images/ui-icons_f9bd01_256x240.png +0 -0
  152. /package/{lib → legacy/lib}/jquery-2.1.1.min.js +0 -0
  153. /package/{lib → legacy/lib}/jquery-ui.min.css +0 -0
  154. /package/{lib → legacy/lib}/jquery-ui.min.js +0 -0
  155. /package/{lib → legacy/lib}/jquery.multi-open-accordion-1.5.3.js +0 -0
  156. /package/{lib → legacy/lib}/paper.js +0 -0
package/wasm-player.js CHANGED
@@ -1,9 +1,10 @@
1
- // WasmPlayer JS bootstrap — replaces playerweb.js for the WASM-hosted player.
1
+ // WasmPlayer JS bootstrap.
2
2
  // Defines the WebPlayer object surface that playercore.js / player.js call into,
3
3
  // then initialises the .NET WASM runtime and wires up [JSImport] callbacks.
4
4
 
5
5
  // Printed as soon as this script runs (i.e. as the start screen appears) —
6
- // window.QuestVivaVersion comes from the repo-root VERSION file, spliced in
6
+ // window.QuestVivaVersion comes from the repo-root VERSION file (or a manual
7
+ // deploy's build version, see deploy-play.yml), spliced in
7
8
  // at build time by scripts/inject-version.mjs, so this doesn't need to wait
8
9
  // for the WASM runtime to boot (which only happens once a game loads).
9
10
  console.log(
@@ -18,7 +19,7 @@ console.log(
18
19
  // used below to build an absolute URL for the dynamic `import()` of
19
20
  // dotnet.js. A relative specifier there (`import('./_framework/dotnet.js')`)
20
21
  // works when this script is same-origin, but when it's loaded cross-origin
21
- // (the single-file CDN-linked export, see scripts/export-embedded.mjs)
22
+ // (the single-file CDN-linked export, see PlayerExport in src/PlayerCore)
22
23
  // Chromium has no usable base URL for a relative dynamic import from a
23
24
  // classic (non-module) cross-origin script and fails the whole import with
24
25
  // "The base URL is about:blank because import() is called from a
@@ -36,8 +37,8 @@ const wasmPlayerScriptUrl = document.currentScript?.src;
36
37
  //
37
38
  // For _framework/ specifically the version is also what makes `immutable`
38
39
  // *safe*. None of those filenames are content-hashed and the build output isn't
39
- // byte-reproducible, so a browser holding dotnet.boot.js (the manifest of
40
- // per-file SHA-256 hashes) from one deploy alongside a binary from the next
40
+ // byte-reproducible, so a browser holding the boot manifest of per-file
41
+ // SHA-256 hashes (inlined into dotnet.js) from one deploy alongside a binary from the next
41
42
  // gets an SRI mismatch and the resource is blocked. Stamping manifest and
42
43
  // binaries with the same version means they can never come from different
43
44
  // deploys — which is what the blanket `Cache-Control: no-cache` on
@@ -51,6 +52,62 @@ const versioned = (url) => (assetVersionQuery && !url.includes('?') ? url + asse
51
52
 
52
53
  var _audio = null;
53
54
 
55
+ // Browsers refuse to play sound on a page nobody has clicked or typed in yet. Every play() on a
56
+ // media element is watched - Play a sound's, and any a game's own <audio> or JavaScript makes -
57
+ // and one refused that way is kept, then played on the player's first click or keypress: the
58
+ // Begin card's (see beginBehindStartScreen) if the game's start played it, or their first
59
+ // command's if a timer played it later. Without this a synchronous sound would never end, and
60
+ // the game would never resume.
61
+ const blockedMedia = new Set();
62
+ let beginShowing = false;
63
+ let startupPlays = null; // play() attempts made while the game's start runs, or null after it
64
+ const nativePlay = HTMLMediaElement.prototype.play;
65
+ const nativePause = HTMLMediaElement.prototype.pause;
66
+ HTMLMediaElement.prototype.play = function () {
67
+ const result = nativePlay.call(this);
68
+ const refused = Promise.resolve(result).then(() => false, (err) => {
69
+ if (err?.name !== 'NotAllowedError') return false;
70
+ blockedMedia.add(this);
71
+ // While Begin shows, only Begin plays them (see beginBehindStartScreen).
72
+ if (!beginShowing) {
73
+ document.addEventListener('pointerdown', playBlockedMedia, { capture: true, once: true });
74
+ document.addEventListener('keydown', playBlockedMedia, { capture: true, once: true });
75
+ }
76
+ return true;
77
+ });
78
+ startupPlays?.push(refused);
79
+ return result;
80
+ };
81
+ HTMLMediaElement.prototype.pause = function () {
82
+ blockedMedia.delete(this);
83
+ return nativePause.call(this);
84
+ };
85
+
86
+ // Game time stands still while the game's start runs behind the start screen, and while Begin is
87
+ // showing, so timers and an intro's pauses start when the player first sees the game, not part
88
+ // way through. Holds the engine's requests to start the clock (requestNextTimerTick) and to pause.
89
+ let heldClockCalls = null; // null while the clock runs
90
+ function whenClockRuns(call) {
91
+ if (heldClockCalls) heldClockCalls.push(call);
92
+ else call();
93
+ }
94
+ function holdClock() {
95
+ heldClockCalls ??= [];
96
+ }
97
+ function releaseClock() {
98
+ const calls = heldClockCalls ?? [];
99
+ heldClockCalls = null;
100
+ for (const call of calls) call();
101
+ }
102
+
103
+ function playBlockedMedia() {
104
+ document.removeEventListener('pointerdown', playBlockedMedia, { capture: true });
105
+ document.removeEventListener('keydown', playBlockedMedia, { capture: true });
106
+ const media = [...blockedMedia];
107
+ blockedMedia.clear();
108
+ for (const element of media) element.play().catch(() => {});
109
+ }
110
+
54
111
  const pendingResources = new Map();
55
112
  let editorChannel = null;
56
113
  let resourceRoot = null;
@@ -75,7 +132,25 @@ let walkthroughStatusMode = null; // null | 'replay' | 'record' | 'play'
75
132
  let recordWalkthroughName = null;
76
133
  let recordedSteps = [];
77
134
 
135
+ // Every input the player has given since the game started or was loaded, as walkthrough steps,
136
+ // for the Save/Load dialog's "Copy for a bug report" (see buildBugReport). Unlike recordedSteps
137
+ // this is always kept, and starts again with each game (resetBugReportSteps).
138
+ let bugReportSteps = [];
139
+ let bugReportFromSave = false;
140
+
141
+ // How many inputs the player has given since the game was last saved, loaded or started: when
142
+ // there are some, the Save/Load dialog checks before loading a save or starting again.
143
+ let stepsSinceSave = 0;
144
+
145
+ function resetBugReportSteps(fromSave) {
146
+ bugReportSteps = [];
147
+ bugReportFromSave = fromSave;
148
+ stepsSinceSave = 0;
149
+ }
150
+
78
151
  function recordStep(step) {
152
+ bugReportSteps.push(step);
153
+ stepsSinceSave++;
79
154
  if (walkthroughStatusMode !== 'record') return;
80
155
  recordedSteps.push(step);
81
156
  updateWalkthroughStatusUi();
@@ -189,11 +264,19 @@ let originalGameFilename = null;
189
264
  // alike), since WasmPlayerBridge's own pending-file dictionary is consumed and cleared on
190
265
  // each load.
191
266
  let originalAdjacentFiles = null;
192
- // The pristine player chrome markup (playercore.htm), fetched once at boot
193
- // and reused verbatim by restartGame() so a mid-session restart gets exactly
194
- // the same clean slate as the initial boot, instead of the previous game's
195
- // live DOM (see swapInPlayerUi()).
196
- let originalPlayerHtml = null;
267
+ // The player UI the game is playing on (see preparePlayerUi): its adapter, which the host
268
+ // calls for everything that's UI behaviour, and its pristine markup, swapped in afresh for
269
+ // each game and restart so a restart gets exactly the same clean slate as the initial boot,
270
+ // instead of the previous game's live DOM (see swapInPlayerUi()).
271
+ let playerUi = null;
272
+ let playerUiHtml = null;
273
+ // The start screen, kept on top of the freshly swapped-in UI until the game has started.
274
+ let bootStartScreenEl = null;
275
+ // Set by restartGameCore, so preparePlayerUi also clears the output state the UI keeps
276
+ // outside its markup.
277
+ let restartingPlayerUi = false;
278
+ // ?clock=manual (a test hook): see preparePlayerUi.
279
+ let manualClock = false;
197
280
 
198
281
  function computeGameId(filename) {
199
282
  return filename.split('/').pop();
@@ -232,7 +315,7 @@ function preloadImageSize(url) {
232
315
  img.onload = () => {
233
316
  window.clearTimeout(timeoutId);
234
317
  if (img.naturalWidth && img.naturalHeight) {
235
- rememberImageSize(url, img.naturalWidth, img.naturalHeight);
318
+ playerUi.rememberImageSize(url, img.naturalWidth, img.naturalHeight);
236
319
  }
237
320
  resolve();
238
321
  };
@@ -295,7 +378,20 @@ function sendEndWait() {
295
378
  // next stopping point and flushed its UI calls, so by now
296
379
  // beginWait() has already run for a chained wait() - which is
297
380
  // exactly what waitEnded() checks before restoring the input.
298
- waitEnded();
381
+ playerUi.waitEnded();
382
+ }
383
+ }, 100);
384
+ }
385
+
386
+ function sendEndPause() {
387
+ // Same short paint-yield as sendEndWait() above.
388
+ window.setTimeout(async function () {
389
+ try {
390
+ await WebPlayer.uiEndPause();
391
+ } finally {
392
+ // Like uiEndWait, uiEndPause only resolves once the resumed turn
393
+ // has reached its next stopping point - see pauseEnded().
394
+ playerUi.pauseEnded();
299
395
  }
300
396
  }, 100);
301
397
  }
@@ -307,15 +403,10 @@ function playSound(url, synchronous, looped) {
307
403
  _audio = new Audio(url);
308
404
  if (looped) _audio.loop = true;
309
405
  if (synchronous) {
310
- // Counts a pause whose restore is still pending as visible - see
311
- // _pauseRestorePending, otherwise finishSync() below leaves the command
312
- // bar hidden for good.
313
- var showCmdDiv = isElementVisible("#txtCommandDiv") || _pauseRestorePending;
314
- _waitingForSoundToFinish = true;
315
- $("#txtCommandDiv").hide();
316
- _audio.addEventListener('ended', function () { finishSync(showCmdDiv); });
406
+ const showCommandBar = playerUi.beginSoundWait();
407
+ _audio.addEventListener('ended', function () { playerUi.endSoundWait(showCommandBar); });
317
408
  }
318
- _audio.play();
409
+ _audio.play().catch(() => {});
319
410
  }
320
411
 
321
412
  function stopSound() {
@@ -326,33 +417,6 @@ function stopSound() {
326
417
  }
327
418
  }
328
419
 
329
- function finishSync(showCommandDiv) {
330
- _waitingForSoundToFinish = false;
331
- window.setTimeout(async function () {
332
- if (showCommandDiv) $("#txtCommandDiv").show();
333
- await WebPlayer.uiEndWait();
334
- }, 100);
335
- }
336
-
337
- // Chrome (and others) block unmuted audio until the page has "user
338
- // activation". A click through to this page (e.g. a target=_blank Play
339
- // button) does transfer that activation across the navigation, but it
340
- // doesn't reliably survive WasmPlayer's boot sequence (fetching the game,
341
- // booting the WASM runtime) for a slow-enough load — by the time the
342
- // game's start logic tries to play a sound, the activation can already be
343
- // gone, and the browser silently rejects it. Only relevant for games that
344
- // might play a sound before the player has had any chance to interact with
345
- // the page themselves (typing a command is itself a fresh activation).
346
- function activationLikelyGranted() {
347
- // Electron's own default autoplay policy is already unrestricted (unlike
348
- // stock Chrome's), and ipc/player.ts's player windows set it explicitly —
349
- // true regardless of how the window was created (in-place nav, popup, or
350
- // a main-process-created window), so the gate below would only ever add
351
- // friction there, never actually prevent a blocked sound.
352
- if (navigator.userAgent.includes('Electron/')) return true;
353
- return !('userActivation' in navigator) || navigator.userActivation.hasBeenActive;
354
- }
355
-
356
420
  // A random ID for this page load, sent with the api/Game/{id} fetch and every progress report, so
357
421
  // textadventures.co.uk can join one load's events up.
358
422
  const playId = crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
@@ -360,24 +424,103 @@ const playId = crypto.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(
360
424
  // For a game from textadventures.co.uk (?id=), tells it how far the game got (its GameProgress
361
425
  // API): "begin" when the Begin card shows, "started" when the game appears, "failed" if it
362
426
  // couldn't be started. Compared with the api/Game/{id} fetch, these show how many players leave
363
- // while a game loads or at Begin. Each is sent at most once a page load, with sendBeacon so it
364
- // still goes if the player is leaving. Nothing is sent for a game from anywhere else.
427
+ // while a game loads or at Begin. Each is sent at most once a page load, with a keepalive fetch
428
+ // so it still goes if the player is leaving. Nothing is sent for a game from anywhere else.
429
+ //
430
+ // Not sendBeacon: EasyPrivacy, which uBlock Origin, AdGuard and Brave turn on by default, blocks
431
+ // every cross-site beacon (`*$ping,third-party`), and sendBeacon still returns true when a
432
+ // blocker drops it, so nothing can notice. A fetch isn't a beacon to them, and a blocked fetch
433
+ // rejects, so only then is the beacon tried instead.
365
434
  let progressUrl = null;
366
435
  const reportedStages = new Set();
436
+ // How long the Begin card waited for its click, once it has. Sent as "waited" with the reports
437
+ // that follow, since their "ms" counts from the page opening and so includes that wait: the load
438
+ // time is ms - waited.
439
+ let beginWaitMs = null;
440
+ // How long the Continue/New Game prompt waited for an answer, when the player had saves for the
441
+ // game. Sent as "savesWaited", since that wait falls inside the stages after it, like "waited".
442
+ let savesWaitMs = null;
443
+ // When each stage of the first load finished, by performance.now(), sent with every report so
444
+ // textadventures.co.uk can tell where a slow load's time went (#2857). A stage that hasn't been
445
+ // reached is left out, so a "failed" report also shows how far the load got:
446
+ // api api/game/{id} responded
447
+ // gameBytes the game file finished downloading (after api: its URL comes from there)
448
+ // runtimeDownloaded the .NET runtime finished downloading (alongside both of those)
449
+ // runtimeReady the runtime started and the player's exports are ready
450
+ // initialised Bridge.Initialise returned: the game is parsed and loaded
451
+ // begun Bridge.Begin returned: the game's start script has run
452
+ // Only the first time counts: a restart runs Initialise and Begin again, long after the reports.
453
+ const loadTimings = {};
454
+ let gameSizeBytes = null;
455
+ function markLoad(stage) {
456
+ loadTimings[stage] ??= Math.round(performance.now());
457
+ }
458
+ // Whether the runtime's dotnet.native.wasm, by far its largest file, came from the HTTP cache,
459
+ // so cold and warm loads can be told apart: "1" cached, "0" downloaded. Left out when there's no
460
+ // timing entry for it yet, or one with no sizes (a cross-origin file without Timing-Allow-Origin
461
+ // reports every size as 0, which would look cached).
462
+ function runtimeCachedParam() {
463
+ const entry = performance.getEntriesByType?.('resource')
464
+ .find(e => new URL(e.name).pathname.endsWith('/dotnet.native.wasm'));
465
+ if (!entry || entry.decodedBodySize === 0) return null;
466
+ return entry.transferSize === 0 ? '1' : '0';
467
+ }
367
468
  function reportProgress(stage, error = null) {
368
469
  if (!progressUrl || reportedStages.has(stage)) return;
369
470
  reportedStages.add(stage);
370
471
  const params = clientInfoParams();
371
472
  params.set('stage', stage);
372
473
  params.set('ms', String(Math.round(performance.now())));
373
- // 6.0 has only the legacy UI; 6.1 also sends 'v2'.
374
- params.set('ui', 'legacy');
474
+ if (currentPlayerUiName) params.set('ui', currentPlayerUiName);
475
+ if (beginWaitMs !== null) params.set('waited', String(beginWaitMs));
476
+ if (savesWaitMs !== null) params.set('savesWaited', String(savesWaitMs));
477
+ for (const [name, ms] of Object.entries(loadTimings)) params.set(name, String(ms));
478
+ const cached = runtimeCachedParam();
479
+ if (cached !== null) params.set('runtimeCached', cached);
480
+ if (gameSizeBytes !== null) params.set('gameSize', String(gameSizeBytes));
375
481
  if (error) params.set('error', String(error).slice(0, 500));
376
482
  const url = `${progressUrl}?${params}`;
483
+ const beacon = () => {
484
+ try { navigator.sendBeacon?.(url); } catch { /* nothing more to try */ }
485
+ };
377
486
  try {
378
- if (navigator.sendBeacon?.(url)) return;
379
- } catch { /* fall back to fetch */ }
380
- fetch(url, { method: 'POST', mode: 'no-cors', keepalive: true }).catch(() => {});
487
+ fetch(url, { method: 'POST', mode: 'no-cors', keepalive: true }).catch(beacon);
488
+ } catch {
489
+ beacon();
490
+ }
491
+ }
492
+
493
+ // Shows the game's name, and its author and cover when known, on the start screen while it
494
+ // loads and on the Begin card. Later calls only fill in what earlier ones didn't have, so the
495
+ // game's own name doesn't replace the one textadventures.co.uk lists it under.
496
+ function showGameInfo({ name, author, cover }) {
497
+ if (document.readyState === 'loading') {
498
+ document.addEventListener('DOMContentLoaded', () => showGameInfo({ name, author, cover }), { once: true });
499
+ return;
500
+ }
501
+ const info = document.getElementById('qv-game-info');
502
+ const nameEl = document.getElementById('qv-game-name');
503
+ if (!info || !nameEl || !document.getElementById('qv-start')) return;
504
+ if (name && !nameEl.textContent) {
505
+ nameEl.textContent = name;
506
+ document.title = name;
507
+ }
508
+ if (!nameEl.textContent) return;
509
+ const authorEl = document.getElementById('qv-game-author');
510
+ if (author && authorEl && authorEl.style.display !== 'block') {
511
+ authorEl.textContent = `by ${author}`;
512
+ authorEl.style.display = 'block';
513
+ }
514
+ const coverEl = document.getElementById('qv-game-cover');
515
+ if (cover && coverEl && !coverEl.getAttribute('src')) {
516
+ coverEl.addEventListener('load', () => { coverEl.style.display = 'block'; }, { once: true });
517
+ coverEl.src = cover;
518
+ }
519
+ info.style.display = 'flex';
520
+ const brand = document.getElementById('qv-brand');
521
+ const brandSmall = document.getElementById('qv-brand-small');
522
+ if (brand) brand.style.display = 'none';
523
+ if (brandSmall) brandSmall.style.display = 'flex';
381
524
  }
382
525
 
383
526
  // Attached to the api/Game/{id} fetch below as analytics metadata (see
@@ -386,8 +529,7 @@ function reportProgress(stage, error = null) {
386
529
  // GameDetails calls. This player window runs untrusted game content and
387
530
  // deliberately has no preload bridge (see ipc/player.ts), so unlike
388
531
  // home-catalog.ts it can't read window.electronApp.platform; Electron and its
389
- // host OS are instead sniffed from the UA, the same signal
390
- // activationLikelyGranted() above already relies on.
532
+ // host OS are instead sniffed from the UA.
391
533
  function clientInfoParams() {
392
534
  const params = new URLSearchParams();
393
535
  params.set('playId', playId);
@@ -405,41 +547,241 @@ function clientInfoParams() {
405
547
  return params;
406
548
  }
407
549
 
408
- // Shows a "click to begin" prompt in the still-visible start screen and
409
- // waits for it, so the resulting click is a fresh, same-page activation —
410
- // but only when it's actually needed (see activationLikelyGranted) and only
411
- // for games that could plausibly play a sound before the player interacts
412
- // (see Bridge.GameLikelyPlaysSound). Call before Bridge.Begin() and before
413
- // the start screen overlay is removed.
414
- async function maybeGateOnActivation(gameBytes) {
415
- if (activationLikelyGranted()) return;
416
-
417
- let usesSound = true;
418
- try { usesSound = Bridge.GameLikelyPlaysSound(gameBytes); } catch { /* don't block boot on detection failure */ }
419
- if (!usesSound) return;
550
+ // Runs the game's start behind the start screen. If it played a sound the browser refused,
551
+ // because nobody has clicked the page yet, shows a Begin button on the start screen and plays
552
+ // the sound when it's clicked (see blockedMedia) - the moment the player first sees the game.
553
+ // Otherwise the game is revealed straight away. Game time starts then too (see holdClock).
554
+ async function beginBehindStartScreen() {
555
+ startupPlays = [];
556
+ holdClock();
557
+ try {
558
+ await Bridge.Begin();
559
+ markLoad('begun');
560
+ // An <audio autoplay> the browser refused never calls play(), so try it here.
561
+ for (const element of document.querySelectorAll('audio[autoplay], video[autoplay]')) {
562
+ if (element.paused && !element.muted) element.play().catch(() => {});
563
+ }
564
+ // A refusal comes as soon as play() is called, but an allowed play() only resolves once
565
+ // its sound has loaded, so don't wait long.
566
+ await Promise.race([Promise.all(startupPlays), new Promise(resolve => setTimeout(resolve, 250))]);
567
+ } catch (err) {
568
+ releaseClock();
569
+ throw err;
570
+ } finally {
571
+ startupPlays = null;
572
+ }
573
+ if (blockedMedia.size === 0) {
574
+ releaseClock();
575
+ return;
576
+ }
420
577
 
421
578
  const pickers = document.getElementById('qv-pickers');
422
579
  const msg = document.getElementById('qv-loading-msg');
423
580
  const gate = document.getElementById('qv-clicktobegin');
581
+ const button = document.getElementById('qv-clicktobegin-btn');
582
+ if (!gate || !button) return;
424
583
  if (pickers) pickers.style.display = 'none';
425
584
  if (msg) msg.style.display = 'none';
426
- if (gate) gate.style.display = 'flex';
585
+ // A click anywhere else would let the browser play the sound, with the game still hidden.
586
+ beginShowing = true;
587
+ document.removeEventListener('pointerdown', playBlockedMedia, { capture: true });
588
+ document.removeEventListener('keydown', playBlockedMedia, { capture: true });
589
+ gate.style.display = 'flex';
590
+ button.focus();
427
591
  reportProgress('begin');
428
-
429
- await new Promise(resolve => {
430
- document.getElementById('qv-clicktobegin-btn')?.addEventListener('click', resolve, { once: true });
592
+ const beginShownAt = performance.now();
593
+
594
+ await new Promise(resolve => button.addEventListener('click', resolve, { once: true }));
595
+ beginWaitMs = Math.round(performance.now() - beginShownAt);
596
+ beginShowing = false;
597
+ playBlockedMedia();
598
+ releaseClock();
599
+ }
600
+
601
+ // Applies a resolved chrome-strings dictionary (see ChromeStrings.Resolve in
602
+ // PlayerCore, surfaced via WebPlayer.setChromeStrings/Bridge.GetChromeStringsJson,
603
+ // or a save's snapshot - see GameSaver.save below) to every chrome element
604
+ // tagged with a data-chrome-key* attribute, e.g. the #cmdSave button and the
605
+ // #qv-saves/Slots dialog. dict is always fully populated (every key defaults
606
+ // to English), so a missing key here just means dict itself is null/undefined
607
+ // (no game loaded, no snapshot available) - existing markup is left untouched
608
+ // in that case.
609
+ function applyChromeStrings(dict) {
610
+ if (!dict) return;
611
+ document.querySelectorAll('[data-chrome-key]').forEach(el => {
612
+ const value = dict[el.dataset.chromeKey];
613
+ if (value) el.textContent = value;
431
614
  });
615
+ document.querySelectorAll('[data-chrome-key-placeholder]').forEach(el => {
616
+ const value = dict[el.dataset.chromeKeyPlaceholder];
617
+ if (value) el.placeholder = value;
618
+ });
619
+ document.querySelectorAll('[data-chrome-key-aria-label]').forEach(el => {
620
+ const value = dict[el.dataset.chromeKeyAriaLabel];
621
+ if (value) el.setAttribute('aria-label', value);
622
+ });
623
+ }
624
+
625
+ // Translates the chrome into the loaded game's language (applyChromeStrings),
626
+ // and sets the page's lang from its LanguageId template, so screen readers
627
+ // pronounce the game and the translated chrome in that language. A game
628
+ // without one (a V4 game, or a library that doesn't set it) stays "en", as
629
+ // its chrome does. Called once the engine has the game, at boot and after a
630
+ // restart, which swaps in fresh markup.
631
+ function applyGameLanguage() {
632
+ WebPlayer.chromeStrings = JSON.parse(Bridge.GetChromeStringsJson());
633
+ applyChromeStrings(WebPlayer.chromeStrings);
634
+ document.documentElement.lang = Bridge.GetLanguageId() || 'en';
635
+ }
636
+
637
+ // ── Transcript ──────────────────────────────────────────────────────────────
638
+ //
639
+ // The player's transcripts ("transcript on"), which the transcript viewer
640
+ // (TranscriptViewer/index.html) lists by name. They belong to the host, so
641
+ // both UIs write to the same store: v2 through WebPlayer.transcript, which
642
+ // QuestUI.transcript.* forwards to, and legacy through its own
643
+ // WriteToTranscript (legacy/player.js), which keeps its own on/off state and
644
+ // text conversion and only uses appendToTranscript here.
645
+
646
+ // Appends text to the named transcript: localStorage's "questtranscript-<name>",
647
+ // or in Electron a file under userData, since the player window's origin (a
648
+ // local loopback port) isn't guaranteed to stay the same across restarts (see
649
+ // transcript-store.ts; window.electronTranscripts is bridged by
650
+ // player-preload.ts). Returns false if there's nowhere to keep it.
651
+ function appendToTranscript(name, text) {
652
+ if (navigator.userAgent.includes('Electron/')) {
653
+ if (window.electronTranscripts) void window.electronTranscripts.append(name, text);
654
+ return true;
655
+ }
656
+ try {
657
+ const key = 'questtranscript-' + name;
658
+ localStorage.setItem(key, (localStorage.getItem(key) || '') + text);
659
+ return true;
660
+ } catch {
661
+ return false;
662
+ }
663
+ }
432
664
 
433
- if (gate) gate.style.display = 'none';
665
+ // Output HTML as transcript text, as legacy's writeToTranscript has always
666
+ // stored it: images, image map areas and inputs become their alt text, line
667
+ // breaks become @@@NEW_LINE@@@ (which the viewer turns back into lines), and
668
+ // the rest is its text.
669
+ function transcriptText(html) {
670
+ const holder = document.createElement('div');
671
+ holder.innerHTML = html;
672
+ for (const el of holder.querySelectorAll('img, area, input')) {
673
+ el.replaceWith(el.getAttribute('alt') || '');
674
+ }
675
+ for (const br of holder.querySelectorAll('br')) br.replaceWith('@@@NEW_LINE@@@');
676
+ return (holder.textContent || '').replace(/ /g, ' ');
434
677
  }
435
678
 
436
- // The WebPlayer object — same surface API as playerweb.js so that playercore.js
437
- // and player.js can call into it without modification.
679
+ let currentGameName = '';
680
+ let currentPlayerUiName = null; // 'legacy' or 'v2', once preparePlayerUi has picked it
681
+
682
+ // Whether any transcript is already stored, from this game or another: the
683
+ // viewer lists them all. Electron's store answers asynchronously
684
+ // (player-preload.ts), so its answer is fetched as the player UI starts
685
+ // (wireTranscriptsButton) and kept here.
686
+ let electronTranscriptsStored = false;
687
+ function anyTranscriptStored() {
688
+ if (navigator.userAgent.includes('Electron/')) return electronTranscriptsStored;
689
+ try {
690
+ for (let i = 0; i < localStorage.length; i++) {
691
+ if (localStorage.key(i)?.startsWith('questtranscript-')) return true;
692
+ }
693
+ } catch {
694
+ // Storage blocked (a private window, or site data turned off)
695
+ }
696
+ return false;
697
+ }
698
+
699
+ const transcript = {
700
+ recording: false,
701
+ // "kill": the game has turned transcripts off for good, until "revive".
702
+ killed: false,
703
+ name: '',
704
+ // Whether anything has been written since the page loaded. Electron's
705
+ // store hasn't been asked again since, so this stands in for it.
706
+ recorded: false,
707
+
708
+ // Each Initialise: 610 Core's InitInterface turns it back on if the game
709
+ // (or the save being restored) has it on.
710
+ reset() {
711
+ this.recording = false;
712
+ this.killed = false;
713
+ this.name = '';
714
+ },
715
+ enable(name) {
716
+ if (this.killed) return;
717
+ this.name = name || this.name || currentGameName || 'Transcript';
718
+ this.recording = true;
719
+ updateTranscriptsButton();
720
+ },
721
+ disable() { this.recording = false; },
722
+ kill() {
723
+ this.killed = true;
724
+ this.recording = false;
725
+ updateTranscriptsButton();
726
+ },
727
+ revive() {
728
+ this.killed = false;
729
+ updateTranscriptsButton();
730
+ },
731
+ setName(name) { this.name = name || ''; },
732
+ write(html) {
733
+ if (!this.recording || this.killed) return;
734
+ if (!appendToTranscript(this.name || currentGameName || 'Transcript', transcriptText(html))) {
735
+ console.error('There is no localStorage. Disabling transcript functionality.');
736
+ this.kill();
737
+ return;
738
+ }
739
+ if (!this.recorded) {
740
+ this.recorded = true;
741
+ updateTranscriptsButton();
742
+ }
743
+ },
744
+ // Whether there's a transcript to view: this game is recording one, or
745
+ // one has been kept, unless the game has turned the feature off
746
+ // ("notranscript", which reaches the player as kill).
747
+ hasTranscript() {
748
+ return !this.killed && (this.recording || this.recorded || anyTranscriptStored());
749
+ },
750
+ viewerUrl: 'TranscriptViewer/index.html',
751
+ };
752
+
753
+ // v2's toolbar button for the transcript viewer, the button version of
754
+ // "view transcript" (issue #2882), shown once there's a transcript to view.
755
+ // Legacy has no such button, so this does nothing there.
756
+ function updateTranscriptsButton() {
757
+ const button = document.getElementById('cmdTranscripts');
758
+ if (button) button.style.display = transcript.hasTranscript() ? 'initial' : 'none';
759
+ }
760
+
761
+ // Called after every WebPlayer.initUI(), like wireDebuggerButton, since the
762
+ // player UI's markup is replaced on every boot and restart.
763
+ function wireTranscriptsButton() {
764
+ const button = document.getElementById('cmdTranscripts');
765
+ if (!button) return;
766
+ // Opened as "view transcript"'s link is, so Electron gives it its viewer
767
+ // window (attachTranscriptWindowHandling).
768
+ button.addEventListener('click', () => window.open(transcript.viewerUrl, '_blank', 'noopener'));
769
+ updateTranscriptsButton();
770
+ window.electronTranscripts?.any?.().then((any) => {
771
+ electronTranscriptsStored = any;
772
+ updateTranscriptsButton();
773
+ }, () => {});
774
+ }
775
+
776
+ // The WebPlayer object — the host API that the shared playercore.js and
777
+ // player.js call into. The name predates WasmPlayer and is kept as-is.
438
778
  window.WebPlayer = {
439
779
  gameId: null,
440
780
  chromeStrings: null,
781
+ transcript,
782
+ appendToTranscript,
441
783
 
442
- initUI() { initPlayerUI(); },
784
+ initUI() { return playerUi.start(); },
443
785
 
444
786
  setCanDebug(value) {
445
787
  const cmdDebug = document.getElementById("cmdDebug");
@@ -449,11 +791,10 @@ window.WebPlayer = {
449
791
  setCanSave(value) {
450
792
  const cmdSave = document.getElementById("cmdSave");
451
793
  if (cmdSave) cmdSave.style.display = value ? "initial" : "none";
452
- canSave = value;
453
- if (!value) window.saveGame = () => addText("Disabled");
794
+ playerUi.setCanSave(value);
454
795
  },
455
796
 
456
- setAnimateScroll(value) { _animateScroll = value; },
797
+ setAnimateScroll(value) { playerUi.setAnimateScroll(value); },
457
798
 
458
799
  runJs(scripts) {
459
800
  const globalEval = window.eval;
@@ -464,21 +805,31 @@ window.WebPlayer = {
464
805
 
465
806
  async sendCommand(command, tickCount, metadata) {
466
807
  const metadataJson = metadata ? JSON.stringify(metadata) : null;
467
- await Bridge.SendCommand(command, tickCount, metadataJson);
808
+ await playerTurn(() => Bridge.SendCommand(command, tickCount, metadataJson));
468
809
  canSendCommand = true;
469
810
  recordStep(command);
470
811
  refreshDebuggerAfterTurn();
471
812
  },
472
813
 
473
- async uiChoice(choice) { await Bridge.SetMenuResponse(choice); recordStep(`menu:${choice}`); },
474
- async uiChoiceCancel() { await Bridge.SetMenuResponse(null); },
475
- async uiTick(tickCount) { await Bridge.Tick(tickCount); },
476
- async uiEndWait() { await Bridge.FinishWait(); },
477
- async uiEndPause() { await Bridge.FinishPause(); },
478
- async uiSetQuestionResponse(response) { await Bridge.SetQuestionResponse(response); recordStep(`answer:${response ? 'yes' : 'no'}`); },
814
+ async uiChoice(choice) { await playerTurn(() => Bridge.SetMenuResponse(choice)); recordStep(`menu:${choice}`); },
815
+ async uiChoiceCancel() { await playerTurn(() => Bridge.SetMenuResponse(null)); },
816
+ async uiTick(tickCount) {
817
+ // A timer firing mid-change would run its script against a half-built UI.
818
+ await interfaceChangesApplied;
819
+ turnsInFlight++;
820
+ try {
821
+ await Bridge.Tick(tickCount);
822
+ } finally {
823
+ turnsInFlight--;
824
+ scheduleInterfaceChanges();
825
+ }
826
+ },
827
+ async uiEndWait() { await playerTurn(() => Bridge.FinishWait()); },
828
+ async uiEndPause() { await playerTurn(() => Bridge.FinishPause()); },
829
+ async uiSetQuestionResponse(response) { await playerTurn(() => Bridge.SetQuestionResponse(response)); recordStep(`answer:${response ? 'yes' : 'no'}`); },
479
830
 
480
831
  async uiSendEvent(eventName, param) {
481
- await Bridge.SendEvent(eventName, param);
832
+ await playerTurn(() => Bridge.SendEvent(eventName, param));
482
833
  canSendCommand = true;
483
834
  recordStep(`event:${eventName};${param ?? ''}`);
484
835
  refreshDebuggerAfterTurn();
@@ -491,6 +842,28 @@ window.WebPlayer = {
491
842
 
492
843
  };
493
844
 
845
+ // One engine round trip started by the player, bracketed for QuestUI's turnStarted/turnEnded
846
+ // events (legacy/questui.js).
847
+ async function playerTurn(run) {
848
+ window.notifyQuestUITurn?.(true);
849
+ turnsInFlight++;
850
+ try {
851
+ // A live interface change being applied finishes first (applyInterfaceChanges).
852
+ await interfaceChangesApplied;
853
+ return await run();
854
+ } finally {
855
+ turnsInFlight--;
856
+ window.notifyQuestUITurn?.(false);
857
+ scheduleInterfaceChanges();
858
+ }
859
+ }
860
+
861
+ // Engine round trips the player has started that haven't returned yet (playerTurn), and whether
862
+ // the engine says a turn is held mid-script (a wait, menu, question or pause): a live interface
863
+ // change waits for both to be over.
864
+ let turnsInFlight = 0;
865
+ let turnPending = false;
866
+
494
867
  // Exported bridge reference — set once WASM is loaded.
495
868
  var Bridge;
496
869
 
@@ -519,19 +892,6 @@ function addPaperScript() {
519
892
  }
520
893
  }
521
894
 
522
- async function setupPaperJs() {
523
- if (!window.paper) return;
524
- const canvas = document.createElement('canvas');
525
- canvas.id = 'gridCanvas';
526
- canvas.width = 700;
527
- canvas.height = 300;
528
- canvas.style.display = 'none';
529
- document.body.appendChild(canvas);
530
- paper.setup(canvas);
531
- const code = await fetch(versioned('grid.js')).then(r => r.text());
532
- paper.PaperScript.evaluate(code, paper);
533
- }
534
-
535
895
  // Replaces document.body with a fresh copy of the player chrome, preserving
536
896
  // #qv-start/#qv-saves/#questVivaDebugger/#qv-recording (the static markup's overlays, which
537
897
  // live outside the swapped-in playerHtml and would otherwise be destroyed by
@@ -543,6 +903,208 @@ async function setupPaperJs() {
543
903
  // again on every restart (RegisterExternalScripts fires on every Initialise
544
904
  // call), so anything short of a full DOM reset here leaves the previous run's
545
905
  // injected elements in place for the new run to duplicate.
906
+ // Initialise() unconditionally re-registers the game's external scripts every
907
+ // time it runs, including on a mid-session restart (Start from the beginning
908
+ // / Load) — but a real <script src> only ever runs once per document, so
909
+ // re-adding the same URL against the *same* live DOM would re-execute the
910
+ // game's setup code against elements it already set up on the previous run
911
+ // (e.g. a custom sidebar pane), producing duplicates. Dedupe by URL so each
912
+ // script tag still only truly executes once per document, same as normal
913
+ // page-load semantics.
914
+ //
915
+ // A restart also wipes and rebuilds the whole player chrome first (see
916
+ // WasmPlayer's swapInPlayerUi()), so by the
917
+ // time Initialise() re-registers scripts against that fresh DOM, the
918
+ // "already set up on the previous run" premise above no longer holds — the
919
+ // old elements are gone, and the dedupe would wrongly skip re-running setup
920
+ // code against the new ones, silently dropping anything the script injects
921
+ // (confirmed via a real game's custom sidebar pane vanishing after restart).
922
+ // Both chrome-reset call sites clear the set via clearLoadedExternalScripts()
923
+ // so a restart's re-registration is treated as a genuinely fresh page load.
924
+ var _loadedExternalScripts = new Set();
925
+
926
+ function addExternalScript(url) {
927
+ if (_loadedExternalScripts.has(url)) return Promise.resolve();
928
+ _loadedExternalScripts.add(url);
929
+
930
+ return new Promise((resolve, reject) => {
931
+ const script = document.createElement("script");
932
+ script.src = url;
933
+ script.onload = () => resolve();
934
+ script.onerror = () => {
935
+ _loadedExternalScripts.delete(url);
936
+ reject(new Error(`Failed to load script: ${url}`));
937
+ };
938
+ document.head.appendChild(script);
939
+ });
940
+ }
941
+
942
+ // A game's own stylesheet (Core's AddExternalStylesheet), added after the player UI's.
943
+ function addExternalStylesheet(source) {
944
+ const link = document.createElement("link");
945
+ link.type = "text/css";
946
+ link.rel = "stylesheet";
947
+ link.href = source;
948
+ document.head.appendChild(link);
949
+ }
950
+
951
+ // The game's own stylesheet (game.stylesheet, from 610), set on every Initialise. It isn't in a
952
+ // cascade layer and comes after the player UI's styles, so the author's CSS wins over the UI's
953
+ // without !important (docs/ui-v2-contract.md, "Game stylesheet").
954
+ function setGameStylesheet(css) {
955
+ let style = document.getElementById("qv-game-stylesheet");
956
+ if (!css) {
957
+ style?.remove();
958
+ return;
959
+ }
960
+ if (!style) {
961
+ style = document.createElement("style");
962
+ style.id = "qv-game-stylesheet";
963
+ }
964
+ style.textContent = css;
965
+ // Last in <head> each time, after anything added since.
966
+ document.head.appendChild(style);
967
+ }
968
+
969
+ // ── Player UIs ──────────────────────────────────────────────────────────────
970
+ //
971
+ // Each player UI is a bundle of markup (swapped into the page for each game and restart),
972
+ // stylesheets and classic scripts, loaded only once a game needs it: the legacy UI (today's, frozen) and v2 (docs/ui-v2-plan.md). The last script
973
+ // registers the UI's adapter as window.QuestPlayerUis[name], which is the only way the host
974
+ // talks to it. Paths are relative to this page and get the ?v= cache key.
975
+ const playerUiBundles = {
976
+ legacy: {
977
+ html: 'legacy/playercore.htm',
978
+ styles: ['legacy/lib/jquery-ui.min.css', 'legacy/playercore.css'],
979
+ scripts: [
980
+ 'legacy/lib/jquery-2.1.1.min.js',
981
+ 'legacy/lib/jquery-ui.min.js',
982
+ 'legacy/lib/jquery.multi-open-accordion-1.5.3.js',
983
+ 'legacy/playercore.js',
984
+ 'legacy/player.js',
985
+ 'legacy/questui.js',
986
+ 'legacy/lib/paper.js',
987
+ 'legacy/adapter.js',
988
+ ],
989
+ },
990
+ v2: {
991
+ // Built from ../ui-v2/ by `npm run build`.
992
+ html: 'v2/player.htm',
993
+ styles: ['v2/v2.css'],
994
+ scripts: ['v2/v2.js'],
995
+ },
996
+ };
997
+
998
+ // ?ui=legacy / ?ui=v2 forces a UI regardless of the game, for development and testing.
999
+ function playerUiOverride() {
1000
+ const ui = new URLSearchParams(window.location.search).get('ui');
1001
+ return Object.hasOwn(playerUiBundles, ui ?? '') ? ui : null;
1002
+ }
1003
+
1004
+ // Fetches a bundle's files into the HTTP cache, at low priority and without running them, so
1005
+ // loading the bundle once the game has been chosen doesn't add a round trip after the engine
1006
+ // has loaded it. Boot doesn't know the game's version yet, so it guesses: a game from the
1007
+ // editor's Preview was saved by this version, so it's 610 or later and gets v2, while most other
1008
+ // games are older and get legacy. ?ui= settles it.
1009
+ function prefetchPlayerUi(name) {
1010
+ const bundle = playerUiBundles[name];
1011
+ for (const path of [bundle.html, ...bundle.styles, ...bundle.scripts]) {
1012
+ const link = document.createElement('link');
1013
+ link.rel = 'prefetch';
1014
+ link.href = versioned(path);
1015
+ document.head.appendChild(link);
1016
+ }
1017
+ }
1018
+
1019
+ // A stylesheet from another origin (the CDN-hosted single-file export, whose <base href>
1020
+ // points there) needs CORS for playercore.js to read its cssRules (issue #2192).
1021
+ function setCrossOriginIfNeeded(element, url) {
1022
+ if (new URL(url, document.baseURI).origin !== window.location.origin) {
1023
+ element.crossOrigin = 'anonymous';
1024
+ }
1025
+ }
1026
+
1027
+ const loadedPlayerUis = new Map();
1028
+
1029
+ // Adds a bundle's stylesheets (before chrome.css, so the app chrome keeps its place in the
1030
+ // cascade) and scripts (run in order), once per page, and resolves to its adapter.
1031
+ function loadPlayerUi(name) {
1032
+ if (!loadedPlayerUis.has(name)) {
1033
+ loadedPlayerUis.set(name, (async () => {
1034
+ const bundle = playerUiBundles[name];
1035
+ const chromeCss = document.querySelector('link[href^="chrome.css"]');
1036
+ for (const href of bundle.styles) {
1037
+ const link = document.createElement('link');
1038
+ link.rel = 'stylesheet';
1039
+ link.type = 'text/css';
1040
+ link.href = versioned(href);
1041
+ setCrossOriginIfNeeded(link, link.href);
1042
+ document.head.insertBefore(link, chromeCss);
1043
+ }
1044
+ // A bundle using jQuery (the legacy UI) registers $(function () { ... }) ready
1045
+ // handlers that expect every script in the bundle to have run first, as they would
1046
+ // have when the bundle was in the page from the start. The page is long since
1047
+ // ready, though, so jQuery would run each handler as soon as it's registered. So
1048
+ // hold jQuery's ready event from the moment jQuery itself has run (a script's load
1049
+ // event fires straight after it executes, before the next script) until the whole
1050
+ // bundle has.
1051
+ let heldJQueryReady = false;
1052
+ const loaded = bundle.scripts.map(src => new Promise((resolve, reject) => {
1053
+ const script = document.createElement('script');
1054
+ script.src = versioned(src);
1055
+ // Dynamically added scripts otherwise run in whatever order they arrive.
1056
+ script.async = false;
1057
+ script.onload = () => {
1058
+ if (!heldJQueryReady && window.jQuery) {
1059
+ window.jQuery.holdReady(true);
1060
+ heldJQueryReady = true;
1061
+ }
1062
+ resolve();
1063
+ };
1064
+ script.onerror = () => reject(new Error(`Failed to load ${src}`));
1065
+ document.head.appendChild(script);
1066
+ }));
1067
+ const [html] = await Promise.all([
1068
+ fetch(versioned(bundle.html)).then(r => r.text()),
1069
+ ...loaded,
1070
+ ]);
1071
+ if (heldJQueryReady) window.jQuery.holdReady(false);
1072
+ const adapter = window.QuestPlayerUis?.[name];
1073
+ if (!adapter) throw new Error(`Player UI "${name}" didn't register an adapter`);
1074
+ return { adapter, html };
1075
+ })());
1076
+ }
1077
+ return loadedPlayerUis.get(name);
1078
+ }
1079
+
1080
+ // Called by WasmPlayerBridge once the engine has loaded the game (or failed to), with the UI
1081
+ // the game gets, and before any of the game's own scripts run: games commonly use their
1082
+ // external <javascript> resources to manipulate the UI's DOM (e.g. inserting a custom pane
1083
+ // next to the built-in Inventory/Status panes), so the UI has to be in place first. If it
1084
+ // isn't, those scripts run against the start screen and silently no-op - a real game, "A
1085
+ // Stranger Unregarded", does exactly this with a custom Inventory2 pane that never appeared.
1086
+ //
1087
+ // #qv-start is a fixed, full-viewport overlay (see chrome.css), so it still covers the
1088
+ // freshly swapped-in UI until the game has started.
1089
+ async function preparePlayerUi(choice) {
1090
+ const name = playerUiOverride() ?? choice;
1091
+ currentPlayerUiName = name;
1092
+ const { adapter, html } = await loadPlayerUi(name);
1093
+ // The host's dialogs (chrome.css) follow the game's light or dark scheme, which v2 sets on
1094
+ // <html> (its scheme.ts). Legacy has no dark scheme, so they're light over a legacy game too.
1095
+ if (name === 'legacy') document.documentElement.setAttribute('data-qv-scheme', 'light');
1096
+ // Game time then only advances via QuestVivaTest's tick/fireNextTimeout.
1097
+ if (manualClock) adapter.useManualClock();
1098
+ playerUi = adapter;
1099
+ playerUiHtml = html;
1100
+ const startScreenEl = swapInPlayerUi();
1101
+ if (restartingPlayerUi) {
1102
+ playerUi.resetOutput();
1103
+ } else {
1104
+ bootStartScreenEl = startScreenEl;
1105
+ }
1106
+ }
1107
+
546
1108
  function swapInPlayerUi() {
547
1109
  const startScreenEl = document.getElementById('qv-start');
548
1110
  const savesDialogEl = document.getElementById('qv-saves');
@@ -555,7 +1117,7 @@ function swapInPlayerUi() {
555
1117
  restartingEl?.remove();
556
1118
  recordingEl?.remove();
557
1119
 
558
- document.body.innerHTML = originalPlayerHtml;
1120
+ document.body.innerHTML = playerUiHtml;
559
1121
 
560
1122
  if (startScreenEl) document.body.appendChild(startScreenEl);
561
1123
  if (savesDialogEl) document.body.appendChild(savesDialogEl);
@@ -563,10 +1125,14 @@ function swapInPlayerUi() {
563
1125
  if (restartingEl) document.body.appendChild(restartingEl);
564
1126
  if (recordingEl) document.body.appendChild(recordingEl);
565
1127
  // This is a genuinely fresh chrome (see above) — addExternalScript's
566
- // dedupe-by-URL (player.js) must not carry over, or the game's external
1128
+ // dedupe-by-URL must not carry over, or the game's external
567
1129
  // scripts silently no-op against it on the very next Initialise() call
568
1130
  // and never re-inject whatever they set up (e.g. that sidebar pane).
569
- clearLoadedExternalScripts();
1131
+ _loadedExternalScripts.clear();
1132
+ // Likewise QuestUI's per-game state (legacy/questui.js): author panes, event listeners,
1133
+ // tokens and the hook flags all belong to the old chrome.
1134
+ window.resetQuestUIState?.();
1135
+ transcript.reset();
570
1136
  return startScreenEl;
571
1137
  }
572
1138
 
@@ -575,6 +1141,9 @@ function swapInPlayerUi() {
575
1141
  // so the Debug button's visibility stays correct after "Start from the
576
1142
  // beginning"/Load in an editor-preview session.
577
1143
  let currentIsPreview = false;
1144
+ // True when the game came from files the player picked (the start screen's file picker, or the
1145
+ // Play tab's): see showGameLoadError's hint about choosing a game's library files too.
1146
+ let gameFromPickedFiles = false;
578
1147
 
579
1148
  // Same idea as currentIsPreview, but for the source=local .aslx case (see
580
1149
  // setCanDebug's call sites below) — kept separate from isPreview because it
@@ -599,8 +1168,8 @@ function loadRuntimeBuilder() {
599
1168
  // (the CDN-linked single-file export) — see wasmPlayerScriptUrl's comment.
600
1169
  // The version query is load-bearing beyond its own cache key too: the
601
1170
  // loader reads it back off its own import.meta.url and propagates it to
602
- // the JS modules it imports and to dotnet.boot.js (`modulesUniqueQuery`),
603
- // so those need no further handling in withResourceLoader below.
1171
+ // the JS modules it imports (`modulesUniqueQuery`), so those need no
1172
+ // further handling in withResourceLoader below.
604
1173
  const dotnetJsUrl = versioned(wasmPlayerScriptUrl
605
1174
  ? new URL('_framework/dotnet.js', wasmPlayerScriptUrl).href
606
1175
  : './_framework/dotnet.js');
@@ -637,46 +1206,58 @@ function loadRuntimeBuilder() {
637
1206
  // downloads some of a runtime it won't use. That costs a failed load some
638
1207
  // bandwidth; not doing it costs every successful load ~1.7s.
639
1208
  function preloadRuntime() {
640
- loadRuntimeBuilder().then(builder => builder.download()).catch(() => {});
1209
+ loadRuntimeBuilder().then(builder => builder.download()).then(() => markLoad('runtimeDownloaded')).catch(() => {});
641
1210
  }
642
1211
 
643
1212
  async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null, isPreview = false, recordWalkthrough = null, runWalkthrough = null, adjacentFiles = null, allowDebug = false) {
644
1213
  currentIsPreview = isPreview;
645
1214
  currentAllowDebug = allowDebug;
646
- const [htmResponse, builder] = await Promise.all([
647
- fetch(versioned('playercore.htm')),
648
- loadRuntimeBuilder(),
649
- ]);
650
- originalPlayerHtml = await htmResponse.text();
651
-
1215
+ prefetchPlayerUi(playerUiOverride() ?? (isPreview ? 'v2' : 'legacy'));
1216
+ const builder = await loadRuntimeBuilder();
652
1217
  const runtime = await builder.create();
653
1218
  const { setModuleImports, getAssemblyExports, getConfig } = runtime;
654
1219
 
1220
+ // Everything that's UI behaviour goes to whichever player UI the game is playing on
1221
+ // (playerUi, set by preparePlayerUi). The rest is the host's own.
655
1222
  setModuleImports("wasm-player", {
656
- addTextAndScroll: (html) => addTextAndScroll(html),
657
- createNewDiv: (alignment) => createNewDiv(alignment),
658
- bindMenu: (linkId, verbs, text, elementId) => bindMenu(linkId, verbs, text, elementId),
659
- showMenu: (caption, optionsJson, allowCancel) => showMenu(caption, JSON.parse(optionsJson), allowCancel),
660
- showQuestion: (caption) => showQuestion(caption),
661
- beginWait: () => beginWait(),
662
- setTurnPending: (pending) => setTurnPending(pending),
663
- beginPause: (ms) => beginPause(ms),
664
- updateLocation: (loc) => updateLocation(loc),
665
- setGameName: (name) => setGameName(name),
666
- clearScreen: () => clearScreen(),
667
- panesVisible: (visible) => panesVisible(visible),
668
- updateStatus: (text) => updateStatus(text),
669
- setBackground: (colour) => setBackground(colour),
670
- setForeground: (colour) => setForeground(colour),
671
- updateList: (listName, itemsJson) => updateList(listName, JSON.parse(itemsJson)),
672
- updateCompass: (data) => updateCompass(data),
673
- updateObjectLinks: (verbsJson) => updateObjectLinks(JSON.parse(verbsJson)),
674
- gameFinished: () => gameFinished(),
675
- requestNextTimerTick: (seconds) => requestNextTimerTick(seconds),
676
- uiShow: (element) => uiShow(element),
677
- uiHide: (element) => uiHide(element),
1223
+ addTextAndScroll: (html) => playerUi.addTextAndScroll(html),
1224
+ createNewDiv: (alignment) => playerUi.createNewDiv(alignment),
1225
+ bindMenu: (linkId, verbs, text, elementId) => playerUi.bindMenu(linkId, verbs, text, elementId),
1226
+ showMenu: (caption, optionsJson, allowCancel) => playerUi.showMenu(caption, JSON.parse(optionsJson), allowCancel),
1227
+ showQuestion: (caption) => playerUi.showQuestion(caption),
1228
+ beginWait: () => playerUi.beginWait(),
1229
+ setTurnPending: (pending) => {
1230
+ turnPending = pending;
1231
+ playerUi.setTurnPending(pending);
1232
+ if (!pending) scheduleInterfaceChanges();
1233
+ },
1234
+ beginPause: (ms) => whenClockRuns(() => playerUi.beginPause(ms)),
1235
+ updateLocation: (loc) => playerUi.updateLocation(loc),
1236
+ setGameName: (name) => {
1237
+ currentGameName = name;
1238
+ playerUi.setGameName(name);
1239
+ showGameInfo({ name });
1240
+ },
1241
+ clearScreen: () => playerUi.clearScreen(),
1242
+ panesVisible: (visible) => playerUi.panesVisible(visible),
1243
+ updateStatus: (text) => playerUi.updateStatus(text),
1244
+ setBackground: (colour) => playerUi.setBackground(colour),
1245
+ setForeground: (colour) => playerUi.setForeground(colour),
1246
+ updateList: (listName, itemsJson) => playerUi.updateList(listName, JSON.parse(itemsJson)),
1247
+ updateCompass: (data) => playerUi.updateCompass(data),
1248
+ updateObjectLinks: (verbsJson) => playerUi.updateObjectLinks(JSON.parse(verbsJson)),
1249
+ gameFinished: () => playerUi.gameFinished(),
1250
+ requestNextTimerTick: (seconds) => whenClockRuns(() => playerUi.requestNextTimerTick(seconds)),
1251
+ uiShow: (element) => playerUi.uiShow(element),
1252
+ uiHide: (element) => playerUi.uiHide(element),
678
1253
  addExternalScript: (url) => addExternalScript(url),
679
1254
  addExternalStylesheet: (url) => addExternalStylesheet(url),
1255
+ setGameStylesheet: (css) => setGameStylesheet(css),
1256
+ preparePlayerUi: (choice) => preparePlayerUi(choice),
1257
+ loadHtml: (html) => playerUi.loadHtml(html),
1258
+ markScrollPosition: () => playerUi.markScrollPosition(),
1259
+ scrollToEnd: () => playerUi.scrollToEnd(),
1260
+ requestSave: () => playerUi.requestSave(),
680
1261
  playSound: (url, synchronous, looped) => playSound(url, synchronous, looped),
681
1262
  stopSound: () => stopSound(),
682
1263
  runScript: (call) => {
@@ -684,9 +1265,9 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
684
1265
  try { globalEval(call); } catch (e) { console.error(e); }
685
1266
  },
686
1267
  jsYield: () => new Promise(resolve => setTimeout(resolve, 0)),
687
- setCompassDirections: (dirsJson) => setCompassDirections(JSON.parse(dirsJson)),
688
- setInterfaceString: (name, text) => setInterfaceString(name, text),
689
- setPanelContents: (html) => setPanelContents(html),
1268
+ setCompassDirections: (dirsJson) => playerUi.setCompassDirections(JSON.parse(dirsJson)),
1269
+ setInterfaceString: (name, text) => playerUi.setInterfaceString(name, text),
1270
+ setPanelContents: (html) => playerUi.setPanelContents(html),
690
1271
  consoleError: (msg) => console.error('[Quest]', msg),
691
1272
  consoleLog: (msg) => console.log('[Quest]', msg),
692
1273
  getResourceUrl: (name) => getResourceUrl(name),
@@ -697,16 +1278,15 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
697
1278
  const config = getConfig();
698
1279
  const exports = await getAssemblyExports(config.mainAssemblyName);
699
1280
  Bridge = exports.QuestViva.WasmPlayer.WasmPlayerBridge;
1281
+ markLoad('runtimeReady');
700
1282
 
701
- // Test hooks for replaying a walkthrough reproducibly: see WasmPlayerBridge.SetRandomSeed.
1283
+ // Hooks for replaying a walkthrough reproducibly (the editor's walkthrough Play and Record
1284
+ // pass ?seed=, and tests use them all): see WasmPlayerBridge.SetRandomSeed.
702
1285
  const testParams = new URLSearchParams(window.location.search);
703
1286
  const seed = Number.parseInt(testParams.get('seed') ?? '', 10);
704
1287
  if (Number.isInteger(seed)) Bridge.SetRandomSeed(seed);
705
1288
  if (testParams.has('transcript')) Bridge.StartTranscriptCapture();
706
- if (testParams.get('clock') === 'manual') {
707
- // Stops player.js's 1-second interval, so game time only advances via tick/fireNextTimeout.
708
- window.startTimer = () => {};
709
- }
1289
+ manualClock = testParams.get('clock') === 'manual';
710
1290
  window.QuestVivaTest = {
711
1291
  takeTranscript: () => JSON.parse(Bridge.TakeTranscriptJson()),
712
1292
  evaluate: (expression) => Bridge.EvaluateExpression(expression),
@@ -721,30 +1301,19 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
721
1301
  if (data.type === 'resource-response') {
722
1302
  pendingResources.get(data.id)?.(data.dataUrl);
723
1303
  pendingResources.delete(data.id);
1304
+ } else if (data.type === 'interface' && isPreview) {
1305
+ queueInterfaceChanges(data.attributes);
724
1306
  }
725
1307
  };
726
1308
  }
727
1309
 
728
- // Swap in the game UI *before* Initialise/Begin run, not after. Initialise
729
- // registers the game's external <javascript> resources (RegisterExternalScripts),
730
- // and games commonly use those to manipulate the game UI's own DOM (e.g.
731
- // inserting a custom pane next to the built-in Inventory/Status panes). If
732
- // the swap happens later, those scripts execute while the start screen is
733
- // still showing, find none of the elements they're looking for, and
734
- // silently no-op — a real game, "A Stranger Unregarded", does exactly this
735
- // with a custom Inventory2 pane that never appeared because of this
736
- // ordering.
737
- //
738
- // #qv-start is a fixed, full-viewport overlay (see chrome.css), so keeping
739
- // it in the DOM on top of the freshly-swapped-in game UI still covers the
740
- // screen exactly as before — the loading spinner/error UI's visible
741
- // behaviour is unchanged.
742
- const startScreenEl = swapInPlayerUi();
743
-
1310
+ // Initialise loads the game, then calls preparePlayerUi to swap in the UI it's playing
1311
+ // on, before registering the game's external <javascript> resources - see there.
744
1312
  stageAdjacentFiles(adjacentFiles);
745
1313
  const ok = saveBytes
746
1314
  ? await Bridge.InitialiseWithSave(gameBytes, filename, saveBytes)
747
1315
  : await Bridge.Initialise(gameBytes, filename);
1316
+ markLoad('initialised');
748
1317
  if (!ok) {
749
1318
  // The game file itself was fine (downloaded/picked), but the engine
750
1319
  // rejected its contents — same errors the Editor shows on load.
@@ -758,10 +1327,11 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
758
1327
  // A live app (Play tab / editor preview) handed this game over via bc —
759
1328
  // it owns the file-picking UI, so don't re-offer the start-screen
760
1329
  // pickers; just show the error, editor-style.
761
- showGameLoadError(errors, !bc);
1330
+ showGameLoadError(errors, !bc, gameFromPickedFiles);
762
1331
  reportProgress('failed', errors.join(' ') || 'Unknown error');
763
1332
  return false;
764
1333
  }
1334
+ resetBugReportSteps(!!saveBytes);
765
1335
 
766
1336
  // Now that a WorldModel is live, resolve the game's own translated chrome
767
1337
  // strings (falls back to English for any key it doesn't define) and apply
@@ -769,21 +1339,14 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
769
1339
  // current for the shared GameSaver in playercore.js (default save label,
770
1340
  // and the snapshot it stashes into the save record for next session's
771
1341
  // boot prompt — see startGame below).
772
- WebPlayer.chromeStrings = JSON.parse(Bridge.GetChromeStringsJson());
773
- applyChromeStrings(WebPlayer.chromeStrings);
774
-
775
- await maybeGateOnActivation(gameBytes);
776
-
777
- // Now that startup has actually succeeded, remove the start screen overlay
778
- // to reveal the game UI underneath.
779
- startScreenEl?.remove();
780
-
781
- await setupPaperJs();
1342
+ applyGameLanguage();
782
1343
 
783
1344
  WebPlayer.onSaveClick = () => openSavesDialog('manage');
784
- WebPlayer.initUI();
1345
+ WebPlayer.onGameSaved = () => { stepsSinceSave = 0; };
1346
+ await WebPlayer.initUI();
785
1347
  wireDebuggerButton();
786
1348
  wireDebuggerRestartButton(isPreview);
1349
+ wireTranscriptsButton();
787
1350
  wireRecordingStopButton();
788
1351
  // Editor-preview sessions (isPreview) don't offer saving at all — by
789
1352
  // design: a save captures the whole game state, so reloading one while
@@ -800,7 +1363,14 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
800
1363
  // though the loaded game itself might have DebugEnabled true.
801
1364
  WebPlayer.setCanDebug((isPreview || allowDebug) && Bridge.IsDebugEnabled());
802
1365
 
803
- await Bridge.Begin();
1366
+ // The game's start runs behind the start screen, so a sound it plays can wait for a click
1367
+ // on Begin if the browser won't play it yet.
1368
+ await beginBehindStartScreen();
1369
+
1370
+ // Now that startup has actually succeeded, remove the start screen overlay
1371
+ // to reveal the game UI underneath.
1372
+ bootStartScreenEl?.remove();
1373
+ bootStartScreenEl = null;
804
1374
 
805
1375
  reportProgress('started');
806
1376
 
@@ -823,6 +1393,67 @@ async function initWasmPlayer(gameBytes, filename, bc = null, saveBytes = null,
823
1393
  return true;
824
1394
  }
825
1395
 
1396
+ // ── Live interface changes from the editor ─────────────────────────────────
1397
+ //
1398
+ // The editor's Preview gets the game's Display and Interface tab attributes as the author changes
1399
+ // them (editor-store.ts's syncPreviewInterface), and shows them without restarting: the
1400
+ // attributes are copied onto the running game, and then, unless only the stylesheet changed, a
1401
+ // fresh copy of the UI is swapped in and set up as a restore would (InitInterface, the lists and
1402
+ // the output so far), so options that are turned off go away too. Changes arriving while a turn
1403
+ // is running or held wait until it's over, since the fresh UI would have none of its prompt.
1404
+ let pendingInterfaceChanges = null;
1405
+ let applyingInterfaceChanges = false;
1406
+ let interfaceChangesApplied = Promise.resolve();
1407
+
1408
+ function queueInterfaceChanges(attributes) {
1409
+ if (!attributes || typeof attributes !== 'object') return;
1410
+ pendingInterfaceChanges = { ...pendingInterfaceChanges, ...attributes };
1411
+ scheduleInterfaceChanges();
1412
+ }
1413
+
1414
+ function scheduleInterfaceChanges() {
1415
+ if (pendingInterfaceChanges) setTimeout(applyInterfaceChanges, 0);
1416
+ }
1417
+
1418
+ function applyInterfaceChanges() {
1419
+ if (!pendingInterfaceChanges || !Bridge || applyingInterfaceChanges) return;
1420
+ if (turnsInFlight > 0 || turnPending || restartInProgress) return;
1421
+ const attributes = pendingInterfaceChanges;
1422
+ pendingInterfaceChanges = null;
1423
+ applyingInterfaceChanges = true;
1424
+ interfaceChangesApplied = applyInterfaceChangesCore(attributes);
1425
+ }
1426
+
1427
+ async function applyInterfaceChangesCore(attributes) {
1428
+ try {
1429
+ Bridge.SetGameAttributes(JSON.stringify(attributes));
1430
+ if (Object.keys(attributes).every(name => name === 'stylesheet')) return;
1431
+
1432
+ const html = playerUi.getOutputHtml();
1433
+ restartingPlayerUi = true;
1434
+ try {
1435
+ await Bridge.RebuildPlayerUi();
1436
+ } finally {
1437
+ restartingPlayerUi = false;
1438
+ }
1439
+ applyGameLanguage();
1440
+ await WebPlayer.initUI();
1441
+ playerUi.setGameName(currentGameName);
1442
+ wireDebuggerButton();
1443
+ wireDebuggerRestartButton(currentIsPreview);
1444
+ wireTranscriptsButton();
1445
+ WebPlayer.setCanSave(!currentIsPreview);
1446
+ WebPlayer.setCanDebug((currentIsPreview || currentAllowDebug) && Bridge.IsDebugEnabled());
1447
+ await Bridge.ReapplyInterface(html);
1448
+ } catch (e) {
1449
+ console.error('[Quest] Failed to apply interface changes', e);
1450
+ } finally {
1451
+ applyingInterfaceChanges = false;
1452
+ // Anything that arrived meanwhile.
1453
+ scheduleInterfaceChanges();
1454
+ }
1455
+ }
1456
+
826
1457
  // Guards restartGame against overlapping calls — e.g. impatiently clicking
827
1458
  // Restart/"Start from the beginning" again while a slow restart (loading a
828
1459
  // large game, low-end device) is still in flight. Two concurrent restarts
@@ -874,8 +1505,6 @@ window.RestartGame = () => {
874
1505
 
875
1506
  async function restartGameCore(saveBytes) {
876
1507
  document.getElementById('qv-saves')?.close();
877
- swapInPlayerUi();
878
- resetGameOutput();
879
1508
 
880
1509
  // Bridge.Initialise/Begin re-run the whole game's startup (Bridge.Initialise
881
1510
  // in particular re-parses the embedded Core library XML from scratch every
@@ -891,9 +1520,16 @@ async function restartGameCore(saveBytes) {
891
1520
 
892
1521
  try {
893
1522
  stageAdjacentFiles(originalAdjacentFiles);
894
- const ok = saveBytes
895
- ? await Bridge.InitialiseWithSave(originalGameBytes, originalGameFilename, saveBytes)
896
- : await Bridge.Initialise(originalGameBytes, originalGameFilename);
1523
+ // Initialise swaps in a fresh copy of the UI (preparePlayerUi), as at boot.
1524
+ restartingPlayerUi = true;
1525
+ let ok;
1526
+ try {
1527
+ ok = saveBytes
1528
+ ? await Bridge.InitialiseWithSave(originalGameBytes, originalGameFilename, saveBytes)
1529
+ : await Bridge.Initialise(originalGameBytes, originalGameFilename);
1530
+ } finally {
1531
+ restartingPlayerUi = false;
1532
+ }
897
1533
  if (!ok) {
898
1534
  // The engine rejected the game's contents again (or the save didn't
899
1535
  // apply) — include the actual error rather than the old generic
@@ -906,12 +1542,15 @@ async function restartGameCore(saveBytes) {
906
1542
  return;
907
1543
  }
908
1544
 
909
- await maybeGateOnActivation(originalGameBytes);
1545
+ resetBugReportSteps(!!saveBytes);
910
1546
 
911
- await setupPaperJs();
912
- WebPlayer.initUI();
1547
+ // The restarted game has a fresh copy of the UI, still in English.
1548
+ applyGameLanguage();
1549
+
1550
+ await WebPlayer.initUI();
913
1551
  wireDebuggerButton();
914
1552
  wireDebuggerRestartButton(currentIsPreview);
1553
+ wireTranscriptsButton();
915
1554
  // Used to be an unconditional true — harmless while restartGame was only
916
1555
  // ever reachable from the Saves dialog, which editor-preview sessions
917
1556
  // never had access to in the first place (Save itself is hidden there).
@@ -957,7 +1596,9 @@ async function startGame(bytes, filename, bc = null, gameIdOverride = null, isPr
957
1596
  WebPlayer.chromeStrings = snapshot;
958
1597
  applyChromeStrings(snapshot);
959
1598
  }
1599
+ const promptShownAt = performance.now();
960
1600
  const choice = await openSavesDialog('boot', gameId);
1601
+ savesWaitMs = Math.round(performance.now() - promptShownAt);
961
1602
  if (choice.type === 'load') {
962
1603
  saveBytes = await GameSaver.load(choice.slotIndex, gameId);
963
1604
  }
@@ -1032,33 +1673,280 @@ function hideSavesError() {
1032
1673
  if (el) el.style.display = 'none';
1033
1674
  }
1034
1675
 
1676
+ // The saves list. A save is titled by its name, else by where the player was, else "Saved game",
1677
+ // with when it was made (and where, when it has a name) underneath. Manage mode gives each row a
1678
+ // Load button and a ⋯ button for its menu: Overwrite, Rename, Save to file and Delete. Boot
1679
+ // mode (the "Continue your game?" prompt) offers the newest save as its Continue button and lists
1680
+ // the rest with just a Load button.
1035
1681
  function renderSavesList(saves, mode) {
1036
1682
  const list = document.getElementById('qv-saves-list');
1037
1683
  if (!list) return;
1684
+ const cs = WebPlayer.chromeStrings ?? {};
1685
+
1686
+ if (mode === 'boot') {
1687
+ const [newest, ...rest] = saves;
1688
+ const continueBtn = document.getElementById('qv-saves-continue');
1689
+ continueBtn.dataset.continueSlot = newest ? String(newest.slotIndex) : '';
1690
+ document.getElementById('qv-saves-continue-detail').textContent = newest ? describeSave(newest).summary : '';
1691
+ document.getElementById('qv-saves-other-heading').hidden = rest.length === 0;
1692
+ saves = rest;
1693
+ }
1694
+
1038
1695
  if (!saves.length) {
1039
- const noSavesText = WebPlayer.chromeStrings?.NoSavedGamesYet ?? 'No saved games yet.';
1040
- list.innerHTML = `<li class="text-sm text-surface-500">${_esc(noSavesText)}</li>`;
1696
+ list.innerHTML = mode === 'manage' && !document.getElementById('qv-saves').hasAttribute('data-storage-blocked')
1697
+ ? `<li class="qv-saves-empty text-sm text-surface-700-300">${_esc(cs.NoSavedGamesYet ?? 'No saved games yet.')}</li>`
1698
+ : '';
1041
1699
  return;
1042
1700
  }
1043
- // s.name already carries a human-readable date/time when the user didn't
1044
- // type a custom one (see GameSaver.save's default label) — don't also
1045
- // render s.timestamp separately, or the same moment shows up twice in
1046
- // two different formats.
1047
- const deleteLabel = _esc(WebPlayer.chromeStrings?.DeleteSave ?? 'Delete');
1701
+
1702
+ const loadLabel = _esc(cs.LoadSave ?? 'Load');
1048
1703
  list.innerHTML = saves.map(s => {
1049
- const deleteBtn = mode === 'manage'
1050
- ? `<button type="button" class="btn-icon preset-tonal-error" data-delete-slot="${s.slotIndex}" aria-label="${deleteLabel}">`
1051
- + `<svg class="qv-icon" aria-hidden="true"><use href="#trash-2"></use></svg></button>`
1704
+ const { title, meta } = describeSave(s);
1705
+ const id = `qv-save-${s.slotIndex}`;
1706
+ const options = mode === 'manage'
1707
+ ? `<button type="button" class="btn-icon btn-icon-sm hover:preset-tonal" data-slot-options="${s.slotIndex}" aria-haspopup="menu" aria-expanded="false" aria-controls="qv-saves-menu" aria-label="${_esc((cs.SaveOptions ?? 'Options for [name]').replace('[name]', title))}">`
1708
+ + `<svg class="qv-icon" aria-hidden="true"><use href="#ellipsis"></use></svg></button>`
1052
1709
  : '';
1053
- return `<li class="flex items-center justify-between gap-2">`
1054
- + `<button type="button" class="anchor text-left flex-1" data-slot="${s.slotIndex}">${_esc(s.name)}</button>`
1055
- + deleteBtn
1710
+ return `<li class="qv-save-row px-3 py-2" data-row-slot="${s.slotIndex}">`
1711
+ + `<div class="flex items-center gap-2">`
1712
+ + `<div class="min-w-0 flex-1">`
1713
+ + `<div class="qv-save-title truncate" id="${id}-title">${_esc(title)}</div>`
1714
+ + (meta ? `<div class="qv-save-meta text-xs">${_esc(meta)}</div>` : '')
1715
+ + `</div>`
1716
+ + `<button type="button" class="btn btn-sm preset-outlined-primary-700-300" data-slot="${s.slotIndex}" aria-describedby="${id}-title">${loadLabel}</button>`
1717
+ + options
1718
+ + `</div>`
1056
1719
  + `</li>`;
1057
1720
  }).join('');
1058
1721
  }
1059
1722
 
1060
- async function downloadSaveToFile() {
1061
- const bytes = await WebPlayer.uiSaveGame($("#divOutput").html());
1723
+ // A save's title and the line under it, and both together for the boot prompt's Continue button.
1724
+ function describeSave(save) {
1725
+ const cs = WebPlayer.chromeStrings ?? {};
1726
+ const name = isDefaultSaveLabel(save.name) ? null : save.name;
1727
+ const location = save.location || null;
1728
+ const when = formatSaveTime(save.timestamp);
1729
+ const title = name || location || cs.SavedGameTitle || 'Saved game';
1730
+ const meta = [when, name && location].filter(Boolean).join(' · ');
1731
+ return { title, meta, summary: [title, meta].filter(Boolean).join(' · ') };
1732
+ }
1733
+
1734
+ // Saves made before saves could be unnamed were given a "Saved game — <date and time>" name.
1735
+ // Those are shown like unnamed saves, since the date is shown anyway.
1736
+ function isDefaultSaveLabel(name) {
1737
+ if (!name) return false;
1738
+ const template = WebPlayer.chromeStrings?.SavedGameDefaultLabel ?? 'Saved game — [timestamp]';
1739
+ const [before, after = ''] = template.split('[timestamp]');
1740
+ return name.startsWith(before) && name.endsWith(after) && name.length > before.length + after.length;
1741
+ }
1742
+
1743
+ // "Today, 12:57", "Yesterday, 21:14", or the date and time for anything older.
1744
+ function formatSaveTime(timestamp) {
1745
+ if (!timestamp) return '';
1746
+ const date = new Date(timestamp);
1747
+ if (isNaN(date)) return '';
1748
+ const cs = WebPlayer.chromeStrings ?? {};
1749
+ const now = new Date();
1750
+ const time = date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' });
1751
+ const startOfDay = d => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
1752
+ const daysAgo = Math.round((startOfDay(now) - startOfDay(date)) / 86400000);
1753
+ if (daysAgo === 0) return (cs.SavedToday ?? 'Today, [time]').replace('[time]', time);
1754
+ if (daysAgo === 1) return (cs.SavedYesterday ?? 'Yesterday, [time]').replace('[time]', time);
1755
+ const day = date.toLocaleDateString(undefined, {
1756
+ day: 'numeric', month: 'short',
1757
+ ...(date.getFullYear() !== now.getFullYear() ? { year: 'numeric' } : {}),
1758
+ });
1759
+ return `${day}, ${time}`;
1760
+ }
1761
+
1762
+ // Asks inside the dialog, in place of a native confirm(): the question goes into container, with
1763
+ // Cancel and a button that does it. Resolves true if the player goes ahead. Escape cancels (see
1764
+ // the dialog's cancel handler in ensureSavesDialogWired).
1765
+ let cancelSavesConfirm = null;
1766
+
1767
+ function confirmInSavesDialog(container, message, actionLabel, danger = false) {
1768
+ cancelSavesConfirm?.();
1769
+ const cs = WebPlayer.chromeStrings ?? {};
1770
+ const box = document.createElement('div');
1771
+ box.className = 'qv-saves-confirm card preset-tonal-warning p-3 mt-2 space-y-2 text-sm';
1772
+ box.setAttribute('role', 'group');
1773
+ box.innerHTML = `<p id="qv-saves-confirm-text"></p>`
1774
+ + `<div class="flex justify-end gap-2">`
1775
+ + `<button type="button" id="qv-saves-confirm-cancel" class="btn btn-sm preset-tonal"></button>`
1776
+ + `<button type="button" id="qv-saves-confirm-yes" class="btn btn-sm ${danger ? 'preset-filled-error-500' : 'preset-filled-primary-500'}" aria-describedby="qv-saves-confirm-text"></button>`
1777
+ + `</div>`;
1778
+ box.querySelector('#qv-saves-confirm-text').textContent = message;
1779
+ box.querySelector('#qv-saves-confirm-cancel').textContent = cs.CancelButton ?? 'Cancel';
1780
+ box.querySelector('#qv-saves-confirm-yes').textContent = actionLabel;
1781
+ box.setAttribute('aria-labelledby', 'qv-saves-confirm-text');
1782
+ container.append(box);
1783
+
1784
+ return new Promise(resolve => {
1785
+ const finish = (yes) => {
1786
+ cancelSavesConfirm = null;
1787
+ box.remove();
1788
+ resolve(yes);
1789
+ };
1790
+ cancelSavesConfirm = () => finish(false);
1791
+ box.querySelector('#qv-saves-confirm-cancel').addEventListener('click', () => finish(false));
1792
+ box.querySelector('#qv-saves-confirm-yes').addEventListener('click', () => finish(true));
1793
+ box.querySelector('#qv-saves-confirm-yes').focus();
1794
+ });
1795
+ }
1796
+
1797
+ // A save's menu (#qv-saves-menu), opened by its ⋯ button: placed under the button, or above it
1798
+ // when there's no room below, with the first item focused. The arrow keys, Home and End move
1799
+ // between items. Escape or a click elsewhere closes it (it's a popover) and focus goes back to
1800
+ // the button.
1801
+ let saveMenuOpener = null;
1802
+ // When the menu last closed because of a press outside it, and whose it was: pressing a save's ⋯
1803
+ // button while its menu is open closes the menu that way before the click arrives, which would
1804
+ // otherwise open it again. Closing it with Escape or by choosing an item doesn't count
1805
+ // (saveMenuClosingByUs), so the button opens it again straight away after those.
1806
+ let saveMenuClosed = { opener: null, at: 0 };
1807
+ let saveMenuClosingByUs = false;
1808
+
1809
+ function openSaveMenu(button) {
1810
+ const menu = document.getElementById('qv-saves-menu');
1811
+ if (!menu) return;
1812
+ if (menu.matches(':popover-open')) {
1813
+ saveMenuClosingByUs = true;
1814
+ menu.hidePopover();
1815
+ if (saveMenuOpener === button) return;
1816
+ } else if (saveMenuClosed.opener === button && performance.now() - saveMenuClosed.at < 500) {
1817
+ return;
1818
+ }
1819
+ cancelSavesConfirm?.();
1820
+ saveMenuOpener = button;
1821
+ menu.dataset.slot = button.dataset.slotOptions;
1822
+ menu.showPopover();
1823
+ const rect = button.getBoundingClientRect();
1824
+ const { width, height } = menu.getBoundingClientRect();
1825
+ const below = rect.bottom + 4;
1826
+ menu.style.top = `${below + height > window.innerHeight - 8 ? Math.max(8, rect.top - 4 - height) : below}px`;
1827
+ menu.style.left = `${Math.max(8, Math.min(rect.right - width, window.innerWidth - 8 - width))}px`;
1828
+ button.setAttribute('aria-expanded', 'true');
1829
+ menu.querySelector('[role="menuitem"]')?.focus();
1830
+ }
1831
+
1832
+ function wireSaveMenu(onAction) {
1833
+ const menu = document.getElementById('qv-saves-menu');
1834
+ if (!menu) return;
1835
+ // beforetoggle, unlike toggle, fires as the menu closes, so it's recorded before the click
1836
+ // that closed it reaches a ⋯ button.
1837
+ menu.addEventListener('beforetoggle', (e) => {
1838
+ if (e.newState !== 'closed' || !saveMenuOpener) return;
1839
+ saveMenuOpener.setAttribute('aria-expanded', 'false');
1840
+ saveMenuClosed = saveMenuClosingByUs ? { opener: null, at: 0 } : { opener: saveMenuOpener, at: performance.now() };
1841
+ saveMenuClosingByUs = false;
1842
+ });
1843
+ menu.addEventListener('toggle', (e) => {
1844
+ if (e.newState !== 'closed' || !saveMenuOpener) return;
1845
+ // Back to the button, unless the menu closed because the player clicked something else.
1846
+ if (!document.activeElement || document.activeElement === document.body || menu.contains(document.activeElement)) {
1847
+ saveMenuOpener.focus();
1848
+ }
1849
+ });
1850
+ menu.addEventListener('keydown', (e) => {
1851
+ const items = [...menu.querySelectorAll('[role="menuitem"]')];
1852
+ const index = items.indexOf(document.activeElement);
1853
+ const next = { ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 }[e.key];
1854
+ if (next === undefined) {
1855
+ if (e.key === 'Escape') saveMenuClosingByUs = true;
1856
+ if (e.key === 'Tab') { saveMenuClosingByUs = true; menu.hidePopover(); }
1857
+ return;
1858
+ }
1859
+ e.preventDefault();
1860
+ items[(next + items.length) % items.length].focus();
1861
+ });
1862
+ menu.addEventListener('click', (e) => {
1863
+ const item = e.target.closest('[data-menu-action]');
1864
+ if (!item) return;
1865
+ const slotIndex = Number(menu.dataset.slot);
1866
+ const opener = saveMenuOpener;
1867
+ saveMenuClosingByUs = true;
1868
+ menu.hidePopover();
1869
+ onAction(item.dataset.menuAction, slotIndex, opener);
1870
+ });
1871
+ }
1872
+
1873
+ // Turns a row's title into a text box. Enter or leaving the box keeps the new name (an empty one
1874
+ // makes the save unnamed again), Escape keeps the old one.
1875
+ function startRenamingSave(slotIndex) {
1876
+ const row = document.querySelector(`#qv-saves-list [data-row-slot="${slotIndex}"]`);
1877
+ const title = row?.querySelector('.qv-save-title');
1878
+ if (!title) return;
1879
+ const cs = WebPlayer.chromeStrings ?? {};
1880
+ const save = currentSaves.find(s => s.slotIndex === slotIndex);
1881
+ const input = document.createElement('input');
1882
+ input.type = 'text';
1883
+ input.className = 'input qv-save-rename py-1';
1884
+ input.autocomplete = 'off';
1885
+ input.value = save && !isDefaultSaveLabel(save.name) ? (save.name ?? '') : '';
1886
+ input.placeholder = describeSave(save ?? {}).title;
1887
+ input.setAttribute('aria-label', cs.RenameSaveLabel ?? 'New name');
1888
+ title.replaceWith(input);
1889
+ input.focus();
1890
+ input.select();
1891
+
1892
+ let done = false;
1893
+ const finish = async (keep) => {
1894
+ if (done) return;
1895
+ done = true;
1896
+ renamingSave = null;
1897
+ if (keep && input.value.trim() !== (save?.name ?? '')) {
1898
+ await GameSaver.rename(slotIndex, input.value.trim() || null);
1899
+ }
1900
+ await refreshSavesList();
1901
+ document.querySelector(`#qv-saves-list [data-slot="${slotIndex}"]`)?.focus();
1902
+ };
1903
+ renamingSave = () => finish(false);
1904
+ input.addEventListener('keydown', (e) => {
1905
+ if (e.key === 'Enter') { e.preventDefault(); finish(true); }
1906
+ });
1907
+ input.addEventListener('blur', () => finish(true));
1908
+ }
1909
+
1910
+ let renamingSave = null;
1911
+ let currentSaves = [];
1912
+
1913
+ async function refreshSavesList(mode = 'manage') {
1914
+ currentSaves = await listSavesOrReportBlocked(WebPlayer.gameId);
1915
+ renderSavesList(currentSaves, mode);
1916
+ }
1917
+
1918
+ // Lists the game's saves, or, when the browser won't open IndexedDB at all (a Firefox private
1919
+ // window, all site data blocked, a privacy add-on), says in the dialog that saving here isn't
1920
+ // available and hides the Save form, instead of the dialog failing to open. Save to file and Load
1921
+ // from file don't use the browser's storage, so they stay.
1922
+ async function listSavesOrReportBlocked(gameId) {
1923
+ const dlg = document.getElementById('qv-saves');
1924
+ try {
1925
+ const saves = await GameSaver.listSaves(gameId);
1926
+ delete dlg.dataset.storageBlocked;
1927
+ return saves;
1928
+ } catch (err) {
1929
+ console.warn('Saved games are unavailable:', err);
1930
+ dlg.dataset.storageBlocked = '';
1931
+ showSavesError(WebPlayer.chromeStrings?.SavingNotAvailable
1932
+ ?? "Saving here isn't available, because this browser is blocking storage (for example in a private window). You can still save to a file and load from one.");
1933
+ return [];
1934
+ }
1935
+ }
1936
+
1937
+ function saveTitle(slotIndex) {
1938
+ const save = currentSaves.find(s => s.slotIndex === slotIndex);
1939
+ return save ? describeSave(save).title : (WebPlayer.chromeStrings?.UnnamedSave ?? 'this save');
1940
+ }
1941
+
1942
+ // Downloads a save from the list as a .quest-save file, the same as "Save to file" gives for the
1943
+ // game as it is now.
1944
+ async function downloadSaveSlot(slotIndex) {
1945
+ const bytes = await GameSaver.load(slotIndex, WebPlayer.gameId);
1946
+ if (bytes) downloadSaveBytes(bytes);
1947
+ }
1948
+
1949
+ function downloadSaveBytes(bytes) {
1062
1950
  const blob = new Blob([bytes], { type: 'application/xml' });
1063
1951
  const url = URL.createObjectURL(blob);
1064
1952
  const a = document.createElement('a');
@@ -1066,7 +1954,13 @@ async function downloadSaveToFile() {
1066
1954
  a.download = WebPlayer.gameId.replace(/\.[^.]+$/, '') + '.quest-save';
1067
1955
  a.click();
1068
1956
  URL.revokeObjectURL(url);
1069
- clearUnsavedProgress();
1957
+ }
1958
+
1959
+ async function downloadSaveToFile() {
1960
+ const bytes = await WebPlayer.uiSaveGame(playerUi.getOutputHtml());
1961
+ downloadSaveBytes(bytes);
1962
+ playerUi.clearUnsavedProgress();
1963
+ stepsSinceSave = 0;
1070
1964
  }
1071
1965
 
1072
1966
  // A .quest-save only carries state, not resources — it must be paired with
@@ -1124,70 +2018,111 @@ function ensureSavesDialogWired() {
1124
2018
 
1125
2019
  const dlg = document.getElementById('qv-saves');
1126
2020
  if (!dlg) return;
2021
+ const cs = () => WebPlayer.chromeStrings ?? {};
1127
2022
 
1128
- // Non-cancellable while a boot-time choice is pending (matches WebPlayer's
1129
- // Slots dialog); freely closable otherwise.
2023
+ // Escape backs out of whatever is open inside the dialog first: a question or a rename (a save's
2024
+ // menu, being a popover, closes itself). Otherwise it closes the manager. The boot prompt can't
2025
+ // be closed: it's waiting for a choice (matches WebPlayer's Slots dialog).
1130
2026
  dlg.addEventListener('cancel', (e) => {
2027
+ if (cancelSavesConfirm) { e.preventDefault(); cancelSavesConfirm(); return; }
2028
+ if (renamingSave) { e.preventDefault(); renamingSave(); return; }
1131
2029
  if (bootChoiceResolve) e.preventDefault();
1132
2030
  });
1133
2031
 
1134
- document.getElementById('qv-saves-start-new').addEventListener('click', (e) => {
1135
- if (bootChoiceResolve) {
1136
- const resolve = bootChoiceResolve;
1137
- bootChoiceResolve = null;
1138
- dlg.close();
1139
- resolve({ type: 'new' });
1140
- return;
2032
+ const chooseAtBoot = (choice) => {
2033
+ const resolve = bootChoiceResolve;
2034
+ bootChoiceResolve = null;
2035
+ dlg.close();
2036
+ resolve(choice);
2037
+ };
2038
+
2039
+ document.getElementById('qv-saves-start-new').addEventListener('click', () => {
2040
+ if (bootChoiceResolve) chooseAtBoot({ type: 'new' });
2041
+ });
2042
+
2043
+ document.getElementById('qv-saves-continue').addEventListener('click', (e) => {
2044
+ const slot = e.currentTarget.dataset.continueSlot;
2045
+ if (bootChoiceResolve && slot) chooseAtBoot({ type: 'load', slotIndex: Number(slot) });
2046
+ });
2047
+
2048
+ // Manage mode: starting again mid-game. The button is disabled meanwhile, so a slow restart
2049
+ // (a large game, a low-end device) can't be started twice; #qv-restarting shows it's working.
2050
+ document.getElementById('qv-saves-restart').addEventListener('click', async (e) => {
2051
+ const button = e.currentTarget;
2052
+ if (stepsSinceSave > 0) {
2053
+ const ok = await confirmInSavesDialog(document.getElementById('qv-saves-footer-confirm'),
2054
+ cs().StartAgainConfirm ?? "Start again from the beginning? You'll lose anything you've done since you last saved.",
2055
+ cs().StartAgain ?? 'Start again');
2056
+ if (!ok) { button.focus(); return; }
2057
+ }
2058
+ withBusyButton(button, '', () => restartGame(null));
2059
+ });
2060
+
2061
+ // A save's menu.
2062
+ wireSaveMenu(async (action, slotIndex, opener) => {
2063
+ const row = document.querySelector(`#qv-saves-list [data-row-slot="${slotIndex}"]`);
2064
+ if (!row) return;
2065
+ if (action === 'overwrite') {
2066
+ const ok = await confirmInSavesDialog(row,
2067
+ (cs().OverwriteSaveConfirm ?? 'Overwrite "[name]"?').replace('[name]', saveTitle(slotIndex)),
2068
+ cs().OverwriteSave ?? 'Overwrite');
2069
+ if (!ok) { opener?.focus(); return; }
2070
+ await GameSaver.overwrite(slotIndex);
2071
+ await refreshSavesList();
2072
+ document.querySelector(`#qv-saves-list [data-slot="${slotIndex}"]`)?.focus();
2073
+ } else if (action === 'rename') {
2074
+ startRenamingSave(slotIndex);
2075
+ } else if (action === 'download') {
2076
+ await downloadSaveSlot(slotIndex);
2077
+ opener?.focus();
2078
+ } else if (action === 'delete') {
2079
+ const ok = await confirmInSavesDialog(row,
2080
+ (cs().DeleteSaveConfirm ?? 'Delete "[name]"? This can\'t be undone.').replace('[name]', saveTitle(slotIndex)),
2081
+ cs().DeleteSave ?? 'Delete', true);
2082
+ if (!ok) { opener?.focus(); return; }
2083
+ await GameSaver.deleteSlot(slotIndex, WebPlayer.gameId);
2084
+ await refreshSavesList();
2085
+ document.getElementById('qv-saves-name-input')?.focus();
1141
2086
  }
1142
- // Manage mode: restarting mid-session, matches WebPlayer's Slots
1143
- // "Start from the beginning" button (no confirm() there either).
1144
- // withBusyButton's disable+busy-label+forced-paint makes a slow
1145
- // restart (a large game, a low-end device) read as "working" rather
1146
- // than unresponsive — restartGame itself also now guards against
1147
- // overlapping calls (see restartInProgress's doc comment), but
1148
- // without this there was no visible feedback at all inviting
1149
- // exactly the impatient re-click that guard exists for.
1150
- withBusyButton(e.currentTarget, WebPlayer.chromeStrings?.RestartingBusy ?? 'Restarting…', () => restartGame(null));
1151
2087
  });
1152
2088
 
1153
2089
  document.getElementById('qv-saves-list').addEventListener('click', async (e) => {
1154
- const loadBtn = e.target.closest('[data-slot]');
1155
- if (loadBtn) {
1156
- const slotIndex = Number(loadBtn.dataset.slot);
2090
+ const target = e.target.closest('button');
2091
+ if (!target) return;
2092
+ const row = target.closest('[data-row-slot]');
2093
+ const slotIndex = Number(row?.dataset.rowSlot);
2094
+
2095
+ if (target.dataset.slot !== undefined) {
1157
2096
  if (bootChoiceResolve) {
1158
- const resolve = bootChoiceResolve;
1159
- bootChoiceResolve = null;
1160
- dlg.close();
1161
- resolve({ type: 'load', slotIndex });
1162
- } else {
1163
- const bytes = await GameSaver.load(slotIndex, WebPlayer.gameId);
1164
- await restartGame(bytes);
2097
+ chooseAtBoot({ type: 'load', slotIndex });
2098
+ return;
1165
2099
  }
1166
- return;
1167
- }
1168
- const delBtn = e.target.closest('[data-delete-slot]');
1169
- if (delBtn) {
1170
- const name = delBtn.closest('li')?.querySelector('[data-slot]')?.textContent ?? (WebPlayer.chromeStrings?.UnnamedSave ?? 'this save');
1171
- const confirmTemplate = WebPlayer.chromeStrings?.DeleteSaveConfirm ?? 'Delete "[name]"? This can\'t be undone.';
1172
- if (!confirm(confirmTemplate.replace('[name]', name))) return;
1173
- await withBusyButton(delBtn, '', async () => {
1174
- await GameSaver.deleteSlot(Number(delBtn.dataset.deleteSlot), WebPlayer.gameId);
1175
- });
1176
- renderSavesList(await GameSaver.listSaves(WebPlayer.gameId), 'manage');
2100
+ if (stepsSinceSave > 0) {
2101
+ const ok = await confirmInSavesDialog(row,
2102
+ (cs().LoadSaveConfirm ?? "Load \"[name]\"? You'll lose anything you've done since you last saved.").replace('[name]', saveTitle(slotIndex)),
2103
+ cs().LoadSave ?? 'Load');
2104
+ if (!ok) { target.focus(); return; }
2105
+ }
2106
+ const bytes = await GameSaver.load(slotIndex, WebPlayer.gameId);
2107
+ await restartGame(bytes);
2108
+ } else if (target.dataset.slotOptions !== undefined) {
2109
+ openSaveMenu(target);
1177
2110
  }
1178
2111
  });
1179
2112
 
1180
- document.getElementById('qv-saves-save-new').addEventListener('click', async (e) => {
2113
+ document.getElementById('qv-saves-save-form').addEventListener('submit', async (e) => {
2114
+ e.preventDefault();
1181
2115
  const input = document.getElementById('qv-saves-name-input');
1182
- await withBusyButton(e.currentTarget, WebPlayer.chromeStrings?.SavingBusy ?? 'Saving…', async () => {
2116
+ const button = document.getElementById('qv-saves-save-new');
2117
+ await withBusyButton(button, cs().SavingBusy ?? 'Saving…', async () => {
1183
2118
  await GameSaver.save(input.value.trim() || undefined);
1184
2119
  });
1185
2120
  input.value = '';
1186
- renderSavesList(await GameSaver.listSaves(WebPlayer.gameId), 'manage');
2121
+ await refreshSavesList();
1187
2122
  });
1188
2123
 
1189
2124
  document.getElementById('qv-saves-download').addEventListener('click', (e) =>
1190
- withBusyButton(e.currentTarget, WebPlayer.chromeStrings?.SavingBusy ?? 'Saving…', downloadSaveToFile));
2125
+ withBusyButton(e.currentTarget, '', downloadSaveToFile));
1191
2126
 
1192
2127
  const uploadBtn = document.getElementById('qv-saves-upload-btn');
1193
2128
  const fileInput = document.getElementById('qv-saves-file-input');
@@ -1198,9 +2133,52 @@ function ensureSavesDialogWired() {
1198
2133
  if (file) await loadSaveFromFile(file);
1199
2134
  });
1200
2135
 
2136
+ document.getElementById('qv-saves-bug-report').addEventListener('click', copyBugReport);
2137
+
1201
2138
  document.getElementById('qv-saves-close').addEventListener('click', () => dlg.close());
1202
2139
  }
1203
2140
 
2141
+ // The text "Copy for a bug report" copies: what an author needs to replay the player's game with a
2142
+ // walkthrough - the game's seed, and the player's inputs as walkthrough steps - plus, when the game
2143
+ // was loaded from a save, a note that the save is needed too, since the steps only start there. In
2144
+ // English whatever the game's language, as it's written for the game's author.
2145
+ function buildBugReport() {
2146
+ const ifid = Bridge.GetGameIfid();
2147
+ const lines = [
2148
+ `Game: ${currentGameName || originalGameFilename || 'unknown'}` + (originalGameFilename && currentGameName ? ` (${originalGameFilename})` : ''),
2149
+ ...(ifid ? [`Game ID: ${ifid}`] : []),
2150
+ `Quest Viva: ${Bridge.GetPlayerVersion()}`,
2151
+ `Random seed: ${Bridge.GetRandomSeed()}`,
2152
+ bugReportFromSave
2153
+ ? 'Started from: a saved game. Send the save too (Save to file); the steps below start from it.'
2154
+ : 'Started from: the beginning',
2155
+ '',
2156
+ `Steps (${bugReportSteps.length}), to paste into a walkthrough with the same random seed:`,
2157
+ ...bugReportSteps,
2158
+ ];
2159
+ return lines.join('\n');
2160
+ }
2161
+
2162
+ async function copyBugReport() {
2163
+ const text = buildBugReport();
2164
+ const status = document.getElementById('qv-saves-bug-report-status');
2165
+ const textarea = document.getElementById('qv-saves-bug-report-text');
2166
+ let copied = false;
2167
+ try {
2168
+ await navigator.clipboard.writeText(text);
2169
+ copied = true;
2170
+ } catch {
2171
+ // No clipboard access, e.g. in an iframe that isn't allowed it: show the text to copy by hand.
2172
+ }
2173
+ status.textContent = copied
2174
+ ? (WebPlayer.chromeStrings?.BugReportCopied ?? 'Copied. Paste it into your bug report.')
2175
+ : (WebPlayer.chromeStrings?.BugReportCopyFailed ?? 'Copy this into your bug report:');
2176
+ status.classList.remove('hidden');
2177
+ textarea.value = text;
2178
+ textarea.classList.toggle('hidden', copied);
2179
+ if (!copied) textarea.select();
2180
+ }
2181
+
1204
2182
  // mode: 'boot' resolves {type:'new'} or {type:'load', slotIndex} once the
1205
2183
  // user picks; 'manage' just opens the persistent manager (callers act via
1206
2184
  // the wired-up click handlers above, nothing to await).
@@ -1208,9 +2186,19 @@ async function openSavesDialog(mode, gameId = WebPlayer.gameId) {
1208
2186
  ensureSavesDialogWired();
1209
2187
  const dlg = document.getElementById('qv-saves');
1210
2188
  hideSavesError();
2189
+ document.getElementById('qv-saves-bug-report-status')?.classList.add('hidden');
2190
+ document.getElementById('qv-saves-bug-report-text')?.classList.add('hidden');
2191
+ cancelSavesConfirm?.();
2192
+ renamingSave = null;
2193
+ const saveMenu = document.getElementById('qv-saves-menu');
2194
+ if (saveMenu?.matches(':popover-open')) {
2195
+ saveMenuClosingByUs = true;
2196
+ saveMenu.hidePopover();
2197
+ }
1211
2198
  dlg.dataset.mode = mode;
1212
2199
  dlg.setAttribute('aria-labelledby', mode === 'boot' ? 'qv-saves-heading-boot' : 'qv-saves-heading-manage');
1213
- renderSavesList(await GameSaver.listSaves(gameId), mode);
2200
+ currentSaves = await listSavesOrReportBlocked(gameId);
2201
+ renderSavesList(currentSaves, mode);
1214
2202
 
1215
2203
  if (mode === 'boot') {
1216
2204
  return new Promise(resolve => {
@@ -1226,11 +2214,9 @@ async function openSavesDialog(mode, gameId = WebPlayer.gameId) {
1226
2214
  // Only ever opened in editor-preview sessions, or a source=local play session
1227
2215
  // for a raw .aslx file (see WebPlayer.setCanDebug's call sites in
1228
2216
  // initWasmPlayer/restartGame) — element browser, per-tab attribute inspector
1229
- // with a "hack your own game" override, and a walkthrough runner. Mirrors
1230
- // WebPlayer's Debugger/Attributes/Walkthrough.razor, which
1231
- // drive IGameDebug directly as Blazor components; here the same data comes
1232
- // over the bridge as JSON (Bridge.Get*Json — see WasmPlayerBridge.cs) for
1233
- // plain-DOM rendering instead.
2217
+ // with a "hack your own game" override, and a walkthrough runner. The
2218
+ // IGameDebug data comes over the bridge as JSON (Bridge.Get*Json — see
2219
+ // WasmPlayerBridge.cs) for plain-DOM rendering.
1234
2220
 
1235
2221
  let debuggerWired = false;
1236
2222
  let debuggerActiveTab = 'Walkthrough';
@@ -1346,8 +2332,8 @@ function clamp(value, min, max) {
1346
2332
  return Math.min(Math.max(value, min), Math.max(min, max));
1347
2333
  }
1348
2334
 
1349
- // Applied right after every showModal() (see wireDebuggerButton/restartGame's
1350
- // call sites), before the browser gets a chance to paint — so the dialog
2335
+ // Applied right after the dialog is opened (see wireDebuggerButton) and on
2336
+ // viewport resize, before the browser gets a chance to paint — so the dialog
1351
2337
  // never visibly flashes at its old browser-default centered position first.
1352
2338
  // Computes a centered default the very first time it's called; every
1353
2339
  // subsequent call (reopening the dialog, or after the user drags/resizes)
@@ -1508,7 +2494,7 @@ function renderDebuggerTabs(types) {
1508
2494
  const tabs = document.getElementById('qv-debugger-tabs');
1509
2495
  const allTabs = ['Walkthrough', ...types];
1510
2496
  tabs.innerHTML = allTabs.map(tab =>
1511
- `<button type="button" class="btn btn-sm ${tab === debuggerActiveTab ? 'preset-filled-primary-500' : 'preset-tonal-surface'}" data-tab="${_esc(tab)}">${_esc(tab)}</button>`
2497
+ `<button type="button" class="btn btn-sm ${tab === debuggerActiveTab ? 'preset-filled-primary-700-300' : 'preset-tonal-surface'}" data-tab="${_esc(tab)}">${_esc(tab)}</button>`
1512
2498
  ).join('');
1513
2499
  }
1514
2500
 
@@ -1530,7 +2516,7 @@ function renderDebuggerList() {
1530
2516
  if (!debuggerListSortAscending) sorted.reverse();
1531
2517
 
1532
2518
  if (!sorted.length) {
1533
- list.innerHTML = '<li class="text-sm text-surface-500 px-2 py-1">Nothing here.</li>';
2519
+ list.innerHTML = '<li class="text-sm text-surface-700-300 px-2 py-1">Nothing here.</li>';
1534
2520
  return items;
1535
2521
  }
1536
2522
 
@@ -1554,7 +2540,7 @@ function renderDebuggerWalkthroughDetail(name) {
1554
2540
  + '</ol>'
1555
2541
  + '</div>'
1556
2542
  + '<div class="qv-debugger-footer flex gap-2 items-center">'
1557
- + `<button type="button" class="btn preset-filled-primary-500" data-run-walkthrough="${_esc(name)}"${running ? ' disabled' : ''}>Run</button>`
2543
+ + `<button type="button" class="btn preset-filled-primary-700-300" data-run-walkthrough="${_esc(name)}"${running ? ' disabled' : ''}>Run</button>`
1558
2544
  + `<button type="button" class="btn preset-tonal-surface${running ? '' : ' hidden'}" data-cancel-walkthrough>Cancel</button>`
1559
2545
  + `<span class="text-sm" data-walkthrough-status>${running ? 'Running…' : ''}</span>`
1560
2546
  + '</div>';
@@ -1610,7 +2596,7 @@ function renderDebuggerAttrRows() {
1610
2596
 
1611
2597
  const attrs = sortedFilteredDebuggerAttrs();
1612
2598
  if (!attrs.length) {
1613
- tbody.innerHTML = '<tr><td colspan="3" class="text-surface-500">No matching attributes.</td></tr>';
2599
+ tbody.innerHTML = '<tr><td colspan="3" class="text-surface-700-300">No matching attributes.</td></tr>';
1614
2600
  return;
1615
2601
  }
1616
2602
 
@@ -1640,7 +2626,7 @@ function renderDebuggerAttributesDetail(tab, obj) {
1640
2626
  const attrs = Object.keys(debuggerAttrData);
1641
2627
 
1642
2628
  if (!attrs.length) {
1643
- detail.innerHTML = '<p class="text-surface-500">No attributes.</p>';
2629
+ detail.innerHTML = '<p class="text-surface-700-300">No attributes.</p>';
1644
2630
  return;
1645
2631
  }
1646
2632
 
@@ -1701,7 +2687,7 @@ function renderDebuggerOverridePanel(attr, item) {
1701
2687
 
1702
2688
  if (!item.CanOverride) {
1703
2689
  panel.innerHTML = `<div class="text-sm font-semibold mb-1">${_esc(attr)}</div>`
1704
- + '<div class="text-xs text-surface-500">This value isn\'t a simple type the debugger can override directly.</div>';
2690
+ + '<div class="text-xs text-surface-700-300">This value isn\'t a simple type the debugger can override directly.</div>';
1705
2691
  return;
1706
2692
  }
1707
2693
 
@@ -1710,14 +2696,14 @@ function renderDebuggerOverridePanel(attr, item) {
1710
2696
  + `<input class="qv-debugger-input flex-1" type="text" value="${_esc(item.EditValue ?? item.Value)}" id="qv-debugger-override-input">`
1711
2697
  + '<button type="button" class="btn preset-tonal-primary" id="qv-debugger-override-apply">Apply</button>'
1712
2698
  + '</div>'
1713
- + `<div class="text-xs text-surface-500 mt-1">${_esc(DEBUGGER_OVERRIDE_HINT)}</div>`
2699
+ + `<div class="text-xs text-surface-700-300 mt-1">${_esc(DEBUGGER_OVERRIDE_HINT)}</div>`
1714
2700
  + '<div class="text-xs preset-tonal-error hidden mt-1" id="qv-debugger-override-error"></div>';
1715
2701
  }
1716
2702
 
1717
2703
  function renderDebuggerDetail() {
1718
2704
  const detail = document.getElementById('qv-debugger-detail');
1719
2705
  if (!debuggerSelectedItem) {
1720
- detail.innerHTML = '<p class="text-surface-500">Select an item to view details.</p>';
2706
+ detail.innerHTML = '<p class="text-surface-700-300">Select an item to view details.</p>';
1721
2707
  return;
1722
2708
  }
1723
2709
 
@@ -1927,28 +2913,16 @@ function ensureDebuggerWired() {
1927
2913
 
1928
2914
  // Called after every WebPlayer.initUI() — #cmdDebug is part of playercore.htm,
1929
2915
  // which is fully replaced on every boot/restart (see swapInPlayerUi), so its
1930
- // showModal() listener (wired in the shared playercore.js) is fresh each time
1931
- // and this "populate on open" listener needs re-attaching alongside it.
2916
+ // click listener needs re-attaching each time.
1932
2917
  function wireDebuggerButton() {
1933
2918
  const cmdDebug = document.getElementById('cmdDebug');
1934
2919
  if (!cmdDebug) return;
1935
2920
  cmdDebug.addEventListener('click', () => {
1936
- // playercore.js's own click listener (registered first — see this
1937
- // function's doc comment — and shared with WebPlayer, whose separate
1938
- // Blazor Debugger.razor still wants the native modal behavior it
1939
- // gives) has already opened this as a *modal* dialog by the time
1940
- // this listener runs. Reopen it non-modally instead of touching that
1941
- // shared file: unlike WebPlayer's dialog, this one is resizable and
1942
- // movable (wireDebuggerMoveResize) rather than a fixed centered
1943
- // overlay, so keeping it modal only got in the way of the thing a
1944
- // dev tool window is actually for — leaving it open while still
1945
- // playing (refreshDebuggerAfterTurn keeps it in sync as turns
1946
- // happen). close()+show() in the same synchronous click handler,
1947
- // before the browser gets a chance to paint the modal state — same
1948
- // reasoning as applyDebuggerRect's doc comment — so there's no
1949
- // visible flash of the modal backdrop.
2921
+ // Non-modal: the dialog is resizable and movable
2922
+ // (wireDebuggerMoveResize), and the point of a dev tool window is
2923
+ // leaving it open while still playing (refreshDebuggerAfterTurn keeps
2924
+ // it in sync as turns happen). show() is a no-op if it's already open.
1950
2925
  const dlg = document.getElementById('questVivaDebugger');
1951
- dlg.close();
1952
2926
  dlg.show();
1953
2927
  ensureDebuggerWired();
1954
2928
  applyDebuggerRect();
@@ -2005,7 +2979,7 @@ function wireDebuggerRestartButton(isPreview) {
2005
2979
  // (applied to them by initPlayerUI's "$('#gameBorder button').button()"
2006
2980
  // — which already ran by the time this is called, so it never touches
2007
2981
  // this button; do it explicitly here instead).
2008
- $(cmdRestart).button();
2982
+ if (window.jQuery) $(cmdRestart).button();
2009
2983
  }
2010
2984
 
2011
2985
  // Nothing here can ever work over file:// — the runtime fetches its own
@@ -2087,6 +3061,15 @@ function showError(downloadUrl, isLocalFile, error) {
2087
3061
  if (isLocalFile) {
2088
3062
  html = '<strong>Couldn\'t open that file.</strong> '
2089
3063
  + 'It doesn\'t look like a Quest game file (.quest, .aslx, .asl or .cas). Choose a different file below.';
3064
+ } else if (error?.fromGameApi && error.status === 410) {
3065
+ // textadventures.co.uk answers 410 Gone for a game it has removed on
3066
+ // purpose. That's nothing the player can fix, so don't suggest checking
3067
+ // the address: say what happened and where to find other games.
3068
+ html = '<strong>This game is no longer available.</strong> '
3069
+ + 'It has been removed from textadventures.co.uk, so it can\'t be played here any more. '
3070
+ + '<a class="anchor" href="https://textadventures.co.uk/" target="_blank" rel="noopener">'
3071
+ + 'Find other games on textadventures.co.uk</a>. '
3072
+ + 'If you have your own copy of the game file, you can still load it with the file picker below.';
2090
3073
  } else if (Number.isInteger(error?.status)) {
2091
3074
  // We got a real HTTP response, so we know exactly why it failed —
2092
3075
  // no need to guess at CORS. downloadUrl may still be unknown here
@@ -2134,7 +3117,7 @@ function showError(downloadUrl, isLocalFile, error) {
2134
3117
  // header+bullets format the Editor uses for a load-time error (see
2135
3118
  // EditorController.cs's "Failed to load game due to the following errors:"),
2136
3119
  // with a blank line between the header and the error message.
2137
- function showGameLoadError(errors, showPickers = true) {
3120
+ function showGameLoadError(errors, showPickers = true, fromPickedFiles = false) {
2138
3121
  document.documentElement.classList.remove('qv-booting');
2139
3122
  const pickers = document.getElementById('qv-pickers');
2140
3123
  const msg = document.getElementById('qv-loading-msg');
@@ -2143,15 +3126,25 @@ function showGameLoadError(errors, showPickers = true) {
2143
3126
  if (pickers) pickers.style.display = showPickers ? 'block' : 'none';
2144
3127
  if (!errorEl) return;
2145
3128
  const list = errors.length ? errors : ['Unknown error'];
3129
+ // A game picked from disk only brings the files the player chose, so a library it includes
3130
+ // from its own folder is missing unless it was chosen too. Say how to fix that.
3131
+ const missingLibraries = fromPickedFiles
3132
+ ? list.map(e => /Library file not found: (.+)$/.exec(e)?.[1]).filter(Boolean)
3133
+ : [];
3134
+ const libraryHint = missingLibraries.length
3135
+ ? `This game uses ${missingLibraries.join(', ')}. Open the game again, and choose `
3136
+ + `${missingLibraries.length === 1 ? 'that file' : 'those files'} too, along with the game file.`
3137
+ : null;
2146
3138
  errorEl.style.whiteSpace = showPickers ? '' : 'pre-wrap';
2147
3139
  if (showPickers) {
2148
3140
  errorEl.innerHTML = '<strong>This game couldn\'t be started.</strong> '
2149
3141
  + 'The game file loaded, but Quest Viva reported a problem with its contents:<br/>'
2150
3142
  + list.map(_esc).join('<br/>')
2151
- + '<br/>You can try a different file below.';
3143
+ + (libraryHint ? '<br/>' + _esc(libraryHint) : '<br/>You can try a different file below.');
2152
3144
  } else {
2153
3145
  errorEl.innerHTML = _esc('Failed to load game due to the following errors:\n\n'
2154
- + list.map(e => '* ' + e).join('\n'));
3146
+ + list.map(e => '* ' + e).join('\n')
3147
+ + (libraryHint ? '\n\n' + libraryHint : ''));
2155
3148
  }
2156
3149
  errorEl.style.display = 'block';
2157
3150
  wireStartScreen();
@@ -2170,6 +3163,31 @@ function setLocationParam(name, value) {
2170
3163
  history.replaceState(null, '', newUrl);
2171
3164
  }
2172
3165
 
3166
+ // An .aslx game can <include ref="..."/> a library from its own folder, and a picked file brings
3167
+ // no folder with it, so the player can choose the game together with its libraries. Of the
3168
+ // files chosen, the game is the .quest/.asl/.cas, or else the .aslx whose root element is <asl>
3169
+ // (a library's is <library>); every other .aslx is passed on as an adjacent file for
3170
+ // WorldModel.GetLibraryStream to find. Returns null when no game is among them.
3171
+ async function splitPickedGameFiles(files) {
3172
+ const read = await Promise.all(files.map(async f => ({ name: f.name, bytes: new Uint8Array(await f.arrayBuffer()) })));
3173
+ const isAslx = f => /\.aslx$/i.test(f.name);
3174
+ const game = read.find(f => /\.(quest|asl|cas)$/i.test(f.name))
3175
+ ?? read.find(f => isAslx(f) && aslxRootElement(f.bytes) === 'asl')
3176
+ ?? (read.length === 1 ? read[0] : null);
3177
+ if (!game) return null;
3178
+ const adjacentFiles = {};
3179
+ for (const f of read) {
3180
+ if (f !== game && isAslx(f)) adjacentFiles[f.name] = f.bytes;
3181
+ }
3182
+ return { bytes: game.bytes, filename: game.name, adjacentFiles };
3183
+ }
3184
+
3185
+ // The name of an XML file's root element, skipping any XML declaration and comments (TextDecoder drops a BOM).
3186
+ function aslxRootElement(bytes) {
3187
+ const text = new TextDecoder().decode(bytes.subarray(0, 4096));
3188
+ return /^\s*(?:<\?[\s\S]*?\?>\s*|<!--[\s\S]*?-->\s*)*<([A-Za-z_][\w.-]*)/.exec(text)?.[1] ?? null;
3189
+ }
3190
+
2173
3191
  let _startScreenWired = false;
2174
3192
  function wireStartScreen() {
2175
3193
  if (_startScreenWired) return;
@@ -2182,15 +3200,23 @@ function wireStartScreen() {
2182
3200
  if (!fileBtn) return;
2183
3201
 
2184
3202
  fileBtn.addEventListener('click', () => fileInput.click());
2185
- fileInput.addEventListener('change', () => {
2186
- const file = fileInput.files?.[0];
2187
- if (!file) return;
3203
+ fileInput.addEventListener('change', async () => {
3204
+ const files = [...(fileInput.files ?? [])];
3205
+ fileInput.value = '';
3206
+ if (!files.length) return;
2188
3207
  setLocationParam(null);
2189
3208
  showLoading();
2190
- const reader = new FileReader();
2191
- reader.onload = () => startGame(new Uint8Array(reader.result), file.name)
2192
- .catch(() => showError(null, true));
2193
- reader.readAsArrayBuffer(file);
3209
+ try {
3210
+ const picked = await splitPickedGameFiles(files);
3211
+ if (!picked) {
3212
+ showError(null, true);
3213
+ return;
3214
+ }
3215
+ gameFromPickedFiles = true;
3216
+ await startGame(picked.bytes, picked.filename, null, null, false, null, null, picked.adjacentFiles);
3217
+ } catch {
3218
+ showError(null, true);
3219
+ }
2194
3220
  });
2195
3221
 
2196
3222
  async function doLoadUrl() {
@@ -2246,7 +3272,7 @@ async function fetchGameBytes(url) {
2246
3272
  return;
2247
3273
  }
2248
3274
 
2249
- // Single-file export (see scripts/export-embedded.mjs): the game bytes are
3275
+ // Single-file export (see PlayerExport in src/PlayerCore): the game bytes are
2250
3276
  // inlined as base64 by a <script> tag before this one, so there's nothing
2251
3277
  // to fetch at all — decode and hand straight to the same startGame() every
2252
3278
  // other boot source converges on. Checked first since, unlike the sources
@@ -2318,12 +3344,56 @@ async function fetchGameBytes(url) {
2318
3344
  // play session (isPreview stays false) since a real save is
2319
3345
  // still wanted here.
2320
3346
  const allowDebug = /\.aslx$/i.test(data.filename ?? '');
3347
+ gameFromPickedFiles = !!data.picked;
2321
3348
  await startGame(data.bytes, data.filename, bc, null, false, null, null, data.adjacentFiles ?? null, allowDebug);
2322
3349
  }
2323
3350
  };
2324
3351
  return;
2325
3352
  }
2326
3353
 
3354
+ // `qv preview` (src/Cli/PreviewServer.cs): this page is served by qv on loopback, with the
3355
+ // author's game folder under game/. qv/game names the game file and every .aslx beside it
3356
+ // that it could include, like the Editor's listLibraryCandidates, so an <include ref> of the
3357
+ // author's own library resolves; resourceRoot makes its images, sounds and scripts load from
3358
+ // the folder. An .aslx is the author's work in progress, so Debug is on for it, as for
3359
+ // source=local. qv/events sends 'reload' when a file in the folder changes, and the page
3360
+ // reloads to play the edited game from the start.
3361
+ if (params.get('source') === 'qv') {
3362
+ preloadRuntime();
3363
+ const gamePromise = (async () => {
3364
+ const infoResponse = await fetch('qv/game', { cache: 'no-store' });
3365
+ if (!infoResponse.ok) throw new Error(`qv/game: HTTP ${infoResponse.status}`);
3366
+ const { file, libraries } = await infoResponse.json();
3367
+ const fetchFile = async (name) => {
3368
+ const response = await fetch('game/' + encodeURIComponent(name), { cache: 'no-store' });
3369
+ if (!response.ok) {
3370
+ const err = new Error(`HTTP ${response.status}`);
3371
+ err.status = response.status;
3372
+ throw err;
3373
+ }
3374
+ return new Uint8Array(await response.arrayBuffer());
3375
+ };
3376
+ const adjacentFiles = {};
3377
+ for (const library of libraries ?? []) adjacentFiles[library] = await fetchFile(library);
3378
+ return { bytes: await fetchFile(file), filename: file, adjacentFiles };
3379
+ })();
3380
+ resourceRoot = 'game/';
3381
+
3382
+ new EventSource('qv/events').addEventListener('reload', () => window.location.reload());
3383
+
3384
+ document.addEventListener('DOMContentLoaded', async () => {
3385
+ showLoading();
3386
+ try {
3387
+ const { bytes, filename, adjacentFiles } = await gamePromise;
3388
+ await startGame(bytes, filename, null, null, false, null, null, adjacentFiles,
3389
+ /\.aslx$/i.test(filename));
3390
+ } catch (err) {
3391
+ showError('qv/game', false, err);
3392
+ }
3393
+ });
3394
+ return;
3395
+ }
3396
+
2327
3397
  const id = params.get('id');
2328
3398
  // A URL-supplied game always wins over the configured default, so authors
2329
3399
  // testing/sharing a specific ?url= link aren't stuck on their own game.
@@ -2340,15 +3410,20 @@ async function fetchGameBytes(url) {
2340
3410
  progressUrl = `${apiRoot}gameprogress/${encodeURIComponent(id)}`;
2341
3411
  const gamePromise = (async () => {
2342
3412
  const apiResponse = await fetch(`${apiRoot}game/${id}?${clientInfoParams()}`);
3413
+ markLoad('api');
2343
3414
  if (!apiResponse.ok) {
2344
3415
  const err = new Error(`API: HTTP ${apiResponse.status}`);
2345
3416
  err.status = apiResponse.status;
3417
+ err.fromGameApi = true;
2346
3418
  throw err;
2347
3419
  }
2348
- const { sourceGameUrl, resourceRoot: resRoot } = await apiResponse.json();
3420
+ const { sourceGameUrl, resourceRoot: resRoot, name, author, cover } = await apiResponse.json();
3421
+ showGameInfo({ name, author, cover });
2349
3422
  resolvedSourceUrl = sourceGameUrl;
2350
3423
  resourceRoot = resRoot || null;
2351
3424
  const { bytes, filename } = await fetchGameBytes(sourceGameUrl);
3425
+ markLoad('gameBytes');
3426
+ gameSizeBytes = bytes.length;
2352
3427
  return { bytes, filename };
2353
3428
  })();
2354
3429