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
@@ -0,0 +1,155 @@
1
+ import { expect, test, beforeEach, afterEach } from "vitest";
2
+ import globalJsdom from "global-jsdom";
3
+ import { init } from "./squiffy.runtime.js";
4
+ import { compile as squiffyCompile } from "squiffy-compiler";
5
+ import type { SquiffyInitOptions } from "./types.js";
6
+
7
+ // Persistent attributes (#539): squiffy.json's "persistent", attributes that belong to the player
8
+ // rather than the playthrough, such as the endings they've found
9
+
10
+ let cleanup: () => void;
11
+
12
+ beforeEach(() => {
13
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
14
+ });
15
+
16
+ afterEach(() => {
17
+ localStorage.clear();
18
+ cleanup();
19
+ });
20
+
21
+ const script = `[[start]]:
22
+ @set score = 1
23
+ Endings: {{#if endings}}{{length endings}}{{else}}none{{/if}}.
24
+ {{#if finished}}Welcome back.{{/if}}
25
+ [[Pebbles]](pebbles) [Forget]
26
+
27
+ [Forget]:
28
+ {{forget}}Forgotten.
29
+
30
+ [[pebbles]]:
31
+ @set endings.pebbles = true
32
+ @set finished
33
+ @set score = 2
34
+ The end.`;
35
+
36
+ const start = async (options: Partial<SquiffyInitOptions> = {}, persistent: string[] | undefined = ["endings", "finished"]) => {
37
+ const element = document.getElementById("squiffy")!;
38
+ element.innerHTML = "";
39
+ const result = await squiffyCompile({ script, persistent, expressions: true });
40
+ if (!result.success) throw new Error("Compile failed");
41
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
42
+ const api = await init({ element, story: { js: js as any, ...result.output.story }, persist: false, scroll: "none", ...options });
43
+ await api.begin();
44
+ return { api, element };
45
+ };
46
+
47
+ const link = (element: HTMLElement, text: string) =>
48
+ [...element.querySelectorAll<HTMLElement>("a.squiffy-link")].filter(l => l.textContent === text).pop()!;
49
+
50
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
51
+
52
+ const text = (element: HTMLElement) => element.textContent!.replace(/\s+/g, " ");
53
+
54
+ test("The story's output lists its persistent attributes", async () => {
55
+ const result = await squiffyCompile({ script, persistent: ["endings"] });
56
+ if (!result.success) throw new Error("Compile failed");
57
+ expect(result.output.story.persistent).toEqual(["endings"]);
58
+ expect(await result.getJs()).toContain("story.persistent = [\"endings\"];");
59
+ });
60
+
61
+ test("Persistent attributes are set and read like any other", async () => {
62
+ const { api, element } = await start();
63
+ expect(text(element)).toContain("Endings: none.");
64
+ await api.clickLink(link(element, "Pebbles"));
65
+ expect(api.get("endings")).toEqual({ pebbles: true });
66
+ expect(api.get("endings.pebbles")).toBe(true);
67
+ expect(api.get("finished")).toBe(true);
68
+ expect(api.getPersistent()).toEqual({ endings: { pebbles: true }, finished: true });
69
+ });
70
+
71
+ test("Restart, Back and saved games leave persistent attributes alone, and saves don't include them", async () => {
72
+ const { api, element } = await start();
73
+ const save = api.getSave();
74
+ await api.clickLink(link(element, "Pebbles"));
75
+ expect(api.getSave().state).not.toHaveProperty("endings");
76
+ expect(api.getSave().state).not.toHaveProperty("finished");
77
+
78
+ api.goBack();
79
+ expect(api.get("score")).toBe(1);
80
+ expect(api.get("endings")).toEqual({ pebbles: true });
81
+
82
+ await api.loadSave(save);
83
+ expect(api.get("finished")).toBe(true);
84
+
85
+ api.restart();
86
+ await settle();
87
+ expect(api.get("_section")).toBe("start");
88
+ expect(api.get("_visits")).toEqual({ start: 1 });
89
+ expect(api.get("finished")).toBe(true);
90
+ expect(text(element)).toContain("Endings: 1.");
91
+ expect(text(element)).toContain("Welcome back.");
92
+ });
93
+
94
+ test("A saved game from before an attribute was persistent doesn't change it", async () => {
95
+ const { api, element } = await start();
96
+ await api.clickLink(link(element, "Pebbles"));
97
+ const save = api.getSave();
98
+ save.state.finished = false;
99
+ await api.loadSave(save);
100
+ expect(api.get("finished")).toBe(true);
101
+ });
102
+
103
+ test("Without \"persistent\", attributes are part of the game as before", async () => {
104
+ const { api, element } = await start({}, []);
105
+ await api.clickLink(link(element, "Pebbles"));
106
+ expect(api.getSave().state).toHaveProperty("finished", true);
107
+ api.restart();
108
+ await settle();
109
+ expect(api.get("finished")).toBeNull();
110
+ expect(api.getPersistent()).toEqual({});
111
+ });
112
+
113
+ test("{{forget}} clears persistent attributes", async () => {
114
+ const { api, element } = await start({ persistent: { finished: true, endings: { pebbles: true } } });
115
+ expect(text(element)).toContain("Welcome back.");
116
+ const changes: string[] = [];
117
+ api.on("set", e => changes.push(e.attribute));
118
+ await api.clickLink(link(element, "Forget"));
119
+ expect(text(element)).toContain("Forgotten.");
120
+ expect(api.get("finished")).toBeNull();
121
+ expect(api.get("endings")).toBeNull();
122
+ expect(api.getPersistent()).toEqual({});
123
+ expect(changes).toEqual(expect.arrayContaining(["endings", "finished"]));
124
+ });
125
+
126
+ test("api.forget() clears the persistent attributes named, and only persistent ones", async () => {
127
+ const { api } = await start({ persistent: { finished: true, endings: { pebbles: true } } });
128
+ api.forget(["finished", "score"]);
129
+ expect(api.get("finished")).toBeNull();
130
+ expect(api.get("score")).toBe(1);
131
+ expect(api.get("endings")).toEqual({ pebbles: true });
132
+ });
133
+
134
+ test("Persistent attributes are kept for the story when persist is on", async () => {
135
+ const first = await start({ persist: true, storyId: "mystory" });
136
+ await first.api.clickLink(link(first.element, "Pebbles"));
137
+ first.api.dispose();
138
+ expect(JSON.parse(localStorage.getItem("squiffy-persistent:mystory")!)).toEqual({ endings: { pebbles: true }, finished: true });
139
+
140
+ // A new game, as after clearing the saved one
141
+ localStorage.removeItem("mystory-_output");
142
+ const { api, element } = await start({ persist: true, storyId: "mystory" });
143
+ expect(text(element)).toContain("Welcome back.");
144
+ expect(api.get("endings")).toEqual({ pebbles: true });
145
+
146
+ api.restart();
147
+ await settle();
148
+ expect(localStorage.getItem("squiffy-persistent:mystory")).not.toBeNull();
149
+ });
150
+
151
+ test("Starting values given to init() are used in place of the browser's", async () => {
152
+ localStorage.setItem("squiffy-persistent:mystory", JSON.stringify({ finished: true }));
153
+ const { api } = await start({ persist: true, storyId: "mystory", persistent: { endings: { rock: true } } });
154
+ expect(api.getPersistent()).toEqual({ endings: { rock: true } });
155
+ });
@@ -0,0 +1,128 @@
1
+ // Player settings (#452): options from squiffy.json's "settings" that the player can change at any
2
+ // time, such as text size or content warnings. The story reads them as settings.name. They're the
3
+ // player's, not the game's, so they aren't attributes: going back, restarting and loading a saved
4
+ // game leave them as they are. They're kept for the story in localStorage, like Mute.
5
+
6
+ import type { PlayerSetting, SettingValue } from "./types.js";
7
+
8
+ export class PlayerSettings {
9
+ // The values the player has changed, by name. A setting that isn't here has its default.
10
+ private values: Record<string, SettingValue> = {};
11
+
12
+ constructor(private getDefinitions: () => PlayerSetting[], private storageKey?: string) {
13
+ if (!storageKey) return;
14
+ try {
15
+ const saved = JSON.parse(localStorage.getItem(storageKey) ?? "{}");
16
+ if (saved && typeof saved == "object" && !Array.isArray(saved)) this.values = saved;
17
+ }
18
+ catch {
19
+ // Nothing saved, or storage that can't be read: every setting has its default
20
+ }
21
+ }
22
+
23
+ definitions() {
24
+ return this.getDefinitions().filter(setting => setting && typeof setting.name == "string");
25
+ }
26
+
27
+ private find(name: string) {
28
+ return this.definitions().find(setting => setting.name == name);
29
+ }
30
+
31
+ // Whether the story has any settings, which is when it reads settings.name as a setting
32
+ any() {
33
+ return this.definitions().length > 0;
34
+ }
35
+
36
+ get(name: string): SettingValue | null {
37
+ const setting = this.find(name);
38
+ if (!setting) return null;
39
+ const value = Object.prototype.hasOwnProperty.call(this.values, name) ? this.values[name] : undefined;
40
+ return value !== undefined && isValid(setting, value) ? value : defaultValue(setting);
41
+ }
42
+
43
+ // Every setting's value, by name: the "settings" the story reads
44
+ all(): Record<string, SettingValue> {
45
+ return Object.fromEntries(this.definitions().map(setting => [setting.name, this.get(setting.name)!]));
46
+ }
47
+
48
+ // Returns whether the value changed. One the setting can't have is ignored.
49
+ set(name: string, value: SettingValue): boolean {
50
+ const setting = this.find(name);
51
+ if (!setting) return false;
52
+ const coerced = coerce(setting, value);
53
+ if (coerced === null || coerced === this.get(name)) return false;
54
+ this.values[name] = coerced;
55
+ this.store();
56
+ return true;
57
+ }
58
+
59
+ reset() {
60
+ this.values = {};
61
+ this.store();
62
+ }
63
+
64
+ // The classes the settings put on the story's element, so the story's CSS can use them: a
65
+ // toggle's name while it's on (setting-warnings), and a list's or range's name and value
66
+ // (setting-textSize-Large)
67
+ classes(): string[] {
68
+ const classes: string[] = [];
69
+ for (const setting of this.definitions()) {
70
+ const value = this.get(setting.name);
71
+ if (setting.type == "toggle") {
72
+ if (value === true) classes.push(`setting-${setting.name}`);
73
+ }
74
+ else if (value !== null) {
75
+ classes.push(`setting-${setting.name}-${String(value).replace(/[^A-Za-z0-9_-]+/g, "-")}`);
76
+ }
77
+ }
78
+ return classes;
79
+ }
80
+
81
+ private store() {
82
+ if (!this.storageKey) return;
83
+ try {
84
+ if (Object.keys(this.values).length) localStorage.setItem(this.storageKey, JSON.stringify(this.values));
85
+ else localStorage.removeItem(this.storageKey);
86
+ }
87
+ catch {
88
+ // Storage that's full or turned off: the setting lasts until the page is closed
89
+ }
90
+ }
91
+ }
92
+
93
+ export function defaultValue(setting: PlayerSetting): SettingValue {
94
+ switch (setting.type) {
95
+ case "toggle": return setting.default ?? false;
96
+ case "list": return setting.default ?? setting.options[0]?.value ?? "";
97
+ case "range": return setting.default ?? setting.min;
98
+ }
99
+ }
100
+
101
+ function isValid(setting: PlayerSetting, value: unknown) {
102
+ return coerce(setting, value) === value;
103
+ }
104
+
105
+ // The value as the setting has it, e.g. "true" for a toggle is true and "3" for a range is 3, or
106
+ // null if the setting can't have it. A range's value is kept within min and max, on a step.
107
+ function coerce(setting: PlayerSetting, value: unknown): SettingValue | null {
108
+ switch (setting.type) {
109
+ case "toggle":
110
+ if (typeof value == "boolean") return value;
111
+ if (value === "true") return true;
112
+ if (value === "false") return false;
113
+ return null;
114
+ case "list": {
115
+ const text = typeof value == "string" || typeof value == "number" || typeof value == "boolean" ? String(value) : null;
116
+ return text !== null && setting.options.some(option => option.value === text) ? text : null;
117
+ }
118
+ case "range": {
119
+ const n = typeof value == "number" ? value : typeof value == "string" && value.trim() ? Number(value) : NaN;
120
+ if (!Number.isFinite(n)) return null;
121
+ const clamped = Math.min(setting.max, Math.max(setting.min, n));
122
+ if (!setting.step) return clamped;
123
+ const stepped = setting.min + Math.round((clamped - setting.min) / setting.step) * setting.step;
124
+ // Without the rounding errors of adding up steps such as 0.1
125
+ return Number(Math.min(setting.max, stepped).toFixed(10));
126
+ }
127
+ }
128
+ }
@@ -59,6 +59,7 @@ export class PluginManager {
59
59
  processText: this.processText,
60
60
  resolveAssetsInHtml: this.resolveAssetsInHtml,
61
61
  addTransition: this.addTransition,
62
+ written: (el) => this.onWrite(el),
62
63
  animation: this.animation,
63
64
  on: (e, h) => this.emitter.on(e, h),
64
65
  off: (e, h) => this.emitter.off(e, h),
@@ -1,6 +1,10 @@
1
1
  import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
2
2
  import Handlebars from "handlebars";
3
3
  import * as marked from "marked";
4
+ import { parseDelay } from "../utils.js";
5
+
6
+ // The parameters to the built-in animations that are times
7
+ const timeParameters = ["start", "interval", "duration", "fadeDuration"];
4
8
 
5
9
  export function AnimatePlugin(): SquiffyPlugin {
6
10
  let squiffy: PluginHost;
@@ -79,9 +83,13 @@ export function AnimatePlugin(): SquiffyPlugin {
79
83
  if (oldLink.classList.contains("disabled")) {
80
84
  link.classList.add("disabled");
81
85
  }
82
- const tabindex = oldLink.getAttribute("tabindex");
83
- if (tabindex !== null) {
84
- link.setAttribute("tabindex", tabindex);
86
+ // tabindex, and which click or {{deactivate}} disabled it, so going back
87
+ // enables the right links
88
+ for (const attr of ["tabindex", "data-clicked", "data-deactivated-by"]) {
89
+ const value = oldLink.getAttribute(attr);
90
+ if (value !== null) {
91
+ link.setAttribute(attr, value);
92
+ }
85
93
  }
86
94
  });
87
95
  };
@@ -122,12 +130,28 @@ export function AnimatePlugin(): SquiffyPlugin {
122
130
  squiffy = sq;
123
131
 
124
132
  squiffy.registerHelper("animate", function(this: any, name: string, options) {
125
- const content = options.fn(this);
133
+ // A block that's only another helper, such as {{#label}}, gives that helper's SafeString
134
+ const content = String(options.fn(this));
126
135
  const dataset: Record<string, any> = {
127
136
  name,
128
137
  content,
129
138
  ...options.hash,
130
139
  };
140
+ // Times can be written like "1.5s" as well as in milliseconds (#451)
141
+ for (const key of timeParameters) {
142
+ if (dataset[key] === undefined) continue;
143
+ const delay = parseDelay(dataset[key]);
144
+ if (delay !== null) {
145
+ dataset[key] = delay;
146
+ }
147
+ else {
148
+ // Something that isn't a time, such as an attribute that was never set,
149
+ // would stop the animation from ever finishing, and its links would never
150
+ // work, so it's left out
151
+ console.warn(`Squiffy: {{#animate}}'s ${key} isn't a time: ${JSON.stringify(dataset[key])}`);
152
+ delete dataset[key];
153
+ }
154
+ }
131
155
 
132
156
  const attrs = Object.entries(dataset)
133
157
  .map(([key, value]) =>
@@ -2,6 +2,7 @@ import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
2
2
  import Handlebars from "handlebars";
3
3
  import { fadeReplace } from "../utils.js";
4
4
  import { SquiffyEventMap } from "../events.js";
5
+ import { parsePath } from "../paths.js";
5
6
 
6
7
  export function LivePlugin(): SquiffyPlugin {
7
8
  let squiffy: PluginHost;
@@ -29,8 +30,18 @@ export function LivePlugin(): SquiffyPlugin {
29
30
 
30
31
  const onSet = async (e: SquiffyEventMap["set"]) => {
31
32
  const promises: Promise<void>[] = [];
32
- const selector = `.squiffy-live[data-attribute="${CSS.escape(e.attribute)}"]`;
33
- for (const el of squiffy.outputElement.querySelectorAll<HTMLElement>(selector)) {
33
+ // The "set" event names the attribute that changed, so {{live "hero.hp"}} is
34
+ // updated when hero is set (#442)
35
+ // Text from a section or passage is only shown again in the current section: in
36
+ // one the player has left, or a screen that's been cleared (kept, hidden, for
37
+ // going back), it would run its helpers again
38
+ const sections = [...squiffy.outputElement.querySelectorAll<HTMLElement>(".squiffy-output-section")]
39
+ .filter(el => !el.closest(".squiffy-clear-stack"));
40
+ const current = sections[sections.length - 1];
41
+ const elements = [...squiffy.outputElement.querySelectorAll<HTMLElement>(".squiffy-live[data-attribute]")]
42
+ .filter(el => parsePath(el.dataset.attribute!)[0] === e.attribute)
43
+ .filter(el => !(el.dataset.section || el.dataset.passage) || el.closest(".squiffy-output-section") === current);
44
+ for (const el of elements) {
34
45
  const oldContent = el.innerHTML;
35
46
  let newContent = "";
36
47
  if (el.dataset.section) {
@@ -44,10 +55,12 @@ export function LivePlugin(): SquiffyPlugin {
44
55
  newContent = squiffy.processText(passageText, true);
45
56
  }
46
57
  } else {
47
- newContent = e.value;
58
+ newContent = el.dataset.attribute == e.attribute ? e.value : squiffy.get(el.dataset.attribute!);
48
59
  }
49
- if (oldContent !== newContent) {
50
- promises.push(fadeReplace(el, newContent));
60
+ // A value that's a number is the same as the text on screen, e.g. when another
61
+ // part of the same attribute changes, such as another setting
62
+ if (oldContent !== String(newContent)) {
63
+ promises.push(fadeReplace(el, newContent, squiffy.written));
51
64
  }
52
65
  }
53
66
  await Promise.all(promises);
@@ -10,9 +10,7 @@ vi.mock("animejs", () => ({
10
10
  setTimeout(() => params.onComplete?.());
11
11
  },
12
12
  stagger: () => 0,
13
- text: {
14
- split: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
15
- },
13
+ splitText: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
16
14
  }));
17
15
 
18
16
  const html = `
@@ -35,8 +33,9 @@ class ResizeObserverMock {
35
33
  }
36
34
  global.ResizeObserver = ResizeObserverMock as any;
37
35
 
38
- const compile = async (script: string) => {
36
+ const compile = async (script: string, expressions = false) => {
39
37
  const compileResult = await squiffyCompile({
38
+ expressions,
40
39
  script: script,
41
40
  });
42
41
 
@@ -55,14 +54,14 @@ const compile = async (script: string) => {
55
54
  };
56
55
  };
57
56
 
58
- const initScript = async (script: string) => {
57
+ const initScript = async (script: string, expressions = false) => {
59
58
  const element = document.getElementById("squiffy");
60
59
 
61
60
  if (!element) {
62
61
  throw new Error("Element not found");
63
62
  }
64
63
 
65
- const compileResult = await compile(script);
64
+ const compileResult = await compile(script, expressions);
66
65
 
67
66
  const squiffyApi = await init({
68
67
  element: element,
@@ -220,6 +219,48 @@ Your score is {{#label "score"}}0{{/label}}.
220
219
  expect(labelSpans[0].classList.contains("fade-in")).toBe(false);
221
220
  });
222
221
 
222
+ test("Replace plugin: replaces the latest label, in a section visited again after the screen is cleared", async () => {
223
+ const script = `
224
+ [[]]:
225
+ @clear
226
+
227
+ [[room]]:
228
+ The box is {{#label "box"}}closed{{/label}}. [Open it](open) or [[go out]](outside).
229
+
230
+ [open]:
231
+ {{#replace "box"}}open{{/replace}}
232
+
233
+ [[outside]]:
234
+ You're outside. [[Go back in]](room)
235
+ `;
236
+
237
+ const { squiffyApi, element } = await initScript(script);
238
+ await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='outside']")!);
239
+ await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='room']")!);
240
+
241
+ expect(element.querySelectorAll(".squiffy-label-box").length).toBe(2);
242
+ const links = element.querySelectorAll<HTMLElement>("a.squiffy-link[data-passage='open']");
243
+ await squiffyApi.clickLink(links[links.length - 1]);
244
+ const labels = element.querySelectorAll(".squiffy-label-box");
245
+ expect(labels[0].textContent).toBe("closed");
246
+ expect(labels[1].textContent).toBe("open");
247
+ });
248
+
249
+ test("Replace plugin: replace with only a label in it", async () => {
250
+ const script = `
251
+ The box is {{#label "box"}}closed{{/label}}. [Open it](open)
252
+
253
+ [open]:
254
+ {{#replace "box"}}{{#label "lid"}}open{{/label}}{{/replace}}
255
+ `;
256
+
257
+ const { squiffyApi, element } = await initScript(script);
258
+ await squiffyApi.clickLink(findPassageLink(element, "open")!);
259
+
260
+ expect(element.querySelector(".squiffy-label-box")?.innerHTML).toBe("<span class=\"squiffy-label-lid\">open</span>");
261
+ expect(element.querySelector(".squiffy-error")).toBeNull();
262
+ });
263
+
223
264
  // ===== RotateSequencePlugin Tests =====
224
265
 
225
266
  test("Sequence plugin: click through sequence", async () => {
@@ -346,6 +387,35 @@ Score: {{live "score"}}.
346
387
  });
347
388
  });
348
389
 
390
+ test("Live plugin: a value inside an object updates when the object changes (#442)", async () => {
391
+ const script = `
392
+ @set hero = { hp: 10 }
393
+
394
+ HP: {{live "hero.hp"}}
395
+
396
+ [Hurt], [Heal]
397
+
398
+ [Hurt]:
399
+ @set hero.hp -= 6
400
+
401
+ [Heal]:
402
+ @set hero = { hp: 7 }
403
+ `;
404
+
405
+ const { squiffyApi, element } = await initScript(script, true);
406
+ const liveSpan = () => element.querySelector(".squiffy-live");
407
+ expect(liveSpan()?.textContent).toBe("10");
408
+
409
+ await squiffyApi.clickLink(findPassageLink(element, "Hurt")!);
410
+ await vi.waitFor(() => {
411
+ expect(liveSpan()?.textContent).toBe("4");
412
+ expect(liveSpan()?.classList.contains("fade-in")).toBe(false);
413
+ });
414
+
415
+ await squiffyApi.clickLink(findPassageLink(element, "Heal")!);
416
+ await vi.waitFor(() => expect(liveSpan()?.textContent).toBe("7"));
417
+ });
418
+
349
419
  test("Live plugin: embed section content", async () => {
350
420
  const script = `
351
421
  [[start]]:
@@ -436,6 +506,23 @@ You clicked!
436
506
  expect(animateSpan?.getAttribute("data-interval")).toBe("50");
437
507
  });
438
508
 
509
+ test("Animate plugin: times can be expressions or written in seconds (#451)", async () => {
510
+ const script = `
511
+ @set n = 3
512
+ {{#animate "typewriter" trigger="link" start="1.5s" interval=n * 10 duration="200ms"}}[Click me]{{/animate}}
513
+
514
+ [Click me]:
515
+ You clicked!
516
+ `;
517
+
518
+ const { element } = await initScript(script);
519
+
520
+ const animateSpan = element.querySelector<HTMLElement>(".squiffy-animate");
521
+ expect(animateSpan?.getAttribute("data-start")).toBe("1500");
522
+ expect(animateSpan?.getAttribute("data-interval")).toBe("30");
523
+ expect(animateSpan?.getAttribute("data-duration")).toBe("200");
524
+ });
525
+
439
526
  test("Animate plugin: trigger on link", async () => {
440
527
  const script = `
441
528
  {{#animate "typewriter" trigger="link"}}[Click me]{{/animate}}
@@ -11,14 +11,18 @@ export function ReplaceLabel() : SquiffyPlugin {
11
11
  return new Handlebars.SafeString(`<span class="squiffy-label-${name}">${options.fn(this)}</span>`);
12
12
  });
13
13
  squiffy.registerHelper("replace", function(this: any, name: string, options) {
14
- const result = options.fn(this);
15
- const element = squiffy.outputElement.querySelector<HTMLElement>(`.squiffy-label-${name}`);
14
+ // A block that's only another helper, such as {{#label}}, gives that helper's SafeString
15
+ const result = String(options.fn(this));
16
+ // The latest label with the name: when a section is visited again, or the screen's been
17
+ // cleared, earlier ones can still be in the output (in the clear stack, hidden)
18
+ const labels = squiffy.outputElement.querySelectorAll<HTMLElement>(`.squiffy-label-${name}`);
19
+ const element = labels[labels.length - 1];
16
20
  if (element) {
17
21
  const isBlock = result.includes("\n\n");
18
22
  const html = isBlock
19
23
  ? marked.parse(result, { async: false }).trim()
20
24
  : marked.parseInline(result, { async: false }).trim();
21
- squiffy.addTransition(() => fadeReplace(element, html as string));
25
+ squiffy.addTransition(() => fadeReplace(element, html as string, squiffy.written));
22
26
  }
23
27
  return "";
24
28
  });