squiffy-runtime 7.0.0-beta.6 → 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 (80) 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 +11 -0
  5. package/dist/every.d.ts +12 -0
  6. package/dist/every.test.d.ts +1 -0
  7. package/dist/paths.d.ts +15 -0
  8. package/dist/paths.test.d.ts +1 -0
  9. package/dist/playerSettings.d.ts +17 -0
  10. package/dist/preview-host.d.ts +2 -0
  11. package/dist/preview-host.js +10 -0
  12. package/dist/preview-host.js.map +2 -2
  13. package/dist/preview-html.js +1 -1
  14. package/dist/preview-protocol.d.ts +6 -0
  15. package/dist/settings.test.d.ts +1 -0
  16. package/dist/settingsDialog.d.ts +17 -0
  17. package/dist/skill.test.d.ts +1 -0
  18. package/dist/sound.d.ts +35 -0
  19. package/dist/sound.test.d.ts +1 -0
  20. package/dist/squiffy.page.css +14 -3
  21. package/dist/squiffy.preview.html +680 -82
  22. package/dist/squiffy.runtime.css +531 -1
  23. package/dist/squiffy.runtime.d.ts +5 -1
  24. package/dist/squiffy.runtime.global.js +117 -96
  25. package/dist/squiffy.runtime.global.js.map +1 -1
  26. package/dist/squiffy.runtime.js +5728 -4520
  27. package/dist/squiffy.runtime.js.map +1 -1
  28. package/dist/state.d.ts +4 -1
  29. package/dist/style.test.d.ts +1 -0
  30. package/dist/textProcessor.d.ts +16 -0
  31. package/dist/transitions.test.d.ts +1 -0
  32. package/dist/types.d.ts +54 -0
  33. package/dist/uiLinks.test.d.ts +1 -0
  34. package/dist/utils.d.ts +1 -0
  35. package/dist/utils.test.d.ts +1 -0
  36. package/package.json +3 -3
  37. package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
  38. package/src/animation.test.ts +44 -0
  39. package/src/animation.ts +9 -5
  40. package/src/assets.test.ts +1 -3
  41. package/src/assets.ts +1 -1
  42. package/src/classes.test.ts +201 -0
  43. package/src/confirmDialog.ts +66 -0
  44. package/src/events.ts +18 -0
  45. package/src/every.test.ts +25 -0
  46. package/src/every.ts +94 -0
  47. package/src/panels.test.ts +24 -0
  48. package/src/paths.test.ts +66 -0
  49. package/src/paths.ts +155 -0
  50. package/src/playerSettings.ts +128 -0
  51. package/src/plugins/animate.ts +16 -3
  52. package/src/plugins/live.ts +10 -4
  53. package/src/plugins/plugins.test.ts +51 -6
  54. package/src/preview-host.test.ts +22 -0
  55. package/src/preview-host.ts +15 -0
  56. package/src/preview-protocol.ts +9 -1
  57. package/src/preview.test.ts +114 -3
  58. package/src/preview.ts +97 -3
  59. package/src/settings.test.ts +233 -0
  60. package/src/settingsDialog.ts +160 -0
  61. package/src/skill.test.ts +67 -0
  62. package/src/sound.test.ts +273 -0
  63. package/src/sound.ts +207 -0
  64. package/src/squiffy.page.css +14 -3
  65. package/src/squiffy.runtime.css +531 -1
  66. package/src/squiffy.runtime.test.ts +1130 -17
  67. package/src/squiffy.runtime.ts +600 -38
  68. package/src/state.ts +45 -10
  69. package/src/style.test.ts +89 -0
  70. package/src/textProcessor.ts +484 -35
  71. package/src/transitions.test.ts +302 -0
  72. package/src/types.ts +79 -0
  73. package/src/uiLinks.test.ts +156 -0
  74. package/src/updater.ts +26 -8
  75. package/src/utils.test.ts +60 -0
  76. package/src/utils.ts +44 -14
  77. package/dist/infixExpressions.d.ts +0 -6
  78. package/src/infixExpressions.test.ts +0 -379
  79. package/src/infixExpressions.ts +0 -488
  80. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -0,0 +1,302 @@
