squiffy-runtime 7.0.0-beta.7 → 7.0.0-beta.8

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 (56) hide show
  1. package/dist/confirmDialog.d.ts +8 -0
  2. package/dist/events.d.ts +10 -0
  3. package/dist/every.d.ts +12 -0
  4. package/dist/every.test.d.ts +1 -0
  5. package/dist/playerSettings.d.ts +17 -0
  6. package/dist/preview-html.js +1 -1
  7. package/dist/settings.test.d.ts +1 -0
  8. package/dist/settingsDialog.d.ts +17 -0
  9. package/dist/squiffy.page.css +4 -1
  10. package/dist/squiffy.preview.html +673 -83
  11. package/dist/squiffy.runtime.css +531 -1
  12. package/dist/squiffy.runtime.d.ts +5 -1
  13. package/dist/squiffy.runtime.global.js +106 -85
  14. package/dist/squiffy.runtime.global.js.map +1 -1
  15. package/dist/squiffy.runtime.js +4743 -4157
  16. package/dist/squiffy.runtime.js.map +1 -1
  17. package/dist/state.d.ts +1 -0
  18. package/dist/style.test.d.ts +1 -0
  19. package/dist/textProcessor.d.ts +8 -0
  20. package/dist/transitions.test.d.ts +1 -0
  21. package/dist/types.d.ts +43 -0
  22. package/dist/uiLinks.test.d.ts +1 -0
  23. package/dist/utils.d.ts +1 -0
  24. package/dist/utils.test.d.ts +1 -0
  25. package/package.json +3 -3
  26. package/src/animation.test.ts +44 -0
  27. package/src/animation.ts +7 -3
  28. package/src/confirmDialog.ts +66 -0
  29. package/src/events.ts +17 -0
  30. package/src/every.test.ts +25 -0
  31. package/src/every.ts +94 -0
  32. package/src/panels.test.ts +24 -0
  33. package/src/playerSettings.ts +128 -0
  34. package/src/plugins/animate.ts +9 -0
  35. package/src/plugins/live.ts +3 -1
  36. package/src/plugins/plugins.test.ts +17 -0
  37. package/src/preview.test.ts +53 -3
  38. package/src/preview.ts +60 -1
  39. package/src/settings.test.ts +233 -0
  40. package/src/settingsDialog.ts +160 -0
  41. package/src/squiffy.page.css +4 -1
  42. package/src/squiffy.runtime.css +531 -1
  43. package/src/squiffy.runtime.test.ts +613 -16
  44. package/src/squiffy.runtime.ts +372 -19
  45. package/src/state.ts +16 -1
  46. package/src/style.test.ts +89 -0
  47. package/src/textProcessor.ts +141 -6
  48. package/src/transitions.test.ts +302 -0
  49. package/src/types.ts +56 -0
  50. package/src/uiLinks.test.ts +156 -0
  51. package/src/utils.test.ts +60 -0
  52. package/src/utils.ts +44 -14
  53. package/dist/infixExpressions.d.ts +0 -7
  54. package/src/infixExpressions.test.ts +0 -516
  55. package/src/infixExpressions.ts +0 -672
  56. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -13,11 +13,20 @@ import { imports } from "./import.js";
13
13
  import { areInputsValid, setupInputValidation } from "./inputValidation.js";
14
14
  import { createAssetHtmlResolver, isAbsolute } from "./assets.js";
15
15
  import { Sound, DEFAULT_FADE } from "./sound.js";
16
+ import { EveryTimers } from "./every.js";
17
+ import { confirmDialog } from "./confirmDialog.js";
18
+ import { createSavesDialog, type SavesDialog } from "./savesDialog.js";
19
+ import { createSettingsDialog, type SettingsDialog } from "./settingsDialog.js";
20
+ import { PlayerSettings } from "./playerSettings.js";
16
21
 
17
- export type { SquiffyApi, SavedGame, LoadSaveResult } from "./types.js";
22
+ export type { SquiffyApi, SavedGame, LoadSaveResult, PlayerSetting, PlayerSettingOption, SettingValue } from "./types.js";
18
23
  export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
19
24
  export { createSavesDialog, formatSaveTime, SAVES_STRINGS, SAVE_FILE_EXTENSION } from "./savesDialog.js";
20
25
  export type { SavesDialog, SavesDialogOptions, SavesStringName } from "./savesDialog.js";
