squiffy-runtime 6.0.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 (117) hide show
  1. package/dist/assets.d.ts +3 -0
  2. package/dist/assets.test.d.ts +1 -0
  3. package/dist/classes.test.d.ts +1 -0
  4. package/dist/confirmDialog.d.ts +8 -0
  5. package/dist/events.d.ts +16 -0
  6. package/dist/every.d.ts +12 -0
  7. package/dist/every.test.d.ts +1 -0
  8. package/dist/helpers.test.d.ts +1 -0
  9. package/dist/numbers.d.ts +3 -0
  10. package/dist/panels.d.ts +14 -0
  11. package/dist/panels.test.d.ts +1 -0
  12. package/dist/paths.d.ts +15 -0
  13. package/dist/paths.test.d.ts +1 -0
  14. package/dist/persistent.test.d.ts +1 -0
  15. package/dist/playerSettings.d.ts +17 -0
  16. package/dist/pluginManager.d.ts +2 -1
  17. package/dist/preview-host.d.ts +33 -0
  18. package/dist/preview-host.js +125 -0
  19. package/dist/preview-host.js.map +7 -0
  20. package/dist/preview-host.test.d.ts +1 -0
  21. package/dist/preview-html.d.ts +2 -0
  22. package/dist/preview-html.js +2 -0
  23. package/dist/preview-protocol.d.ts +69 -0
  24. package/dist/preview.d.ts +15 -0
  25. package/dist/preview.main.d.ts +1 -0
  26. package/dist/preview.test.d.ts +1 -0
  27. package/dist/saveSlots.d.ts +16 -0
  28. package/dist/saves.test.d.ts +1 -0
  29. package/dist/savesDialog.d.ts +43 -0
  30. package/dist/savesDialog.test.d.ts +1 -0
  31. package/dist/scripts.test.d.ts +1 -0
  32. package/dist/settings.test.d.ts +1 -0
  33. package/dist/settingsDialog.d.ts +17 -0
  34. package/dist/skill.test.d.ts +1 -0
  35. package/dist/sound.d.ts +35 -0
  36. package/dist/sound.test.d.ts +1 -0
  37. package/dist/squiffy.page.css +155 -0
  38. package/dist/squiffy.preview.html +1631 -0
  39. package/dist/squiffy.runtime.css +1123 -20
  40. package/dist/squiffy.runtime.d.ts +13 -1
  41. package/dist/squiffy.runtime.global.js +146 -76
  42. package/dist/squiffy.runtime.global.js.map +1 -1
  43. package/dist/squiffy.runtime.js +7105 -4681
  44. package/dist/squiffy.runtime.js.map +1 -1
  45. package/dist/state.d.ts +17 -0
  46. package/dist/storyLists.d.ts +4 -0
  47. package/dist/storyLists.test.d.ts +1 -0
  48. package/dist/style.test.d.ts +1 -0
  49. package/dist/textProcessor.d.ts +27 -0
  50. package/dist/transitions.test.d.ts +1 -0
  51. package/dist/types.d.ts +137 -1
  52. package/dist/types.plugins.d.ts +2 -0
  53. package/dist/uiLinks.test.d.ts +1 -0
  54. package/dist/utils.d.ts +2 -1
  55. package/dist/utils.test.d.ts +1 -0
  56. package/package.json +25 -11
  57. package/src/__snapshots__/squiffy.runtime.test.ts.snap +22 -22
  58. package/src/animation.test.ts +44 -0
  59. package/src/animation.ts +9 -5
  60. package/src/assets.test.ts +225 -0
  61. package/src/assets.ts +92 -0
  62. package/src/classes.test.ts +201 -0
  63. package/src/confirmDialog.ts +66 -0
  64. package/src/events.ts +20 -0
  65. package/src/every.test.ts +25 -0
  66. package/src/every.ts +94 -0
  67. package/src/helpers.test.ts +34 -0
  68. package/src/numbers.ts +21 -0
  69. package/src/panels.test.ts +225 -0
  70. package/src/panels.ts +187 -0
  71. package/src/paths.test.ts +66 -0
  72. package/src/paths.ts +155 -0
  73. package/src/persistent.test.ts +155 -0
  74. package/src/playerSettings.ts +128 -0
  75. package/src/pluginManager.ts +6 -1
  76. package/src/plugins/animate.ts +34 -9
  77. package/src/plugins/live.ts +18 -5
  78. package/src/plugins/plugins.test.ts +93 -6
  79. package/src/plugins/replaceLabel.ts +7 -3
  80. package/src/preview-host.test.ts +171 -0
  81. package/src/preview-host.ts +190 -0
  82. package/src/preview-protocol.ts +79 -0
  83. package/src/preview.main.ts +34 -0
  84. package/src/preview.test.ts +367 -0
  85. package/src/preview.ts +331 -0
  86. package/src/saveSlots.ts +159 -0
  87. package/src/saves.test.ts +199 -0
  88. package/src/savesDialog.test.ts +290 -0
  89. package/src/savesDialog.ts +499 -0
  90. package/src/scripts.test.ts +130 -0
  91. package/src/settings.test.ts +233 -0
  92. package/src/settingsDialog.ts +160 -0
  93. package/src/skill.test.ts +67 -0
  94. package/src/sound.test.ts +273 -0
  95. package/src/sound.ts +207 -0
  96. package/src/squiffy.page.css +155 -0
  97. package/src/squiffy.runtime.css +1123 -20
  98. package/src/squiffy.runtime.test.ts +2806 -44
  99. package/src/squiffy.runtime.ts +1130 -64
  100. package/src/state.ts +172 -11
  101. package/src/storyLists.test.ts +134 -0
  102. package/src/storyLists.ts +57 -0
  103. package/src/style.test.ts +89 -0
  104. package/src/textProcessor.ts +739 -58
  105. package/src/transitions.test.ts +343 -0
  106. package/src/types.plugins.ts +7 -0
  107. package/src/types.ts +226 -2
  108. package/src/uiLinks.test.ts +156 -0
  109. package/src/updater.ts +26 -8
  110. package/src/utils.test.ts +60 -0
  111. package/src/utils.ts +46 -14
  112. package/vite.config.ts +3 -4
  113. package/vite.preview.config.ts +83 -0
  114. package/dist/infixExpressions.d.ts +0 -2
  115. package/src/infixExpressions.test.ts +0 -187
  116. package/src/infixExpressions.ts +0 -323
  117. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