1
+ // @transition (#489): how a section or passage appears
2
+ import { expect, test, beforeEach, afterEach, vi } from "vitest";
3
+ import globalJsdom from "global-jsdom";
4
+ import { init } from "./squiffy.runtime.js";
5
+ import { compile as squiffyCompile } from "squiffy-compiler";
6
+
7
+ let cleanup: () => void;
8
+
9
+ beforeEach(() => {
10
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
11
+ vi.useFakeTimers();
12
+ });
13
+
14
+ afterEach(() => {
15
+ vi.useRealTimers();
16
+ localStorage.clear();
17
+ cleanup();
18
+ });
19
+
20
+ const start = async (script: string, options: { persist?: boolean } = {}) => {
21
+ const result = await squiffyCompile({ script });
22
+ if (!result.success) throw new Error("Compile failed");
23
+ const story = {
24
+ ...result.output.story,
25
+ js: result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n"))) as any,
26
+ };
27
+ const element = document.getElementById("squiffy")!;
28
+ const api = await init({ element, story, persist: options.persist ?? false, storyId: "test", scroll: "none" });
29
+ await api.begin();
30
+ return { api, element };
31
+ };
32
+
33
+ const click = async (element: HTMLElement, text: string) => {
34
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
35
+ .find(l => l.textContent == text && !l.classList.contains("disabled"));
36
+ if (!link) throw new Error(`No link "${text}"`);
37
+ link.click();
38
+ await vi.runAllTimersAsync();
39
+ };
40
+
41
+ const sectionElement = (element: HTMLElement, name: string) =>
42
+ element.querySelector<HTMLElement>(`.squiffy-output-section[data-section="${name}"]`)!;
43
+
44
+ const passageElement = (element: HTMLElement, name: string) =>
45
+ element.querySelector<HTMLElement>(`.squiffy-output-passage[data-passage="${name}"]`)!;
46
+
47
+ // What a transition puts on an element while it plays
48
+ const transition = (el: HTMLElement) => el.classList.contains("squiffy-transition")
49
+ ? { name: el.getAttribute("data-transition"), time: el.style.getPropertyValue("--squiffy-transition-time") }
50
+ : null;
51
+
52
+ const story = `
53
+ [[forest]]:
54
+ @transition fade
55
+ The forest. [[Go to the cave]](cave), [look up], [listen]
56
+
57
+ [look up]:
58
+ @transition zoom 300ms
59
+ The stars are out.
60
+
61
+ [listen]:
62
+ Owls.
63
+
64
+ [[cave]]:
65
+ @transition slide-up 1.5s
66
+ @clear
67
+ The cave. [[Leave]](outside)
68
+
69
+ [[outside]]:
70
+ Outside.
71
+ `;
72
+
73
+ test("A section's transition plays as it appears, with its time", async () => {
74
+ const { element } = await start(story);
75
+ expect(transition(sectionElement(element, "forest"))).toEqual({ name: "fade", time: "" });
76
+ expect(sectionElement(element, "forest").classList).toContain("fade");
77
+
78
+ await click(element, "Go to the cave");
79
+ expect(transition(sectionElement(element, "cave"))).toEqual({ name: "slide-up", time: "1500ms" });
80
+
81
+ await click(element, "Leave");
82
+ expect(transition(sectionElement(element, "outside"))).toBeNull();
83
+ });
84
+
85
+ test("A passage has its own transition, or else its section's", async () => {
86
+ const { element } = await start(story);
87
+ await click(element, "look up");
88
+ expect(transition(passageElement(element, "look up"))).toEqual({ name: "zoom", time: "300ms" });
89
+
90
+ await click(element, "listen");
91
+ expect(transition(passageElement(element, "listen"))).toEqual({ name: "fade", time: "" });
92
+ });
93
+
94
+ test("The master section's transition is for every section, unless one has @transition none", async () => {
95
+ const { element } = await start(`
96
+ [[]]:
97
+ @transition blur 1s
98
+
99
+ [[a]]:
100
+ A. [[b]] [p]
101
+
102
+ [p]:
103
+ P.
104
+
105
+ [[b]]:
106
+ @transition none
107
+ B.
108
+ `);
109
+ expect(transition(sectionElement(element, "a"))).toEqual({ name: "blur", time: "1000ms" });
110
+ await click(element, "p");
111
+ expect(transition(passageElement(element, "p"))).toEqual({ name: "blur", time: "1000ms" });
112
+ await click(element, "b");
113
+ expect(transition(sectionElement(element, "b"))).toBeNull();
114
+ });
115
+
116
+ test("The transition's class comes off when it ends", async () => {
117
+ const { element } = await start(story);
118
+ const forest = sectionElement(element, "forest");
119
+ // An animation in the text doesn't end the section's transition
120
+ forest.querySelector("p, div")!.dispatchEvent(new window.Event("animationend", { bubbles: true }));
121
+ expect(transition(forest)).not.toBeNull();
122
+
123
+ forest.dispatchEvent(new window.Event("animationend", { bubbles: true }));
124
+ expect(transition(forest)).toBeNull();
125
+ expect(forest.classList).not.toContain("fade");
126
+ expect(forest.hasAttribute("style")).toBe(false);
127
+ });
128
+
129
+ test("Going back past @clear doesn't play the transition again", async () => {
130
+ const { api, element } = await start(story);
131
+ await click(element, "Go to the cave");
132
+ api.goBack();
133
+ await vi.runAllTimersAsync();
134
+ expect(transition(sectionElement(element, "forest"))).toBeNull();
135
+ });
136
+
137
+ test("A saved game doesn't play the transitions again when it's loaded", async () => {
138
+ const first = await start(story, { persist: true });
139
+ await click(first.element, "Go to the cave");
140
+ expect(transition(sectionElement(first.element, "cave"))).not.toBeNull();
141
+ first.api.dispose();
142
+ first.element.innerHTML = "";
143
+
144
+ const second = await start(story, { persist: true });
145
+ expect(sectionElement(second.element, "cave")).not.toBeNull();
146
+ expect(second.element.querySelector(".squiffy-transition")).toBeNull();
147
+ });
148
+
149
+ // @leave: how the old text goes when the screen is cleared
150
+
151
+ // So the leave transitions have an animation, which jsdom doesn't play: it's ended by hand
152
+ const animateLeaving = () => {
153
+ const style = document.createElement("style");
154
+ style.textContent = ".squiffy-leave { animation-name: leaving; animation-duration: 1s; }";
155
+ document.head.appendChild(style);
156
+ };
157
+
158
+ const clickWithoutWaiting = async (element: HTMLElement, text: string) => {
159
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
160
+ .find(l => l.textContent == text && !l.classList.contains("disabled"));
161
+ if (!link) throw new Error(`No link "${text}"`);
162
+ link.click();
163
+ await vi.advanceTimersByTimeAsync(0);
164
+ };
165
+
166
+ const leaving = (el: HTMLElement) => el.classList.contains("squiffy-leave")
167
+ ? { name: el.getAttribute("data-transition"), time: el.style.getPropertyValue("--squiffy-transition-time") }
168
+ : null;
169
+
170
+ const leaveStory = `
171
+ [[forest]]:
172
+ The forest. [[Go to the cave]](cave), [look up]
173
+
174
+ [look up]:
175
+ The stars are out.
176
+
177
+ [[cave]]:
178
+ @clear
179
+ @leave blur 2s
180
+ The cave. [listen]
181
+
182
+ [listen]:
183
+ @clear
184
+ Water dripping. [[Leave]](outside)
185
+
186
+ [[outside]]:
187
+ @clear
188
+ @leave none
189
+ Outside.
190
+ `;
191
+
192
+ test("The old text plays the leave transition before the screen is cleared", async () => {
193
+ animateLeaving();
194
+ const { api, element } = await start(leaveStory);
195
+ await click(element, "look up");
196
+ await clickWithoutWaiting(element, "Go to the cave");
197
+
198
+ // Everything on the screen is leaving, and the cave isn't there yet
199
+ const forest = sectionElement(element, "forest");
200
+ expect(leaving(forest)).toEqual({ name: "blur", time: "2000ms" });
201
+ expect(forest.classList).toContain("squiffy-transition");
202
+ expect(sectionElement(element, "cave")).toBeNull();
203
+ // Back waits for it
204
+ api.goBack();
205
+ await vi.advanceTimersByTimeAsync(0);
206
+ expect(leaving(forest)).not.toBeNull();
207
+ expect(passageElement(element, "look up")).not.toBeNull();
208
+
209
+ forest.dispatchEvent(new window.Event("animationend", { bubbles: true }));
210
+ await vi.runAllTimersAsync();
211
+ expect(sectionElement(element, "cave")).not.toBeNull();
212
+ // The old text is put away as it was, for going back
213
+ const putAway = element.querySelector<HTMLElement>(".squiffy-clear-stack .squiffy-output-section")!;
214
+ expect(putAway.getAttribute("data-section")).toBe("forest");
215
+ expect(putAway.classList).not.toContain("squiffy-leave");
216
+ expect(putAway.hasAttribute("style")).toBe(false);
217
+ });
218
+
219
+ test("A passage that clears the screen uses its section's leave transition, and @leave none plays none", async () => {
220
+ animateLeaving();
221
+ const { element } = await start(leaveStory);
222
+ await click(element, "Go to the cave");
223
+
224
+ await clickWithoutWaiting(element, "listen");
225
+ expect(leaving(sectionElement(element, "cave"))).toEqual({ name: "blur", time: "2000ms" });
226
+ await vi.runAllTimersAsync();
227
+ expect(passageElement(element, "listen")).not.toBeNull();
228
+
229
+ await clickWithoutWaiting(element, "Leave");
230
+ expect(sectionElement(element, "outside")).not.toBeNull();
231
+ });
232
+
233
+ test("The story goes on if the leave transition never ends", async () => {
234
+ animateLeaving();
235
+ const { element } = await start(leaveStory);
236
+ await clickWithoutWaiting(element, "Go to the cave");
237
+ await vi.advanceTimersByTimeAsync(1500);
238
+ expect(sectionElement(element, "cave")).toBeNull();
239
+ // Its 1s animation, and a second more
240
+ await vi.advanceTimersByTimeAsync(600);
241
+ expect(sectionElement(element, "cave")).not.toBeNull();
242
+ });
243
+
244
+ test("Without an animation for it, the leave transition doesn't hold the story up", async () => {
245
+ const { element } = await start(leaveStory);
246
+ await clickWithoutWaiting(element, "Go to the cave");
247
+ expect(sectionElement(element, "cave")).not.toBeNull();
248
+ });
249
+
250
+ test("Going back brings the old text back as it was", async () => {
251
+ animateLeaving();
252
+ const { api, element } = await start(leaveStory);
253
+ await click(element, "Go to the cave");
254
+ api.goBack();
255
+ await vi.runAllTimersAsync();
256
+ const forest = sectionElement(element, "forest");
257
+ expect(leaving(forest)).toBeNull();
258
+ expect(transition(forest)).toBeNull();
259
+ expect(sectionElement(element, "cave")).toBeNull();
260
+ });
261
+
262
+ test("The master section's leave transition is for every section that clears the screen", async () => {
263
+ animateLeaving();
264
+ const { element } = await start(`
265
+ [[]]:
266
+ @leave fade
267
+
268
+ [[a]]:
269
+ A. [[b]]
270
+
271
+ [[b]]:
272
+ @clear
273
+ B.
274
+ `);
275
+ await clickWithoutWaiting(element, "b");
276
+ expect(leaving(sectionElement(element, "a"))).toEqual({ name: "fade", time: "" });
277
+ });
278
+
279
+ test("A slide moves the way it's named, arriving or leaving", async () => {
280
+ const { readFileSync } = await import("fs");
281
+ const style = document.createElement("style");
282
+ style.textContent = readFileSync(new URL("./squiffy.runtime.css", import.meta.url), "utf8");
283
+ document.head.appendChild(style);
284
+
285
+ const animation = (classes: string) => {
286
+ const el = document.createElement("div");
287
+ el.className = classes;
288
+ document.body.appendChild(el);
289
+ const computed = getComputedStyle(el);
290
+ const result = `${computed.animationName} ${computed.animationDirection || "normal"}`;
291
+ el.remove();
292
+ return result;
293
+ };
294
+ // Arriving, slide-left comes in from the right, and leaving, goes off to the left, by playing
295
+ // the animation from the left backwards
296
+ expect(animation("squiffy-transition slide-left")).toBe("squiffy-transition-from-right normal");
297
+ expect(animation("squiffy-transition squiffy-leave slide-left")).toBe("squiffy-transition-from-left reverse");
298
+ expect(animation("squiffy-transition slide-up")).toBe("squiffy-transition-from-below normal");
299
+ expect(animation("squiffy-transition squiffy-leave slide-up")).toBe("squiffy-transition-from-above reverse");
300
+ // Others play backwards to leave
301
+ expect(animation("squiffy-transition squiffy-leave zoom")).toBe("squiffy-transition-zoom reverse");
302
+ });
package/src/types.ts CHANGED
@@ -14,6 +14,12 @@ export interface SquiffyInitOptions {
14
14
  * left alone. When not provided, paths are used as they are.
15
15
  */
16
16
  resolveAssetUrl?: (path: string) => string,
17
+ /**
18
+ * The page's text, for a story in another language: squiffy.json's "strings", by the same
19
+ * names. Used for the text of {{restart}} and {{saves}} links (#452), and the dialogs they
20
+ * open when the page doesn't handle them itself. Anything left out is in English.
21
+ */
22
+ strings?: Partial<Record<string, string>>,
17
23
  }