26
+ export { confirmDialog } from "./confirmDialog.js";
27
+ export { createSettingsDialog, SETTINGS_STRINGS } from "./settingsDialog.js";
28
+ export type { SettingsDialog, SettingsDialogOptions } from "./settingsDialog.js";
29
+ export type { ConfirmDialogOptions } from "./confirmDialog.js";
21
30
  export { indexedDbSaveSlots, memorySaveSlots } from "./saveSlots.js";
22
31
  export { createPanels } from "./panels.js";
23
32
  export type { Panels, PanelsOptions } from "./panels.js";
@@ -46,6 +55,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
46
55
  // the browser
47
56
  let gotoHops = 0;
48
57
  const MAX_GOTO_HOPS = 100;
58
+ // The {{#every}}s showing their text again and again (#451), and how many sections or passages
59
+ // are being shown, which they wait for
60
+ const everyTimers = new EveryTimers(() => currentSectionElement, tickEvery);
61
+ let navigating = 0;
49
62
 
50
63
  async function handleLink(link: HTMLElement): Promise<boolean> {
51
64
  if (runningTransitions) return false;
@@ -64,6 +77,13 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
64
77
 
65
78
  if (passage !== null || section !== null) {
66
79
  gotoHops = 0;
80
+ // A text box that goes somewhere when Enter is pressed (#454) keeps what was typed
81
+ // first, so the section or passage it goes to can use it. Other text boxes are only
82
+ // kept when the player leaves the section.
83
+ if (link instanceof window.HTMLInputElement) {
84
+ const attribute = link.getAttribute("data-attribute") || link.id;
85
+ if (attribute) set(attribute, link.value);
86
+ }
67
87
  // The story-wide turn count (#377). A {{goto}} isn't a turn, as the player didn't click it.
68
88
  set("turns", (get("turns") || 0) + 1);
69
89
  }
@@ -127,12 +147,23 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
127
147
  return !!(masterPassages && passageName in masterPassages && masterPassages[passageName].repeat);
128
148
  }
129
149
 
150
+ // A link, or a text box that goes to a passage when Enter is pressed (#454)
130
151
  function disableLink(link: Element) {
152
+ if (link instanceof window.HTMLInputElement) {
153
+ link.disabled = true;
154
+ link.classList.add("disabled");
155
+ return;
156
+ }
131
157
  link.classList.add("disabled");
132
158
  link.setAttribute("tabindex", "-1");
133
159
  }
134
160
 
135
161
  function enableLink(link: Element) {
162
+ if (link instanceof window.HTMLInputElement) {
163
+ link.disabled = false;
164
+ link.classList.remove("disabled");
165
+ return;
166
+ }
136
167
  link.classList.remove("disabled");
137
168
  link.removeAttribute("tabindex");
138
169
  }
