squiffy-runtime 7.0.0-beta.1 → 7.0.0-beta.11

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 (111) hide show
  1. package/dist/assets.d.ts +1 -0
  2. package/dist/classes.test.d.ts +1 -0
  3. package/dist/confirmDialog.d.ts +8 -0
  4. package/dist/events.d.ts +12 -0
  5. package/dist/every.d.ts +12 -0
  6. package/dist/every.test.d.ts +1 -0
  7. package/dist/helpers.test.d.ts +1 -0
  8. package/dist/numbers.d.ts +3 -0
  9. package/dist/panels.d.ts +14 -0
  10. package/dist/panels.test.d.ts +1 -0
  11. package/dist/paths.d.ts +15 -0
  12. package/dist/paths.test.d.ts +1 -0
  13. package/dist/persistent.test.d.ts +1 -0
  14. package/dist/playerSettings.d.ts +17 -0
  15. package/dist/preview-host.d.ts +7 -3
  16. package/dist/preview-host.js +47 -5
  17. package/dist/preview-host.js.map +2 -2
  18. package/dist/preview-html.js +1 -1
  19. package/dist/preview-protocol.d.ts +16 -0
  20. package/dist/preview.d.ts +1 -0
  21. package/dist/saveSlots.d.ts +16 -0
  22. package/dist/saves.test.d.ts +1 -0
  23. package/dist/savesDialog.d.ts +43 -0
  24. package/dist/savesDialog.test.d.ts +1 -0
  25. package/dist/scripts.test.d.ts +1 -0
  26. package/dist/settings.test.d.ts +1 -0
  27. package/dist/settingsDialog.d.ts +17 -0
  28. package/dist/skill.test.d.ts +1 -0
  29. package/dist/sound.d.ts +35 -0
  30. package/dist/sound.test.d.ts +1 -0
  31. package/dist/squiffy.page.css +155 -0
  32. package/dist/squiffy.preview.html +1469 -136
  33. package/dist/squiffy.runtime.css +1123 -20
  34. package/dist/squiffy.runtime.d.ts +13 -1
  35. package/dist/squiffy.runtime.global.js +144 -79
  36. package/dist/squiffy.runtime.global.js.map +1 -1
  37. package/dist/squiffy.runtime.js +6771 -4424
  38. package/dist/squiffy.runtime.js.map +1 -1
  39. package/dist/state.d.ts +17 -0
  40. package/dist/storyLists.d.ts +4 -0
  41. package/dist/storyLists.test.d.ts +1 -0
  42. package/dist/style.test.d.ts +1 -0
  43. package/dist/textProcessor.d.ts +27 -0
  44. package/dist/transitions.test.d.ts +1 -0
  45. package/dist/types.d.ts +125 -0
  46. package/dist/types.plugins.d.ts +1 -0
  47. package/dist/uiLinks.test.d.ts +1 -0
  48. package/dist/utils.d.ts +2 -1
  49. package/dist/utils.test.d.ts +1 -0
  50. package/package.json +11 -6
  51. package/src/__snapshots__/squiffy.runtime.test.ts.snap +22 -22
  52. package/src/animation.test.ts +44 -0
  53. package/src/animation.ts +9 -5
  54. package/src/assets.test.ts +1 -3
  55. package/src/assets.ts +1 -1
  56. package/src/classes.test.ts +201 -0
  57. package/src/confirmDialog.ts +66 -0
  58. package/src/events.ts +19 -0
  59. package/src/every.test.ts +25 -0
  60. package/src/every.ts +94 -0
  61. package/src/helpers.test.ts +34 -0
  62. package/src/numbers.ts +21 -0
  63. package/src/panels.test.ts +225 -0
  64. package/src/panels.ts +187 -0
  65. package/src/paths.test.ts +66 -0
  66. package/src/paths.ts +155 -0
  67. package/src/persistent.test.ts +155 -0
  68. package/src/playerSettings.ts +128 -0
  69. package/src/pluginManager.ts +1 -0
  70. package/src/plugins/animate.ts +28 -4
  71. package/src/plugins/live.ts +18 -5
  72. package/src/plugins/plugins.test.ts +93 -6
  73. package/src/plugins/replaceLabel.ts +7 -3
  74. package/src/preview-host.test.ts +97 -1
  75. package/src/preview-host.ts +71 -10
  76. package/src/preview-protocol.ts +25 -3
  77. package/src/preview.main.ts +1 -0
  78. package/src/preview.test.ts +203 -4
  79. package/src/preview.ts +178 -12
  80. package/src/saveSlots.ts +159 -0
  81. package/src/saves.test.ts +199 -0
  82. package/src/savesDialog.test.ts +290 -0
  83. package/src/savesDialog.ts +499 -0
  84. package/src/scripts.test.ts +130 -0
  85. package/src/settings.test.ts +233 -0
  86. package/src/settingsDialog.ts +160 -0
  87. package/src/skill.test.ts +67 -0
  88. package/src/sound.test.ts +273 -0
  89. package/src/sound.ts +207 -0
  90. package/src/squiffy.page.css +155 -0
  91. package/src/squiffy.runtime.css +1123 -20
  92. package/src/squiffy.runtime.test.ts +2806 -44
  93. package/src/squiffy.runtime.ts +1111 -64
  94. package/src/state.ts +172 -11
  95. package/src/storyLists.test.ts +134 -0
  96. package/src/storyLists.ts +57 -0
  97. package/src/style.test.ts +89 -0
  98. package/src/textProcessor.ts +739 -58
  99. package/src/transitions.test.ts +343 -0
  100. package/src/types.plugins.ts +3 -0
  101. package/src/types.ts +209 -1
  102. package/src/uiLinks.test.ts +156 -0
  103. package/src/updater.ts +26 -8
  104. package/src/utils.test.ts +60 -0
  105. package/src/utils.ts +46 -14
  106. package/vite.config.ts +3 -4
  107. package/vite.preview.config.ts +16 -5
  108. package/dist/infixExpressions.d.ts +0 -2
  109. package/src/infixExpressions.test.ts +0 -187
  110. package/src/infixExpressions.ts +0 -323
  111. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -1,7 +1,10 @@
1
- import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt } from "./types.js";
2
- import { TextProcessor } from "./textProcessor.js";
1
+ import { SquiffyApi, SquiffyInitOptions, SquiffyScriptApi, SquiffyScriptEvent, Story, Section, Passage, StartAt, SavedGame, LoadSaveResult, TagFilter } from "./types.js";
2
+ import { listPassages, listSections, tagsOf } from "./storyLists.js";
3
+ import { TextProcessor, afterClear, errorHtml } from "./textProcessor.js";
4
+ import { toNumber } from "./numbers.js";
3
5
  import { Emitter, SquiffyEventMap } from "./events.js";
4
6
  import { State } from "./state.js";
7
+ import { checkSegment, readTarget, Target } from "./paths.js";
5
8
  import { updateStory } from "./updater.js";
6
9
  import { PluginManager } from "./pluginManager.js";
7
10
  import { Plugins } from "./plugins/index.js";
@@ -9,10 +12,28 @@ import { LinkHandler } from "./linkHandler.js";
9
12
  import { Animation } from "./animation.js";
10
13
  import { imports } from "./import.js";
11
14
  import { areInputsValid, setupInputValidation } from "./inputValidation.js";
12
- import { createAssetHtmlResolver } from "./assets.js";
13
-
14
- export type { SquiffyApi } from "./types.js";
15
+ import { createAssetHtmlResolver, isAbsolute } from "./assets.js";
16
+ import { Sound, DEFAULT_FADE } from "./sound.js";
17
+ import { EveryTimers } from "./every.js";
18
+ import { confirmDialog } from "./confirmDialog.js";
19
+ import { createSavesDialog, type SavesDialog } from "./savesDialog.js";
20
+ import { createSettingsDialog, type SettingsDialog } from "./settingsDialog.js";
21
+ import { PlayerSettings } from "./playerSettings.js";
22
+
23
+ export type { SquiffyApi, SquiffyScriptApi, SquiffyScriptEvent, SavedGame, LoadSaveResult, PlayerSetting, PlayerSettingOption, SettingValue } from "./types.js";
15
24
  export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
25
+ export { createSavesDialog, formatSaveTime, SAVES_STRINGS, SAVE_FILE_EXTENSION } from "./savesDialog.js";
26
+ export type { SavesDialog, SavesDialogOptions, SavesStringName } from "./savesDialog.js";
27
+ export { confirmDialog } from "./confirmDialog.js";
28
+ export { createSettingsDialog, SETTINGS_STRINGS } from "./settingsDialog.js";
29
+ export type { SettingsDialog, SettingsDialogOptions } from "./settingsDialog.js";
30
+ export type { ConfirmDialogOptions } from "./confirmDialog.js";
31
+ export { indexedDbSaveSlots, memorySaveSlots } from "./saveSlots.js";
32
+ export { createPanels } from "./panels.js";
33
+ export type { Panels, PanelsOptions } from "./panels.js";
34
+ export { PANEL_ICONS } from "./types.js";
35
+ export type { Panel, PanelIcon } from "./types.js";
36
+ export type { SaveSlot, SaveSlots } from "./saveSlots.js";
16
37
 
