squiffy-runtime 7.0.0-beta.7 → 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 (56) hide show
  1. package/dist/confirmDialog.d.ts +8 -0
  2. package/dist/events.d.ts +10 -0
  3. package/dist/every.d.ts +12 -0
  4. package/dist/every.test.d.ts +1 -0
  5. package/dist/playerSettings.d.ts +17 -0
  6. package/dist/preview-html.js +1 -1
  7. package/dist/settings.test.d.ts +1 -0
  8. package/dist/settingsDialog.d.ts +17 -0
  9. package/dist/squiffy.page.css +4 -1
  10. package/dist/squiffy.preview.html +673 -83
  11. package/dist/squiffy.runtime.css +531 -1
  12. package/dist/squiffy.runtime.d.ts +5 -1
  13. package/dist/squiffy.runtime.global.js +106 -85
  14. package/dist/squiffy.runtime.global.js.map +1 -1
  15. package/dist/squiffy.runtime.js +4743 -4157
  16. package/dist/squiffy.runtime.js.map +1 -1
  17. package/dist/state.d.ts +1 -0
  18. package/dist/style.test.d.ts +1 -0
  19. package/dist/textProcessor.d.ts +8 -0
  20. package/dist/transitions.test.d.ts +1 -0
  21. package/dist/types.d.ts +43 -0
  22. package/dist/uiLinks.test.d.ts +1 -0
  23. package/dist/utils.d.ts +1 -0
  24. package/dist/utils.test.d.ts +1 -0
  25. package/package.json +3 -3
  26. package/src/animation.test.ts +44 -0
  27. package/src/animation.ts +7 -3
  28. package/src/confirmDialog.ts +66 -0
  29. package/src/events.ts +17 -0
  30. package/src/every.test.ts +25 -0
  31. package/src/every.ts +94 -0
  32. package/src/panels.test.ts +24 -0
  33. package/src/playerSettings.ts +128 -0
  34. package/src/plugins/animate.ts +9 -0
  35. package/src/plugins/live.ts +3 -1
  36. package/src/plugins/plugins.test.ts +17 -0
  37. package/src/preview.test.ts +53 -3
  38. package/src/preview.ts +60 -1
  39. package/src/settings.test.ts +233 -0
  40. package/src/settingsDialog.ts +160 -0
  41. package/src/squiffy.page.css +4 -1
  42. package/src/squiffy.runtime.css +531 -1
  43. package/src/squiffy.runtime.test.ts +613 -16
  44. package/src/squiffy.runtime.ts +372 -19
  45. package/src/state.ts +16 -1
  46. package/src/style.test.ts +89 -0
  47. package/src/textProcessor.ts +141 -6
  48. package/src/transitions.test.ts +302 -0
  49. package/src/types.ts +56 -0
  50. package/src/uiLinks.test.ts +156 -0
  51. package/src/utils.test.ts +60 -0
  52. package/src/utils.ts +44 -14
  53. package/dist/infixExpressions.d.ts +0 -7
  54. package/src/infixExpressions.test.ts +0 -516
  55. package/src/infixExpressions.ts +0 -672
  56. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
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 {
@@ -57,6 +63,17 @@ export interface SquiffyApi {
57
63
  // Whether the story plays music or sounds: it names some files, or has played one. The
58
64
  // "sound" event says when something plays.
59
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;
60
77
  // Stops the story's music and sounds for good, when it's being replaced, e.g. in the editor's preview
61
78
  dispose: () => void;
62
79
 
@@ -109,6 +126,8 @@ export interface Story {
109
126
  expressions?: boolean;
110
127
  // squiffy.json's "panels": passages shown beside the story, or in a dialog from a button
111
128
  panels?: Panel[];
129
+ // squiffy.json's "settings": options the player can change, which the story reads as settings.name
130
+ settings?: PlayerSetting[];
112
131
  sections: Record<string, Section>;
113
132
  }
114
133
 
@@ -128,6 +147,31 @@ export interface Panel {
128
147
  icon?: PanelIcon;
129
148
  }
130
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
+
131
175
  export interface Section {
132
176
  text?: string;
133
177
  clear?: boolean;
@@ -137,6 +181,12 @@ export interface Section {
137
181
  sounds?: string[];
138
182
  // @class (#449): classes on the story's element while this is the current section
139
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;
140
190
  attributes?: string[],
141
191
  jsIndex?: number;
142
192
  passages?: Record<string, Passage>;
@@ -152,6 +202,12 @@ export interface Passage {
152
202
  sounds?: string[];
153
203
  // @class (#449): classes added to the section's when this passage is shown
154
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;
155
211
  // @repeat: its links stay clickable, and clicking one doesn't count towards @1, @2... and @last (#104)
156
212
  repeat?: boolean;
157
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
+ });
@@ -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
+ });
package/src/utils.ts CHANGED
@@ -1,17 +1,47 @@
1
- export function fadeReplace(element: HTMLElement, text: string): Promise<void> {
2
- return new Promise((resolve) => {
3
- element.addEventListener("transitionend", function () {
4
- element.innerHTML = text;
1
+ // {{#replace}}: fades the label's text out, replaces it, and fades it in. The section's links wait
2
+ // for it, so it always finishes: see transitionEnd.
3
+ export async function fadeReplace(element: HTMLElement, text: string): Promise<void> {
4
+ const fadedOut = transitionEnd(element);
5
+ element.classList.add("fade-out");
6
+ await fadedOut;
5
7
 
6
- element.addEventListener("transitionend", function () {
7
- element.classList.remove("fade-in");
8
- resolve();
9
- }, { once: true });
8
+ element.innerHTML = text;
9
+ const fadedIn = transitionEnd(element);
10
+ element.classList.remove("fade-out");
11
+ element.classList.add("fade-in");
12
+ await fadedIn;
13
+ element.classList.remove("fade-in");
14
+ }
10
15
 
11
- element.classList.remove("fade-out");
12
- element.classList.add("fade-in");
13
- }, { once: true });
14
-
15
- element.classList.add("fade-out");
16
+ // When the element's own transition ends. Not one inside it, whose transitionend bubbles up to it,
17
+ // such as the colour of a link that's just been clicked. And not more than a moment longer than
18
+ // the fades take (200ms), in case it doesn't run at all, e.g. if the element isn't shown, or its
19
+ // classes change back within a frame.
20
+ function transitionEnd(element: HTMLElement, timeout = 1000): Promise<void> {
21
+ return new Promise(resolve => {
22
+ const done = () => {
23
+ element.removeEventListener("transitionend", ended);
24
+ element.removeEventListener("transitioncancel", ended);
25
+ clearTimeout(timer);
26
+ resolve();
27
+ };
28
+ const ended = (event: Event) => {
29
+ if (event.target === element) done();
30
+ };
31
+ element.addEventListener("transitionend", ended);
32
+ element.addEventListener("transitioncancel", ended);
33
+ const timer = setTimeout(done, timeout);
16
34
  });
17
- }
35
+ }
36
+
37
+ // A delay in milliseconds (#451): a number, or text with a number of seconds or milliseconds in
38
+ // it, as in CSS and Twine, e.g. "3s", "1.5s" or "500ms" ("500" is milliseconds too). Returns null
39
+ // if it isn't one, or is negative.
40
+ export function parseDelay(value: unknown): number | null {
41
+ if (typeof value == "number") return Number.isFinite(value) && value >= 0 ? value : null;
42
+ if (typeof value != "string") return null;
43
+ const match = /^\s*(\d+(?:\.\d+)?|\.\d+)\s*(ms|s)?\s*$/i.exec(value);
44
+ if (!match) return null;
45
+ const n = Number(match[1]);
46
+ return match[2]?.toLowerCase() == "s" ? n * 1000 : n;
47
+ }
@@ -1,7 +0,0 @@
1
- export declare function rewriteInfixCondition(condition: string): string | null;
2
- export declare function rewriteInfixArguments(args: string): string | null;
3
- export declare function rewriteInfixEmbed(args: string): string | null;
4
- export declare function rewriteDisplayExpression(expression: string): string;
5
- export declare function rewriteValueExpression(expression: string): string;
6
- export declare function splitSetters(setters: string): string[];
7
- export declare function rewriteInfixExpressions(text: string): string;