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/paths.ts ADDED
@@ -0,0 +1,155 @@
1
+ // Values inside objects and lists (#442). An attribute can hold an object, such as
2
+ // { hp: 10, name: "Ann" }, or a list, and a path names a value inside it:
3
+ //
4
+ // hero.hp the hp of the object in the attribute hero
5
+ // inventory.0.name the name of the first item in the list inventory
6
+ // inventory[0].name the same
7
+ // hero["max hp"] a name that isn't a plain word
8
+ //
9
+ // squiffy.get, squiffy.set, {{set}}, {{inc}}, {{live}} and the like take a path as text, with
10
+ // these rules. Setters (@set hero.hp = 10) can also use another attribute as an index,
11
+ // inventory[i].name, which runtime/src/squiffy.runtime.ts reads with readTarget.
12
+
13
+ // Names that would reach an object's prototype rather than a value in it
14
+ const forbidden = new Set(["__proto__", "prototype", "constructor"]);
15
+
16
+ export function checkSegment(segment: string) {
17
+ if (forbidden.has(segment)) {
18
+ throw new Error(`"${segment}" can't be used as a name inside an object`);
19
+ }
20
+ }
21
+
22
+ // The segments of a path, e.g. ["inventory", "0", "name"] for inventory[0].name. A name with no
23
+ // "." or "[" is a whole attribute name, and so is one that isn't a path at all, such as "a..b".
24
+ export function parsePath(name: string): string[] {
25
+ if (!name.includes(".") && !name.includes("[")) return [name];
26
+ const root = /^[^.[\]]+/.exec(name);
27
+ if (!root) return [name];
28
+ const segments: string[] = [root[0]];
29
+ let i = root[0].length;
30
+ while (i < name.length) {
31
+ if (name[i] === ".") {
32
+ // inventory.0.name, or Handlebars' inventory.[0].name
33
+ if (name[i + 1] === "[") {
34
+ i++;
35
+ continue;
36
+ }
37
+ const segment = /^[^.[\]]+/.exec(name.substring(i + 1));
38
+ if (!segment) return [name];
39
+ segments.push(segment[0]);
40
+ i += 1 + segment[0].length;
41
+ }
42
+ else if (name[i] === "[") {
43
+ const close = name.indexOf("]", i);
44
+ if (close === -1) return [name];
45
+ let segment = name.substring(i + 1, close).trim();
46
+ const quoted = /^(["'])(.*)\1$/.exec(segment);
47
+ if (quoted) segment = quoted[2];
48
+ segments.push(segment);
49
+ i = close + 1;
50
+ }
51
+ else {
52
+ return [name];
53
+ }
54
+ }
55
+ segments.forEach(checkSegment);
56
+ return segments;
57
+ }
58
+
59
+ const isContainer = (value: unknown): value is Record<string, unknown> =>
60
+ typeof value === "object" && value !== null;
61
+
62
+ // The value at a path inside a value, or null if there's nothing there
63
+ export function valueAt(value: unknown, segments: string[]): unknown {
64
+ for (const segment of segments) {
65
+ if (!isContainer(value) || !Object.prototype.hasOwnProperty.call(value, segment)) return null;
66
+ value = value[segment];
67
+ }
68
+ return value ?? null;
69
+ }
70
+
71
+ // A copy of root with the value at the path inside it changed. Objects that aren't there yet are
72
+ // made, so @set hero.hp = 10 works before hero has been set. Throws if the path goes through a
73
+ // value that isn't an object or a list, such as a number.
74
+ export function withValueAt(root: unknown, segments: string[], name: string, value: unknown): unknown {
75
+ const result = isContainer(root) ? structuredClone(root) : root === null || root === undefined ? {} : null;
76
+ if (result === null) {
77
+ throw new Error(`${name} isn't an object, so it has no ${segments[0]}`);
78
+ }
79
+ let container: Record<string, unknown> = result;
80
+ let path = name;
81
+ segments.forEach((segment, i) => {
82
+ checkSegment(segment);
83
+ if (i === segments.length - 1) {
84
+ container[segment] = value;
85
+ return;
86
+ }
87
+ path += "." + segment;
88
+ let next = Object.prototype.hasOwnProperty.call(container, segment) ? container[segment] : undefined;
89
+ if (next === undefined || next === null) {
90
+ next = {};
91
+ container[segment] = next;
92
+ }
93
+ if (!isContainer(next)) {
94
+ throw new Error(`${path} isn't an object, so it has no ${segments[i + 1]}`);
95
+ }
96
+ container = next;
97
+ });
98
+ return result;
99
+ }
100
+
101
+ // The target of a setter, e.g. hero.hp in hero.hp += 5 or inventory[i].name in
102
+ // inventory[i].name = "lamp": the attribute, then each name or index after it. An index is an
103
+ // expression, which the runtime works out when the setter runs.
104
+ export type TargetSegment = { name: string } | { index: string };
105
+
106
+ export interface Target {
107
+ attribute: string;
108
+ segments: TargetSegment[];
109
+ // Everything after the target, e.g. " += 5"
110
+ rest: string;
111
+ }
112
+
113
+ // Reads a setter's target from the start of a setter, or returns null if it doesn't start with an
114
+ // attribute name. Whitespace before it is skipped.
115
+ export function readTarget(text: string): Target | null {
116
+ const start = /^\s*(\w+)/.exec(text);
117
+ if (!start) return null;
118
+ const segments: TargetSegment[] = [];
119
+ let i = start[0].length;
120
+ for (;;) {
121
+ const name = /^\.(\w+)/.exec(text.substring(i));
122
+ if (name) {
123
+ segments.push({ name: name[1] });
124
+ i += name[0].length;
125
+ continue;
126
+ }
127
+ if (text[i] !== "[") break;
128
+ const close = findClose(text, i);
129
+ if (close === -1) return null;
130
+ segments.push({ index: text.substring(i + 1, close) });
131
+ i = close + 1;
132
+ }
133
+ return { attribute: start[1], segments, rest: text.substring(i) };
134
+ }
135
+
136
+ // The index of the "]" that closes the "[" at `open`, skipping quoted text and brackets inside it,
137
+ // or -1
138
+ function findClose(text: string, open: number): number {
139
+ let depth = 0;
140
+ let quote: string | null = null;
141
+ for (let i = open; i < text.length; i++) {
142
+ const c = text[i];
143
+ if (quote) {
144
+ if (c === "\\") i++;
145
+ else if (c === quote) quote = null;
146
+ }
147
+ else if (c === "\"" || c === "'") quote = c;
148
+ else if (c === "[" || c === "(" || c === "{") depth++;
149
+ else if (c === "]" || c === ")" || c === "}") {
150
+ depth--;
151
+ if (depth === 0) return c === "]" ? i : -1;
152
+ }
153
+ }
154
+ return -1;
155
+ }
@@ -0,0 +1,155 @@
1
+ import { expect, test, beforeEach, afterEach } from "vitest";
2
+ import globalJsdom from "global-jsdom";
3
+ import { init } from "./squiffy.runtime.js";
4
+ import { compile as squiffyCompile } from "squiffy-compiler";
5
+ import type { SquiffyInitOptions } from "./types.js";
6
+
7
+ // Persistent attributes (#539): squiffy.json's "persistent", attributes that belong to the player
8
+ // rather than the playthrough, such as the endings they've found
9
+
10
+ let cleanup: () => void;
11
+
12
+ beforeEach(() => {
13
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
14
+ });
15
+
16
+ afterEach(() => {
17
+ localStorage.clear();
18
+ cleanup();
19
+ });
20
+
21
+ const script = `[[start]]:
22
+ @set score = 1
23
+ Endings: {{#if endings}}{{length endings}}{{else}}none{{/if}}.
24
+ {{#if finished}}Welcome back.{{/if}}
25
+ [[Pebbles]](pebbles) [Forget]
26
+
27
+ [Forget]:
28
+ {{forget}}Forgotten.
29
+
30
+ [[pebbles]]:
31
+ @set endings.pebbles = true
32
+ @set finished
33
+ @set score = 2
34
+ The end.`;
35
+
36
+ const start = async (options: Partial<SquiffyInitOptions> = {}, persistent: string[] | undefined = ["endings", "finished"]) => {
37
+ const element = document.getElementById("squiffy")!;
38
+ element.innerHTML = "";
39
+ const result = await squiffyCompile({ script, persistent, expressions: true });
40
+ if (!result.success) throw new Error("Compile failed");
41
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
42
+ const api = await init({ element, story: { js: js as any, ...result.output.story }, persist: false, scroll: "none", ...options });
43
+ await api.begin();
44
+ return { api, element };
45
+ };
46
+
47
+ const link = (element: HTMLElement, text: string) =>
48
+ [...element.querySelectorAll<HTMLElement>("a.squiffy-link")].filter(l => l.textContent === text).pop()!;
49
+
50
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
51
+
52
+ const text = (element: HTMLElement) => element.textContent!.replace(/\s+/g, " ");
53
+
54
+ test("The story's output lists its persistent attributes", async () => {
55
+ const result = await squiffyCompile({ script, persistent: ["endings"] });
56
+ if (!result.success) throw new Error("Compile failed");
57
+ expect(result.output.story.persistent).toEqual(["endings"]);
58
+ expect(await result.getJs()).toContain("story.persistent = [\"endings\"];");
59
+ });
60
+
61
+ test("Persistent attributes are set and read like any other", async () => {
62
+ const { api, element } = await start();
63
+ expect(text(element)).toContain("Endings: none.");
64
+ await api.clickLink(link(element, "Pebbles"));
65
+ expect(api.get("endings")).toEqual({ pebbles: true });
66
+ expect(api.get("endings.pebbles")).toBe(true);
67
+ expect(api.get("finished")).toBe(true);
68
+ expect(api.getPersistent()).toEqual({ endings: { pebbles: true }, finished: true });
69
+ });
70
+
71
+ test("Restart, Back and saved games leave persistent attributes alone, and saves don't include them", async () => {
72
+ const { api, element } = await start();
73
+ const save = api.getSave();
74
+ await api.clickLink(link(element, "Pebbles"));
75
+ expect(api.getSave().state).not.toHaveProperty("endings");
76
+ expect(api.getSave().state).not.toHaveProperty("finished");
77
+
78
+ api.goBack();
79
+ expect(api.get("score")).toBe(1);
80
+ expect(api.get("endings")).toEqual({ pebbles: true });
81
+
82
+ await api.loadSave(save);
83
+ expect(api.get("finished")).toBe(true);
84
+
85
+ api.restart();
86
+ await settle();
87
+ expect(api.get("_section")).toBe("start");
88
+ expect(api.get("_visits")).toEqual({ start: 1 });
89
+ expect(api.get("finished")).toBe(true);
90
+ expect(text(element)).toContain("Endings: 1.");
91
+ expect(text(element)).toContain("Welcome back.");
92
+ });
93
+
94
+ test("A saved game from before an attribute was persistent doesn't change it", async () => {
95
+ const { api, element } = await start();
96
+ await api.clickLink(link(element, "Pebbles"));
97
+ const save = api.getSave();
98
+ save.state.finished = false;
99
+ await api.loadSave(save);
100
+ expect(api.get("finished")).toBe(true);
101
+ });
102
+
103
+ test("Without \"persistent\", attributes are part of the game as before", async () => {
104
+ const { api, element } = await start({}, []);
105
+ await api.clickLink(link(element, "Pebbles"));
106
+ expect(api.getSave().state).toHaveProperty("finished", true);
107
+ api.restart();
108
+ await settle();
109
+ expect(api.get("finished")).toBeNull();
110
+ expect(api.getPersistent()).toEqual({});
111
+ });
112
+
113
+ test("{{forget}} clears persistent attributes", async () => {
114
+ const { api, element } = await start({ persistent: { finished: true, endings: { pebbles: true } } });
115
+ expect(text(element)).toContain("Welcome back.");
116
+ const changes: string[] = [];
117
+ api.on("set", e => changes.push(e.attribute));
118
+ await api.clickLink(link(element, "Forget"));
119
+ expect(text(element)).toContain("Forgotten.");
120
+ expect(api.get("finished")).toBeNull();
121
+ expect(api.get("endings")).toBeNull();
122
+ expect(api.getPersistent()).toEqual({});
123
+ expect(changes).toEqual(expect.arrayContaining(["endings", "finished"]));
124
+ });
125
+
126
+ test("api.forget() clears the persistent attributes named, and only persistent ones", async () => {
127
+ const { api } = await start({ persistent: { finished: true, endings: { pebbles: true } } });
128
+ api.forget(["finished", "score"]);
129
+ expect(api.get("finished")).toBeNull();
130
+ expect(api.get("score")).toBe(1);
131
+ expect(api.get("endings")).toEqual({ pebbles: true });
132
+ });
133
+
134
+ test("Persistent attributes are kept for the story when persist is on", async () => {
135
+ const first = await start({ persist: true, storyId: "mystory" });
136
+ await first.api.clickLink(link(first.element, "Pebbles"));
137
+ first.api.dispose();
138
+ expect(JSON.parse(localStorage.getItem("squiffy-persistent:mystory")!)).toEqual({ endings: { pebbles: true }, finished: true });
139
+
140
+ // A new game, as after clearing the saved one
141
+ localStorage.removeItem("mystory-_output");
142
+ const { api, element } = await start({ persist: true, storyId: "mystory" });
143
+ expect(text(element)).toContain("Welcome back.");
144
+ expect(api.get("endings")).toEqual({ pebbles: true });
145
+
146
+ api.restart();
147
+ await settle();
148
+ expect(localStorage.getItem("squiffy-persistent:mystory")).not.toBeNull();
149
+ });
150
+
151
+ test("Starting values given to init() are used in place of the browser's", async () => {
152
+ localStorage.setItem("squiffy-persistent:mystory", JSON.stringify({ finished: true }));
153
+ const { api } = await start({ persist: true, storyId: "mystory", persistent: { endings: { rock: true } } });
154
+ expect(api.getPersistent()).toEqual({ endings: { rock: true } });
155
+ });
@@ -0,0 +1,128 @@
1
+ // Player settings (#452): options from squiffy.json's "settings" that the player can change at any
2
+ // time, such as text size or content warnings. The story reads them as settings.name. They're the
3
+ // player's, not the game's, so they aren't attributes: going back, restarting and loading a saved
4
+ // game leave them as they are. They're kept for the story in localStorage, like Mute.
5
+
6
+ import type { PlayerSetting, SettingValue } from "./types.js";
7
+
8
+ export class PlayerSettings {
9
+ // The values the player has changed, by name. A setting that isn't here has its default.
10
+ private values: Record<string, SettingValue> = {};
11
+
12
+ constructor(private getDefinitions: () => PlayerSetting[], private storageKey?: string) {
13
+ if (!storageKey) return;
14
+ try {
15
+ const saved = JSON.parse(localStorage.getItem(storageKey) ?? "{}");
16
+ if (saved && typeof saved == "object" && !Array.isArray(saved)) this.values = saved;
17
+ }
18
+ catch {
19
+ // Nothing saved, or storage that can't be read: every setting has its default
20
+ }
21
+ }
22
+
23
+ definitions() {
24
+ return this.getDefinitions().filter(setting => setting && typeof setting.name == "string");
25
+ }
26
+
27
+ private find(name: string) {
28
+ return this.definitions().find(setting => setting.name == name);
29
+ }
30
+
31
+ // Whether the story has any settings, which is when it reads settings.name as a setting
32
+ any() {
33
+ return this.definitions().length > 0;
34
+ }
35
+
36
+ get(name: string): SettingValue | null {
37
+ const setting = this.find(name);
38
+ if (!setting) return null;
39
+ const value = Object.prototype.hasOwnProperty.call(this.values, name) ? this.values[name] : undefined;
40
+ return value !== undefined && isValid(setting, value) ? value : defaultValue(setting);
41
+ }
42
+
43
+ // Every setting's value, by name: the "settings" the story reads
44
+ all(): Record<string, SettingValue> {
45
+ return Object.fromEntries(this.definitions().map(setting => [setting.name, this.get(setting.name)!]));
46
+ }
47
+
48
+ // Returns whether the value changed. One the setting can't have is ignored.
49
+ set(name: string, value: SettingValue): boolean {
50
+ const setting = this.find(name);
51
+ if (!setting) return false;
52
+ const coerced = coerce(setting, value);
53
+ if (coerced === null || coerced === this.get(name)) return false;
54
+ this.values[name] = coerced;
55
+ this.store();
56
+ return true;
57
+ }
58
+
59
+ reset() {
60
+ this.values = {};
61
+ this.store();
62
+ }
63
+
64
+ // The classes the settings put on the story's element, so the story's CSS can use them: a
65
+ // toggle's name while it's on (setting-warnings), and a list's or range's name and value
66
+ // (setting-textSize-Large)
67
+ classes(): string[] {
68
+ const classes: string[] = [];
69
+ for (const setting of this.definitions()) {
70
+ const value = this.get(setting.name);
71
+ if (setting.type == "toggle") {
72
+ if (value === true) classes.push(`setting-${setting.name}`);
73
+ }
74
+ else if (value !== null) {
75
+ classes.push(`setting-${setting.name}-${String(value).replace(/[^A-Za-z0-9_-]+/g, "-")}`);
76
+ }
77
+ }
78
+ return classes;
79
+ }
80
+
81
+ private store() {
82
+ if (!this.storageKey) return;
83
+ try {
84
+ if (Object.keys(this.values).length) localStorage.setItem(this.storageKey, JSON.stringify(this.values));
85
+ else localStorage.removeItem(this.storageKey);
86
+ }
87
+ catch {
88
+ // Storage that's full or turned off: the setting lasts until the page is closed
89
+ }
90
+ }
91
+ }
92
+
93
+ export function defaultValue(setting: PlayerSetting): SettingValue {
94
+ switch (setting.type) {
95
+ case "toggle": return setting.default ?? false;
96
+ case "list": return setting.default ?? setting.options[0]?.value ?? "";
97
+ case "range": return setting.default ?? setting.min;
98
+ }
99
+ }
100
+
101
+ function isValid(setting: PlayerSetting, value: unknown) {
102
+ return coerce(setting, value) === value;
103
+ }
104
+
105
+ // The value as the setting has it, e.g. "true" for a toggle is true and "3" for a range is 3, or
106
+ // null if the setting can't have it. A range's value is kept within min and max, on a step.
107
+ function coerce(setting: PlayerSetting, value: unknown): SettingValue | null {
108
+ switch (setting.type) {
109
+ case "toggle":
110
+ if (typeof value == "boolean") return value;
111
+ if (value === "true") return true;
112
+ if (value === "false") return false;
113
+ return null;
114
+ case "list": {
115
+ const text = typeof value == "string" || typeof value == "number" || typeof value == "boolean" ? String(value) : null;
116
+ return text !== null && setting.options.some(option => option.value === text) ? text : null;
117
+ }
118
+ case "range": {
119
+ const n = typeof value == "number" ? value : typeof value == "string" && value.trim() ? Number(value) : NaN;
120
+ if (!Number.isFinite(n)) return null;
121
+ const clamped = Math.min(setting.max, Math.max(setting.min, n));
122
+ if (!setting.step) return clamped;
123
+ const stepped = setting.min + Math.round((clamped - setting.min) / setting.step) * setting.step;
124
+ // Without the rounding errors of adding up steps such as 0.1
125
+ return Number(Math.min(setting.max, stepped).toFixed(10));
126
+ }
127
+ }
128
+ }
@@ -13,6 +13,7 @@ export class PluginManager {
13
13
  getSectionText: (name: string) => string | null;
14
14
  getPassageText: (name: string) => string | null;
15
15
  processText: (text: string, inline: boolean) => string;
16
+ resolveAssetsInHtml: (html: string) => string;
16
17
  addTransition: (fn: () => Promise<void>) => void;
17
18
  emitter: Emitter<SquiffyEventMap>;
18
19
  plugins: SquiffyPlugin[] = [];
@@ -27,7 +28,8 @@ export class PluginManager {
27
28
  processText: (text: string, inline: boolean) => string,
28
29
  addTransition: (fn: () => Promise<void>) => void,
29
30
  animation: Animation,
30
- emitter: Emitter<SquiffyEventMap>) {
31
+ emitter: Emitter<SquiffyEventMap>,
32
+ resolveAssetsInHtml: (html: string) => string) {
31
33
  this.outputElement = outputElement;
32
34
  this.textProcessor = textProcessor;
33
35
  this.state = state;
@@ -38,6 +40,7 @@ export class PluginManager {
38
40
  this.addTransition = addTransition;
39
41
  this.animation = animation;
40
42
  this.emitter = emitter;
43
+ this.resolveAssetsInHtml = resolveAssetsInHtml;
41
44
  }
42
45
 
43
46
  add(plugin: SquiffyPlugin) {
@@ -54,7 +57,9 @@ export class PluginManager {
54
57
  getSectionText: this.getSectionText,
55
58
  getPassageText: this.getPassageText,
56
59
  processText: this.processText,
60
+ resolveAssetsInHtml: this.resolveAssetsInHtml,
57
61
  addTransition: this.addTransition,
62
+ written: (el) => this.onWrite(el),
58
63
  animation: this.animation,
59
64
  on: (e, h) => this.emitter.on(e, h),
60
65
  off: (e, h) => this.emitter.off(e, h),
@@ -1,6 +1,10 @@
1
1
  import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
2
2
  import Handlebars from "handlebars";
3
3
  import * as marked from "marked";
4
+ import { parseDelay } from "../utils.js";
5
+
6
+ // The parameters to the built-in animations that are times
7
+ const timeParameters = ["start", "interval", "duration", "fadeDuration"];
4
8
 
5
9
  export function AnimatePlugin(): SquiffyPlugin {
6
10
  let squiffy: PluginHost;
@@ -32,12 +36,13 @@ export function AnimatePlugin(): SquiffyPlugin {
32
36
  if (!params.content) {
33
37
  continue;
34
38
  }
39
+ // The content is stored unrendered in data-content, so asset URLs in it haven't been
40
+ // resolved yet. On load it's rendered again, so it picks up the current resolver.
35
41
  const isBlock = params.content.includes("\n\n");
36
- if (isBlock) {
37
- el.innerHTML = marked.parse(params.content, { async: false }).trim();
38
- } else {
39
- el.innerHTML = marked.parseInline(params.content, { async: false }).trim();
40
- }
42
+ const html = isBlock
43
+ ? marked.parse(params.content, { async: false })
44
+ : marked.parseInline(params.content, { async: false });
45
+ el.innerHTML = squiffy.resolveAssetsInHtml(html.trim());
41
46
 
42
47
  if (!params.name) {
43
48
  continue;
@@ -78,9 +83,13 @@ export function AnimatePlugin(): SquiffyPlugin {
78
83
  if (oldLink.classList.contains("disabled")) {
79
84
  link.classList.add("disabled");
80
85
  }
81
- const tabindex = oldLink.getAttribute("tabindex");
82
- if (tabindex !== null) {
83
- link.setAttribute("tabindex", tabindex);
86
+ // tabindex, and which click or {{deactivate}} disabled it, so going back
87
+ // enables the right links
88
+ for (const attr of ["tabindex", "data-clicked", "data-deactivated-by"]) {
89
+ const value = oldLink.getAttribute(attr);
90
+ if (value !== null) {
91
+ link.setAttribute(attr, value);
92
+ }
84
93
  }
85
94
  });
86
95
  };
@@ -121,12 +130,28 @@ export function AnimatePlugin(): SquiffyPlugin {
121
130
  squiffy = sq;
122
131
 
123
132
  squiffy.registerHelper("animate", function(this: any, name: string, options) {
124
- const content = options.fn(this);
133
+ // A block that's only another helper, such as {{#label}}, gives that helper's SafeString
134
+ const content = String(options.fn(this));
125
135
  const dataset: Record<string, any> = {
126
136
  name,
127
137
  content,
128
138
  ...options.hash,
129
139
  };
140
+ // Times can be written like "1.5s" as well as in milliseconds (#451)
141
+ for (const key of timeParameters) {
142
+ if (dataset[key] === undefined) continue;
143
+ const delay = parseDelay(dataset[key]);
144
+ if (delay !== null) {
145
+ dataset[key] = delay;
146
+ }
147
+ else {
148
+ // Something that isn't a time, such as an attribute that was never set,
149
+ // would stop the animation from ever finishing, and its links would never
150
+ // work, so it's left out
151
+ console.warn(`Squiffy: {{#animate}}'s ${key} isn't a time: ${JSON.stringify(dataset[key])}`);
152
+ delete dataset[key];
153
+ }
154
+ }
130
155
 
131
156
  const attrs = Object.entries(dataset)
132
157
  .map(([key, value]) =>
@@ -2,6 +2,7 @@ import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
2
2
  import Handlebars from "handlebars";
3
3
  import { fadeReplace } from "../utils.js";
4
4
  import { SquiffyEventMap } from "../events.js";
5
+ import { parsePath } from "../paths.js";
5
6
 
6
7
  export function LivePlugin(): SquiffyPlugin {
7
8
  let squiffy: PluginHost;
@@ -29,8 +30,18 @@ export function LivePlugin(): SquiffyPlugin {
29
30
 
30
31
  const onSet = async (e: SquiffyEventMap["set"]) => {
31
32
  const promises: Promise<void>[] = [];
32
- const selector = `.squiffy-live[data-attribute="${CSS.escape(e.attribute)}"]`;
33
- for (const el of squiffy.outputElement.querySelectorAll<HTMLElement>(selector)) {
33
+ // The "set" event names the attribute that changed, so {{live "hero.hp"}} is
34
+ // updated when hero is set (#442)
35
+ // Text from a section or passage is only shown again in the current section: in
36
+ // one the player has left, or a screen that's been cleared (kept, hidden, for
37
+ // going back), it would run its helpers again
38
+ const sections = [...squiffy.outputElement.querySelectorAll<HTMLElement>(".squiffy-output-section")]
39
+ .filter(el => !el.closest(".squiffy-clear-stack"));
40
+ const current = sections[sections.length - 1];
41
+ const elements = [...squiffy.outputElement.querySelectorAll<HTMLElement>(".squiffy-live[data-attribute]")]
42
+ .filter(el => parsePath(el.dataset.attribute!)[0] === e.attribute)
43
+ .filter(el => !(el.dataset.section || el.dataset.passage) || el.closest(".squiffy-output-section") === current);
44
+ for (const el of elements) {
34
45
  const oldContent = el.innerHTML;
35
46
  let newContent = "";
36
47
  if (el.dataset.section) {
@@ -44,10 +55,12 @@ export function LivePlugin(): SquiffyPlugin {
44
55
  newContent = squiffy.processText(passageText, true);
45
56
  }
46
57
  } else {
47
- newContent = e.value;
58
+ newContent = el.dataset.attribute == e.attribute ? e.value : squiffy.get(el.dataset.attribute!);
48
59
  }
49
- if (oldContent !== newContent) {
50
- promises.push(fadeReplace(el, newContent));
60
+ // A value that's a number is the same as the text on screen, e.g. when another
61
+ // part of the same attribute changes, such as another setting
62
+ if (oldContent !== String(newContent)) {
63
+ promises.push(fadeReplace(el, newContent, squiffy.written));
51
64
  }
52
65
  }
53
66
  await Promise.all(promises);