18
24
 
19
25
  export interface SquiffySettings {
@@ -50,6 +56,26 @@ export interface SquiffyApi {
50
56
  // for a panel beside the story or a dialog (#14, #443). It changes nothing: {{set}} and the
51
57
  // like are ignored, its @set and JavaScript don't run, and its links are disabled.
52
58
  renderPassage: (name: string) => string;
59
+ // Whether the story's music and sounds are muted (#444). It's remembered for the story when
60
+ // persist is on, like the light or dark theme.
61
+ isMuted: () => boolean;
62
+ setMuted: (muted: boolean) => void;
63
+ // Whether the story plays music or sounds: it names some files, or has played one. The
64
+ // "sound" event says when something plays.
65
+ usesSound: () => boolean;
66
+ // The story's player settings (squiffy.json's "settings", #452), which the Settings dialog shows
67
+ getSettings: () => PlayerSetting[];
68
+ // A setting's value, as the story reads it with settings.name: its default if the player
69
+ // hasn't changed it
70
+ getSetting: (name: string) => SettingValue | null;
71
+ // Changes a setting, as the player does in the Settings dialog. A value that isn't one the
72
+ // setting can have is ignored. It's remembered for the story when persist is on, and going
73
+ // back, restarting or loading a saved game doesn't change it.
74
+ setSetting: (name: string, value: SettingValue) => void;
75
+ // Puts every setting back to its default
76
+ resetSettings: () => void;
77
+ // Stops the story's music and sounds for good, when it's being replaced, e.g. in the editor's preview
78
+ dispose: () => void;
53
79
 
54
80
  on<E extends keyof SquiffyEventMap>(
55
81
  event: E,
@@ -93,11 +119,15 @@ export interface Story {
93
119
  // squiffy.json's "id", which a saved game is checked against
94
120
  projectId?: string;
95
121
  uiJsIndex?: number;
122
+ // The sound files the story names (#444), to load before they're needed
123
+ audio?: string[];
96
124
  // Whether @set and link setters take expressions, with the same rules as {{#if}}: attributes
97
125
  // by name, and text in quotes. True for a story with a squiffy.json (#373).
98
126
  expressions?: boolean;
99
127
  // squiffy.json's "panels": passages shown beside the story, or in a dialog from a button
100
128
  panels?: Panel[];
129
+ // squiffy.json's "settings": options the player can change, which the story reads as settings.name
130
+ settings?: PlayerSetting[];
101
131
  sections: Record<string, Section>;
102
132
  }
103
133
 
@@ -117,9 +147,46 @@ export interface Panel {
117
147
  icon?: PanelIcon;
118
148
  }
119
149
 
150
+ // A player setting (#452), from squiffy.json's "settings": "toggle" is on or off, "list" is one of
151
+ // its options, and "range" a number from min to max
152
+ export type PlayerSetting =
153
+ | PlayerSettingBase & { type: "toggle"; default?: boolean }
154
+ | PlayerSettingBase & { type: "list"; options: PlayerSettingOption[]; default?: string }
155
+ | PlayerSettingBase & { type: "range"; min: number; max: number; step?: number; default?: number };
156
+
157
+ interface PlayerSettingBase {
158
+ // How the story refers to it: settings.name
159
+ name: string;
160
+ // What the Settings dialog calls it
161
+ label: string;
162
+ // More about it, shown under the label
163
+ description?: string;
164
+ }
165
+
166
+ export interface PlayerSettingOption {
167
+ // What the story reads
168
+ value: string;
169
+ // What the Settings dialog shows
170
+ label: string;
171
+ }
172
+
173
+ export type SettingValue = boolean | string | number;
174
+
120
175
  export interface Section {
121
176
  text?: string;
122
177
  clear?: boolean;
178
+ // @music (#444): the file to play, or null to stop it
179
+ music?: string | null;
180
+ // @sound: files to play once, in order, with "stop" for @sound stop
181
+ sounds?: string[];
182
+ // @class (#449): classes on the story's element while this is the current section
183
+ classes?: string[];
184
+ // @transition (#489): how it appears, or "none", and how long that takes in milliseconds
185
+ transition?: string;
186
+ transitionTime?: number;
187
+ // @leave: how the old text goes when this clears the screen, or "none", and how long that takes
188
+ leave?: string;
189
+ leaveTime?: number;
123
190
  attributes?: string[],
124
191
  jsIndex?: number;
125
192
  passages?: Record<string, Passage>;
@@ -129,6 +196,18 @@ export interface Section {
129
196
  export interface Passage {
130
197
  text?: string;
131
198
  clear?: boolean;
199
+ // @music (#444): the file to play, or null to stop it
200
+ music?: string | null;
201
+ // @sound: files to play once, in order, with "stop" for @sound stop
202
+ sounds?: string[];
203
+ // @class (#449): classes added to the section's when this passage is shown
204
+ classes?: string[];
205
+ // @transition (#489): how it appears, or "none", and how long that takes in milliseconds
206
+ transition?: string;
207
+ transitionTime?: number;
208
+ // @leave: how the old text goes when this clears the screen, or "none", and how long that takes
209
+ leave?: string;
210
+ leaveTime?: number;
132
211
  // @repeat: its links stay clickable, and clicking one doesn't count towards @1, @2... and @last (#104)
133
212
  repeat?: boolean;
134
213
  attributes?: string[];
@@ -0,0 +1,156 @@
1
+ import { expect, test, beforeEach, afterEach, beforeAll, vi } 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 { confirmDialog } from "./confirmDialog.js";
6
+ import type { SquiffyApi, SquiffyInitOptions } from "./types.js";
7
+
8
+ // {{restart}} and {{saves}} links (#452), and the dialog that asks before restarting
9
+
10
+ beforeAll(() => {
11
+ vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
12
+ });
13
+
14
+ let cleanup: () => void;
15
+
16
+ beforeEach(() => {
17
+ cleanup = globalJsdom("<!DOCTYPE html><html><head><title>My Story</title></head><body><div id=\"squiffy\"></div></body></html>");
18
+ // jsdom has no showModal()
19
+ window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", ""); };
20
+ window.HTMLDialogElement.prototype.close = function () {
21
+ this.removeAttribute("open");
22
+ this.dispatchEvent(new window.Event("close"));
23
+ };
24
+ });
25
+
26
+ afterEach(() => {
27
+ localStorage.clear();
28
+ cleanup();
29
+ });
30
+
31
+ const script = `[[start]]:
32
+ @set score = 1
33
+ Hello. [[Next]](end)
34
+
35
+ [[end]]:
36
+ The end. {{restart text="Play again"}} {{restart confirm=false}} {{saves}} {{saves text="Save your game"}}`;
37
+
38
+ const start = async (options: Partial<SquiffyInitOptions> = {}) => {
39
+ const element = document.getElementById("squiffy")!;
40
+ const result = await squiffyCompile({ script });
41
+ if (!result.success) throw new Error("Compile failed");
42
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
43
+ const api = await init({ element, story: { js: js as any, ...result.output.story }, persist: false, scroll: "none", ...options });
44
+ await api.begin();
45
+ return { api, element };
46
+ };
47
+
48
+ const link = (element: HTMLElement, text: string) =>
49
+ [...element.querySelectorAll<HTMLElement>("a.squiffy-link")].filter(l => l.textContent === text).pop()!;
50
+
51
+ const click = async (api: SquiffyApi, element: HTMLElement, text: string) => {
52
+ expect(await api.clickLink(link(element, text))).toBe(true);
53
+ await settle();
54
+ };
55
+
56
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
57
+
58
+ const confirmDialogElement = () => document.querySelector<HTMLDialogElement>("dialog.squiffy-confirm");
59
+
60
+ test("{{restart}} and {{saves}} are links, with their own text or the page's", async () => {
61
+ const { api, element } = await start({ strings: { restart: "Recommencer", saves: "Parties" } });
62
+ await click(api, element, "Next");
63
+ const links = [...element.querySelectorAll<HTMLElement>(".link-restart, .link-saves")];
64
+ expect(links.map(l => l.textContent)).toEqual(["Play again", "Recommencer", "Parties", "Save your game"]);
65
+ expect(links[0].getAttribute("data-confirm")).toBeNull();
66
+ expect(links[1].getAttribute("data-confirm")).toBe("false");
67
+ });
68
+
69
+ test("{{restart}} asks first, in a dialog, and restarts only if the player says so", async () => {
70
+ const { api, element } = await start();
71
+ await click(api, element, "Next");
72
+
73
+ await click(api, element, "Play again");
74
+ let dialog = confirmDialogElement()!;
75
+ expect(dialog.open).toBe(true);
76
+ expect(dialog.querySelector("p")!.textContent).toBe("Are you sure you want to restart?");
77
+ dialog.querySelector<HTMLButtonElement>("[data-answer=no]")!.click();
78
+ await settle();
79
+ expect(confirmDialogElement()).toBeNull();
80
+ expect(api.get("_section")).toBe("end");
81
+
82
+ await click(api, element, "Play again");
83
+ dialog = confirmDialogElement()!;
84
+ dialog.querySelector<HTMLButtonElement>("[data-answer=yes]")!.click();
85
+ await settle();
86
+ expect(confirmDialogElement()).toBeNull();
87
+ expect(api.get("_section")).toBe("start");
88
+ expect(element.textContent).not.toContain("The end.");
89
+ });
90
+
91
+ test("{{restart confirm=false}} restarts straight away", async () => {
92
+ const { api, element } = await start();
93
+ await click(api, element, "Next");
94
+ await click(api, element, "Restart");
95
+ expect(confirmDialogElement()).toBeNull();
96
+ expect(api.get("_section")).toBe("start");
97
+ });
98
+
99
+ test("{{saves}} opens a Saved games dialog", async () => {
100
+ const { api, element } = await start();
101
+ await click(api, element, "Next");
102
+ await click(api, element, "Saved games");
103
+ const dialogs = document.querySelectorAll<HTMLDialogElement>("dialog.squiffy-saves");
104
+ expect(dialogs.length).toBe(1);
105
+ expect(dialogs[0].open).toBe(true);
106
+ dialogs[0].close();
107
+ // The same dialog again
108
+ await click(api, element, "Save your game");
109
+ expect(document.querySelectorAll("dialog.squiffy-saves").length).toBe(1);
110
+ expect(dialogs[0].open).toBe(true);
111
+ api.dispose();
112
+ expect(document.querySelectorAll("dialog.squiffy-saves").length).toBe(0);
113
+ });
114
+
115
+ test("The page can handle {{restart}} and {{saves}} itself", async () => {
116
+ const { api, element } = await start();
117
+ const restarts: boolean[] = [];
118
+ let saves = 0;
119
+ api.on("restartRequested", e => restarts.push(e.confirm));
120
+ api.on("savesRequested", () => saves++);
121
+ await click(api, element, "Next");
122
+ await click(api, element, "Play again");
123
+ await click(api, element, "Restart");
124
+ await click(api, element, "Saved games");
125
+ expect(restarts).toEqual([true, false]);
126
+ expect(saves).toBe(1);
127
+ expect(document.querySelector("dialog")).toBeNull();
128
+ expect(api.get("_section")).toBe("end");
129
+ });
130
+
131
+ test("The links are only clickable in the current section", async () => {
132
+ const twoEndings = `[[a]]:
133
+ {{restart confirm=false}} [[b]]
134
+
135
+ [[b]]:
136
+ B`;
137
+ const element = document.getElementById("squiffy")!;
138
+ const result = await squiffyCompile({ script: twoEndings });
139
+ if (!result.success) throw new Error("Compile failed");
140
+ const api = await init({ element, story: { js: [], ...result.output.story }, persist: false, scroll: "none" });
141
+ await api.begin();
142
+ await click(api, element, "b");
143
+ expect(await api.clickLink(link(element, "Restart"))).toBe(false);
144
+ });
145
+
146
+ test("confirmDialog resolves false on Escape, and uses the given text", async () => {
147
+ const answer = confirmDialog({ message: "Delete it?", confirm: "Delete", cancel: "Keep", danger: true });
148
+ const dialog = confirmDialogElement()!;
149
+ expect(dialog.getAttribute("role")).toBe("alertdialog");
150
+ expect([...dialog.querySelectorAll("button")].map(b => b.textContent)).toEqual(["Keep", "Delete"]);
151
+ expect(dialog.querySelector("[data-answer=yes]")!.classList.contains("squiffy-confirm-danger")).toBe(true);
152
+ expect(document.activeElement).toBe(dialog.querySelector("[data-answer=yes]"));
153
+ dialog.dispatchEvent(new window.Event("cancel", { cancelable: true }));
154
+ expect(await answer).toBe(false);
155
+ expect(confirmDialogElement()).toBeNull();
156
+ });
package/src/updater.ts CHANGED
@@ -26,18 +26,36 @@ export function updateStory(oldStory: Story,
26
26
  return outputElement.querySelectorAll(`[data-source='[[${safeQuerySelector(section)}]][${safeQuerySelector(passage)}]']`);
27
27
  }
28
28
 
29
+ // Links to the same passage are matched up in order, so that in an {{#each}}, the item's link
30
+ // that was clicked is the one that stays disabled (#448)
31
+ function passageLinksByName(element: Element) {
32
+ const byName = new Map<string, Element[]>();
33
+ for (const link of element.querySelectorAll("a.link-passage[data-passage]")) {
34
+ const name = link.getAttribute("data-passage")!;
35
+ if (!byName.has(name)) byName.set(name, []);
36
+ byName.get(name)!.push(link);
37
+ }
38
+ return byName;
39
+ }
40
+
29
41
  function updateElementTextPreservingDisabledPassageLinks(element: Element, text: string) {
30
- // Record which passage links are disabled
31
- const disabledPassages = Array.from(element
32
- .querySelectorAll("a.link-passage.disabled"))
33
- .map((el: Element) => el.getAttribute("data-passage"));
42
+ const oldLinks = passageLinksByName(element);
34
43
 
35
44
  element.innerHTML = text;
36
45
 
37
- // Re-disable links that were disabled before the update
38
- for (const passage of disabledPassages) {
39
- const link = element.querySelector(`a.link-passage[data-passage="${passage}"]`);
40
- if (link) disableLink(link);
46
+ // Re-disable links that were disabled before the update, keeping which click or
47
+ // {{deactivate}} disabled them, so going back enables the right ones
48
+ const newLinks = passageLinksByName(element);
49
+ for (const [name, links] of oldLinks) {
50
+ links.forEach((oldLink, i) => {
51
+ const link = newLinks.get(name)?.[i];
52
+ if (!link || !oldLink.classList.contains("disabled")) return;
53
+ disableLink(link);
54
+ for (const attr of ["data-clicked", "data-deactivated-by"]) {
55
+ const value = oldLink.getAttribute(attr);
56
+ if (value !== null) link.setAttribute(attr, value);
57
+ }
58
+ });
41
59
  }
42
60
  }
43
61
 
@@ -0,0 +1,60 @@
1
+ import { afterEach, beforeEach, expect, test, vi } from "vitest";
2
+ import globalJsdom from "global-jsdom";
3
+ import { fadeReplace } from "./utils.js";
4
+
5
+ let cleanup: () => void;
6
+
7
+ beforeEach(() => {
8
+ cleanup = globalJsdom("<!DOCTYPE html><html><body></body></html>");
9
+ vi.useFakeTimers();
10
+ });
11
+
12
+ afterEach(() => {
13
+ vi.useRealTimers();
14
+ cleanup();
15
+ });
16
+
17
+ const label = () => {
18
+ const element = document.createElement("span");
19
+ element.innerHTML = "Old, with <a class=\"squiffy-link\">a link</a>";
20
+ document.body.appendChild(element);
21
+ return element;
22
+ };
23
+
24
+ const transitionEnd = (target: Element) => target.dispatchEvent(new window.Event("transitionend", { bubbles: true }));
25
+
26
+ test("fadeReplace fades the text out, replaces it, and fades it in", async () => {
27
+ const element = label();
28
+ let done = false;
29
+ void fadeReplace(element, "New").then(() => { done = true; });
30
+ expect(element.classList.contains("fade-out")).toBe(true);
31
+
32
+ transitionEnd(element);
33
+ await vi.advanceTimersByTimeAsync(0);
34
+ expect(element.innerHTML).toBe("New");
35
+ expect(element.classList.contains("fade-in")).toBe(true);
36
+
37
+ transitionEnd(element);
38
+ await vi.advanceTimersByTimeAsync(0);
39
+ expect(done).toBe(true);
40
+ expect(element.className).toBe("");
41
+ });
42
+
43
+ test("fadeReplace isn't fooled by a transition ending inside the text, such as a link's colour", async () => {
44
+ const element = label();
45
+ void fadeReplace(element, "New");
46
+
47
+ transitionEnd(element.querySelector("a")!);
48
+ await vi.advanceTimersByTimeAsync(0);
49
+ expect(element.innerHTML).toContain("Old");
50
+ });
51
+
52
+ test("fadeReplace finishes even if the fades never run, so the section's links come back", async () => {
53
+ const element = label();
54
+ let done = false;
55
+ void fadeReplace(element, "New").then(() => { done = true; });
56
+
57
+ await vi.advanceTimersByTimeAsync(5000);
58
+ expect(element.innerHTML).toBe("New");
59
+ expect(done).toBe(true);
60
+ });