17
38
  export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> => {
18
39
  let story: Story;
@@ -21,9 +42,27 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
21
42
  let currentPassageElement: HTMLElement | null;
22
43
  let currentBlockOutputElement: HTMLElement | null;
23
44
  let scrollPosition = 0;
45
+ // Set when the screen is cleared, so the next scroll goes up to the top of the new screen (#54)
46
+ let scrollToTop = false;
47
+ // The section or passage being shown, and the ones it takes its @transition and @leave from,
48
+ // for a {{clear}} in its text (#524)
49
+ let shownFrom: (Section | Passage | undefined)[] = [];
50
+ // Errors from setting attributes (e.g. @set gold += abc), shown at the start of the next text
51
+ // written. A link's setters run before the next section has anywhere to show them.
52
+ const pendingErrors: string[] = [];
24
53
  const emitter = new Emitter<SquiffyEventMap>();
25
54
  const transitions: (() => Promise<void>)[] = [];
26
55
  let runningTransitions = false;
56
+ // A {{goto ... after=}} waiting to happen (#375)
57
+ let gotoTimer: ReturnType<typeof setTimeout> | undefined;
58
+ // {{goto}}s followed one after another without the player doing anything, so a loop can't hang
59
+ // the browser
60
+ let gotoHops = 0;
61
+ const MAX_GOTO_HOPS = 100;
62
+ // The {{#every}}s showing their text again and again (#451), and how many sections or passages
63
+ // are being shown, which they wait for
64
+ const everyTimers = new EveryTimers(() => currentSectionElement, tickEvery);
65
+ let navigating = 0;
27
66
 
28
67
  async function handleLink(link: HTMLElement): Promise<boolean> {
29
68
  if (runningTransitions) return false;
@@ -40,13 +79,31 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
40
79
  const passage = link.getAttribute("data-passage");
41
80
  const section = link.getAttribute("data-section");
42
81
 
82
+ if (passage !== null || section !== null) {
83
+ gotoHops = 0;
84
+ // A text box that goes somewhere when Enter is pressed (#454) keeps what was typed
85
+ // first, so the section or passage it goes to can use it. Other text boxes are only
86
+ // kept when the player leaves the section.
87
+ if (link instanceof window.HTMLInputElement) {
88
+ const attribute = link.getAttribute("data-attribute") || link.id;
89
+ if (attribute) set(attribute, link.value);
90
+ }
91
+ // The story-wide turn count (#377). A {{goto}} isn't a turn, as the player didn't click it.
92
+ set("turns", (get("turns") || 0) + 1);
93
+ }
94
+
43
95
  if (passage !== null) {
44
- disableLink(link);
45
- set("_turncount", get("_turncount") + 1);
96
+ // A passage with @repeat can be clicked again, and doesn't count towards @1, @2... and @last
97
+ let clicked: string | undefined;
98
+ if (!isRepeatPassage(passage)) {
99
+ disableLink(link);
100
+ clicked = markClicked(link);
101
+ set("_turncount", get("_turncount") + 1);
102
+ }
46
103
  await processLink(link);
47
104
  if (passage) {
48
105
  currentBlockOutputElement = null;
49
- await showPassage(passage);
106
+ await showPassage(passage, clicked);
50
107
  }
51
108
 
52
109
  emitter.emit("linkClick", { linkType: "passage" });
@@ -86,19 +143,51 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
86
143
  }
87
144
  }
88
145
 
146
+ function isRepeatPassage(passageName: string) {
147
+ if (!passageName) return false;
148
+ const sectionPassages = currentSection?.passages;
149
+ if (sectionPassages && passageName in sectionPassages) return !!sectionPassages[passageName].repeat;
150
+ const masterPassages = story.sections[""]?.passages;
151
+ return !!(masterPassages && passageName in masterPassages && masterPassages[passageName].repeat);
152
+ }
153
+
154
+ // A link, or a text box that goes to a passage when Enter is pressed (#454)
89
155
  function disableLink(link: Element) {
156
+ if (link instanceof window.HTMLInputElement) {
157
+ link.disabled = true;
158
+ link.classList.add("disabled");
159
+ return;
160
+ }
90
161
  link.classList.add("disabled");
91
162
  link.setAttribute("tabindex", "-1");
92
163
  }
93
164
 
94
165
  function enableLink(link: Element) {
166
+ if (link instanceof window.HTMLInputElement) {
167
+ link.disabled = false;
168
+ link.classList.remove("disabled");
169
+ return;
170
+ }
95
171
  link.classList.remove("disabled");
96
172
  link.removeAttribute("tabindex");
97
173
  }
174
+
175
+ // Numbers a passage link that was clicked, so that going back can enable just that link, and
176
+ // not the others to the same passage, such as the other items' links in an {{#each}} (#448)
177
+ function markClicked(link: Element) {
178
+ let max = 0;
179
+ for (const other of outputElement.querySelectorAll("[data-clicked]")) {
180
+ max = Math.max(max, Number(other.getAttribute("data-clicked")) || 0);
181
+ }
182
+ const id = String(max + 1);
183
+ link.setAttribute("data-clicked", id);
184
+ return id;
185
+ }
98
186
 
99
187
  async function begin(startAt?: StartAt) {
100
188
  if (startAt && startAt.section in story.sections) {
101
189
  // Start somewhere else in a fresh story, e.g. from the section being edited
190
+ runUiJs();
102
191
  await go(startAt.section);
103
192
  if (startAt.passage !== undefined && get("_section") == startAt.section) {
104
193
  await showPassage(startAt.passage);
@@ -107,7 +196,92 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
107
196
  }
108
197
  if (!load()) {
109
198
  await go(story.start);
199
+ return;
200
+ }
201
+ // As when a saved game is loaded, so that panels show the attributes it has
202
+ const passage = get("_passage");
203
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
204
+ // Saved while waiting for a {{goto}}, so carry on waiting
205
+ await resumeGoto();
206
+ everyTimers.sync();
207
+ }
208
+
209
+ async function resumeGoto() {
210
+ const element = currentPassageElement ?? currentSectionElement;
211
+ const section = element?.getAttribute("data-goto");
212
+ if (section && section in story.sections) {
213
+ await followGoto({ section, after: Number(element.getAttribute("data-goto-after") || 0) });
214
+ }
215
+ }
216
+
217
+ function cancelGoto() {
218
+ clearTimeout(gotoTimer);
219
+ gotoTimer = undefined;
220
+ textProcessor.goto = null;
221
+ textProcessor.deactivate.clear();
222
+ }
223
+
224
+ // Disables the links to the passages that a {{deactivate}} in the text just shown asked for
225
+ // (#13). The element that did it, and each link it disabled, get the same number, so that going
226
+ // back can enable just those links again. A link already disabled by a click is left alone.
227
+ function takeDeactivate(element: HTMLElement) {
228
+ const names = textProcessor.deactivate;
229
+ if (names.size == 0) return;
230
+ const id = String((get("_deactivations") || 0) + 1);
231
+ set("_deactivations", Number(id));
232
+ element.setAttribute("data-deactivates", id);
233
+ for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
234
+ if (names.has(link.getAttribute("data-passage")!) && !link.classList.contains("disabled")) {
235
+ disableLink(link);
236
+ link.setAttribute("data-deactivated-by", id);
237
+ }
238
+ }
239
+ names.clear();
240
+ }
241
+
242
+ // Going back: enables the links that the element's {{deactivate}} disabled
243
+ function undoDeactivate(element: HTMLElement) {
244
+ const id = element.getAttribute("data-deactivates");
245
+ if (!id) return;
246
+ for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-deactivated-by="${id}"]`)) {
247
+ enableLink(link);
248
+ link.removeAttribute("data-deactivated-by");
249
+ }
250
+ }
251
+
252
+ // Takes the {{goto}} from the text just shown, if there was one, and marks the section or
253
+ // passage element with it, so that going back skips it, and loading resumes it.
254
+ function takeGoto(element: HTMLElement) {
255
+ const pending = textProcessor.goto;
256
+ textProcessor.goto = null;
257
+ if (pending) {
258
+ element.setAttribute("data-goto", pending.section);
259
+ if (pending.after) element.setAttribute("data-goto-after", String(pending.after));
110
260
  }
261
+ return pending;
262
+ }
263
+
264
+ async function followGoto(pending: { section: string; after: number } | null) {
265
+ if (!pending) return;
266
+ if (pending.after > 0) {
267
+ gotoTimer = setTimeout(() => {
268
+ gotoTimer = undefined;
269
+ gotoHops = 0;
270
+ void go(pending.section);
271
+ }, pending.after);
272
+ return;
273
+ }
274
+ if (++gotoHops > MAX_GOTO_HOPS) {
275
+ gotoHops = 0;
276
+ const element = currentPassageElement ?? currentSectionElement;
277
+ element.removeAttribute("data-goto");
278
+ const message = `stopped after ${MAX_GOTO_HOPS} in a row without the player clicking anything, going to "${pending.section}". Is there a loop?`;
279
+ console.error("Squiffy error in {{goto}}:", message);
280
+ element.insertAdjacentHTML("beforeend", errorHtml("Error in {{goto}}:", message));
281
+ save();
282
+ return;
283
+ }
284
+ await go(pending.section);
111
285
  }
112
286
 
113
287
  async function processLink(link: HTMLElement) {
@@ -122,7 +296,87 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
122
296
  }
123
297
  }
124
298
 
299
+ // Runs a setter from @set or a link, e.g. gold += 5. An error leaves the attribute as it was,
300
+ // and is shown with the next text written.
125
301
  function setAttribute(expr: string) {
302
+ try {
303
+ if (story.expressions) {
304
+ setWithExpression(expr);
305
+ }
306
+ else {
307
+ setWithoutExpression(expr);
308
+ }
309
+ }
310
+ catch (e) {
311
+ const message = e instanceof Error ? e.message : String(e);
312
+ console.error(`Squiffy error in "${expr}":`, message);
313
+ pendingErrors.push(errorHtml(`Error in "${expr}":`, message));
314
+ }
315
+ }
316
+
317
+ // +=, -=, *= and /=, which only work on numbers (#374)
318
+ function operate(lhs: string | string[], op: string, amountValue: unknown) {
319
+ const what = op + "=";
320
+ const amount = toNumber(what, amountValue);
321
+ const path = typeof lhs == "string" ? [lhs] : lhs;
322
+ let value = toNumber(what, state.getAt(path));
323
+ if (op == "+") value += amount;
324
+ if (op == "-") value -= amount;
325
+ if (op == "*") value *= amount;
326
+ if (op == "/") value /= amount;
327
+ state.setAt(path, value);
328
+ }
329
+
330
+ // The path a setter's target names, with any [index] in it worked out, e.g. ["inventory", "2",
331
+ // "name"] for inventory[i].name when i is 2 (#442)
332
+ function targetPath(target: Target): string[] {
333
+ return [target.attribute, ...target.segments.map(segment => {
334
+ if ("name" in segment) return segment.name;
335
+ const index = textProcessor.evaluate(segment.index);
336
+ if (typeof index != "string" && typeof index != "number") {
337
+ throw new Error(`[${segment.index.trim()}] should be a number or text, to say which value to set`);
338
+ }
339
+ const name = String(index);
340
+ checkSegment(name);
341
+ return name;
342
+ })];
343
+ }
344
+
345
+ // A story with a squiffy.json (#373): the right-hand side is an expression, with the same rules
346
+ // as {{#if}}, e.g. weapon = "sword", gold = gold + price * 2, rich = gold > 100. The left-hand
347
+ // side can be a value inside an object, e.g. hero.hp = 10 or inventory[i].name = "lamp" (#442).
348
+ function setWithExpression(expr: string) {
349
+ const target = readTarget(expr);
350
+ const textMatch = target && /^\s*:=(.*)$/.exec(target.rest);
351
+ if (target && textMatch) {
352
+ // Text with {{...}} processed, as before
353
+ state.setAt(targetPath(target), ui.processText(textMatch[1], true));
354
+ return;
355
+ }
356
+ const match = target && /^\s*([+\-*/]?)=(?!=)(.*)$/.exec(target.rest);
357
+ if (target && match) {
358
+ const [, op, rhs] = match;
359
+ const path = targetPath(target);
360
+ const value = textProcessor.evaluate(rhs);
361
+ if (op) {
362
+ operate(path, op, value);
363
+ }
364
+ else {
365
+ state.setAt(path, value);
366
+ }
367
+ return;
368
+ }
369
+ const not = /^\s*not\s+/.exec(expr);
370
+ const flag = readTarget(not ? expr.substring(not[0].length) : expr);
371
+ if (!flag || flag.rest.trim()) {
372
+ throw new Error("expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key");
373
+ }
374
+ state.setAt(targetPath(flag), !not);
375
+ }
376
+
377
+ // A story without a squiffy.json, as in Squiffy 6: the right-hand side is a number, true,
378
+ // false, @attribute, or else text
379
+ function setWithoutExpression(expr: string) {
126
380
  expr = expr.replace(/^(\w*\s*):=(.*)$/, (_, name, value) => (name + "=" + ui.processText(value, true)));
127
381
  const setRegex = /^([\w]*)\s*=\s*(.*)$/;
128
382
  const setMatch = setRegex.exec(expr);
@@ -149,24 +403,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
149
403
  if (incDecMatch) {
150
404
  const lhs = incDecMatch[1];
151
405
  const op = incDecMatch[2];
152
- let rhs = incDecMatch[3];
153
- if (rhs.startsWith("@")) rhs = get(rhs.substring(1));
154
- const rhsNumeric = parseFloat(rhs);
155
- let value = get(lhs);
156
- if (value === null) value = 0;
157
- if (op == "+") {
158
- value += rhsNumeric;
159
- }
160
- if (op == "-") {
161
- value -= rhsNumeric;
162
- }
163
- if (op == "*") {
164
- value *= rhsNumeric;
165
- }
166
- if (op == "/") {
167
- value /= rhsNumeric;
168
- }
169
- set(lhs, value);
406
+ const rhsText = incDecMatch[3].trim();
407
+ operate(lhs, op, rhsText.startsWith("@") ? get(rhsText.substring(1)) : rhsText);
170
408
  }
171
409
  else {
172
410
  let value = true;
@@ -180,16 +418,45 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
180
418
  }
181
419
 
182
420
  async function go(sectionName: string) {
421
+ navigating++;
422
+ try {
423
+ await goNow(sectionName);
424
+ }
425
+ finally {
426
+ navigating--;
427
+ everyTimers.sync();
428
+ }
429
+ }
430
+
431
+ async function goNow(sectionName: string) {
432
+ cancelGoto();
183
433
  const oldCanGoBack = canGoBack();
184
434
  currentSection = story.sections[sectionName];
185
435
  if (!currentSection) return;
436
+ const sectionBefore = get("_section");
437
+ if (sectionBefore !== null) {
438
+ // Where the player was before this (#56): the section, or the passage in it shown last
439
+ set("previous", get("_passage") ?? sectionBefore);
440
+ set("previous_section", sectionBefore);
441
+ }
442
+ if (get("_passage") !== null) set("_passage", null);
186
443
  set("_section", sectionName);
444
+ // The story-wide turn count starts at 0 (#377), in a new story or one saved before it existed.
445
+ // It isn't a change the player made, so it isn't undone.
446
+ if (get("turns") === null) state.setInternal("turns", 0, false);
187
447
  state.setSeen(sectionName);
188
448
  const master = story.sections[""];
189
- if (master?.clear || currentSection.clear) {
449
+ const clear = master?.clear || currentSection.clear;
450
+ shownFrom = [currentSection, master];
451
+ // @leave: the old text goes before anything changes on the screen
452
+ if (clear) await leaveTransition(shownFrom);
453
+ // @class (#449): this section's classes replace the last one's
454
+ setSectionClasses([...(master?.classes ?? []), ...(currentSection.classes ?? [])]);
455
+ if (clear) {
190
456
  clearScreen();
191
457
  }
192
458
  newSection(sectionName);
459
+ startTransition(currentSectionElement, [currentSection, master]);
193
460
  const sectionElement = currentSectionElement;
194
461
  if (master) {
195
462
  await run(master, "[[]]");
@@ -211,6 +478,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
211
478
  setupInputValidation(currentSectionElement);
212
479
 
213
480
  set("_turncount", 0);
481
+ takeDeactivate(currentSectionElement);
482
+ const pending = takeGoto(currentSectionElement);
214
483
  writeUndoLog();
215
484
  save();
216
485
 
@@ -219,9 +488,13 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
219
488
  emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
220
489
  }
221
490
  emitter.emit("navigated", { section: sectionName });
491
+ await followGoto(pending);
222
492
  }
223
493
 
224
- function runJs(index: number, extra: any = null) {
494
+ let inAfterWrite = false;
495
+
496
+ // afterWrite: where squiffy.ui.afterWrite queues its functions, for a section or passage's JS (#106)
497
+ function runJs(index: number, extra: any = null, afterWrite?: (() => void)[]) {
225
498
  const squiffy = {
226
499
  get: get,
227
500
  set: set,
@@ -229,10 +502,30 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
229
502
  transition: addTransition,
230
503
  write: ui.write,
231
504
  scrollToEnd: ui.scrollToEnd,
505
+ afterWrite: (fn: () => void) => {
506
+ if (!afterWrite) {
507
+ throw new Error("squiffy.ui.afterWrite can only be used in a section or passage's JavaScript");
508
+ }
509
+ afterWrite.push(fn);
510
+ },
232
511
  },
233
512
  story: {
234
- go: go,
513
+ // In an afterWrite function, the section's text is already on the page, so going
514
+ // somewhere else waits until it has finished, like {{goto}} (#106)
515
+ go: (sectionName: string) => {
516
+ if (!inAfterWrite) return go(sectionName);
517
+ textProcessor.goto ??= { section: sectionName, after: 0 };
518
+ return Promise.resolve();
519
+ },
235
520
  seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
521
+ visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
522
+ lastVisited: (sectionOrPassage: string) => state.getLastVisited(sectionOrPassage),
523
+ // As the passages, sections and tags helpers (#527)
524
+ passages: (section?: string, filter?: TagFilter) => listPassages(story, section, get("_section"), filter),
525
+ sections: (filter?: TagFilter) => listSections(story, filter),
526
+ tags: (name?: string) => name === undefined
527
+ ? [...(story.sections[get("_section")]?.tags ?? [])]
528
+ : tagsOf(story, name, get("_section")),
236
529
  },
237
530
  element: outputElementContainer,
238
531
  import: imports,
@@ -245,9 +538,16 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
245
538
  if (section.attributes) {
246
539
  await processAttributes(section.attributes);
247
540
  }
541
+ // @music and @sound (#444)
542
+ if (section.music !== undefined) set("_music", section.music);
543
+ for (const file of section.sounds ?? []) {
544
+ if (file == "stop") sound.stopSounds();
545
+ else sound.play(file);
546
+ }
547
+ const afterWrite: (() => void)[] = [];
248
548
  if (section.jsIndex !== undefined) {
249
549
  const sectionBefore = get("_section");
250
- runJs(section.jsIndex);
550
+ runJs(section.jsIndex, null, afterWrite);
251
551
  if (get("_section") !== sectionBefore) {
252
552
  // JS called squiffy.story.go() and navigated away; the destination
253
553
  // section will handle rendering its own content.
@@ -255,7 +555,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
255
555
  }
256
556
  }
257
557
 
258
- ui.write(section.text || "", source);
558
+ let html = ui.renderHtml(section.text || "", false);
559
+ const cleared = afterClear(html);
560
+ if (cleared !== null) {
561
+ html = cleared;
562
+ await clearPartWay();
563
+ }
564
+ ui.writeHtml(html, source);
565
+
566
+ // Functions from squiffy.ui.afterWrite run once the text and its {{...}} are on the page (#106)
567
+ inAfterWrite = true;
568
+ try {
569
+ for (const fn of afterWrite) fn();
570
+ }
571
+ finally {
572
+ inAfterWrite = false;
573
+ }
259
574
 
260
575
  await runTransitions();
261
576
  }
@@ -271,7 +586,20 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
271
586
  currentSectionElement.classList.remove("links-disabled");
272
587
  }
273
588
 
274
- async function showPassage(passageName: string) {
589
+ // clicked: the number markClicked gave the link that was clicked to get here, if any
590
+ async function showPassage(passageName: string, clicked?: string) {
591
+ navigating++;
592
+ try {
593
+ await showPassageNow(passageName, clicked);
594
+ }
595
+ finally {
596
+ navigating--;
597
+ everyTimers.sync();
598
+ }
599
+ }
600
+
601
+ async function showPassageNow(passageName: string, clicked?: string) {
602
+ cancelGoto();
275
603
  const oldCanGoBack = canGoBack();
276
604
  let passage = currentSection.passages && currentSection.passages[passageName];
277
605
  const masterSection = story.sections[""];
@@ -279,6 +607,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
279
607
  if (!passage) {
280
608
  throw `No passage named ${passageName} in the current section or master section`;
281
609
  }
610
+ // The section or passage shown before this one (#56)
611
+ set("previous", get("_passage") ?? get("_section"));
612
+ set("_passage", passageName);
282
613
  state.setSeen(passageName);
283
614
 
284
615
  const passages: Passage[] = [];
@@ -301,8 +632,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
301
632
  passages.push(passage);
302
633
  runFns.push(() => run(passage, `[[${get("_section")}]][${passageName}]`));
303
634
 
635
+ // [@after] runs after every passage, including those with @repeat (#523): the section's,
636
+ // then the master section's, the other way round from [], so the master's wraps the section's
637
+ const after = currentSection.passages?.["@after"];
638
+ if (after) {
639
+ passages.push(after);
640
+ runFns.push(() => run(after, `[[${get("_section")}]][@after]`));
641
+ }
642
+ const masterAfter = masterSection?.passages?.["@after"];
643
+ if (masterAfter) {
644
+ passages.push(masterAfter);
645
+ runFns.push(() => run(masterAfter, "[[]][@after]"));
646
+ }
647
+
304
648
  const turnPassageName = "@" + get("_turncount");
305
- if (currentSection.passages) {
649
+ // A passage with @repeat doesn't count as a turn, so @1, @2... and @last ran already if they're due
650
+ if (currentSection.passages && !passage.repeat) {
306
651
  if (turnPassageName in currentSection.passages) {
307
652
  const turnPassage = currentSection.passages[turnPassageName];
308
653
  passages.push(turnPassage);
@@ -311,11 +656,20 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
311
656
  if ("@last" in currentSection.passages && get("_turncount") >= (currentSection.passageCount || 0)) {
312
657
  const turnPassage = currentSection.passages["@last"];
313
658
  passages.push(turnPassage);
314
- runFns.push(() => run(turnPassage, `[[${get("_section")}]][${turnPassageName}]`));
659
+ runFns.push(() => run(turnPassage, `[[${get("_section")}]][@last]`));
315
660
  }
316
661
  }
317
662
 
318
- if (passages.some(p => p.clear)) {
663
+ const clear = passages.some(p => p.clear);
664
+ shownFrom = [passage, master, masterSection?.passages?.[""], currentSection, masterSection];
665
+ // @leave: the passage's own, or else a master passage's, or else its section's, or the master section's
666
+ if (clear) await leaveTransition(shownFrom);
667
+
668
+ // @class in a passage (#449) adds to the section's classes
669
+ const passageClasses = passages.flatMap(p => p.classes ?? []);
670
+ if (passageClasses.length) setSectionClasses([...sectionClasses(), ...passageClasses]);
671
+
672
+ if (clear) {
319
673
  clearScreen();
320
674
  createSectionElement();
321
675
  }
@@ -323,8 +677,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
323
677
  currentPassageElement = document.createElement("div");
324
678
  currentPassageElement.classList.add("squiffy-output-passage");
325
679
  currentPassageElement.setAttribute("data-passage", `${passageName}`);
680
+ if (clicked) currentPassageElement.setAttribute("data-clicked-link", clicked);
326
681
 
327
682
  currentSectionElement.appendChild(currentPassageElement);
683
+ // @transition (#489): the passage's own, or else a master passage's, or else its section's, or the master section's
684
+ startTransition(currentPassageElement, shownFrom);
328
685
 
329
686
  for (const fn of runFns) {
330
687
  await fn();
@@ -333,6 +690,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
333
690
  // Setup validation for any inputs added by passages
334
691
  setupInputValidation(currentSectionElement);
335
692
 
693
+ takeDeactivate(currentPassageElement!);
694
+ const pending = takeGoto(currentPassageElement!);
336
695
  writeUndoLog();
337
696
  save();
338
697
  const newCanGoBack = canGoBack();
@@ -340,6 +699,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
340
699
  emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
341
700
  }
342
701
  emitter.emit("navigated", { section: get("_section"), passage: passageName });
702
+ await followGoto(pending);
343
703
  }
344
704
 
345
705
  async function processAttributes(attributes: string[]) {
@@ -349,7 +709,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
349
709
  }
350
710
 
351
711
  function restart() {
712
+ cancelGoto();
713
+ everyTimers.stopAll();
352
714
  state.reset();
715
+ uiJsRun = false;
716
+ sound.sync();
717
+ syncClasses();
353
718
  // TODO: This feels like the wrong way of triggering location.reload()
354
719
  // - should be a separate setting to the scroll setting.
355
720
  if (settings.scroll === "element" || settings.scroll === "none") {
@@ -363,27 +728,50 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
363
728
 
364
729
  function save() {
365
730
  // TODO: Queue up all attribute changes and save them only when this is called
366
- set("_output", outputElement.innerHTML);
731
+ // A transition still playing isn't saved, so loading the game doesn't play it again (#489)
732
+ let output = outputElement;
733
+ if (output.querySelector(".squiffy-transition")) {
734
+ output = outputElement.cloneNode(true) as HTMLDivElement;
735
+ output.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
736
+ }
737
+ set("_output", output.innerHTML);
367
738
  }
368
739
 
369
- function load() {
370
- const runUiJs = () => {
371
- if (story.uiJsIndex !== undefined) {
372
- runJs(story.uiJsIndex, {
373
- registerAnimation: animation.registerAnimation.bind(animation),
374
- registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
375
- SafeString: textProcessor.handlebars.SafeString,
376
- });
377
- }
378
- };
740
+ // The story's @ui JavaScript, which registers its helpers and animations. It runs once before
741
+ // any text is shown, however the story starts: from the beginning, from a section the author
742
+ // chose, or from a saved game. Restarting runs it again, as that resets the attributes.
743
+ let uiJsRun = false;
744
+ function runUiJs() {
745
+ if (uiJsRun) return;
746
+ uiJsRun = true;
747
+ if (story.uiJsIndex !== undefined) {
748
+ runJs(story.uiJsIndex, {
749
+ registerAnimation: animation.registerAnimation.bind(animation),
750
+ registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
751
+ SafeString: textProcessor.handlebars.SafeString,
752
+ });
753
+ }
754
+ }
379
755
 
756
+ function load() {
380
757
  state.load();
758
+ sound.sync();
759
+ syncClasses();
381
760
  const output = get("_output");
382
761
  if (!output) {
383
762
  runUiJs();
384
763
  return false;
385
764
  }
386
765
 
766
+ showSavedOutput(output);
767
+ runUiJs();
768
+ pluginManager.onLoad();
769
+ setupInputValidation(currentSectionElement);
770
+ return true;
771
+ }
772
+
773
+ // Puts a saved game's text back on screen, and carries on from the end of it
774
+ function showSavedOutput(output: string) {
387
775
  // Saved output may contain asset URLs that are no longer valid (e.g. blob: URLs), so resolve them again
388
776
  outputElement.innerHTML = resolveAssetsInHtml(output);
389
777
 
@@ -392,10 +780,104 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
392
780
  currentBlockOutputElement = outputElement.querySelector(".squiffy-output-block:last-child");
393
781
 
394
782
  currentSection = story.sections[get("_section")];
783
+ }
784
+
785
+ // The game as it is now. The attributes include the text on screen (_output), and the undo
786
+ // log is in that text, so a loaded game can go back too.
787
+ function getSave(): SavedGame {
788
+ return {
789
+ format: "squiffy-save",
790
+ version: 1,
791
+ storyId: story.projectId ?? null,
792
+ section: get("_section"),
793
+ passage: get("_passage"),
794
+ summary: getSummary(),
795
+ savedAt: new Date().toISOString(),
796
+ // Persistent attributes aren't part of the game (#539)
797
+ state: Object.fromEntries(Object.entries(structuredClone(state.store)).filter(([name]) => !state.isPersistent(name))),
798
+ };
799
+ }
800
+
801
+ // The start of the text in the current section, to tell saves apart by. If it starts with a
802
+ // heading, that's it, as it's likely to name where the player is.
803
+ function getSummary() {
804
+ const MAX_LENGTH = 100;
805
+ const blocks = currentSectionElement?.querySelectorAll(".squiffy-output-block") ?? [];
806
+ for (const block of blocks) {
807
+ const text = textOf(block);
808
+ if (!text) continue;
809
+ const first = [...block.querySelectorAll("h1, h2, h3, h4, h5, h6, p, li")].find(child => textOf(child));
810
+ if (first && /^H[1-6]$/.test(first.tagName) && textOf(block).startsWith(textOf(first))) {
811
+ return textOf(first).substring(0, MAX_LENGTH);
812
+ }
813
+ if (text.length <= MAX_LENGTH) return text;
814
+ const cut = text.substring(0, MAX_LENGTH);
815
+ const space = cut.lastIndexOf(" ");
816
+ return (space > MAX_LENGTH / 2 ? cut.substring(0, space) : cut) + "…";
817
+ }
818
+ return "";
819
+ }
820
+
821
+ // An element's text, with a space between paragraphs, headings and lines
822
+ function textOf(element: Element) {
823
+ const clone = element.cloneNode(true) as Element;
824
+ clone.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, div, br, tr, blockquote").forEach(el => el.after(" "));
825
+ return (clone.textContent ?? "").replace(/\s+/g, " ").trim();
826
+ }
827
+
828
+ function isSavedGame(save: unknown): save is SavedGame {
829
+ if (!save || typeof save != "object") return false;
830
+ const s = save as Partial<SavedGame>;
831
+ return s.format === "squiffy-save" && s.version === 1 && !!s.state && typeof s.state == "object"
832
+ && !Array.isArray(s.state) && typeof s.state._output == "string";
833
+ }
834
+
835
+ async function loadSave(save: SavedGame): Promise<LoadSaveResult> {
836
+ if (!isSavedGame(save)) return { success: false, error: "notASave" };
837
+ // A story without an id, or a save from one, can't be checked, so it's loaded
838
+ if (save.storyId && story.projectId && save.storyId !== story.projectId) {
839
+ return { success: false, error: "wrongStory" };
840
+ }
841
+
842
+ // Wait for anything being shown to finish, so it doesn't carry on into the loaded game
843
+ while (runningTransitions) {
844
+ await new Promise(resolve => setTimeout(resolve, 50));
845
+ }
846
+ cancelGoto();
847
+ everyTimers.stopAll();
848
+ pendingErrors.length = 0;
849
+ state.reset();
850
+ for (const [attribute, value] of Object.entries(save.state)) {
851
+ state.setInternal(attribute, value, false);
852
+ }
853
+ sound.sync();
854
+ syncClasses();
855
+ undoLog = {};
856
+ scrollPosition = 0;
857
+ scrollToTop = false;
858
+ showSavedOutput(save.state._output as string);
859
+ // As load() does, for a game loaded before the story has begun
395
860
  runUiJs();
861
+
862
+ if (!currentSection) {
863
+ // The section the game was saved in isn't in the story any more, so start again from
864
+ // the beginning, keeping the attributes
865
+ outputElement.innerHTML = "";
866
+ await go(story.start);
867
+ emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
868
+ return { success: true };
869
+ }
870
+
396
871
  pluginManager.onLoad();
397
872
  setupInputValidation(currentSectionElement);
398
- return true;
873
+ emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
874
+ const passage = get("_passage");
875
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
876
+
877
+ // Saved while waiting for a {{goto}}, so carry on waiting
878
+ await resumeGoto();
879
+ everyTimers.sync();
880
+ return { success: true };
399
881
  }
400
882
 
401
883
  function newBlockOutputElement() {
@@ -447,7 +929,35 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
447
929
  return outputElement.querySelector<HTMLElement>(".squiffy-clear-stack");
448
930
  }
449
931
 
450
- function clearScreen() {
932
+
933
+ // For scroll: "element", scrolls the story's own scrolling box (its nearest ancestor that
934
+ // scrolls, or else its own window) so that the top or the bottom of el is at the top or the
935
+ // bottom of it. Unlike scrollIntoView, this never scrolls the page around that box, or the page
936
+ // the story is in a frame of, such as the docs' samples.
937
+ function scrollWithin(el: Element, block: "start" | "end") {
938
+ const rect = el.getBoundingClientRect();
939
+ const box = scrollingBox(el);
940
+ if (box) {
941
+ const bounds = box.getBoundingClientRect();
942
+ const by = block === "start" ? rect.top - bounds.top : rect.bottom - bounds.bottom;
943
+ box.scrollTo({ top: box.scrollTop + by, behavior: "smooth" });
944
+ }
945
+ else {
946
+ const by = block === "start" ? rect.top : rect.bottom - window.innerHeight;
947
+ window.scrollTo({ top: window.scrollY + by, behavior: "smooth" });
948
+ }
949
+ }
950
+
951
+ function scrollingBox(el: Element): HTMLElement | null {
952
+ for (let e = el.parentElement; e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
953
+ const overflow = getComputedStyle(e).overflowY;
954
+ if ((overflow === "auto" || overflow === "scroll") && e.scrollHeight > e.clientHeight) return e;
955
+ }
956
+ return null;
957
+ }
958
+
959
+ // keep: an element that stays on the screen, for {{clear}} part-way through a section
960
+ function clearScreen(keep?: Element) {
451
961
  // Callers should call createSectionElement() after calling this function, so there's a place for new
452
962
  // output to go. We don't call this automatically within this function, in case we're just about to create
453
963
  // a new section anyway.
@@ -461,21 +971,137 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
461
971
 
462
972
  const clearStackItem = document.createElement("div");
463
973
  clearStack.appendChild(clearStackItem);
974
+ scrollToTop = true;
464
975
 
465
976
  // Move everything in the outputElement (except the clearStack itself) into the new clearStackItem
466
977
  for (const child of [...outputElement.children]) {
467
- if (child !== clearStack) {
978
+ if (child !== clearStack && child !== keep) {
468
979
  clearStackItem.appendChild(child);
469
980
  }
470
981
  }
982
+ // Without its transitions, so it's as it was if the player goes back to it
983
+ clearStackItem.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
471
984
 
472
985
  // NOTE: If we offer an option to disable the "back" feature, all of the above can be replaced with:
473
986
  // outputElement.innerHTML = '';
474
987
  }
475
988
 
989
+ // {{clear}} (#524): clears the screen while a section or passage is being shown, as @clear
990
+ // would have before it, taking away what it has shown so far too
991
+ async function clearPartWay() {
992
+ if (currentPassageElement) {
993
+ await leaveTransition(shownFrom);
994
+ // The passage starts again on a screen of its own, as with @clear, so going back
995
+ // takes it away and brings back the screen as it was before it
996
+ const passageElement = currentPassageElement.cloneNode(false) as HTMLElement;
997
+ currentPassageElement.remove();
998
+ endTransition(passageElement);
999
+ clearScreen();
1000
+ createSectionElement();
1001
+ currentPassageElement = passageElement;
1002
+ currentSectionElement.appendChild(passageElement);
1003
+ startTransition(passageElement, shownFrom);
1004
+ }
1005
+ else {
1006
+ // The section element stays, playing its @transition, and what's in it so far goes,
1007
+ // such as the master section's text, along with what came before it
1008
+ const sectionElement = currentSectionElement;
1009
+ await leaveTransition(shownFrom, [...screenElements().filter(e => e !== sectionElement), ...sectionElement.children]);
1010
+ sectionElement.replaceChildren();
1011
+ clearScreen(sectionElement);
1012
+ }
1013
+ newBlockOutputElement();
1014
+ }
1015
+
1016
+ // @transition (#489): plays the first transition given, as a class that the stylesheet animates.
1017
+ // "none" (or Harlowe's "instant") plays none, so a section can turn off the master section's.
1018
+ function startTransition(element: HTMLElement, from: (Section | Passage | undefined)[]) {
1019
+ const source = from.find(s => s?.transition);
1020
+ const name = source?.transition;
1021
+ if (!name || name == "none" || name == "instant") return;
1022
+ element.classList.add("squiffy-transition", name);
1023
+ element.setAttribute("data-transition", name);
1024
+ if (source!.transitionTime !== undefined) {
1025
+ element.style.setProperty("--squiffy-transition-time", `${source!.transitionTime}ms`);
1026
+ }
1027
+ const end = (event: Event) => {
1028
+ // A @leave transition started before this one ended takes the element off the screen itself
1029
+ if (event.target !== element || element.classList.contains("squiffy-leave")) return;
1030
+ element.removeEventListener("animationend", end);
1031
+ element.removeEventListener("animationcancel", end);
1032
+ endTransition(element);
1033
+ };
1034
+ element.addEventListener("animationend", end);
1035
+ element.addEventListener("animationcancel", end);
1036
+ }
1037
+
1038
+ // @leave: plays the first leave transition given on everything on the screen, the arrival
1039
+ // transitions backwards, and waits for it to finish, so that clearScreen() can take it away.
1040
+ // Links and Back wait too.
1041
+ async function leaveTransition(from: (Section | Passage | undefined)[], on: Element[] = screenElements()) {
1042
+ const source = from.find(s => s?.leave);
1043
+ const name = source?.leave;
1044
+ if (!name || name == "none" || name == "instant") return;
1045
+ const elements = on.filter((e): e is HTMLElement => e instanceof HTMLElement);
1046
+ if (!elements.length) return;
1047
+ for (const element of elements) {
1048
+ endTransition(element);
1049
+ element.classList.add("squiffy-transition", "squiffy-leave", name);
1050
+ element.setAttribute("data-transition", name);
1051
+ if (source!.leaveTime !== undefined) {
1052
+ element.style.setProperty("--squiffy-transition-time", `${source!.leaveTime}ms`);
1053
+ }
1054
+ }
1055
+ // Each element plays the same animation, so the first one finishing means they all have
1056
+ const first = elements[0];
1057
+ const style = getComputedStyle(first);
1058
+ if (!style.animationName || style.animationName == "none") return;
1059
+ // In case the animation never ends, such as in a page that isn't shown
1060
+ const seconds = (value: string) => Math.max(0, ...value.split(",").map(v => parseFloat(v) * (v.trim().endsWith("ms") ? 0.001 : 1) || 0));
1061
+ const timeout = (seconds(style.animationDuration) + seconds(style.animationDelay)) * 1000 + 1000;
1062
+ const wasRunning = runningTransitions;
1063
+ runningTransitions = true;
1064
+ try {
1065
+ await new Promise<void>(resolve => {
1066
+ const timer = setTimeout(done, timeout);
1067
+ function done(event?: Event) {
1068
+ if (event && event.target !== first) return;
1069
+ clearTimeout(timer);
1070
+ first.removeEventListener("animationend", done);
1071
+ first.removeEventListener("animationcancel", done);
1072
+ resolve();
1073
+ }
1074
+ first.addEventListener("animationend", done);
1075
+ first.addEventListener("animationcancel", done);
1076
+ });
1077
+ }
1078
+ finally {
1079
+ runningTransitions = wasRunning;
1080
+ }
1081
+ }
1082
+
1083
+ // What's on the screen: the output, but not the clear stack hidden in it
1084
+ function screenElements() {
1085
+ const clearStack = getClearStack();
1086
+ return [...outputElement.children].filter(c => c !== clearStack);
1087
+ }
1088
+
1089
+ // Takes off a transition's class, so it doesn't play again when the element is shown again,
1090
+ // such as after going back past a @clear
1091
+ function endTransition(element: HTMLElement) {
1092
+ const name = element.getAttribute("data-transition");
1093
+ if (name) element.classList.remove(name);
1094
+ element.classList.remove("squiffy-transition", "squiffy-leave");
1095
+ if (!element.classList.length) element.removeAttribute("class");
1096
+ element.removeAttribute("data-transition");
1097
+ element.style.removeProperty("--squiffy-transition-time");
1098
+ if (!element.getAttribute("style")) element.removeAttribute("style");
1099
+ }
1100
+
476
1101
  function unClearScreen() {
477
1102
  const clearStack = getClearStack();
478
1103
  if (!clearStack) return;
1104
+ clearStack.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
479
1105
  for (const child of [...outputElement.children]) {
480
1106
  if (child !== clearStack) {
481
1107
  child.remove();
@@ -491,9 +1117,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
491
1117
 
492
1118
  const ui = {
493
1119
  write: (text: string, source: string) => {
1120
+ ui.writeHtml(ui.renderHtml(text, false), source);
1121
+ },
1122
+ writeHtml: (rendered: string, source: string) => {
494
1123
  scrollPosition = outputElement.scrollHeight;
495
1124
 
496
- const html = ui.renderHtml(text, false).trim();
1125
+ const html = pendingErrors.splice(0).join("") + rendered.trim();
497
1126
 
498
1127
  // Previously, we skipped the rest of this if "html" came back as an empty string.
499
1128
  // But, we _do_ always want the block to be created, in the editor at least - as the
@@ -528,8 +1157,24 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
528
1157
  if (settings.scroll === "none") {
529
1158
  // do nothing
530
1159
  }
1160
+ else if (scrollToTop) {
1161
+ // The screen was cleared, so the new text starts at the top of the output, which may be
1162
+ // above where the reader has scrolled to.
1163
+ scrollToTop = false;
1164
+ if (settings.scroll === "element") {
1165
+ scrollWithin(currentSectionElement, "start");
1166
+ }
1167
+ else {
1168
+ const currentScrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
1169
+ const outputTop = outputElement.getBoundingClientRect().top + currentScrollTop;
1170
+ if (outputTop < currentScrollTop) {
1171
+ window.scrollTo({ top: outputTop, behavior: "smooth" });
1172
+ }
1173
+ }
1174
+ }
531
1175
  else if (settings.scroll === "element") {
532
- outputElement.lastElementChild?.scrollIntoView({ block: "end", inline: "nearest", behavior: "smooth" });
1176
+ const last = outputElement.lastElementChild;
1177
+ if (last) scrollWithin(last, "end");
533
1178
  }
534
1179
  else {
535
1180
  let scrollTo = scrollPosition;
@@ -554,6 +1199,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
554
1199
  if (newStory.start != story.start) {
555
1200
  story = newStory;
556
1201
  state.reset();
1202
+ sound.sync();
1203
+ syncClasses();
1204
+ sound.preload(story.audio ?? []);
557
1205
  outputElement.innerHTML = "";
558
1206
  go(story.start);
559
1207
  return;
@@ -563,16 +1211,24 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
563
1211
  // sees sections that were added in this update.
564
1212
  const oldStory = story;
565
1213
  story = newStory;
1214
+ // Its settings may have changed
1215
+ syncClasses();
1216
+ sound.preload(story.audio ?? []);
566
1217
 
567
1218
  // When re-rendering a section or passage, {{embed}} should look up passages in the
568
1219
  // (new version of the) section being rendered.
569
1220
  const processTextInSection = (text: string, section: Section) => {
570
1221
  const previousSection = currentSection;
571
1222
  currentSection = section;
1223
+ // Text shown again after an edit doesn't play its {{sound}}s again
1224
+ quiet = true;
572
1225
  try {
573
- return ui.renderHtml(text, false);
1226
+ const html = ui.renderHtml(text, false);
1227
+ // Only what comes after a {{clear}} was shown (#524)
1228
+ return afterClear(html) ?? html;
574
1229
  } finally {
575
1230
  currentSection = previousSection;
1231
+ quiet = false;
576
1232
  }
577
1233
  };
578
1234
 
@@ -580,6 +1236,35 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
580
1236
 
581
1237
  setCurrentSectionElement();
582
1238
  setCurrentPassageElement();
1239
+ // The {{#every}}s shown again start again
1240
+ everyTimers.sync();
1241
+ emitter.emit("storyUpdated", {});
1242
+ }
1243
+
1244
+ // A master section passage for a panel or dialog (#14, #443): rendered with the attributes as
1245
+ // they are, changing nothing, with its links disabled
1246
+ function renderPassage(name: string): string {
1247
+ const passage = story.sections[""]?.passages?.[name];
1248
+ if (!passage) {
1249
+ return errorHtml("Error in panel:", `there is no passage called "${name}" in the master section [[]]`);
1250
+ }
1251
+ // Anything the story's own text has asked for, which this mustn't change
1252
+ const goto = textProcessor.goto;
1253
+ const deactivate = [...textProcessor.deactivate];
1254
+ state.readOnly = true;
1255
+ let html: string;
1256
+ try {
1257
+ html = ui.renderHtml(passage.text || "", false);
1258
+ }
1259
+ finally {
1260
+ state.readOnly = false;
1261
+ textProcessor.goto = goto;
1262
+ textProcessor.deactivate = new Set(deactivate);
1263
+ }
1264
+ const template = document.createElement("template");
1265
+ template.innerHTML = html;
1266
+ template.content.querySelectorAll("a.squiffy-link").forEach(disableLink);
1267
+ return template.innerHTML;
583
1268
  }
584
1269
 
585
1270
  function setCurrentSectionElement() {
@@ -620,7 +1305,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
620
1305
  }
621
1306
 
622
1307
  function canGoBack() {
623
- return getHistoryCount() > 1;
1308
+ // Sections and passages that went somewhere else with {{goto}} are skipped by goBack(), so
1309
+ // they don't count, unless it's the current one, still waiting for its after= delay
1310
+ const current = currentPassageElement ?? currentSectionElement;
1311
+ const redirected = [...outputElement.querySelectorAll("[data-goto]")].filter(el => el !== current).length;
1312
+ return getHistoryCount() - redirected > 1;
624
1313
  }
625
1314
 
626
1315
  function goBack() {
@@ -630,11 +1319,36 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
630
1319
  return;
631
1320
  }
632
1321
 
1322
+ cancelGoto();
1323
+ // Undo back to the section or passage the player clicked through to, not one that went
1324
+ // somewhere else with {{goto}}
1325
+ do {
1326
+ undoLast();
1327
+ } while ((currentPassageElement ?? currentSectionElement).hasAttribute("data-goto") && getHistoryCount() > 1);
1328
+ // The music goes back to what it was, as _music was undone
1329
+ sound.sync();
1330
+ syncClasses();
1331
+ // The attributes were saved as they were undone, so save the output to match. Otherwise a saved
1332
+ // game would come back with the text that was undone.
1333
+ save();
1334
+
1335
+ if (!canGoBack()) {
1336
+ emitter.emit("canGoBackChanged", { canGoBack: false });
1337
+ }
1338
+ const passage = currentPassageElement?.getAttribute("data-passage");
1339
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
1340
+ // The {{#every}}s that were undone stop, and any in the section gone back to start again
1341
+ everyTimers.sync();
1342
+ }
1343
+
1344
+ function undoLast() {
633
1345
  const clearStack = getClearStack();
634
1346
 
635
1347
  if (currentPassageElement) {
636
1348
  const currentPassage = currentPassageElement.getAttribute("data-passage");
1349
+ const clicked = currentPassageElement.getAttribute("data-clicked-link");
637
1350
  doUndo(currentPassageElement.getAttribute("data-undo"));
1351
+ undoDeactivate(currentPassageElement);
638
1352
  currentPassageElement.remove();
639
1353
 
640
1354
  // If there's nothing left in the outputElement except for an empty section element that
@@ -659,9 +1373,18 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
659
1373
  setCurrentSectionElement();
660
1374
  }
661
1375
 
662
- for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
663
- if (link.getAttribute("data-passage") == currentPassage) {
1376
+ if (clicked) {
1377
+ for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-clicked="${clicked}"], input[data-clicked="${clicked}"]`)) {
664
1378
  enableLink(link);
1379
+ link.removeAttribute("data-clicked");
1380
+ }
1381
+ }
1382
+ else if (currentPassage && !isRepeatPassage(currentPassage)) {
1383
+ // Saved before links were numbered when clicked, so enable every link to the passage
1384
+ for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
1385
+ if (link.getAttribute("data-passage") == currentPassage) {
1386
+ enableLink(link);
1387
+ }
665
1388
  }