@@ -152,6 +183,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
152
183
  async function begin(startAt?: StartAt) {
153
184
  if (startAt && startAt.section in story.sections) {
154
185
  // Start somewhere else in a fresh story, e.g. from the section being edited
186
+ runUiJs();
155
187
  await go(startAt.section);
156
188
  if (startAt.passage !== undefined && get("_section") == startAt.section) {
157
189
  await showPassage(startAt.passage);
@@ -162,8 +194,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
162
194
  await go(story.start);
163
195
  return;
164
196
  }
197
+ // As when a saved game is loaded, so that panels show the attributes it has
198
+ const passage = get("_passage");
199
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
165
200
  // Saved while waiting for a {{goto}}, so carry on waiting
166
201
  await resumeGoto();
202
+ everyTimers.sync();
167
203
  }
168
204
 
169
205
  async function resumeGoto() {
@@ -378,6 +414,17 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
378
414
  }
379
415
 
380
416
  async function go(sectionName: string) {
417
+ navigating++;
418
+ try {
419
+ await goNow(sectionName);
420
+ }
421
+ finally {
422
+ navigating--;
423
+ everyTimers.sync();
424
+ }
425
+ }
426
+
427
+ async function goNow(sectionName: string) {
381
428
  cancelGoto();
382
429
  const oldCanGoBack = canGoBack();
383
430
  currentSection = story.sections[sectionName];
@@ -395,12 +442,16 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
395
442
  if (get("turns") === null) state.setInternal("turns", 0, false);
396
443
  state.setSeen(sectionName);
397
444
  const master = story.sections[""];
445
+ const clear = master?.clear || currentSection.clear;
446
+ // @leave: the old text goes before anything changes on the screen
447
+ if (clear) await leaveTransition([currentSection, master]);
398
448
  // @class (#449): this section's classes replace the last one's
399
449
  setSectionClasses([...(master?.classes ?? []), ...(currentSection.classes ?? [])]);
400
- if (master?.clear || currentSection.clear) {
450
+ if (clear) {
401
451
  clearScreen();
402
452
  }
403
453
  newSection(sectionName);
454
+ startTransition(currentSectionElement, [currentSection, master]);
404
455
  const sectionElement = currentSectionElement;
405
456
  if (master) {
406
457
  await run(master, "[[]]");
@@ -519,6 +570,17 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
519
570
 
520
571
  // clicked: the number markClicked gave the link that was clicked to get here, if any
521
572
  async function showPassage(passageName: string, clicked?: string) {
573
+ navigating++;
574
+ try {
575
+ await showPassageNow(passageName, clicked);
576
+ }
577
+ finally {
578
+ navigating--;
579
+ everyTimers.sync();
580
+ }
581
+ }
582
+
583
+ async function showPassageNow(passageName: string, clicked?: string) {
522
584
  cancelGoto();
523
585
  const oldCanGoBack = canGoBack();
524
586
  let passage = currentSection.passages && currentSection.passages[passageName];
@@ -567,11 +629,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
567
629
  }
568
630
  }
569
631
 
632
+ const clear = passages.some(p => p.clear);
633
+ // @leave: the passage's own, or else a master passage's, or else its section's, or the master section's
634
+ if (clear) await leaveTransition([passage, master, masterSection?.passages?.[""], currentSection, masterSection]);
635
+
570
636
  // @class in a passage (#449) adds to the section's classes
571
637
  const passageClasses = passages.flatMap(p => p.classes ?? []);
572
638
  if (passageClasses.length) setSectionClasses([...sectionClasses(), ...passageClasses]);
573
639
 
574
- if (passages.some(p => p.clear)) {
640
+ if (clear) {
575
641
  clearScreen();
576
642
  createSectionElement();
577
643
  }
@@ -582,6 +648,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
582
648
  if (clicked) currentPassageElement.setAttribute("data-clicked-link", clicked);
583
649
 
584
650
  currentSectionElement.appendChild(currentPassageElement);
651
+ // @transition (#489): the passage's own, or else a master passage's, or else its section's, or the master section's
652
+ startTransition(currentPassageElement, [passage, master, masterSection?.passages?.[""], currentSection, masterSection]);
585
653
 
586
654
  for (const fn of runFns) {
587
655
  await fn();
@@ -610,7 +678,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
610
678
 
611
679
  function restart() {
612
680
  cancelGoto();
681
+ everyTimers.stopAll();
613
682
  state.reset();
683
+ uiJsRun = false;
614
684
  sound.sync();
615
685
  syncClasses();
616
686
  // TODO: This feels like the wrong way of triggering location.reload()
@@ -626,20 +696,32 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
626
696
 
627
697
  function save() {
628
698
  // TODO: Queue up all attribute changes and save them only when this is called
629
- set("_output", outputElement.innerHTML);
699
+ // A transition still playing isn't saved, so loading the game doesn't play it again (#489)
700
+ let output = outputElement;
701
+ if (output.querySelector(".squiffy-transition")) {
702
+ output = outputElement.cloneNode(true) as HTMLDivElement;
703
+ output.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
704
+ }
705
+ set("_output", output.innerHTML);
630
706
  }
631
707
 
632
- function load() {
633
- const runUiJs = () => {
634
- if (story.uiJsIndex !== undefined) {
635
- runJs(story.uiJsIndex, {
636
- registerAnimation: animation.registerAnimation.bind(animation),
637
- registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
638
- SafeString: textProcessor.handlebars.SafeString,
639
- });
640
- }
641
- };
708
+ // The story's @ui JavaScript, which registers its helpers and animations. It runs once before
709
+ // any text is shown, however the story starts: from the beginning, from a section the author
710
+ // chose, or from a saved game. Restarting runs it again, as that resets the attributes.
711
+ let uiJsRun = false;
712
+ function runUiJs() {
713
+ if (uiJsRun) return;
714
+ uiJsRun = true;
715
+ if (story.uiJsIndex !== undefined) {
716
+ runJs(story.uiJsIndex, {
717
+ registerAnimation: animation.registerAnimation.bind(animation),
718
+ registerHelper: textProcessor.handlebars.registerHelper.bind(textProcessor.handlebars),
719
+ SafeString: textProcessor.handlebars.SafeString,
720
+ });
721
+ }
722
+ }
642
723
 
724
+ function load() {
643
725
  state.load();
644
726
  sound.sync();
645
727
  syncClasses();
@@ -729,6 +811,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
729
811
  await new Promise(resolve => setTimeout(resolve, 50));
730
812
  }
731
813
  cancelGoto();
814
+ everyTimers.stopAll();
732
815
  pendingErrors.length = 0;
733
816
  state.reset();
734
817
  for (const [attribute, value] of Object.entries(save.state)) {
@@ -740,6 +823,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
740
823
  scrollPosition = 0;
741
824
  scrollToTop = false;
742
825
  showSavedOutput(save.state._output as string);
826
+ // As load() does, for a game loaded before the story has begun
827
+ runUiJs();
743
828
 
744
829
  if (!currentSection) {
745
830
  // The section the game was saved in isn't in the story any more, so start again from
@@ -758,6 +843,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
758
843
 
759
844
  // Saved while waiting for a {{goto}}, so carry on waiting
760
845
  await resumeGoto();
846
+ everyTimers.sync();
761
847
  return { success: true };
762
848
  }
763
849
 
@@ -810,6 +896,33 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
810
896
  return outputElement.querySelector<HTMLElement>(".squiffy-clear-stack");
811
897
  }
812
898
 
899
+
900
+ // For scroll: "element", scrolls the story's own scrolling box (its nearest ancestor that
901
+ // scrolls, or else its own window) so that the top or the bottom of el is at the top or the
902
+ // bottom of it. Unlike scrollIntoView, this never scrolls the page around that box, or the page
903
+ // the story is in a frame of, such as the docs' samples.
904
+ function scrollWithin(el: Element, block: "start" | "end") {
905
+ const rect = el.getBoundingClientRect();
906
+ const box = scrollingBox(el);
907
+ if (box) {
908
+ const bounds = box.getBoundingClientRect();
909
+ const by = block === "start" ? rect.top - bounds.top : rect.bottom - bounds.bottom;
910
+ box.scrollTo({ top: box.scrollTop + by, behavior: "smooth" });
911
+ }
912
+ else {
913
+ const by = block === "start" ? rect.top : rect.bottom - window.innerHeight;
914
+ window.scrollTo({ top: window.scrollY + by, behavior: "smooth" });
915
+ }
916
+ }
917
+
918
+ function scrollingBox(el: Element): HTMLElement | null {
919
+ for (let e = el.parentElement; e && e !== document.body && e !== document.documentElement; e = e.parentElement) {
920
+ const overflow = getComputedStyle(e).overflowY;
921
+ if ((overflow === "auto" || overflow === "scroll") && e.scrollHeight > e.clientHeight) return e;
922
+ }
923
+ return null;
924
+ }
925
+
813
926
  function clearScreen() {
814
927
  // Callers should call createSectionElement() after calling this function, so there's a place for new
815
928
  // output to go. We don't call this automatically within this function, in case we're just about to create
@@ -832,14 +945,97 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
832
945
  clearStackItem.appendChild(child);
833
946
  }
834
947
  }
948
+ // Without its transitions, so it's as it was if the player goes back to it
949
+ clearStackItem.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
835
950
 
836
951
  // NOTE: If we offer an option to disable the "back" feature, all of the above can be replaced with:
837
952
  // outputElement.innerHTML = '';
838
953
  }
839
954
 
955
+ // @transition (#489): plays the first transition given, as a class that the stylesheet animates.
956
+ // "none" (or Harlowe's "instant") plays none, so a section can turn off the master section's.
957
+ function startTransition(element: HTMLElement, from: (Section | Passage | undefined)[]) {
958
+ const source = from.find(s => s?.transition);
959
+ const name = source?.transition;
960
+ if (!name || name == "none" || name == "instant") return;
961
+ element.classList.add("squiffy-transition", name);
962
+ element.setAttribute("data-transition", name);
963
+ if (source!.transitionTime !== undefined) {
964
+ element.style.setProperty("--squiffy-transition-time", `${source!.transitionTime}ms`);
965
+ }
966
+ const end = (event: Event) => {
967
+ // A @leave transition started before this one ended takes the element off the screen itself
968
+ if (event.target !== element || element.classList.contains("squiffy-leave")) return;
969
+ element.removeEventListener("animationend", end);
970
+ element.removeEventListener("animationcancel", end);
971
+ endTransition(element);
972
+ };
973
+ element.addEventListener("animationend", end);
974
+ element.addEventListener("animationcancel", end);
975
+ }
976
+
977
+ // @leave: plays the first leave transition given on everything on the screen, the arrival
978
+ // transitions backwards, and waits for it to finish, so that clearScreen() can take it away.
979
+ // Links and Back wait too.
980
+ async function leaveTransition(from: (Section | Passage | undefined)[]) {
981
+ const source = from.find(s => s?.leave);
982
+ const name = source?.leave;
983
+ if (!name || name == "none" || name == "instant") return;
984
+ const clearStack = getClearStack();
985
+ const elements = [...outputElement.children].filter((c): c is HTMLElement => c !== clearStack && c instanceof HTMLElement);
986
+ if (!elements.length) return;
987
+ for (const element of elements) {
988
+ endTransition(element);
989
+ element.classList.add("squiffy-transition", "squiffy-leave", name);
990
+ element.setAttribute("data-transition", name);
991
+ if (source!.leaveTime !== undefined) {
992
+ element.style.setProperty("--squiffy-transition-time", `${source!.leaveTime}ms`);
993
+ }
994
+ }
995
+ // Each element plays the same animation, so the first one finishing means they all have
996
+ const first = elements[0];
997
+ const style = getComputedStyle(first);
998
+ if (!style.animationName || style.animationName == "none") return;
999
+ // In case the animation never ends, such as in a page that isn't shown
1000
+ const seconds = (value: string) => Math.max(0, ...value.split(",").map(v => parseFloat(v) * (v.trim().endsWith("ms") ? 0.001 : 1) || 0));
1001
+ const timeout = (seconds(style.animationDuration) + seconds(style.animationDelay)) * 1000 + 1000;
1002
+ const wasRunning = runningTransitions;
1003
+ runningTransitions = true;
1004
+ try {
1005
+ await new Promise<void>(resolve => {
1006
+ const timer = setTimeout(done, timeout);
1007
+ function done(event?: Event) {
1008
+ if (event && event.target !== first) return;
1009
+ clearTimeout(timer);
1010
+ first.removeEventListener("animationend", done);
1011
+ first.removeEventListener("animationcancel", done);
1012
+ resolve();
1013
+ }
1014
+ first.addEventListener("animationend", done);
1015
+ first.addEventListener("animationcancel", done);
1016
+ });
1017
+ }
1018
+ finally {
1019
+ runningTransitions = wasRunning;
1020
+ }
1021
+ }
1022
+
1023
+ // Takes off a transition's class, so it doesn't play again when the element is shown again,
1024
+ // such as after going back past a @clear
1025
+ function endTransition(element: HTMLElement) {
1026
+ const name = element.getAttribute("data-transition");
1027
+ if (name) element.classList.remove(name);
1028
+ element.classList.remove("squiffy-transition", "squiffy-leave");
1029
+ if (!element.classList.length) element.removeAttribute("class");
1030
+ element.removeAttribute("data-transition");
1031
+ element.style.removeProperty("--squiffy-transition-time");
1032
+ if (!element.getAttribute("style")) element.removeAttribute("style");
1033
+ }
1034
+
840
1035
  function unClearScreen() {
841
1036
  const clearStack = getClearStack();
842
1037
  if (!clearStack) return;
1038
+ clearStack.querySelectorAll<HTMLElement>(".squiffy-transition").forEach(endTransition);
843
1039
  for (const child of [...outputElement.children]) {
844
1040
  if (child !== clearStack) {
845
1041
  child.remove();
@@ -897,7 +1093,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
897
1093
  // above where the reader has scrolled to.
898
1094
  scrollToTop = false;
899
1095
  if (settings.scroll === "element") {
900
- currentSectionElement.scrollIntoView({ block: "start", inline: "nearest", behavior: "smooth" });
1096
+ scrollWithin(currentSectionElement, "start");
901
1097
  }
902
1098
  else {
903
1099
  const currentScrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
@@ -908,7 +1104,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
908
1104
  }
909
1105
  }
910
1106
  else if (settings.scroll === "element") {
911
- outputElement.lastElementChild?.scrollIntoView({ block: "end", inline: "nearest", behavior: "smooth" });
1107
+ const last = outputElement.lastElementChild;
1108
+ if (last) scrollWithin(last, "end");
912
1109
  }
913
1110
  else {
914
1111
  let scrollTo = scrollPosition;
@@ -945,6 +1142,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
945
1142
  // sees sections that were added in this update.
946
1143
  const oldStory = story;
947
1144
  story = newStory;
1145
+ // Its settings may have changed
1146
+ syncClasses();
948
1147
  sound.preload(story.audio ?? []);
949
1148
 
950
1149
  // When re-rendering a section or passage, {{embed}} should look up passages in the
@@ -966,6 +1165,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
966
1165
 
967
1166
  setCurrentSectionElement();
968
1167
  setCurrentPassageElement();
1168
+ // The {{#every}}s shown again start again
1169
+ everyTimers.sync();
969
1170
  emitter.emit("storyUpdated", {});
970
1171
  }
971
1172
 
@@ -1065,6 +1266,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1065
1266
  }
1066
1267
  const passage = currentPassageElement?.getAttribute("data-passage");
1067
1268
  emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
1269
+ // The {{#every}}s that were undone stop, and any in the section gone back to start again
1270
+ everyTimers.sync();
1068
1271
  }
1069
1272
 
1070
1273
  function undoLast() {
@@ -1100,7 +1303,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1100
1303
  }
1101
1304
 
1102
1305
  if (clicked) {
1103
- for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-clicked="${clicked}"]`)) {
1306
+ for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-clicked="${clicked}"], input[data-clicked="${clicked}"]`)) {
1104
1307
  enableLink(link);
1105
1308
  link.removeAttribute("data-clicked");
1106
1309
  }
@@ -1182,6 +1385,22 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1182
1385
  outputElement.addEventListener("click", handleClick);
1183
1386
  outputElement.addEventListener("keypress", async function (event) {
1184
1387
  if (event.key !== "Enter") return;
1388
+ const target = event.target;
1389
+ // A text box with data-section or data-passage goes there when Enter is pressed (#454),
1390
+ // like a link, once every text box in the section is filled in properly
1391
+ if (target instanceof window.HTMLInputElement && (target.hasAttribute("data-section") || target.hasAttribute("data-passage"))) {
1392
+ if (event.isComposing) return;
1393
+ event.preventDefault();
1394
+ if (!areInputsValid(currentSectionElement)) {
1395
+ // Shows which ones need filling in
1396
+ for (const input of currentSectionElement.querySelectorAll<HTMLInputElement>("input:not([disabled]), textarea:not([disabled]), select:not([disabled])")) {
1397
+ input.reportValidity();
1398
+ }
1399
+ return;
1400
+ }
1401
+ await handleLink(target);
1402
+ return;
1403
+ }
1185
1404
  await handleClick(event);
1186
1405
  });
1187
1406
 
@@ -1198,6 +1417,66 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1198
1417
  undoLog = {};
1199
1418
  };
1200
1419
 
1420
+ // Adds what's changed since to the undo log of the section or passage already shown, keeping
1421
+ // the value from before it was shown, e.g. for an {{#every}}'s text (#451)
1422
+ const mergeUndoLog = function() {
1423
+ const element = currentPassageElement ?? currentSectionElement;
1424
+ const log = JSON.parse(element.getAttribute("data-undo") || "{}");
1425
+ for (const [attribute, value] of Object.entries(undoLog)) {
1426
+ if (!(attribute in log)) log[attribute] = value;
1427
+ }
1428
+ element.setAttribute("data-undo", JSON.stringify(log));
1429
+ undoLog = {};
1430
+ };
1431
+
1432
+ // Shows an {{#every}}'s text again (#451). Returns false if it has to wait, while a section or
1433
+ // passage is being shown.
1434
+ function tickEvery(el: HTMLElement): boolean {
1435
+ if (runningTransitions || navigating > 0) return false;
1436
+ const inline = el.tagName == "SPAN";
1437
+ const body = decodeURIComponent(el.getAttribute("data-every") || "");
1438
+ let html: string;
1439
+ textProcessor.stopEvery = false;
1440
+ try {
1441
+ html = ui.renderHtml(body, inline);
1442
+ // Text added after text keeps its spaces, e.g. {{#every 1000 append=true}}Drip. {{/every}}
1443
+ if (inline) html = (/^\s/.test(body) ? " " : "") + html + (/\s$/.test(body) ? " " : "");
1444
+ }
1445
+ catch (e) {
1446
+ html = errorHtml("Error in {{#every}}:", e instanceof Error ? e.message : String(e));
1447
+ textProcessor.stopEvery = true;
1448
+ }
1449
+ const text = document.createElement(inline ? "span" : "div");
1450
+ text.className = "squiffy-every-text";
1451
+ text.innerHTML = html;
1452
+ if (el.hasAttribute("data-every-append")) el.append(text);
1453
+ else el.replaceChildren(text);
1454
+ pluginManager.onWrite(text);
1455
+ // It's empty until its first tick, so when the text was written the page may not have been
1456
+ // tall enough to scroll down to where it starts. This finishes that scroll, as the text is
1457
+ // taller now. It never scrolls past where the new text starts, or up.
1458
+ ui.scrollToEnd();
1459
+
1460
+ const count = (Number(el.getAttribute("data-every-count")) || 0) + 1;
1461
+ el.setAttribute("data-every-count", String(count));
1462
+ const times = Number(el.getAttribute("data-every-times")) || 0;
1463
+ if (textProcessor.stopEvery || (times && count >= times)) el.setAttribute("data-every-stopped", "");
1464
+ textProcessor.stopEvery = false;
1465
+
1466
+ const element = currentPassageElement ?? currentSectionElement;
1467
+ takeDeactivate(element);
1468
+ const pending = takeGoto(element);
1469
+ mergeUndoLog();
1470
+ save();
1471
+ if (pending) {
1472
+ // It replaces any {{goto ... after=}} still waiting
1473
+ clearTimeout(gotoTimer);
1474
+ gotoHops = 0;
1475
+ void followGoto(pending);
1476
+ }
1477
+ return true;
1478
+ }
1479
+
1201
1480
  const doUndo = function(undosJson: string | null) {
1202
1481
  if (!undosJson) return;
1203
1482
  const undos = JSON.parse(undosJson) as Record<string, any>;
@@ -1211,7 +1490,21 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1211
1490
  const get = state.get.bind(state);
1212
1491
  const set = state.set.bind(state);
1213
1492
 
1493
+ // The player's settings (#452), which the story reads as settings.name
1494
+ const playerSettings = new PlayerSettings(() => story.settings ?? [], settings.persist ? "squiffy-settings:" + storageKey : undefined);
1495
+ state.playerSettings = () => playerSettings.any() ? playerSettings.all() : null;
1496
+ // After a setting changes: its classes, and text that shows it, such as {{live "settings"}} and panels
1497
+ const settingChanged = (name: string, value: unknown) => {
1498
+ syncClasses();
1499
+ emitter.emit("settingChanged", { name, value });
1500
+ emitter.emit("set", { attribute: "settings", value: playerSettings.all() });
1501
+ };
1502
+
1214
1503
  const textProcessor = new TextProcessor(() => story, state, () => currentSection);
1504
+ const strings = options.strings ?? {};
1505
+ if (typeof strings.restart == "string") textProcessor.strings.restart = strings.restart;
1506
+ if (typeof strings.saves == "string") textProcessor.strings.saves = strings.saves;
1507
+ if (typeof strings.settings == "string") textProcessor.strings.settings = strings.settings;
1215
1508
 
1216
1509
  // Music and sound effects (#444)
1217
1510
  let playedSound = false;
@@ -1301,8 +1594,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1301
1594
  for (const c of classes) outputElementContainer.classList.add(c);
1302
1595
  appliedClasses = classes;
1303
1596
  }
1597
+ // With the classes from the player's settings, such as setting-textSize-Large
1304
1598
  function syncClasses() {
1305
- applyClasses([...new Set([...sectionClasses(), ...classList(CLASSES)])]);
1599
+ applyClasses([...new Set([...sectionClasses(), ...classList(CLASSES), ...playerSettings.classes()])]);
1306
1600
  }
1307
1601
  emitter.on("set", ({ attribute }) => {
1308
1602
  if (attribute == SECTION_CLASSES || attribute == CLASSES) syncClasses();
@@ -1339,6 +1633,49 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1339
1633
 
1340
1634
  const linkHandler = new LinkHandler();
1341
1635
 
1636
+ // {{restart}} and {{saves}} links (#452). The page can handle them itself, with its own
1637
+ // dialogs, by listening for restartRequested and savesRequested. Otherwise the runtime asks
1638
+ // before restarting, and opens a Saved games dialog of its own.
1639
+ let savesDialog: SavesDialog | null = null;
1640
+ linkHandler.registerLinkHandler("restart", link => {
1641
+ const confirm = link.getAttribute("data-confirm") !== "false";
1642
+ // After the click has been handled, which saves the game as it is
1643
+ queueMicrotask(async () => {
1644
+ if (emitter.has("restartRequested")) {
1645
+ emitter.emit("restartRequested", { confirm });
1646
+ return;
1647
+ }
1648
+ if (confirm && !await confirmDialog({
1649
+ message: strings.restartConfirm ?? "Are you sure you want to restart?",
1650
+ confirm: strings.restart ?? "Restart",
1651
+ cancel: strings.cancel,
1652
+ })) return;
1653
+ restart();
1654
+ });
1655
+ return {};
1656
+ });
1657
+ let settingsDialog: SettingsDialog | null = null;
1658
+ linkHandler.registerLinkHandler("settings", () => {
1659
+ if (emitter.has("settingsRequested")) {
1660
+ emitter.emit("settingsRequested", {});
1661
+ }
1662
+ else {
1663
+ settingsDialog ??= createSettingsDialog(api, { strings });
1664
+ settingsDialog.open();
1665
+ }
1666
+ return {};
1667
+ });
1668
+ linkHandler.registerLinkHandler("saves", () => {
1669
+ if (emitter.has("savesRequested")) {
1670
+ emitter.emit("savesRequested", {});
1671
+ }
1672
+ else {
1673
+ savesDialog ??= createSavesDialog(api, { strings });
1674
+ savesDialog.open();
1675
+ }
1676
+ return {};
1677
+ });
1678
+
1342
1679
  const getSectionText = (sectionName: string) => {
1343
1680
  if (sectionName in story.sections) {
1344
1681
  return story.sections[sectionName].text || null;
@@ -1369,7 +1706,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1369
1706
  pluginManager.add(Plugins.LivePlugin());
1370
1707
  pluginManager.add(Plugins.AnimatePlugin());
1371
1708
 
1372
- return {
1709
+ const api: SquiffyApi = {
1373
1710
  begin: begin,
1374
1711
  restart: restart,
1375
1712
  get: get,
@@ -1384,13 +1721,29 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
1384
1721
  isMuted: () => sound.isMuted(),
1385
1722
  setMuted: (muted: boolean) => sound.setMuted(muted),
1386
1723
  usesSound: () => playedSound || !!story.audio?.length,
1724
+ getSettings: () => structuredClone(playerSettings.definitions()),
1725
+ getSetting: (name: string) => playerSettings.get(name),
1726
+ setSetting: (name, value) => {
1727
+ if (playerSettings.set(name, value)) settingChanged(name, playerSettings.get(name));
1728
+ },
1729
+ resetSettings: () => {
1730
+ const before = playerSettings.all();
1731
+ playerSettings.reset();
1732
+ for (const [name, value] of Object.entries(playerSettings.all())) {
1733
+ if (value !== before[name]) settingChanged(name, value);
1734
+ }
1735
+ },
1387
1736
  dispose: () => {
1388
1737
  cancelGoto();
1738
+ everyTimers.stopAll();
1389
1739
  sound.dispose();
1390
1740
  applyClasses([]);
1741
+ savesDialog?.element.remove();
1742
+ settingsDialog?.element.remove();
1391
1743
  },
1392
1744
  on: (e, h) => emitter.on(e, h),
1393
1745
  off: (e, h) => emitter.off(e, h),
1394
1746
  once: (e, h) => emitter.once(e, h),
1395
1747
  };
1748
+ return api;
1396
1749
  };