squiffy-runtime 7.0.0-beta.4 → 7.0.0-beta.6

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 (47) hide show
  1. package/dist/events.d.ts +1 -0
  2. package/dist/panels.d.ts +14 -0
  3. package/dist/panels.test.d.ts +1 -0
  4. package/dist/preview-host.d.ts +2 -1
  5. package/dist/preview-host.js +4 -1
  6. package/dist/preview-host.js.map +2 -2
  7. package/dist/preview-html.js +1 -1
  8. package/dist/preview-protocol.d.ts +4 -0
  9. package/dist/saveSlots.d.ts +16 -0
  10. package/dist/saves.test.d.ts +1 -0
  11. package/dist/savesDialog.d.ts +43 -0
  12. package/dist/savesDialog.test.d.ts +1 -0
  13. package/dist/squiffy.page.css +46 -22
  14. package/dist/squiffy.preview.html +612 -109
  15. package/dist/squiffy.runtime.css +476 -9
  16. package/dist/squiffy.runtime.d.ts +9 -1
  17. package/dist/squiffy.runtime.global.js +113 -72
  18. package/dist/squiffy.runtime.global.js.map +1 -1
  19. package/dist/squiffy.runtime.js +4146 -3460
  20. package/dist/squiffy.runtime.js.map +1 -1
  21. package/dist/state.d.ts +4 -0
  22. package/dist/textProcessor.d.ts +5 -0
  23. package/dist/types.d.ts +32 -0
  24. package/package.json +3 -3
  25. package/src/__snapshots__/squiffy.runtime.test.ts.snap +21 -21
  26. package/src/events.ts +1 -0
  27. package/src/panels.test.ts +201 -0
  28. package/src/panels.ts +187 -0
  29. package/src/plugins/plugins.test.ts +42 -0
  30. package/src/plugins/replaceLabel.ts +6 -2
  31. package/src/preview-host.test.ts +5 -1
  32. package/src/preview-host.ts +9 -3
  33. package/src/preview-protocol.ts +6 -2
  34. package/src/preview.test.ts +71 -3
  35. package/src/preview.ts +74 -13
  36. package/src/saveSlots.ts +159 -0
  37. package/src/saves.test.ts +199 -0
  38. package/src/savesDialog.test.ts +290 -0
  39. package/src/savesDialog.ts +499 -0
  40. package/src/squiffy.page.css +46 -22
  41. package/src/squiffy.runtime.css +476 -9
  42. package/src/squiffy.runtime.test.ts +890 -4
  43. package/src/squiffy.runtime.ts +322 -17
  44. package/src/state.ts +34 -4
  45. package/src/textProcessor.ts +76 -9
  46. package/src/types.ts +57 -1
  47. package/vite.preview.config.ts +7 -0
@@ -1,4 +1,4 @@
1
- import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt } from "./types.js";
1
+ import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt, SavedGame, LoadSaveResult } from "./types.js";
2
2
  import { TextProcessor, errorHtml } from "./textProcessor.js";
3
3
  import { toNumber } from "./numbers.js";
4
4
  import { Emitter, SquiffyEventMap } from "./events.js";
@@ -12,8 +12,16 @@ import { imports } from "./import.js";
12
12
  import { areInputsValid, setupInputValidation } from "./inputValidation.js";
13
13
  import { createAssetHtmlResolver } from "./assets.js";
14
14
 
15
- export type { SquiffyApi } from "./types.js";
15
+ export type { SquiffyApi, SavedGame, LoadSaveResult } from "./types.js";
16
16
  export type { SquiffyEventHandler, SquiffyEventMap } from "./events.js";
17
+ export { createSavesDialog, formatSaveTime, SAVES_STRINGS, SAVE_FILE_EXTENSION } from "./savesDialog.js";
18
+ export type { SavesDialog, SavesDialogOptions, SavesStringName } from "./savesDialog.js";
19
+ export { indexedDbSaveSlots, memorySaveSlots } from "./saveSlots.js";
20
+ export { createPanels } from "./panels.js";
21
+ export type { Panels, PanelsOptions } from "./panels.js";
22
+ export { PANEL_ICONS } from "./types.js";
23
+ export type { Panel, PanelIcon } from "./types.js";
24
+ export type { SaveSlot, SaveSlots } from "./saveSlots.js";
17
25
 