666
1389
  }
667
1390
 
@@ -689,12 +1412,6 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
689
1412
  setCurrentPassageElement();
690
1413
  enableInputs(currentSectionElement);
691
1414
  }
692
-
693
- if (!canGoBack()) {
694
- emitter.emit("canGoBackChanged", { canGoBack: false });
695
- }
696
- const passage = currentPassageElement?.getAttribute("data-passage");
697
- emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
698
1415
  }
699
1416
 
700
1417
  // We create a separate div inside the passed-in element. This allows us to clear the text output, but
@@ -739,6 +1456,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
739
1456
  outputElement.addEventListener("click", handleClick);
740
1457
  outputElement.addEventListener("keypress", async function (event) {
741
1458
  if (event.key !== "Enter") return;
1459
+ const target = event.target;
1460
+ // A text box with data-section or data-passage goes there when Enter is pressed (#454),
1461
+ // like a link, once every text box in the section is filled in properly
1462
+ if (target instanceof window.HTMLInputElement && (target.hasAttribute("data-section") || target.hasAttribute("data-passage"))) {
1463
+ if (event.isComposing) return;
1464
+ event.preventDefault();
1465
+ if (!areInputsValid(currentSectionElement)) {
1466
+ // Shows which ones need filling in
1467
+ for (const input of currentSectionElement.querySelectorAll<HTMLInputElement>("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")) {
1468
+ input.reportValidity();
1469
+ }
1470
+ return;
1471
+ }
1472
+ await handleLink(target);
1473
+ return;
1474
+ }
742
1475
  await handleClick(event);
743
1476
  });
