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
@@ -11,9 +11,7 @@ vi.mock("animejs", () => ({
11
11
  setTimeout(() => params.onComplete?.());
12
12
  },
13
13
  stagger: () => 0,
14
- text: {
15
- split: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
16
- },
14
+ splitText: (el: HTMLElement) => ({ chars: [el], words: [el], lines: [el] }),
17
15
  }));
18
16
 
19
17
  const html = `
package/src/assets.ts CHANGED
@@ -18,7 +18,7 @@ const selector = [...urlAttributes, "srcset", "style"].map(a => `[${a}]`).join("
18
18
 
19
19
  // Anything with a scheme (http:, https:, data:, blob:, mailto: etc.), protocol-relative URLs,
20
20
  // and fragment-only references are left alone.
21
- const isAbsolute = (url: string) => /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//") || url.startsWith("#");
21
+ export const isAbsolute = (url: string) => /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith("//") || url.startsWith("#");
22
22
 
23
23
  const resolveUrl = (url: string, resolve: AssetUrlResolver): string => {
24
24
  const trimmed = url.trim();
@@ -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
@@ -5,6 +5,20 @@ export type SquiffyEventMap = {
5
5
  set: { attribute: string, value: any }; // an attribute was set
6
6
  canGoBackChanged: { canGoBack: boolean }; // whether the "back" button should be enabled
7
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 };
8
22
  };
9
23
 
10
24
  export type SquiffyEventHandler<E extends keyof SquiffyEventMap> =
@@ -31,6 +45,11 @@ export class Emitter<Events extends Record<string, any>> {
31
45
  return off;
32
46
  }
33
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
+
34
53
  emit<E extends keyof Events>(event: E, payload: Events[E]) {
35
54
  this.listeners.get(event)?.forEach(h => {
36
55
  try { (h as any)(payload); } catch (err) {
@@ -0,0 +1,25 @@
1
+ import { expect, test } from "vitest";
2
+ import { captureEveryBodies } from "./every.js";
3
+
4
+ const body = (text: string) => `__body="${encodeURIComponent(text)}"`;
5
+
6
+ test("captureEveryBodies copies each {{#every}}'s text into it (#451)", () => {
7
+ expect(captureEveryBodies("A {{#every 1000}}Tick {{n}}{{/every}} B"))
8
+ .toBe(`A {{#every 1000 ${body("Tick {{n}}")}}}Tick {{n}}{{/every}} B`);
9
+ expect(captureEveryBodies("{{~#every 1000 times=2~}}x{{~/every~}}"))
10
+ .toBe(`{{~#every 1000 times=2 ${body("x")}~}}x{{~/every~}}`);
11
+ expect(captureEveryBodies("{{#every \"1s\"}}\"quoted}}\"{{/every}}"))
12
+ .toBe(`{{#every "1s" ${body("\"quoted}}\"")}}}"quoted}}"{{/every}}`);
13
+ });
14
+
15
+ test("captureEveryBodies handles {{#every}} inside {{#every}}", () => {
16
+ const inner = "{{#every 500}}in{{/every}}";
17
+ expect(captureEveryBodies(`{{#every 1000}}out ${inner}{{/every}}`))
18
+ .toBe(`{{#every 1000 ${body(`out ${inner}`)}}}out {{#every 500 ${body("in")}}}in{{/every}}{{/every}}`);
19
+ });
20
+
21
+ test("captureEveryBodies leaves other text alone", () => {
22
+ for (const text of ["no tags", "{{#if a}}x{{/if}}", "\\{{#every 1000}}x{{/every}}", "{{#everything}}x{{/everything}}"]) {
23
+ expect(captureEveryBodies(text)).toBe(text);
24
+ }
25
+ });
package/src/every.ts ADDED
@@ -0,0 +1,94 @@
1
+ // {{#every 1000}}...{{/every}} (#451): text shown again and again, every so often, while the
2
+ // player is in the section. Each time, its text is worked out again and replaces what it showed
3
+ // before (or, with append=true, is added after it), until a {{stop}} inside it, times= ticks, or
4
+ // the player moving on to another section.
5
+ //
6
+ // The text is kept in the page, so a saved game, going back and the editor's preview can start
7
+ // it again: before the text is compiled, captureEveryBodies() copies each {{#every}}'s text into a
8
+ // hidden __body= parameter, which the helper puts in the element it writes.
9
+
10
+ import { findTagEnd } from "squiffy-compiler/infix-expressions";
11
+
12
+ const everyTag = /(\\*)\{\{~?\s*(?:(#every)(?=[\s}~])|(\/every)\s*~?\}\})/g;
13
+
14
+ // Adds __body="..." to each {{#every}}, with the text between it and its {{/every}}, encoded so
15
+ // that it can't end the string or the tag
16
+ export function captureEveryBodies(text: string): string {
17
+ if (!text.includes("#every")) return text;
18
+ const insertions: { at: number; text: string }[] = [];
19
+ const open: { tagEnd: number; bodyStart: number }[] = [];
20
+ everyTag.lastIndex = 0;
21
+ let match: RegExpExecArray | null;
22
+ while ((match = everyTag.exec(text)) !== null) {
23
+ // An odd number of backslashes escapes the mustache
24
+ if (match[1].length % 2 === 1) continue;
25
+ if (match[2]) {
26
+ const tagEnd = findTagEnd(text, match.index + match[0].length);
27
+ if (tagEnd === -1) break;
28
+ const bodyStart = text.indexOf("}}", tagEnd) + 2;
29
+ // With no delay, it's left for the helper to report, as __body= would be the delay
30
+ const hasDelay = text.slice(match.index + match[0].length, tagEnd).trim() !== "";
31
+ open.push({ tagEnd: hasDelay ? tagEnd : -1, bodyStart });
32
+ everyTag.lastIndex = bodyStart;
33
+ } else {
34
+ const start = open.pop();
35
+ if (!start) continue;
36
+ if (start.tagEnd === -1) continue;
37
+ const body = text.slice(start.bodyStart, match.index + match[1].length);
38
+ insertions.push({ at: start.tagEnd, text: ` __body="${encodeURIComponent(body)}"` });
39
+ }
40
+ }
41
+ insertions.sort((a, b) => b.at - a.at);
42
+ for (const { at, text: insert } of insertions) {
43
+ text = text.slice(0, at) + insert + text.slice(at);
44
+ }
45
+ return text;
46
+ }
47
+
48
+ export const everySelector = ".squiffy-every:not([data-every-stopped])";
49
+
50
+ // A tick's timer function is marked, so that the CLI's --play can tell a story that's only
51
+ // repeating some text from one that's still moving on by itself
52
+ export const EVERY_TICK = "squiffyEvery";
53
+
54
+ // The timers for the {{#every}}s in the current section. sync() starts a timer for each one that
55
+ // hasn't got one, and stops those that aren't there any more.
56
+ export class EveryTimers {
57
+ private timers = new Map<HTMLElement, ReturnType<typeof setTimeout>>();
58
+
59
+ // tick: shows the text again. It returns false if it can't yet, e.g. while a transition is
60
+ // running, so it's tried again a little later.
61
+ constructor(private getRoot: () => HTMLElement | undefined, private tick: (el: HTMLElement) => boolean) {}
62
+
63
+ sync() {
64
+ const root = this.getRoot();
65
+ const active = new Set(root?.isConnected ? root.querySelectorAll<HTMLElement>(everySelector) : []);
66
+ for (const [el, timer] of this.timers) {
67
+ if (!active.has(el)) {
68
+ clearTimeout(timer);
69
+ this.timers.delete(el);
70
+ }
71
+ }
72
+ for (const el of active) {
73
+ if (!this.timers.has(el)) this.schedule(el, Number(el.getAttribute("data-every-delay")) || 0);
74
+ }
75
+ }
76
+
77
+ stopAll() {
78
+ for (const timer of this.timers.values()) clearTimeout(timer);
79
+ this.timers.clear();
80
+ }
81
+
82
+ private schedule(el: HTMLElement, ms: number) {
83
+ const fn = () => {
84
+ this.timers.delete(el);
85
+ if (!this.tick(el)) {
86
+ this.schedule(el, 50);
87
+ return;
88
+ }
89
+ this.sync();
90
+ };
91
+ (fn as unknown as Record<string, boolean>)[EVERY_TICK] = true;
92
+ this.timers.set(el, setTimeout(fn, ms));
93
+ }
94
+ }
@@ -0,0 +1,34 @@
1
+ // The compiler's list of the runtime's helpers, which its unknown-name warning relies on
2
+ // (squiffy/unknown-name, #526), must have every helper the runtime registers, and no others.
3
+ import { expect, test, vi, beforeEach, afterEach } from "vitest";
4
+ import globalJsdom from "global-jsdom";
5
+ import Handlebars from "handlebars";
6
+ import { init } from "./squiffy.runtime.js";
7
+ import { compile, BUILT_IN_HELPERS } from "squiffy-compiler";
8
+
9
+ let cleanup: () => void;
10
+
11
+ beforeEach(() => {
12
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
13
+ });
14
+
15
+ afterEach(() => {
16
+ vi.restoreAllMocks();
17
+ cleanup();
18
+ });
19
+
20
+ test("the compiler knows every helper the runtime registers", async () => {
21
+ const create = vi.spyOn(Handlebars, "create");
22
+ const result = await compile({ script: "Hello" });
23
+ if (!result.success) throw new Error("Compile failed");
24
+ const story = { ...result.output.story, js: [] } as any;
25
+ await init({ element: document.getElementById("squiffy")!, story, persist: false, storyId: "test", scroll: "none" });
26
+ const registered = new Set<string>();
27
+ for (const created of create.mock.results) {
28
+ for (const name of Object.keys((created.value as typeof Handlebars).helpers)) {
29
+ // The runtime's internal helpers, and Handlebars' for a missing helper
30
+ if (!name.startsWith("__") && name != "helperMissing" && name != "blockHelperMissing") registered.add(name);
31
+ }
32
+ }
33
+ expect([...BUILT_IN_HELPERS].sort(), "Update BUILT_IN_HELPERS in compiler/src/helpers.ts").toEqual([...registered].sort());
34
+ });
package/src/numbers.ts ADDED
@@ -0,0 +1,21 @@
1
+ // The rules for turning attribute values into numbers, shared by everything that does arithmetic:
2
+ // the maths helpers ({{add}}, {{sub}} etc., which infix arithmetic is rewritten to), {{inc}} and
3
+ // {{dec}}, and @set's +=, -=, *= and /= (which @inc and @dec compile to).
4
+ //
5
+ // Attributes often hold numbers as text: values from user input, {{set "x" "5"}}, or JavaScript.
6
+ // So text that's a number counts as that number. A blank value (unset, null, false or "") counts
7
+ // as 0, so a counter can start from nothing. Anything else is an error, rather than giving NaN or
8
+ // joining text together.
9
+
10
+ export const isBlank = (v: unknown) => v === undefined || v === null || v === false || v === "";
11
+
12
+ export const isNumeric = (v: unknown) =>
13
+ typeof v === "number" || isBlank(v) || (typeof v === "string" && v.trim() !== "" && !isNaN(Number(v)));
14
+
15
+ // "what" names the operation in the error, e.g. "inc" gives: "inc" needs numbers, but was given "abc"
16
+ export function toNumber(what: string, v: unknown): number {
17
+ if (!isNumeric(v)) {
18
+ throw new Error(`"${what}" needs numbers, but was given ${JSON.stringify(v)}`);
19
+ }
20
+ return isBlank(v) ? 0 : Number(v);
21
+ }