package/src/animation.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { animate, stagger, text } from "animejs";
1
+ import { animate, splitText, stagger } from "animejs";
2
2
 
3
3
  export type AnimationHandler = (el: HTMLElement, params: Record<string, any>, onComplete: () => void, loop: boolean) => void;
4
4
 
@@ -50,7 +50,10 @@ export class Animation {
50
50
 
51
51
  constructor() {
52
52
  this.registerAnimation("typewriter", function(el, params, onComplete, loop) {
53
- const { chars } = text.split(el, { words: false, chars: true });
53
+ // Each character in a span, inside a span for its word, so a line only breaks
54
+ // between words: without the words, it could break anywhere, e.g. at the
55
+ // apostrophe in "let's"
56
+ const { chars } = splitText(el, { words: true, chars: true });
54
57
 
55
58
  const fadeDuration = params.fadeDuration || 100; // ms fade-in per character
56
59
  const interval = params.interval || 100; // ms between each character appearing
@@ -66,7 +69,7 @@ export class Animation {
66
69
  }, { initiallyHidden: true });
67
70
 
68
71
  this.registerAnimation("toast", function(el, params, onComplete, loop) {
69
- const { words } = text.split(el, { words: true, chars: false });
72
+ const { words } = splitText(el, { words: true, chars: false });
70
73
 
71
74
  const fadeDuration = params.fadeDuration || 100; // ms fade-in per word
72
75
  const interval = params.interval || 200; // ms between each word appearing
@@ -106,9 +109,10 @@ export class Animation {
106
109
  let chars: HTMLElement[] | null = null;
107
110
 
108
111
  if (style === "wave") {
109
- // Wave style needs JS animation - split into chars and animate opacity
112
+ // Wave style needs JS animation - split into chars and animate opacity. Words too,
113
+ // so a line only breaks between words, as with typewriter.
110
114
  el.classList.add("squiffy-continue-wave");
111
- const split = text.split(el, { words: false, chars: true });
115
+ const split = splitText(el, { words: true, chars: true });
112
116
  chars = split.chars as HTMLElement[];
113
117
 
114
118
  waveAnimation = animate(chars, {
@@ -0,0 +1,225 @@
1
+ import { expect, test, beforeEach, afterEach, 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 { SquiffyInitOptions } from "./types.js";
6
+
7
+ // anime.js captures the global document when it's imported, which is before each test
8
+ // sets up jsdom, so it can't run here. Replace it with a stub that completes immediately.
9
+ vi.mock("animejs", () => ({
10
+ animate: (_targets: unknown, params: { onComplete?: () => void }) => {
11
+ setTimeout(() => params.onComplete?.());
12
+ },
13
+ stagger: () => 0,
14
+ splitText: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
15
+ }));
16
+
17
+ const html = `
18
+ <!DOCTYPE html>
19
+ <html>
20
+ <body>
21
+ <div id="squiffy"></div>
22
+ </body>
23
+ </html>
24
+ `;
25
+
26
+ const compile = async (script: string) => {
27
+ const compileResult = await squiffyCompile({ script });
28
+ if (!compileResult.success) {
29
+ throw new Error("Compile failed");
30
+ }
31
+ const js = compileResult.output.js.map(jsLines => new Function("squiffy", "get", "set", jsLines.join("\n")));
32
+ return { js: js as any, ...compileResult.output.story };
33
+ };
34
+
35
+ const resolveAssetUrl = (path: string) => `blob:test/${path}`;
36
+
37
+ const initScript = async (script: string, options: Partial<SquiffyInitOptions> = {}) => {
38
+ const element = document.getElementById("squiffy")!;
39
+ const squiffyApi = await init({
40
+ element,
41
+ story: await compile(script),
42
+ persist: false,
43
+ ...options,
44
+ });
45
+ await squiffyApi.begin();
46
+ return { squiffyApi, element };
47
+ };
48
+
49
+ let cleanup: () => void;
50
+
51
+ beforeEach(() => {
52
+ cleanup = globalJsdom(html, { url: "http://localhost/" });
53
+ });
54
+
55
+ afterEach(() => {
56
+ localStorage.clear();
57
+ cleanup();
58
+ });
59
+
60
+ test("Asset paths are unchanged without resolveAssetUrl", async () => {
61
+ const { element } = await initScript(`![A cat](cat.png)
62
+
63
+ <img src="dog.png">`);
64
+ const images = element.querySelectorAll("img");
65
+ expect(images[0].getAttribute("src")).toBe("cat.png");
66
+ expect(images[1].getAttribute("src")).toBe("dog.png");
67
+ expect(element.innerHTML).not.toContain("data-squiffy-asset");
68
+ });
69
+
70
+ test("resolveAssetUrl is applied to img src from Markdown and HTML", async () => {
71
+ const { element } = await initScript(`![A cat](cat.png)
72
+
73
+ <img src="images/dog.png">`, { resolveAssetUrl });
74
+ const images = element.querySelectorAll("img");
75
+ expect(images[0].getAttribute("src")).toBe("blob:test/cat.png");
76
+ expect(images[0].getAttribute("alt")).toBe("A cat");
77
+ expect(images[1].getAttribute("src")).toBe("blob:test/images/dog.png");
78
+ });
79
+
80
+ test("resolveAssetUrl is applied to audio, video, source, poster and srcset", async () => {
81
+ const { element } = await initScript(`<audio src="music.mp3"></audio>
82
+ <video poster="poster.jpg"><source src="clip.webm" type="video/webm"></video>
83
+ <img srcset="small.png 1x, large.png 2x, https://example.com/x.png 3x">`, { resolveAssetUrl });
84
+ expect(element.querySelector("audio")!.getAttribute("src")).toBe("blob:test/music.mp3");
85
+ expect(element.querySelector("video")!.getAttribute("poster")).toBe("blob:test/poster.jpg");
86
+ expect(element.querySelector("source")!.getAttribute("src")).toBe("blob:test/clip.webm");
87
+ expect(element.querySelector("img")!.getAttribute("srcset"))
88
+ .toBe("blob:test/small.png 1x, blob:test/large.png 2x, https://example.com/x.png 3x");
89
+ });
90
+
91
+ test("resolveAssetUrl is applied to url() in inline styles", async () => {
92
+ const { element } = await initScript("<div id=\"bg\" style=\"background-image: url('bg.png'); color: red\"></div>", { resolveAssetUrl });
93
+ const style = element.querySelector("#bg")!.getAttribute("style");
94
+ expect(style).toBe("background-image: url(\"blob:test/bg.png\"); color: red");
95
+ });
96
+
97
+ test("Absolute URLs are not passed to resolveAssetUrl", async () => {
98
+ const paths: string[] = [];
99
+ const { element } = await initScript(`<img src="http://example.com/a.png">
100
+ <img src="https://example.com/b.png">
101
+ <img src="data:image/png;base64,AAAA">
102
+ <img src="blob:http://localhost/1234">
103
+ <img src="//example.com/c.png">
104
+ <img src="local.png">`, {
105
+ resolveAssetUrl: path => {
106
+ paths.push(path);
107
+ return resolveAssetUrl(path);
108
+ }
109
+ });
110
+ expect(paths).toEqual(["local.png"]);
111
+ const srcs = [...element.querySelectorAll("img")].map(img => img.getAttribute("src"));
112
+ expect(srcs).toEqual([
113
+ "http://example.com/a.png",
114
+ "https://example.com/b.png",
115
+ "data:image/png;base64,AAAA",
116
+ "blob:http://localhost/1234",
117
+ "//example.com/c.png",
118
+ "blob:test/local.png",
119
+ ]);
120
+ });
121
+
122
+ test("Percent-encoded paths are decoded before being passed to resolveAssetUrl", async () => {
123
+ const { element } = await initScript("<img src=\"my%20cat.png\">", { resolveAssetUrl });
124
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/my cat.png");
125
+ });
126
+
127
+ test("Links are not passed to resolveAssetUrl", async () => {
128
+ const { element } = await initScript(`<a href="page.html">link</a> [[next]]
129
+
130
+ [[next]]:
131
+ Next`, { resolveAssetUrl });
132
+ expect(element.querySelector("a[href]")!.getAttribute("href")).toBe("page.html");
133
+ });
134
+
135
+ test("resolveAssetUrl is applied to passages", async () => {
136
+ const { squiffyApi, element } = await initScript(`Click [here].
137
+
138
+ [here]:
139
+ ![A cat](cat.png)`, { resolveAssetUrl });
140
+ const link = [...element.querySelectorAll<HTMLElement>("a.link-passage")].find(a => a.textContent === "here")!;
141
+ await squiffyApi.clickLink(link);
142
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/cat.png");
143
+ });
144
+
145
+ test("resolveAssetUrl is applied when the story is updated", async () => {
146
+ const { squiffyApi, element } = await initScript("Hello", { resolveAssetUrl });
147
+ squiffyApi.update(await compile("Hello ![A cat](cat.png)"));
148
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/cat.png");
149
+ });
150
+
151
+ test("Saved output is resolved again when it's loaded", async () => {
152
+ const script = "![A cat](cat.png)";
153
+ const story = await compile(script);
154
+
155
+ // First run, e.g. in a previous editor session, where cat.png was a different blob URL
156
+ let element = document.getElementById("squiffy")!;
157
+ let api = await init({ element, story, persist: true, storyId: "assets-test", resolveAssetUrl: p => `blob:old/${p}` });
158
+ await api.begin();
159
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:old/cat.png");
160
+
161
+ // Load the saved output into a fresh element
162
+ element.innerHTML = "";
163
+ element = document.getElementById("squiffy")!;
164
+ api = await init({ element, story, persist: true, storyId: "assets-test", resolveAssetUrl: p => `blob:new/${p}` });
165
+ await api.begin();
166
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:new/cat.png");
167
+ });
168
+
169
+ test("Asset paths in animate blocks are unchanged without resolveAssetUrl", async () => {
170
+ const { element } = await initScript("{{#animate \"typewriter\"}}![A cat](cat.png){{/animate}}");
171
+ await vi.waitFor(() => expect(element.querySelector(".squiffy-animate")).toBeNull());
172
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("cat.png");
173
+ expect(element.innerHTML).not.toContain("data-squiffy-asset");
174
+ });
175
+
176
+ test("resolveAssetUrl is applied to inline animate content", async () => {
177
+ const { element } = await initScript("{{#animate \"typewriter\"}}![A cat](cat.png){{/animate}}", { resolveAssetUrl });
178
+ await vi.waitFor(() => expect(element.querySelector(".squiffy-animate")).toBeNull());
179
+ // The content is restored after the animation completes, so check it's still resolved
180
+ expect(element.querySelector("img")!.getAttribute("src")).toBe("blob:test/cat.png");
181
+ });
182
+
183
+ test("resolveAssetUrl is applied to block animate content", async () => {
184
+ const { element } = await initScript(`{{#animate "typewriter"}}
185
+ ![A cat](cat.png)
186
+
187
+ <img src="dog.png">
188
+ {{/animate}}`, { resolveAssetUrl });
189
+ await vi.waitFor(() => expect(element.querySelector(".squiffy-animate")).toBeNull());
190
+ const srcs = [...element.querySelectorAll("img")].map(img => img.getAttribute("src"));
191
+ expect(srcs).toEqual(["blob:test/cat.png", "blob:test/dog.png"]);
192
+ });
193
+
194
+ test("resolveAssetUrl is applied to animate content waiting for a link trigger", async () => {
195
+ const { element } = await initScript(`{{#animate "typewriter" trigger="link"}}![A cat](cat.png) [next]{{/animate}}
196
+
197
+ [next]:
198
+ Next`, { resolveAssetUrl });
199
+ expect(element.querySelector(".squiffy-animate img")!.getAttribute("src")).toBe("blob:test/cat.png");
200
+ });
201
+
202
+ test("Saved animate content is resolved again when it's loaded", async () => {
203
+ const script = `{{#animate "typewriter" trigger="link"}}![A cat](cat.png) [next]{{/animate}}
204
+
205
+ {{#animate "typewriter"}}![A dog](dog.png){{/animate}}
206
+
207
+ [next]:
208
+ Next`;
209
+ const story = await compile(script);
210
+ const srcs = (element: HTMLElement) => [...element.querySelectorAll("img")].map(img => img.getAttribute("src"));
211
+
212
+ let element = document.getElementById("squiffy")!;
213
+ let api = await init({ element, story, persist: true, storyId: "assets-animate-test", resolveAssetUrl: p => `blob:old/${p}` });
214
+ await api.begin();
215
+ await vi.waitFor(() => expect(element.querySelectorAll(".squiffy-animate").length).toBe(1));
216
+ expect(srcs(element)).toEqual(["blob:old/cat.png", "blob:old/dog.png"]);
217
+
218
+ // Load the saved output: the pending (link-triggered) animation is rendered again from
219
+ // its stored content, and the completed one is re-resolved with the rest of the output.
220
+ element.innerHTML = "";
221
+ element = document.getElementById("squiffy")!;
222
+ api = await init({ element, story, persist: true, storyId: "assets-animate-test", resolveAssetUrl: p => `blob:new/${p}` });
223
+ await api.begin();
224
+ expect(srcs(element)).toEqual(["blob:new/cat.png", "blob:new/dog.png"]);
225
+ });
package/src/assets.ts ADDED
@@ -0,0 +1,92 @@
1
+ // Support for the resolveAssetUrl init option, which maps asset paths in story output (e.g. "cat.png")
2
+ // to the URLs they should load from (e.g. a blob: URL in the editor preview, or a data: URI in a
3
+ // single-file export).
4
+ //
5
+ // We rewrite the HTML string before it's inserted into the page, so the browser never requests the
6
+ // unresolved path. The original value is kept in a data-squiffy-asset-* attribute, so that output
7
+ // saved to localStorage (which will contain resolved URLs that may no longer be valid, e.g. blob: URLs)
8
+ // can be resolved again when it's restored.
9
+
10
+ export type AssetUrlResolver = (path: string) => string;
11
+
12
+ // Attributes that contain a single URL.
13
+ const urlAttributes = ["src", "poster"];
14
+
15
+ const originalPrefix = "data-squiffy-asset-";
16
+
17
+ const selector = [...urlAttributes, "srcset", "style"].map(a => `[${a}]`).join(",");
18
+
19
+ // Anything with a scheme (http:, https:, data:, blob:, mailto: etc.), protocol-relative URLs,
20
+ // and fragment-only references are left alone.
21
+ export const isAbsolute = (url: string) => /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//") || url.startsWith("#");
22
+
23
+ const resolveUrl = (url: string, resolve: AssetUrlResolver): string => {
24
+ const trimmed = url.trim();
25
+ if (!trimmed || isAbsolute(trimmed)) return url;
26
+ let path = trimmed;
27
+ try {
28
+ // Markdown (and authors) may percent-encode paths, e.g. "my%20cat.png". The resolver
29
+ // works with file paths, so give it "my cat.png".
30
+ path = decodeURI(trimmed);
31
+ } catch {
32
+ // Not valid percent-encoding - pass it through as it is
33
+ }
34
+ return resolve(path);
35
+ };
36
+
37
+ // srcset is a comma-separated list of "url [descriptor]" candidates.
38
+ const resolveSrcset = (srcset: string, resolve: AssetUrlResolver) =>
39
+ srcset.split(",").map(candidate => {
40
+ const match = candidate.match(/^(\s*)(\S+)(.*)$/s);
41
+ if (!match) return candidate;
42
+ return match[1] + resolveUrl(match[2], resolve) + match[3];
43
+ }).join(",");
44
+
45
+ // CSS url(...) references in inline style attributes.
46
+ const resolveCssUrls = (css: string, resolve: AssetUrlResolver) =>
47
+ css.replace(/url\(\s*(['"]?)(.*?)\1\s*\)/gi, (whole, _quote: string, url: string) => {
48
+ const resolved = resolveUrl(url, resolve);
49
+ if (resolved === url) return whole;
50
+ return `url("${resolved.replace(/["\\\n]/g, c => "\\" + (c === "\n" ? "a " : c))}")`;
51
+ });
52
+
53
+ const resolveAttribute = (el: Element, attribute: string, resolve: AssetUrlResolver) => {
54
+ const originalAttribute = originalPrefix + attribute;
55
+ const original = el.getAttribute(originalAttribute) ?? el.getAttribute(attribute);
56
+ if (original === null) return;
57
+
58
+ let resolved: string;
59
+ if (attribute === "srcset") {
60
+ resolved = resolveSrcset(original, resolve);
61
+ } else if (attribute === "style") {
62
+ resolved = resolveCssUrls(original, resolve);
63
+ } else {
64
+ resolved = resolveUrl(original, resolve);
65
+ }
66
+
67
+ if (resolved === original) {
68
+ el.removeAttribute(originalAttribute);
69
+ } else {
70
+ el.setAttribute(originalAttribute, original);
71
+ }
72
+ el.setAttribute(attribute, resolved);
73
+ };
74
+
75
+ // Returns a function that rewrites asset URLs in an HTML string. With no resolver, HTML is returned unchanged.
76
+ export const createAssetHtmlResolver = (resolve: AssetUrlResolver | undefined) => (html: string): string => {
77
+ if (!resolve) return html;
78
+ // Quick check to avoid parsing HTML that can't contain anything to resolve.
79
+ if (!/\b(src|srcset|poster|style)\s*=/i.test(html)) return html;
80
+
81
+ // A <template>'s content is inert, so parsing into it doesn't start loading any images.
82
+ const template = document.createElement("template");
83
+ template.innerHTML = html;
84
+ for (const el of template.content.querySelectorAll(selector)) {
85
+ for (const attribute of [...urlAttributes, "srcset", "style"]) {
86
+ if (el.hasAttribute(attribute)) {
87
+ resolveAttribute(el, attribute, resolve);
88
+ }
89
+ }
90
+ }
91
+ return template.innerHTML;
92
+ };
@@ -0,0 +1,201 @@
1
+ // Classes on the story's element (#449): @class for the current section, and {{addclass}},
2
+ // {{removeclass}}, {{toggleclass}} and {{hasclass}}
3
+ import { expect, test, beforeEach, afterEach, vi } from "vitest";
4
+ import globalJsdom from "global-jsdom";
5
+ import { init } from "./squiffy.runtime.js";
6
+ import { compile as squiffyCompile } from "squiffy-compiler";
7
+
8
+ let cleanup: () => void;
9
+
10
+ beforeEach(() => {
11
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\" class=\"mine\"></div></body></html>");
12
+ vi.useFakeTimers();
13
+ });
14
+
15
+ afterEach(() => {
16
+ vi.useRealTimers();
17
+ localStorage.clear();
18
+ cleanup();
19
+ });
20
+
21
+ const start = async (script: string, options: { persist?: boolean } = {}) => {
22
+ const result = await squiffyCompile({ script });
23
+ if (!result.success) throw new Error("Compile failed");
24
+ const story = {
25
+ ...result.output.story,
26
+ js: result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n"))) as any,
27
+ };
28
+ const element = document.getElementById("squiffy")!;
29
+ const api = await init({ element, story, persist: options.persist ?? false, storyId: "test", scroll: "none" });
30
+ await api.begin();
31
+ return { api, element };
32
+ };
33
+
34
+ const click = async (element: HTMLElement, text: string) => {
35
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
36
+ .find(l => l.textContent == text && !l.classList.contains("disabled"));
37
+ if (!link) throw new Error(`No link "${text}"`);
38
+ link.click();
39
+ await vi.runAllTimersAsync();
40
+ };
41
+
42
+ // The classes on the story's element, other than the page's own
43
+ const classes = (element: HTMLElement) => [...element.classList].filter(c => c != "mine").sort();
44
+
45
+ const story = `
46
+ [[forest]]:
47
+ @class night forest
48
+ The forest. [[Go to the cave]](cave), [look up]
49
+
50
+ [look up]:
51
+ @class stars
52
+ The stars are out.
53
+
54
+ [[cave]]:
55
+ @class dark
56
+ The cave. [[Leave]](outside)
57
+
58
+ [[outside]]:
59
+ Outside.
60
+ `;
61
+
62
+ test("@class puts classes on the story's element while the section is the current one", async () => {
63
+ const { element } = await start(story);
64
+ expect(classes(element)).toEqual(["forest", "night"]);
65
+
66
+ await click(element, "Go to the cave");
67
+ expect(classes(element)).toEqual(["dark"]);
68
+
69
+ await click(element, "Leave");
70
+ expect(classes(element)).toEqual([]);
71
+ // The page's own class is left alone
72
+ expect(element.classList.contains("mine")).toBe(true);
73
+ });
74
+
75
+ test("@class in a passage adds to the section's classes, until the section changes", async () => {
76
+ const { element } = await start(story);
77
+ await click(element, "look up");
78
+ expect(classes(element)).toEqual(["forest", "night", "stars"]);
79
+
80
+ await click(element, "Go to the cave");
81
+ expect(classes(element)).toEqual(["dark"]);
82
+ });
83
+
84
+ test("Going back puts the classes back", async () => {
85
+ const { api, element } = await start(story);
86
+ await click(element, "look up");
87
+ await click(element, "Go to the cave");
88
+
89
+ api.goBack();
90
+ await vi.runAllTimersAsync();
91
+ expect(classes(element)).toEqual(["forest", "night", "stars"]);
92
+
93
+ api.goBack();
94
+ await vi.runAllTimersAsync();
95
+ expect(classes(element)).toEqual(["forest", "night"]);
96
+ });
97
+
98
+ test("Loading a saved game puts its classes on", async () => {
99
+ const { api, element } = await start(story);
100
+ const save = api.getSave();
101
+ await click(element, "Go to the cave");
102
+ expect(classes(element)).toEqual(["dark"]);
103
+
104
+ await api.loadSave(save);
105
+ await vi.runAllTimersAsync();
106
+ expect(classes(element)).toEqual(["forest", "night"]);
107
+ });
108
+
109
+ test("A story carried on from where it was left has its classes", async () => {
110
+ const first = await start(story, { persist: true });
111
+ await click(first.element, "Go to the cave");
112
+ first.api.dispose();
113
+ expect(classes(first.element)).toEqual([]);
114
+ first.element.innerHTML = "";
115
+
116
+ const second = await start(story, { persist: true });
117
+ expect(classes(second.element)).toEqual(["dark"]);
118
+ });
119
+
120
+ test("The master section's @class is on every section", async () => {
121
+ const { element } = await start(`
122
+ [[]]:
123
+ @class story
124
+
125
+ [[a]]:
126
+ @class one
127
+ [[b]]
128
+
129
+ [[b]]:
130
+ B
131
+ `);
132
+ expect(classes(element)).toEqual(["one", "story"]);
133
+ await click(element, "b");
134
+ expect(classes(element)).toEqual(["story"]);
135
+ });
136
+
137
+ test("{{addclass}} and {{removeclass}} change classes that stay until they're removed", async () => {
138
+ const { api, element } = await start(`
139
+ [[a]]:
140
+ {{addclass "dark" "rain"}}[[b]]
141
+
142
+ [[b]]:
143
+ @class cave
144
+ [[c]]
145
+
146
+ [[c]]:
147
+ {{removeclass "dark"}}{{#if (hasclass "rain")}}Still raining.{{/if}}
148
+ `);
149
+ expect(classes(element)).toEqual(["dark", "rain"]);
150
+ await click(element, "b");
151
+ expect(classes(element)).toEqual(["cave", "dark", "rain"]);
152
+ await click(element, "c");
153
+ expect(classes(element)).toEqual(["rain"]);
154
+ expect(element.textContent).toContain("Still raining.");
155
+
156
+ api.goBack();
157
+ await vi.runAllTimersAsync();
158
+ expect(classes(element)).toEqual(["cave", "dark", "rain"]);
159
+ });
160
+
161
+ test("{{toggleclass}} turns a class on and off, and takes several separated by spaces", async () => {
162
+ const { element } = await start(`
163
+ [[a]]:
164
+ {{toggleclass "big loud"}}[[b]]
165
+
166
+ [[b]]:
167
+ {{toggleclass "loud"}}B
168
+ `);
169
+ expect(classes(element)).toEqual(["big", "loud"]);
170
+ await click(element, "b");
171
+ expect(classes(element)).toEqual(["big"]);
172
+ });
173
+
174
+ test("{{hasclass}} checks classes from @class and {{addclass}}", async () => {
175
+ const { element } = await start(`
176
+ [[a]]:
177
+ @class night
178
+ {{#if (hasclass "night")}}It's night.{{/if}}
179
+ {{#if (hasclass "day")}}It's day.{{/if}}
180
+ {{#if (hasclass "night day")}}Both.{{/if}}
181
+ `);
182
+ expect(element.textContent).toContain("It's night.");
183
+ expect(element.textContent).not.toContain("It's day.");
184
+ expect(element.textContent).not.toContain("Both.");
185
+ });
186
+
187
+ test("Restarting takes the classes off", async () => {
188
+ const { api, element } = await start(`
189
+ [[a]]:
190
+ {{addclass "dark"}}[[b]]
191
+
192
+ [[b]]:
193
+ @class cave
194
+ B
195
+ `);
196
+ await click(element, "b");
197
+ expect(classes(element)).toEqual(["cave", "dark"]);
198
+ api.restart();
199
+ await vi.runAllTimersAsync();
200
+ expect(classes(element)).toEqual(["dark"]);
201
+ });
@@ -0,0 +1,66 @@
1
+ // A question for the player, such as "Are you sure you want to restart?", in a dialog that looks
2
+ // like the rest of the page, in place of the browser's confirm()
3
+
4
+ export interface ConfirmDialogOptions {
5
+ message: string;
6
+ // The button that goes ahead, e.g. "Restart"
7
+ confirm: string;
8
+ // "Cancel" by default
9
+ cancel?: string;
10
+ // Whether going ahead loses something, which colours its button as a warning
11
+ danger?: boolean;
12
+ // Where the dialog goes in the page: the end of the body by default
13
+ container?: HTMLElement;
14
+ }
15
+
16
+ let dialogCount = 0;
17
+
18
+ // Shows the question, and resolves true if the player goes ahead. Escape, Cancel and clicking
19
+ // outside the dialog all resolve false. The dialog is taken off the page once it's answered.
20
+ export function confirmDialog(options: ConfirmDialogOptions): Promise<boolean> {
21
+ const id = `squiffy-confirm-${++dialogCount}`;
22
+ const dialog = document.createElement("dialog");
23
+ dialog.className = "squiffy-confirm";
24
+ dialog.setAttribute("role", "alertdialog");
25
+ dialog.setAttribute("aria-labelledby", `${id}-message`);
26
+ dialog.innerHTML = `
27
+ <p id="${id}-message"></p>
28
+ <div class="squiffy-confirm-buttons">
29
+ <button type="button" class="squiffy-confirm-button" data-answer="no"></button>
30
+ <button type="button" class="squiffy-confirm-button ${options.danger ? "squiffy-confirm-danger" : "squiffy-confirm-primary"}" data-answer="yes"></button>
31
+ </div>`;
32
+ dialog.querySelector("p")!.textContent = options.message;
33
+ const no = dialog.querySelector<HTMLButtonElement>("[data-answer=no]")!;
34
+ const yes = dialog.querySelector<HTMLButtonElement>("[data-answer=yes]")!;
35
+ no.textContent = options.cancel ?? "Cancel";
36
+ yes.textContent = options.confirm;
37
+ (options.container ?? document.body).appendChild(dialog);
38
+
39
+ return new Promise<boolean>(resolve => {
40
+ let answered = false;
41
+ const finish = (answer: boolean) => {
42
+ if (answered) return;
43
+ answered = true;
44
+ if (dialog.open) dialog.close();
45
+ dialog.remove();
46
+ resolve(answer);
47
+ };
48
+ no.addEventListener("click", () => finish(false));
49
+ yes.addEventListener("click", () => finish(true));
50
+ // Escape
51
+ dialog.addEventListener("cancel", e => {
52
+ e.preventDefault();
53
+ finish(false);
54
+ });
55
+ dialog.addEventListener("close", () => finish(false));
56
+ // A click on the backdrop is on the dialog itself, outside its content
57
+ dialog.addEventListener("click", e => {
58
+ if (e.target !== dialog) return;
59
+ const rect = dialog.getBoundingClientRect();
60
+ const inside = e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom;
61
+ if (!inside) finish(false);
62
+ });
63
+ dialog.showModal();
64
+ yes.focus();
65
+ });
66
+ }
package/src/events.ts CHANGED
@@ -4,6 +4,21 @@ export type SquiffyEventMap = {
4
4
  linkClick: { linkType: string }; // a story link was clicked
5
5
  set: { attribute: string, value: any }; // an attribute was set
6
6
  canGoBackChanged: { canGoBack: boolean }; // whether the "back" button should be enabled
7
+ navigated: { section: string, passage?: string }; // a section or passage was shown, or Back went to one
8
+ sound: Record<string, never>; // music or a sound started playing (#444), even if it's muted
9
+ storyUpdated: Record<string, never>; // update() changed the story, e.g. after an edit in the editor
10
+ // A {{restart}} link was clicked (#452). With a handler, the page does the restarting, asking
11
+ // first if confirm is true. Without one, the runtime asks in its own dialog.
12
+ restartRequested: { confirm: boolean };
13
+ // A {{saves}} link was clicked (#452). With a handler, the page opens its Saved games dialog.
14
+ // Without one, the runtime opens one of its own.
15
+ savesRequested: Record<string, never>;
16
+ // A {{settings}} link was clicked (#452). With a handler, the page opens its Settings dialog.
17
+ // Without one, the runtime opens one of its own.
18
+ settingsRequested: Record<string, never>;
19
+ // The player changed a setting (#452). Putting them back to their defaults raises it for each
20
+ // one that changes.
21
+ settingChanged: { name: string, value: unknown };
7
22
  };
8
23
 
9
24
  export type SquiffyEventHandler<E extends keyof SquiffyEventMap> =
@@ -30,6 +45,11 @@ export class Emitter<Events extends Record<string, any>> {
30
45
  return off;
31
46
  }
32
47
 
48
+ // Whether anything is listening for the event
49
+ has<E extends keyof Events>(event: E) {
50
+ return (this.listeners.get(event)?.size ?? 0) > 0;
51
+ }
52
+
33
53
  emit<E extends keyof Events>(event: E, payload: Events[E]) {
34
54
  this.listeners.get(event)?.forEach(h => {
35
55
  try { (h as any)(payload); } catch (err) {