744
1477
 
@@ -755,6 +1488,66 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
755
1488
  undoLog = {};
756
1489
  };
757
1490
 
1491
+ // Adds what's changed since to the undo log of the section or passage already shown, keeping
1492
+ // the value from before it was shown, e.g. for an {{#every}}'s text (#451)
1493
+ const mergeUndoLog = function() {
1494
+ const element = currentPassageElement ?? currentSectionElement;
1495
+ const log = JSON.parse(element.getAttribute("data-undo") || "{}");
1496
+ for (const [attribute, value] of Object.entries(undoLog)) {
1497
+ if (!(attribute in log)) log[attribute] = value;
1498
+ }
1499
+ element.setAttribute("data-undo", JSON.stringify(log));
1500
+ undoLog = {};
1501
+ };
1502
+
1503
+ // Shows an {{#every}}'s text again (#451). Returns false if it has to wait, while a section or
1504
+ // passage is being shown.
1505
+ function tickEvery(el: HTMLElement): boolean {
1506
+ if (runningTransitions || navigating > 0) return false;
1507
+ const inline = el.tagName == "SPAN";
1508
+ const body = decodeURIComponent(el.getAttribute("data-every") || "");
1509
+ let html: string;
1510
+ textProcessor.stopEvery = false;
1511
+ try {
1512
+ html = ui.renderHtml(body, inline);
1513
+ // Text added after text keeps its spaces, e.g. {{#every 1000 append=true}}Drip. {{/every}}
1514
+ if (inline) html = (/^\s/.test(body) ? " " : "") + html + (/\s$/.test(body) ? " " : "");
1515
+ }
1516
+ catch (e) {
1517
+ html = errorHtml("Error in {{#every}}:", e instanceof Error ? e.message : String(e));
1518
+ textProcessor.stopEvery = true;
1519
+ }
1520
+ const text = document.createElement(inline ? "span" : "div");
1521
+ text.className = "squiffy-every-text";
1522
+ text.innerHTML = html;
1523
+ if (el.hasAttribute("data-every-append")) el.append(text);
1524
+ else el.replaceChildren(text);
1525
+ pluginManager.onWrite(text);
1526
+ // It's empty until its first tick, so when the text was written the page may not have been
1527
+ // tall enough to scroll down to where it starts. This finishes that scroll, as the text is
1528
+ // taller now. It never scrolls past where the new text starts, or up.
1529
+ ui.scrollToEnd();
1530
+
1531
+ const count = (Number(el.getAttribute("data-every-count")) || 0) + 1;
1532
+ el.setAttribute("data-every-count", String(count));
1533
+ const times = Number(el.getAttribute("data-every-times")) || 0;
1534
+ if (textProcessor.stopEvery || (times && count >= times)) el.setAttribute("data-every-stopped", "");
1535
+ textProcessor.stopEvery = false;
1536
+
1537
+ const element = currentPassageElement ?? currentSectionElement;
1538
+ takeDeactivate(element);
1539
+ const pending = takeGoto(element);
1540
+ mergeUndoLog();
1541
+ save();
1542
+ if (pending) {
1543
+ // It replaces any {{goto ... after=}} still waiting
1544
+ clearTimeout(gotoTimer);
1545
+ gotoHops = 0;
1546
+ void followGoto(pending);
1547
+ }
1548
+ return true;
1549
+ }
1550
+
758
1551
  const doUndo = function(undosJson: string | null) {
759
1552
  if (!undosJson) return;
760
1553
  const undos = JSON.parse(undosJson) as Record<string, any>;
@@ -767,10 +1560,196 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
767
1560
  const state = new State(settings.persist, storageKey, settings.onSet, emitter, onSet);
768
1561
  const get = state.get.bind(state);
769
1562
  const set = state.set.bind(state);
1563
+ // Persistent attributes (#539), kept for the story apart from the rest, like the player's settings
1564
+ state.persistentNames = () => story.persistent ?? [];
1565
+ state.initPersistent(settings.persist ? "squiffy-persistent:" + storageKey : undefined, options.persistent);
1566
+
1567
+ // The player's settings (#452), which the story reads as settings.name
1568
+ const playerSettings = new PlayerSettings(() => story.settings ?? [], settings.persist ? "squiffy-settings:" + storageKey : undefined);
1569
+ state.playerSettings = () => playerSettings.any() ? playerSettings.all() : null;
1570
+ // After a setting changes: its classes, and text that shows it, such as {{live "settings"}} and panels
1571
+ const settingChanged = (name: string, value: unknown) => {
1572
+ syncClasses();
1573
+ emitter.emit("settingChanged", { name, value });
1574
+ emitter.emit("set", { attribute: "settings", value: playerSettings.all() });
1575
+ };
770
1576
 
771
1577
  const textProcessor = new TextProcessor(() => story, state, () => currentSection);
1578
+ const strings = options.strings ?? {};
1579
+ if (typeof strings.restart == "string") textProcessor.strings.restart = strings.restart;
1580
+ if (typeof strings.saves == "string") textProcessor.strings.saves = strings.saves;
1581
+ if (typeof strings.settings == "string") textProcessor.strings.settings = strings.settings;
1582
+
1583
+ // Music and sound effects (#444)
1584
+ let playedSound = false;
1585
+ // While text is shown again rather than for the first time, {{sound}} doesn't play
1586
+ let quiet = false;
1587
+ // How long the next change to _music fades for: fade= on {{music}} or {{stopmusic}}
1588
+ let musicFade = DEFAULT_FADE;
1589
+ const sound = new Sound({
1590
+ resolveUrl: path => isAbsolute(path) || !options.resolveAssetUrl
1591
+ ? path
1592
+ : options.resolveAssetUrl(path.replace(/^(\.\/)+/, "")),
1593
+ getMusic: () => get("_music"),
1594
+ mutedKey: settings.persist ? "squiffy-muted:" + storageKey : undefined,
1595
+ onPlay: () => {
1596
+ playedSound = true;
1597
+ emitter.emit("sound", {});
1598
+ },
1599
+ });
1600
+ sound.preload(story.audio ?? []);
1601
+ emitter.on("set", ({ attribute }) => {
1602
+ if (attribute != "_music") return;
1603
+ const fade = musicFade;
1604
+ musicFade = DEFAULT_FADE;
1605
+ sound.sync(fade);
1606
+ });
1607
+ const fadeOption = (options: { hash?: Record<string, unknown> } | undefined) => {
1608
+ const fade = Number(options?.hash?.fade);
1609
+ return options?.hash && "fade" in options.hash && Number.isFinite(fade) && fade >= 0 ? fade : DEFAULT_FADE;
1610
+ };
1611
+ // {{music}} and {{sound}} with nothing after them are still an attribute called music or
1612
+ // sound, as they were before these helpers
1613
+ const isHelperOptions = (value: unknown) => typeof value == "object" && value !== null && "hash" in value;
1614
+ textProcessor.handlebars.registerHelper("music", (file: unknown, options?: { hash?: Record<string, unknown> }) => {
1615
+ if (isHelperOptions(file)) return get("music");
1616
+ if (state.readOnly || typeof file != "string") return "";
1617
+ musicFade = fadeOption(options);
1618
+ set("_music", file || null);
1619
+ musicFade = DEFAULT_FADE;
1620
+ return "";
1621
+ });
1622
+ textProcessor.handlebars.registerHelper("stopmusic", (options?: { hash?: Record<string, unknown> }) => {
1623
+ if (state.readOnly) return "";
1624
+ musicFade = fadeOption(options);
1625
+ set("_music", null);
1626
+ musicFade = DEFAULT_FADE;
1627
+ return "";
1628
+ });
1629
+ textProcessor.handlebars.registerHelper("sound", (file: unknown, options?: { hash?: Record<string, unknown> }) => {
1630
+ if (isHelperOptions(file)) return get("sound");
1631
+ if (state.readOnly || quiet || typeof file != "string" || !file) return "";
1632
+ const volume = Number(options?.hash?.volume ?? 1);
1633
+ sound.play(file, volume);
1634
+ return "";
1635
+ });
1636
+ textProcessor.handlebars.registerHelper("stopsounds", () => {
1637
+ if (!state.readOnly && !quiet) sound.stopSounds();
1638
+ return "";
1639
+ });
1640
+
1641
+ // Classes on the story's element (#449): the current section's, from @class, which change with
1642
+ // the section, and ones from {{addclass}}, which stay until they're removed. They're attributes,
1643
+ // so they come back with Back and saved games.
1644
+ const SECTION_CLASSES = "_sectionclasses";
1645
+ const CLASSES = "_classes";
1646
+ // The classes this put on the element, so it leaves any others alone
1647
+ let appliedClasses: string[] = [];
1648
+ const classList = (attribute: string): string[] => {
1649
+ const value = get(attribute);
1650
+ return Array.isArray(value) ? value.filter((c): c is string => typeof c == "string" && c.length > 0) : [];
1651
+ };
1652
+ const sectionClasses = () => classList(SECTION_CLASSES);
1653
+ // Class names from helper arguments, which can each hold several separated by spaces
1654
+ const classNames = (values: unknown[]) => values
1655
+ .filter(v => !isHelperOptions(v))
1656
+ .flatMap(v => String(v ?? "").split(/\s+/))
1657
+ .filter(c => c.length > 0);
1658
+ function setSectionClasses(classes: string[]) {
1659
+ const unique = [...new Set(classes)];
1660
+ const current = sectionClasses();
1661
+ if (unique.length == current.length && unique.every((c, i) => c == current[i])) return;
1662
+ set(SECTION_CLASSES, unique);
1663
+ }
1664
+ function applyClasses(classes: string[]) {
1665
+ for (const c of appliedClasses) {
1666
+ if (!classes.includes(c)) outputElementContainer.classList.remove(c);
1667
+ }
1668
+ for (const c of classes) outputElementContainer.classList.add(c);
1669
+ appliedClasses = classes;
1670
+ }
1671
+ // With the classes from the player's settings, such as setting-textSize-Large
1672
+ function syncClasses() {
1673
+ applyClasses([...new Set([...sectionClasses(), ...classList(CLASSES), ...playerSettings.classes()])]);
1674
+ }
1675
+ emitter.on("set", ({ attribute }) => {
1676
+ if (attribute == SECTION_CLASSES || attribute == CLASSES) syncClasses();
1677
+ });
1678
+ textProcessor.handlebars.registerHelper("addclass", (...args: unknown[]) => {
1679
+ if (state.readOnly) return "";
1680
+ const classes = classList(CLASSES);
1681
+ const added = classNames(args).filter(c => !classes.includes(c));
1682
+ if (added.length) set(CLASSES, [...classes, ...added]);
1683
+ return "";
1684
+ });
1685
+ textProcessor.handlebars.registerHelper("removeclass", (...args: unknown[]) => {
1686
+ if (state.readOnly) return "";
1687
+ const removed = classNames(args);
1688
+ const classes = classList(CLASSES);
1689
+ if (classes.some(c => removed.includes(c))) set(CLASSES, classes.filter(c => !removed.includes(c)));
1690
+ return "";
1691
+ });
1692
+ textProcessor.handlebars.registerHelper("toggleclass", (...args: unknown[]) => {
1693
+ if (state.readOnly) return "";
1694
+ let classes = classList(CLASSES);
1695
+ for (const c of new Set(classNames(args))) {
1696
+ classes = classes.includes(c) ? classes.filter(x => x != c) : [...classes, c];
1697
+ }
1698
+ set(CLASSES, classes);
1699
+ return "";
1700
+ });
1701
+ // Whether the story's element has all these classes, from @class or {{addclass}}
1702
+ textProcessor.handlebars.registerHelper("hasclass", (...args: unknown[]) => {
1703
+ const names = classNames(args);
1704
+ const classes = [...sectionClasses(), ...classList(CLASSES)];
1705
+ return names.length > 0 && names.every(c => classes.includes(c));
1706
+ });
1707
+
772
1708
  const linkHandler = new LinkHandler();
773
1709
 
1710
+ // {{restart}} and {{saves}} links (#452). The page can handle them itself, with its own
1711
+ // dialogs, by listening for restartRequested and savesRequested. Otherwise the runtime asks
1712
+ // before restarting, and opens a Saved games dialog of its own.
1713
+ let savesDialog: SavesDialog | null = null;
1714
+ linkHandler.registerLinkHandler("restart", link => {
1715
+ const confirm = link.getAttribute("data-confirm") !== "false";
1716
+ // After the click has been handled, which saves the game as it is
1717
+ queueMicrotask(async () => {
1718
+ if (emitter.has("restartRequested")) {
1719
+ emitter.emit("restartRequested", { confirm });
1720
+ return;
1721
+ }
1722
+ if (confirm && !await confirmDialog({
1723
+ message: strings.restartConfirm ?? "Are you sure you want to restart?",
1724
+ confirm: strings.restart ?? "Restart",
1725
+ cancel: strings.cancel,
1726
+ })) return;
1727
+ restart();
1728
+ });
1729
+ return {};
1730
+ });
1731
+ let settingsDialog: SettingsDialog | null = null;
1732
+ linkHandler.registerLinkHandler("settings", () => {
1733
+ if (emitter.has("settingsRequested")) {
1734
+ emitter.emit("settingsRequested", {});
1735
+ }
1736
+ else {
1737
+ settingsDialog ??= createSettingsDialog(api, { strings });
1738
+ settingsDialog.open();
1739
+ }
1740
+ return {};
1741
+ });
1742
+ linkHandler.registerLinkHandler("saves", () => {
1743
+ if (emitter.has("savesRequested")) {
1744
+ emitter.emit("savesRequested", {});
1745
+ }
1746
+ else {
1747
+ savesDialog ??= createSavesDialog(api, { strings });
1748
+ savesDialog.open();
1749
+ }
1750
+ return {};
1751
+ });
1752
+
774
1753
  const getSectionText = (sectionName: string) => {
775
1754
  if (sectionName in story.sections) {
776
1755
  return story.sections[sectionName].text || null;
@@ -781,7 +1760,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
781
1760
  const getPassageText = (name: string) => {
782
1761
  if (currentSection.passages && name in currentSection.passages) {
783
1762
  return currentSection.passages[name].text || null;
784
- } else if ("passages" in story.sections[""] && story.sections[""].passages && name in story.sections[""].passages) {
1763
+ } else if (story.sections[""]?.passages && name in story.sections[""].passages) {
785
1764
  return story.sections[""].passages![name].text || null;
786
1765
  }
787
1766
  return null;
@@ -801,7 +1780,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
801
1780
  pluginManager.add(Plugins.LivePlugin());
802
1781
  pluginManager.add(Plugins.AnimatePlugin());
803
1782
 
804
- return {
1783
+ const api: SquiffyApi = {
805
1784
  begin: begin,
806
1785
  restart: restart,
807
1786
  get: get,
@@ -809,8 +1788,76 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
809
1788
  clickLink: handleLink,
810
1789
  update: update,
811
1790
  goBack: goBack,
1791
+ canGoBack: canGoBack,
1792
+ getSave: getSave,
1793
+ loadSave: loadSave,
1794
+ renderPassage: renderPassage,
1795
+ isMuted: () => sound.isMuted(),
1796
+ setMuted: (muted: boolean) => sound.setMuted(muted),
1797
+ usesSound: () => playedSound || !!story.audio?.length,
1798
+ getSettings: () => structuredClone(playerSettings.definitions()),
1799
+ getSetting: (name: string) => playerSettings.get(name),
1800
+ setSetting: (name, value) => {
1801
+ if (playerSettings.set(name, value)) settingChanged(name, playerSettings.get(name));
1802
+ },
1803
+ resetSettings: () => {
1804
+ const before = playerSettings.all();
1805
+ playerSettings.reset();
1806
+ for (const [name, value] of Object.entries(playerSettings.all())) {
1807
+ if (value !== before[name]) settingChanged(name, value);
1808
+ }
1809
+ },
1810
+ getPersistent: () => state.getPersistent(),
1811
+ forget: (names?: string[]) => state.forget(names),
1812
+ dispose: () => {
1813
+ cancelGoto();
1814
+ everyTimers.stopAll();
1815
+ sound.dispose();
1816
+ applyClasses([]);
1817
+ savesDialog?.element.remove();
1818
+ settingsDialog?.element.remove();
1819
+ },
812
1820
  on: (e, h) => emitter.on(e, h),
813
1821
  off: (e, h) => emitter.off(e, h),
814
1822
  once: (e, h) => emitter.once(e, h),
815
1823
  };
816
- };
1824
+
1825
+ // For the story's own scripts (#528): the events that are about the story, and what a
1826
+ // section's JavaScript can do
1827
+ // Checked as well as typed, as the story's scripts aren't TypeScript
1828
+ const scriptEvent = <E extends SquiffyScriptEvent>(event: E): E => {
1829
+ if (!SCRIPT_EVENTS.includes(event)) {
1830
+ throw new Error(`A story's script can't listen for "${event}": it can listen for ${SCRIPT_EVENTS.map(e => `"${e}"`).join(", ")}`);
1831
+ }
1832
+ return event;
1833
+ };
1834
+ const scriptApi: SquiffyScriptApi = {
1835
+ get: get,
1836
+ set: set,
1837
+ story: {
1838
+ go: (sectionName: string) => go(sectionName),
1839
+ seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
1840
+ visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
1841
+ lastVisited: (sectionOrPassage: string) => state.getLastVisited(sectionOrPassage),
1842
+ passages: (section?: string, filter?: TagFilter) => listPassages(story, section, get("_section"), filter),
1843
+ sections: (filter?: TagFilter) => listSections(story, filter),
1844
+ tags: (name?: string) => name === undefined
1845
+ ? [...(story.sections[get("_section")]?.tags ?? [])]
1846
+ : tagsOf(story, name, get("_section")),
1847
+ },
1848
+ getSetting: (name: string) => playerSettings.get(name),
1849
+ element: outputElementContainer,
1850
+ on: (e, h) => emitter.on(scriptEvent(e), h),
1851
+ off: (e, h) => emitter.off(scriptEvent(e), h),
1852
+ once: (e, h) => emitter.once(scriptEvent(e), h),
1853
+ };
1854
+ // Before begin(), so a script hears about the first section. It bubbles, so a script can
1855
+ // listen on document, as it runs before the story's element is there.
1856
+ const view = outputElementContainer.ownerDocument.defaultView;
1857
+ if (view) {
1858
+ outputElementContainer.dispatchEvent(new view.CustomEvent("squiffy:ready", { bubbles: true, detail: scriptApi }));
1859
+ }
1860
+ return api;
1861
+ };
1862
+
1863
+ const SCRIPT_EVENTS: SquiffyScriptEvent[] = ["navigated", "set", "settingChanged"];