18
26
  export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> => {
19
27
  let story: Story;
@@ -30,6 +38,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
30
38
  const emitter = new Emitter<SquiffyEventMap>();
31
39
  const transitions: (() => Promise<void>)[] = [];
32
40
  let runningTransitions = false;
41
+ // A {{goto ... after=}} waiting to happen (#375)
42
+ let gotoTimer: ReturnType<typeof setTimeout> | undefined;
43
+ // {{goto}}s followed one after another without the player doing anything, so a loop can't hang
44
+ // the browser
45
+ let gotoHops = 0;
46
+ const MAX_GOTO_HOPS = 100;
33
47
 
34
48
  async function handleLink(link: HTMLElement): Promise<boolean> {
35
49
  if (runningTransitions) return false;
@@ -46,9 +60,18 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
46
60
  const passage = link.getAttribute("data-passage");
47
61
  const section = link.getAttribute("data-section");
48
62
 
63
+ if (passage !== null || section !== null) {
64
+ gotoHops = 0;
65
+ // The story-wide turn count (#377). A {{goto}} isn't a turn, as the player didn't click it.
66
+ set("turns", (get("turns") || 0) + 1);
67
+ }
68
+
49
69
  if (passage !== null) {
50
- disableLink(link);
51
- set("_turncount", get("_turncount") + 1);
70
+ // A passage with @repeat can be clicked again, and doesn't count towards @1, @2... and @last
71
+ if (!isRepeatPassage(passage)) {
72
+ disableLink(link);
73
+ set("_turncount", get("_turncount") + 1);
74
+ }
52
75
  await processLink(link);
53
76
  if (passage) {
54
77
  currentBlockOutputElement = null;
@@ -92,6 +115,14 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
92
115
  }
93
116
  }
94
117
 
118
+ function isRepeatPassage(passageName: string) {
119
+ if (!passageName) return false;
120
+ const sectionPassages = currentSection?.passages;
121
+ if (sectionPassages && passageName in sectionPassages) return !!sectionPassages[passageName].repeat;
122
+ const masterPassages = story.sections[""]?.passages;
123
+ return !!(masterPassages && passageName in masterPassages && masterPassages[passageName].repeat);
124
+ }
125
+
95
126
  function disableLink(link: Element) {
96
127
  link.classList.add("disabled");
97
128
  link.setAttribute("tabindex", "-1");
@@ -113,7 +144,88 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
113
144
  }
114
145
  if (!load()) {
115
146
  await go(story.start);
147
+ return;
148
+ }
149
+ // Saved while waiting for a {{goto}}, so carry on waiting
150
+ await resumeGoto();
151
+ }
152
+
153
+ async function resumeGoto() {
154
+ const element = currentPassageElement ?? currentSectionElement;
155
+ const section = element?.getAttribute("data-goto");
156
+ if (section && section in story.sections) {
157
+ await followGoto({ section, after: Number(element.getAttribute("data-goto-after") || 0) });
158
+ }
159
+ }
160
+
161
+ function cancelGoto() {
162
+ clearTimeout(gotoTimer);
163
+ gotoTimer = undefined;
164
+ textProcessor.goto = null;
165
+ textProcessor.deactivate.clear();
166
+ }
167
+
168
+ // Disables the links to the passages that a {{deactivate}} in the text just shown asked for
169
+ // (#13). The element that did it, and each link it disabled, get the same number, so that going
170
+ // back can enable just those links again. A link already disabled by a click is left alone.
171
+ function takeDeactivate(element: HTMLElement) {
172
+ const names = textProcessor.deactivate;
173
+ if (names.size == 0) return;
174
+ const id = String((get("_deactivations") || 0) + 1);
175
+ set("_deactivations", Number(id));
176
+ element.setAttribute("data-deactivates", id);
177
+ for (const link of currentSectionElement.querySelectorAll("a.squiffy-link[data-passage]")) {
178
+ if (names.has(link.getAttribute("data-passage")!) && !link.classList.contains("disabled")) {
179
+ disableLink(link);
180
+ link.setAttribute("data-deactivated-by", id);
181
+ }
182
+ }
183
+ names.clear();
184
+ }
185
+
186
+ // Going back: enables the links that the element's {{deactivate}} disabled
187
+ function undoDeactivate(element: HTMLElement) {
188
+ const id = element.getAttribute("data-deactivates");
189
+ if (!id) return;
190
+ for (const link of currentSectionElement.querySelectorAll(`a.squiffy-link[data-deactivated-by="${id}"]`)) {
191
+ enableLink(link);
192
+ link.removeAttribute("data-deactivated-by");
193
+ }
194
+ }
195
+
196
+ // Takes the {{goto}} from the text just shown, if there was one, and marks the section or
197
+ // passage element with it, so that going back skips it, and loading resumes it.
198
+ function takeGoto(element: HTMLElement) {
199
+ const pending = textProcessor.goto;
200
+ textProcessor.goto = null;
201
+ if (pending) {
202
+ element.setAttribute("data-goto", pending.section);
203
+ if (pending.after) element.setAttribute("data-goto-after", String(pending.after));
116
204
  }
205
+ return pending;
206
+ }
207
+
208
+ async function followGoto(pending: { section: string; after: number } | null) {
209
+ if (!pending) return;
210
+ if (pending.after > 0) {
211
+ gotoTimer = setTimeout(() => {
212
+ gotoTimer = undefined;
213
+ gotoHops = 0;
214
+ void go(pending.section);
215
+ }, pending.after);
216
+ return;
217
+ }
218
+ if (++gotoHops > MAX_GOTO_HOPS) {
219
+ gotoHops = 0;
220
+ const element = currentPassageElement ?? currentSectionElement;
221
+ element.removeAttribute("data-goto");
222
+ const message = `stopped after ${MAX_GOTO_HOPS} in a row without the player clicking anything, going to "${pending.section}". Is there a loop?`;
223
+ console.error("Squiffy error in {{goto}}:", message);
224
+ element.insertAdjacentHTML("beforeend", errorHtml("Error in {{goto}}:", message));
225
+ save();
226
+ return;
227
+ }
228
+ await go(pending.section);
117
229
  }
118
230
 
119
231
  async function processLink(link: HTMLElement) {
@@ -230,10 +342,21 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
230
342
  }
231
343
 
232
344
  async function go(sectionName: string) {
345
+ cancelGoto();
233
346
  const oldCanGoBack = canGoBack();
234
347
  currentSection = story.sections[sectionName];
235
348
  if (!currentSection) return;
349
+ const sectionBefore = get("_section");
350
+ if (sectionBefore !== null) {
351
+ // Where the player was before this (#56): the section, or the passage in it shown last
352
+ set("previous", get("_passage") ?? sectionBefore);
353
+ set("previous_section", sectionBefore);
354
+ }
355
+ if (get("_passage") !== null) set("_passage", null);
236
356
  set("_section", sectionName);
357
+ // The story-wide turn count starts at 0 (#377), in a new story or one saved before it existed.
358
+ // It isn't a change the player made, so it isn't undone.
359
+ if (get("turns") === null) state.setInternal("turns", 0, false);
237
360
  state.setSeen(sectionName);
238
361
  const master = story.sections[""];
239
362
  if (master?.clear || currentSection.clear) {
@@ -261,6 +384,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
261
384
  setupInputValidation(currentSectionElement);
262
385
 
263
386
  set("_turncount", 0);
387
+ takeDeactivate(currentSectionElement);
388
+ const pending = takeGoto(currentSectionElement);
264
389
  writeUndoLog();
265
390
  save();
266
391
 
@@ -269,9 +394,13 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
269
394
  emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
270
395
  }
271
396
  emitter.emit("navigated", { section: sectionName });
397
+ await followGoto(pending);
272
398
  }
273
399
 
274
- function runJs(index: number, extra: any = null) {
400
+ let inAfterWrite = false;
401
+
402
+ // afterWrite: where squiffy.ui.afterWrite queues its functions, for a section or passage's JS (#106)
403
+ function runJs(index: number, extra: any = null, afterWrite?: (() => void)[]) {
275
404
  const squiffy = {
276
405
  get: get,
277
406
  set: set,
@@ -279,10 +408,23 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
279
408
  transition: addTransition,
280
409
  write: ui.write,
281
410
  scrollToEnd: ui.scrollToEnd,
411
+ afterWrite: (fn: () => void) => {
412
+ if (!afterWrite) {
413
+ throw new Error("squiffy.ui.afterWrite can only be used in a section or passage's JavaScript");
414
+ }
415
+ afterWrite.push(fn);
416
+ },
282
417
  },
283
418
  story: {
284
- go: go,
419
+ // In an afterWrite function, the section's text is already on the page, so going
420
+ // somewhere else waits until it has finished, like {{goto}} (#106)
421
+ go: (sectionName: string) => {
422
+ if (!inAfterWrite) return go(sectionName);
423
+ textProcessor.goto ??= { section: sectionName, after: 0 };
424
+ return Promise.resolve();
425
+ },
285
426
  seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
427
+ visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
286
428
  },
287
429
  element: outputElementContainer,
288
430
  import: imports,
@@ -295,9 +437,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
295
437
  if (section.attributes) {
296
438
  await processAttributes(section.attributes);
297
439
  }
440
+ const afterWrite: (() => void)[] = [];
298
441
  if (section.jsIndex !== undefined) {
299
442
  const sectionBefore = get("_section");
300
- runJs(section.jsIndex);
443
+ runJs(section.jsIndex, null, afterWrite);
301
444
  if (get("_section") !== sectionBefore) {
302
445
  // JS called squiffy.story.go() and navigated away; the destination
303
446
  // section will handle rendering its own content.
@@ -307,6 +450,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
307
450
 
308
451
  ui.write(section.text || "", source);
309
452
 
453
+ // Functions from squiffy.ui.afterWrite run once the text and its {{...}} are on the page (#106)
454
+ inAfterWrite = true;
455
+ try {
456
+ for (const fn of afterWrite) fn();
457
+ }
458
+ finally {
459
+ inAfterWrite = false;
460
+ }
461
+
310
462
  await runTransitions();
311
463
  }
312
464
 
@@ -322,6 +474,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
322
474
  }
323
475
 
324
476
  async function showPassage(passageName: string) {
477
+ cancelGoto();
325
478
  const oldCanGoBack = canGoBack();
326
479
  let passage = currentSection.passages && currentSection.passages[passageName];
327
480
  const masterSection = story.sections[""];
@@ -329,6 +482,9 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
329
482
  if (!passage) {
330
483
  throw `No passage named ${passageName} in the current section or master section`;
331
484
  }
485
+ // The section or passage shown before this one (#56)
486
+ set("previous", get("_passage") ?? get("_section"));
487
+ set("_passage", passageName);
332
488
  state.setSeen(passageName);
333
489
 
334
490
  const passages: Passage[] = [];
@@ -352,7 +508,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
352
508
  runFns.push(() => run(passage, `[[${get("_section")}]][${passageName}]`));
353
509
 
354
510
  const turnPassageName = "@" + get("_turncount");
355
- if (currentSection.passages) {
511
+ // A passage with @repeat doesn't count as a turn, so @1, @2... and @last ran already if they're due
512
+ if (currentSection.passages && !passage.repeat) {
356
513
  if (turnPassageName in currentSection.passages) {
357
514
  const turnPassage = currentSection.passages[turnPassageName];
358
515
  passages.push(turnPassage);
@@ -383,6 +540,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
383
540
  // Setup validation for any inputs added by passages
384
541
  setupInputValidation(currentSectionElement);
385
542
 
543
+ takeDeactivate(currentPassageElement!);
544
+ const pending = takeGoto(currentPassageElement!);
386
545
  writeUndoLog();
387
546
  save();
388
547
  const newCanGoBack = canGoBack();
@@ -390,6 +549,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
390
549
  emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
391
550
  }
392
551
  emitter.emit("navigated", { section: get("_section"), passage: passageName });
552
+ await followGoto(pending);
393
553
  }
394
554
 
395
555
  async function processAttributes(attributes: string[]) {
@@ -399,6 +559,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
399
559
  }
400
560
 
401
561
  function restart() {
562
+ cancelGoto();
402
563
  state.reset();
403
564
  // TODO: This feels like the wrong way of triggering location.reload()
404
565
  // - should be a separate setting to the scroll setting.
@@ -434,6 +595,15 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
434
595
  return false;
435
596
  }
436
597
 
598
+ showSavedOutput(output);
599
+ runUiJs();
600
+ pluginManager.onLoad();
601
+ setupInputValidation(currentSectionElement);
602
+ return true;
603
+ }
604
+
605
+ // Puts a saved game's text back on screen, and carries on from the end of it
606
+ function showSavedOutput(output: string) {
437
607
  // Saved output may contain asset URLs that are no longer valid (e.g. blob: URLs), so resolve them again
438
608
  outputElement.innerHTML = resolveAssetsInHtml(output);
439
609
 
@@ -442,10 +612,97 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
442
612
  currentBlockOutputElement = outputElement.querySelector(".squiffy-output-block:last-child");
443
613
 
444
614
  currentSection = story.sections[get("_section")];
445
- runUiJs();
615
+ }
616
+
617
+ // The game as it is now. The attributes include the text on screen (_output), and the undo
618
+ // log is in that text, so a loaded game can go back too.
619
+ function getSave(): SavedGame {
620
+ return {
621
+ format: "squiffy-save",
622
+ version: 1,
623
+ storyId: story.projectId ?? null,
624
+ section: get("_section"),
625
+ passage: get("_passage"),
626
+ summary: getSummary(),
627
+ savedAt: new Date().toISOString(),
628
+ state: structuredClone(state.store),
629
+ };
630
+ }
631
+
632
+ // The start of the text in the current section, to tell saves apart by. If it starts with a
633
+ // heading, that's it, as it's likely to name where the player is.
634
+ function getSummary() {
635
+ const MAX_LENGTH = 100;
636
+ const blocks = currentSectionElement?.querySelectorAll(".squiffy-output-block") ?? [];
637
+ for (const block of blocks) {
638
+ const text = textOf(block);
639
+ if (!text) continue;
640
+ const first = [...block.querySelectorAll("h1, h2, h3, h4, h5, h6, p, li")].find(child => textOf(child));
641
+ if (first && /^H[1-6]$/.test(first.tagName) && textOf(block).startsWith(textOf(first))) {
642
+ return textOf(first).substring(0, MAX_LENGTH);
643
+ }
644
+ if (text.length <= MAX_LENGTH) return text;
645
+ const cut = text.substring(0, MAX_LENGTH);
646
+ const space = cut.lastIndexOf(" ");
647
+ return (space > MAX_LENGTH / 2 ? cut.substring(0, space) : cut) + "…";
648
+ }
649
+ return "";
650
+ }
651
+
652
+ // An element's text, with a space between paragraphs, headings and lines
653
+ function textOf(element: Element) {
654
+ const clone = element.cloneNode(true) as Element;
655
+ clone.querySelectorAll("p, h1, h2, h3, h4, h5, h6, li, div, br, tr, blockquote").forEach(el => el.after(" "));
656
+ return (clone.textContent ?? "").replace(/\s+/g, " ").trim();
657
+ }
658
+
659
+ function isSavedGame(save: unknown): save is SavedGame {
660
+ if (!save || typeof save != "object") return false;
661
+ const s = save as Partial<SavedGame>;
662
+ return s.format === "squiffy-save" && s.version === 1 && !!s.state && typeof s.state == "object"
663
+ && !Array.isArray(s.state) && typeof s.state._output == "string";
664
+ }
665
+
666
+ async function loadSave(save: SavedGame): Promise<LoadSaveResult> {
667
+ if (!isSavedGame(save)) return { success: false, error: "notASave" };
668
+ // A story without an id, or a save from one, can't be checked, so it's loaded
669
+ if (save.storyId && story.projectId && save.storyId !== story.projectId) {
670
+ return { success: false, error: "wrongStory" };
671
+ }
672
+
673
+ // Wait for anything being shown to finish, so it doesn't carry on into the loaded game
674
+ while (runningTransitions) {
675
+ await new Promise(resolve => setTimeout(resolve, 50));
676
+ }
677
+ cancelGoto();
678
+ pendingErrors.length = 0;
679
+ state.reset();
680
+ for (const [attribute, value] of Object.entries(save.state)) {
681
+ state.setInternal(attribute, value, false);
682
+ }
683
+ undoLog = {};
684
+ scrollPosition = 0;
685
+ scrollToTop = false;
686
+ showSavedOutput(save.state._output as string);
687
+
688
+ if (!currentSection) {
689
+ // The section the game was saved in isn't in the story any more, so start again from
690
+ // the beginning, keeping the attributes
691
+ outputElement.innerHTML = "";
692
+ await go(story.start);
693
+ emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
694
+ return { success: true };
695
+ }
696
+
446
697
  pluginManager.onLoad();
447
698
  setupInputValidation(currentSectionElement);
448
- return true;
699
+ emitter.emit("canGoBackChanged", { canGoBack: canGoBack() });
700
+ const passage = get("_passage");
701
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
702
+
703
+ // Saved while waiting for a {{goto}}, so carry on waiting
704
+ await resumeGoto();
705
+ return { success: true };
449
706
  }
450
707
 
451
708
  function newBlockOutputElement() {
@@ -646,6 +903,33 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
646
903
 
647
904
  setCurrentSectionElement();
648
905
  setCurrentPassageElement();
906
+ emitter.emit("storyUpdated", {});
907
+ }
908
+
909
+ // A master section passage for a panel or dialog (#14, #443): rendered with the attributes as
910
+ // they are, changing nothing, with its links disabled
911
+ function renderPassage(name: string): string {
912
+ const passage = story.sections[""]?.passages?.[name];
913
+ if (!passage) {
914
+ return errorHtml("Error in panel:", `there is no passage called "${name}" in the master section [[]]`);
915
+ }
916
+ // Anything the story's own text has asked for, which this mustn't change
917
+ const goto = textProcessor.goto;
918
+ const deactivate = [...textProcessor.deactivate];
919
+ state.readOnly = true;
920
+ let html: string;
921
+ try {
922
+ html = ui.renderHtml(passage.text || "", false);
923
+ }
924
+ finally {
925
+ state.readOnly = false;
926
+ textProcessor.goto = goto;
927
+ textProcessor.deactivate = new Set(deactivate);
928
+ }
929
+ const template = document.createElement("template");
930
+ template.innerHTML = html;
931
+ template.content.querySelectorAll("a.squiffy-link").forEach(disableLink);
932
+ return template.innerHTML;
649
933
  }
650
934
 
651
935
  function setCurrentSectionElement() {
@@ -686,7 +970,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
686
970
  }
687
971
 
688
972
  function canGoBack() {
689
- return getHistoryCount() > 1;
973
+ // Sections and passages that went somewhere else with {{goto}} are skipped by goBack(), so
974
+ // they don't count, unless it's the current one, still waiting for its after= delay
975
+ const current = currentPassageElement ?? currentSectionElement;
976
+ const redirected = [...outputElement.querySelectorAll("[data-goto]")].filter(el => el !== current).length;
977
+ return getHistoryCount() - redirected > 1;
690
978
  }
691
979
 
692
980
  function goBack() {
@@ -696,11 +984,30 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
696
984
  return;
697
985
  }
698
986
 
987
+ cancelGoto();
988
+ // Undo back to the section or passage the player clicked through to, not one that went
989
+ // somewhere else with {{goto}}
990
+ do {
991
+ undoLast();
992
+ } while ((currentPassageElement ?? currentSectionElement).hasAttribute("data-goto") && getHistoryCount() > 1);
993
+ // The attributes were saved as they were undone, so save the output to match. Otherwise a saved
994
+ // game would come back with the text that was undone.
995
+ save();
996
+
997
+ if (!canGoBack()) {
998
+ emitter.emit("canGoBackChanged", { canGoBack: false });
999
+ }
1000
+ const passage = currentPassageElement?.getAttribute("data-passage");
1001
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
1002
+ }
1003
+
1004
+ function undoLast() {
699
1005
  const clearStack = getClearStack();
700
1006
 
701
1007
  if (currentPassageElement) {
702
1008
  const currentPassage = currentPassageElement.getAttribute("data-passage");
703
1009
  doUndo(currentPassageElement.getAttribute("data-undo"));
1010
+ undoDeactivate(currentPassageElement);
704
1011
  currentPassageElement.remove();
705
1012
 
706
1013
  // If there's nothing left in the outputElement except for an empty section element that
@@ -755,12 +1062,6 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
755
1062
  setCurrentPassageElement();
756
1063
  enableInputs(currentSectionElement);
757
1064
  }
758
-
759
- if (!canGoBack()) {
760
- emitter.emit("canGoBackChanged", { canGoBack: false });
761
- }
762
- const passage = currentPassageElement?.getAttribute("data-passage");
763
- emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
764
1065
  }
765
1066
 
766
1067
  // We create a separate div inside the passed-in element. This allows us to clear the text output, but
@@ -875,6 +1176,10 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
875
1176
  clickLink: handleLink,
876
1177
  update: update,
877
1178
  goBack: goBack,
1179
+ canGoBack: canGoBack,
1180
+ getSave: getSave,
1181
+ loadSave: loadSave,
1182
+ renderPassage: renderPassage,
878
1183
  on: (e, h) => emitter.on(e, h),
879
1184
  off: (e, h) => emitter.off(e, h),
880
1185
  once: (e, h) => emitter.once(e, h),
package/src/state.ts CHANGED
@@ -24,7 +24,12 @@ export class State {
24
24
  return this.persist && window.localStorage && this.storyId;
25
25
  }
26
26
 
27
+ // While this is true, set() does nothing: e.g. while a panel is rendered, so its {{set}}s
28
+ // don't change the story
29
+ readOnly = false;
30
+
27
31
  set(attribute: string, value: any) {
32
+ if (this.readOnly) return;
28
33
  this.setInternal(attribute, value, true);
29
34
  }
30
35
 
@@ -48,8 +53,13 @@ export class State {
48
53
  this.onSet(attribute, value);
49
54
  }
50
55
 
56
+ // Only the store's own properties are attributes, not ones it inherits, such as valueOf
57
+ private has(attribute: string) {
58
+ return Object.prototype.hasOwnProperty.call(this.store, attribute);
59
+ }
60
+
51
61
  get(attribute: string): any {
52
- if (attribute in this.store) {
62
+ if (this.has(attribute)) {
53
63
  return structuredClone(this.store[attribute]);
54
64
  }
55
65
 
@@ -61,12 +71,16 @@ export class State {
61
71
  // This allows {{attribute}} in templates to reflect changes made
62
72
  // by helpers like {{inc}} during the same render pass.
63
73
  return new Proxy({} as Record<string, any>, {
64
- get: (_, prop) => this.get(String(prop)),
65
- has: (_, prop) => String(prop) in this.store,
74
+ // A name that isn't an attribute is null, unless it's one every object has, like
75
+ // valueOf, which Handlebars can use
76
+ get: (target, prop) => typeof prop == "string" && (this.has(prop) || !(prop in target))
77
+ ? this.get(prop)
78
+ : Reflect.get(target, prop),
79
+ has: (_, prop) => this.has(String(prop)),
66
80
  ownKeys: () => Object.keys(this.store),
67
81
  getOwnPropertyDescriptor: (_, prop) => {
68
82
  const key = String(prop);
69
- if (key in this.store) {
83
+ if (this.has(key)) {
70
84
  return {
71
85
  enumerable: true,
72
86
  configurable: true,
@@ -107,9 +121,15 @@ export class State {
107
121
  }
108
122
  }
109
123
 
124
+ // Records a visit to a section or passage: adds it to _seen_sections, and counts it in
125
+ // _visits (#377). Both are attributes, so going back undoes them.
110
126
  setSeen(sectionName: string) {
111
127
  let seenSections = this.get("_seen_sections");
112
128
  if (!seenSections) seenSections = [];
129
+ const visits = this.get("_visits") || {};
130
+ // A save from before _visits has the name in _seen_sections with no count: that's one visit
131
+ visits[sectionName] = this.getVisitsFrom(visits, seenSections, sectionName) + 1;
132
+ this.set("_visits", visits);
113
133
  if (seenSections.indexOf(sectionName) == -1) {
114
134
  seenSections.push(sectionName);
115
135
  this.set("_seen_sections", seenSections);
@@ -121,4 +141,14 @@ export class State {
121
141
  if (!seenSections) return false;
122
142
  return (seenSections.indexOf(sectionName) > -1);
123
143
  }
144
+
145
+ // How many times a section or passage has been visited, or 0 if it hasn't
146
+ getVisits(sectionName: string): number {
147
+ return this.getVisitsFrom(this.get("_visits") || {}, this.get("_seen_sections") || [], sectionName);
148
+ }
149
+
150
+ private getVisitsFrom(visits: Record<string, number>, seenSections: string[], sectionName: string): number {
151
+ if (Object.prototype.hasOwnProperty.call(visits, sectionName)) return visits[sectionName];
152
+ return seenSections.indexOf(sectionName) > -1 ? 1 : 0;
153
+ }
124
154
  }