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
@@ -0,0 +1,225 @@
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, PANEL_ICONS as COMPILER_PANEL_ICONS } from "squiffy-compiler";
5
+ import { createPanels } from "./panels.js";
6
+ import { PANEL_ICONS, type Panel, type SquiffyApi } from "./types.js";
7
+
8
+ let cleanup: () => void;
9
+
10
+ beforeEach(() => {
11
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"container\"><div id=\"header\"><button id=\"restart\"></button></div><div id=\"squiffy\"></div></div></body></html>");
12
+ // jsdom has no showModal()
13
+ window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", ""); };
14
+ window.HTMLDialogElement.prototype.close = function () {
15
+ this.removeAttribute("open");
16
+ this.dispatchEvent(new window.Event("close"));
17
+ };
18
+ });
19
+
20
+ afterEach(() => {
21
+ cleanup();
22
+ });
23
+
24
+ const script = `[[]]:
25
+
26
+ [status]:
27
+ Gold: {{gold}}
28
+
29
+ [lamp]:
30
+ {{#if lamp}}You have a lamp.{{/if}}
31
+
32
+ [inventory]:
33
+ {{#if lamp}}You have a lamp.{{/if}}{{set "gold" 1000}}{{goto "end"}} Go to [[end]] or [here](b).
34
+
35
+ [[start]]:
36
+ @set gold = 5
37
+ Welcome. [Get the lamp](b, lamp, gold += 10) or go to [[end]].
38
+
39
+ [b]:
40
+ You have it.
41
+
42
+ [[end]]:
43
+ The end.`;
44
+
45
+ const start = async () => {
46
+ const element = document.getElementById("squiffy")!;
47
+ const result = await squiffyCompile({ script });
48
+ if (!result.success) throw new Error("Compile failed");
49
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
50
+ const api = await init({ element, story: { js: js as any, ...result.output.story }, persist: false });
51
+ await api.begin();
52
+ return { api, element };
53
+ };
54
+
55
+ const click = async (api: SquiffyApi, element: HTMLElement, text: string) => {
56
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
57
+ .filter(l => l.textContent === text && !l.classList.contains("disabled")).pop()!;
58
+ expect(await api.clickLink(link)).toBe(true);
59
+ };
60
+
61
+ // Lets the panels' queued refresh happen
62
+ const settle = () => new Promise(resolve => setTimeout(resolve, 0));
63
+
64
+ const panelsFor = (api: SquiffyApi, panels: Panel[]) => createPanels(api, {
65
+ panels,
66
+ buttons: document.getElementById("header")!,
67
+ side: document.getElementById("container")!,
68
+ });
69
+
70
+ test("renderPassage renders a master section passage with the attributes as they are", async () => {
71
+ const { api } = await start();
72
+ expect(api.renderPassage("status")).toBe("<p>Gold: 5</p>");
73
+ });
74
+
75
+ test("renderPassage changes nothing, and disables its links", async () => {
76
+ const { api, element } = await start();
77
+ const html = api.renderPassage("inventory");
78
+ expect(api.get("gold")).toBe(5);
79
+ expect(api.get("_section")).toBe("start");
80
+ expect(html).toContain("class=\"squiffy-link link-section disabled\"");
81
+ expect(html).toContain("class=\"squiffy-link link-passage disabled\"");
82
+ // Its {{goto}} isn't followed when the story moves on
83
+ await click(api, element, "Get the lamp");
84
+ expect(api.get("_section")).toBe("start");
85
+ expect(api.get("gold")).toBe(15);
86
+ });
87
+
88
+ test("renderPassage shows an error for a passage that isn't in the master section", async () => {
89
+ const { api } = await start();
90
+ expect(api.renderPassage("b")).toContain("there is no passage called \"b\" in the master section [[]]");
91
+ });
92
+
93
+ test("a side panel is shown beside the story, and rendered again as the story goes on", async () => {
94
+ const { api, element } = await start();
95
+ panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
96
+ const container = document.getElementById("container")!;
97
+ expect(container.classList.contains("squiffy-has-side")).toBe(true);
98
+ const panel = container.querySelector("aside.squiffy-panels-side > section.squiffy-panel")!;
99
+ expect(panel.getAttribute("aria-label")).toBe("Status");
100
+ expect(panel.innerHTML).toBe("<p>Gold: 5</p>");
101
+
102
+ await click(api, element, "Get the lamp");
103
+ await settle();
104
+ expect(panel.innerHTML).toBe("<p>Gold: 15</p>");
105
+
106
+ api.goBack();
107
+ await settle();
108
+ expect(panel.innerHTML).toBe("<p>Gold: 5</p>");
109
+
110
+ // Its button is for narrow screens, where CSS hides the panel
111
+ const button = document.querySelector<HTMLButtonElement>("#header button.squiffy-panel-button")!;
112
+ expect(button.classList.contains("squiffy-panel-side-button")).toBe(true);
113
+ });
114
+
115
+ test("a side panel whose text comes out empty is hidden", async () => {
116
+ const { api, element } = await start();
117
+ panelsFor(api, [{ passage: "lamp", label: "Lamp", position: "side" }]);
118
+ const aside = document.querySelector<HTMLElement>("aside.squiffy-panels-side")!;
119
+ const section = aside.querySelector<HTMLElement>("section")!;
120
+ expect(section.hidden).toBe(true);
121
+ expect(aside.hidden).toBe(true);
122
+ await click(api, element, "Get the lamp");
123
+ await settle();
124
+ expect(section.hidden).toBe(false);
125
+ expect(aside.hidden).toBe(false);
126
+ });
127
+
128
+ test("a button panel's button opens it in a dialog, rendered fresh", async () => {
129
+ const { api, element } = await start();
130
+ panelsFor(api, [{ passage: "status", label: "Status" }, { passage: "inventory", label: "Bag", icon: "bag" }]);
131
+ const buttons = [...document.querySelectorAll<HTMLButtonElement>("#header button")];
132
+ // Before the page's own buttons, in the order they're listed
133
+ expect(buttons.map(b => b.id || b.dataset.passage)).toEqual(["status", "inventory", "restart"]);
134
+ expect(buttons[0].textContent).toBe("Status");
135
+ expect(buttons[0].classList.contains("squiffy-panel-text-button")).toBe(true);
136
+ expect(buttons[1].getAttribute("aria-label")).toBe("Bag");
137
+ expect(buttons[1].querySelector("svg")).not.toBeNull();
138
+ // No side panels, so no aside
139
+ expect(document.querySelector("aside")).toBeNull();
140
+
141
+ buttons[0].click();
142
+ const dialog = document.querySelector<HTMLDialogElement>("dialog.squiffy-panel-dialog")!;
143
+ expect(dialog.hasAttribute("open")).toBe(true);
144
+ expect(dialog.querySelector("h2")!.textContent).toBe("Status");
145
+ expect(dialog.querySelector(".squiffy-panel-dialog-content")!.innerHTML).toBe("<p>Gold: 5</p>");
146
+ // The story's text isn't touched
147
+ expect(element.textContent).not.toContain("Gold:");
148
+
149
+ // While it's open, it follows the story
150
+ api.set("gold", 7);
151
+ await settle();
152
+ expect(dialog.querySelector(".squiffy-panel-dialog-content")!.innerHTML).toBe("<p>Gold: 7</p>");
153
+
154
+ dialog.querySelector<HTMLButtonElement>(".squiffy-panel-dialog-close")!.click();
155
+ expect(dialog.hasAttribute("open")).toBe(false);
156
+ });
157
+
158
+ test("opening a panel doesn't count as a move", async () => {
159
+ const { api } = await start();
160
+ const panels = panelsFor(api, [{ passage: "status", label: "Status" }]);
161
+ panels.open("status");
162
+ expect(api.canGoBack()).toBe(false);
163
+ });
164
+
165
+ test("without a side element, a side panel only has its button", async () => {
166
+ const { api } = await start();
167
+ createPanels(api, { panels: [{ passage: "status", label: "Status", position: "side" }], buttons: document.getElementById("header")! });
168
+ expect(document.querySelector("aside")).toBeNull();
169
+ const button = document.querySelector<HTMLButtonElement>("button.squiffy-panel-button")!;
170
+ expect(button.classList.contains("squiffy-panel-side-button")).toBe(false);
171
+ });
172
+
173
+ test("dispose takes the panels off the page", async () => {
174
+ const { api } = await start();
175
+ const panels = panelsFor(api, [{ passage: "status", label: "Status", position: "side" }, { passage: "inventory", label: "Bag" }]);
176
+ panels.dispose();
177
+ expect(document.querySelector("aside, dialog, button.squiffy-panel-button")).toBeNull();
178
+ expect(document.getElementById("container")!.classList.contains("squiffy-has-side")).toBe(false);
179
+ expect(document.getElementById("restart")).not.toBeNull();
180
+ });
181
+
182
+ test("the dialog's Close button can be translated", async () => {
183
+ const { api } = await start();
184
+ createPanels(api, { panels: [{ passage: "status", label: "État" }], buttons: document.getElementById("header")!, strings: { close: "Fermer" } });
185
+ expect(document.querySelector(".squiffy-panel-dialog-close")!.getAttribute("aria-label")).toBe("Fermer");
186
+ });
187
+
188
+ test("a hot update renders the panels again", async () => {
189
+ const { api } = await start();
190
+ panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
191
+ const result = await squiffyCompile({ script: script.replace("Gold: {{gold}}", "Coins: {{gold}}") });
192
+ if (!result.success) throw new Error("Compile failed");
193
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
194
+ api.update({ js: js as any, ...result.output.story });
195
+ await settle();
196
+ expect(document.querySelector("aside section")!.innerHTML).toBe("<p>Coins: 5</p>");
197
+ });
198
+
199
+ test("the compiler checks for the same icons the runtime has", () => {
200
+ expect([...COMPILER_PANEL_ICONS]).toEqual([...PANEL_ICONS]);
201
+ });
202
+
203
+ test("shows the attributes of a game restored when the page loads", async () => {
204
+ const element = document.getElementById("squiffy")!;
205
+ const result = await squiffyCompile({ script });
206
+ if (!result.success) throw new Error("Compile failed");
207
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
208
+ const story = { js: js as any, ...result.output.story };
209
+
210
+ const first = await init({ element, story, persist: true, storyId: "panels-restore" });
211
+ await first.begin();
212
+ await click(first, element, "Get the lamp");
213
+ expect(first.get("gold")).toBe(15);
214
+
215
+ // The page again, as it does it: the panels first, then the story begins, from the saved game
216
+ document.getElementById("container")!.querySelector("aside")?.remove();
217
+ element.innerHTML = "";
218
+ const api = await init({ element, story, persist: true, storyId: "panels-restore" });
219
+ panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
220
+ await api.begin();
221
+ await settle();
222
+
223
+ expect(document.querySelector("aside.squiffy-panels-side")!.textContent).toContain("Gold: 15");
224
+ localStorage.clear();
225
+ });
package/src/panels.ts ADDED
@@ -0,0 +1,187 @@
1
+ // Panels (#14, #443): passages in the master section that are always to hand, rendered again with
2
+ // the attributes as they are whenever the story moves on, e.g. the player's stats, inventory or
3
+ // a map. A "side" panel is shown beside the story, and a "button" panel is shown in a dialog,
4
+ // opened by a button in the header. Neither is part of the story's text, so they don't count as
5
+ // moves for Back or saved games. On a screen too narrow for a side panel, it has a button too.
6
+ //
7
+ // const panels = createPanels(squiffyApi, {
8
+ // panels: story.panels,
9
+ // buttons: document.getElementById("squiffy-header"),
10
+ // side: document.getElementById("squiffy-container"),
11
+ // });
12
+
13
+ import { PANEL_ICONS, type Panel, type PanelIcon, type SquiffyApi } from "./types.js";
14
+
15
+ export interface PanelsOptions {
16
+ // From the story's squiffy.json "panels" (story.panels)
17
+ panels: Panel[];
18
+ // Where the panels' buttons go: at the start of this element, e.g. the page's header
19
+ buttons: HTMLElement;
20
+ // Where side panels go: an <aside class="squiffy-panels-side"> is added at the end of this
21
+ // element, which gets the class squiffy-has-side, so its CSS can make room. Without it,
22
+ // side panels only have their buttons.
23
+ side?: HTMLElement;
24
+ // The dialog's text, for a story in another language: "close". Anything left out is in English.
25
+ strings?: Partial<Record<string, string>>;
26
+ // Where the dialog goes in the page: the end of the body by default
27
+ container?: HTMLElement;
28
+ }
29
+
30
+ export interface Panels {
31
+ // Renders the panels again, e.g. after changing an attribute from outside the story
32
+ refresh: () => void;
33
+ // Opens a panel's dialog, by its passage name
34
+ open: (passage: string) => void;
35
+ // Takes the panels, their buttons and their dialog off the page
36
+ dispose: () => void;
37
+ }
38
+
39
+ const ICON_CLOSE = "<path d=\"M18 6 6 18M6 6l12 12\"/>";
40
+
41
+ // Lucide icons (ISC licence), as are the page's other buttons
42
+ const ICONS: Record<PanelIcon, string> = {
43
+ bag: "<path d=\"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z\"/><path d=\"M8 10h8\"/><path d=\"M8 18h8\"/><path d=\"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6\"/><path d=\"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2\"/>",
44
+ person: "<path d=\"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2\"/><circle cx=\"12\" cy=\"7\" r=\"4\"/>",
45
+ map: "<path d=\"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z\"/><path d=\"M15 5.764v15\"/><path d=\"M9 3.236v15\"/>",
46
+ help: "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3\"/><path d=\"M12 17h.01\"/>",
47
+ info: "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/>",
48
+ list: "<path d=\"M3 6h.01M3 12h.01M3 18h.01M8 6h13M8 12h13M8 18h13\"/>",
49
+ book: "<path d=\"M12 7v14\"/><path d=\"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\"/>",
50
+ star: "<path d=\"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z\"/>",
51
+ heart: "<path d=\"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z\"/>",
52
+ };
53
+
54
+ const svg = (paths: string) => `<svg viewBox="0 0 24 24" aria-hidden="true">${paths}</svg>`;
55
+
56
+ let dialogCount = 0;
57
+
58
+ export function createPanels(api: SquiffyApi, options: PanelsOptions): Panels {
59
+ const close = typeof options.strings?.close == "string" ? options.strings.close : "Close";
60
+ const id = `squiffy-panel-${++dialogCount}`;
61
+ const cleanups: (() => void)[] = [];
62
+
63
+ // The dialog that button panels are shown in, one at a time
64
+ const dialog = document.createElement("dialog");
65
+ dialog.className = "squiffy-panel-dialog";
66
+ dialog.setAttribute("aria-labelledby", `${id}-heading`);
67
+ dialog.innerHTML = `
68
+ <div class="squiffy-panel-dialog-header">
69
+ <h2 id="${id}-heading"></h2>
70
+ <button type="button" class="squiffy-panel-dialog-close">${svg(ICON_CLOSE)}</button>
71
+ </div>
72
+ <div class="squiffy-panel squiffy-panel-dialog-content"></div>`;
73
+ const heading = dialog.querySelector("h2")!;
74
+ const closeButton = dialog.querySelector<HTMLButtonElement>(".squiffy-panel-dialog-close")!;
75
+ closeButton.title = close;
76
+ closeButton.setAttribute("aria-label", close);
77
+ closeButton.addEventListener("click", () => dialog.close());
78
+ const content = dialog.querySelector<HTMLDivElement>(".squiffy-panel-dialog-content")!;
79
+ // Clicking the backdrop closes it too
80
+ dialog.addEventListener("click", event => {
81
+ if (event.target === dialog) dialog.close();
82
+ });
83
+ (options.container ?? document.body).appendChild(dialog);
84
+ cleanups.push(() => dialog.remove());
85
+ // The panel the dialog is showing
86
+ let shown: Panel | null = null;
87
+
88
+ const panels = options.panels.filter(panel => panel && typeof panel.passage == "string");
89
+
90
+ // The side panels, beside the story
91
+ const sidePanels = options.side ? panels.filter(panel => panel.position == "side") : [];
92
+ const sideSections = new Map<Panel, HTMLElement>();
93
+ let aside: HTMLElement | null = null;
94
+ if (sidePanels.length && options.side) {
95
+ aside = document.createElement("aside");
96
+ aside.className = "squiffy-panels-side";
97
+ for (const panel of sidePanels) {
98
+ const section = document.createElement("section");
99
+ section.className = "squiffy-panel";
100
+ section.dataset.passage = panel.passage;
101
+ section.setAttribute("aria-label", panel.label || panel.passage);
102
+ aside.appendChild(section);
103
+ sideSections.set(panel, section);
104
+ }
105
+ const side = options.side;
106
+ side.appendChild(aside);
107
+ side.classList.add("squiffy-has-side");
108
+ cleanups.push(() => {
109
+ aside!.remove();
110
+ side.classList.remove("squiffy-has-side");
111
+ });
112
+ }
113
+
114
+ // A button for each panel, in the order they're listed, before anything already in the header.
115
+ // A side panel's button is only shown on screens too narrow for the panel.
116
+ const first = options.buttons.firstChild;
117
+ for (const panel of panels) {
118
+ const label = panel.label || panel.passage;
119
+ const button = document.createElement("button");
120
+ button.type = "button";
121
+ button.className = "squiffy-header-button squiffy-panel-button";
122
+ if (panel.position == "side" && sideSections.has(panel)) button.classList.add("squiffy-panel-side-button");
123
+ button.dataset.passage = panel.passage;
124
+ button.setAttribute("aria-haspopup", "dialog");
125
+ const icon = panel.icon && (PANEL_ICONS as readonly string[]).includes(panel.icon) ? ICONS[panel.icon] : null;
126
+ if (icon) {
127
+ button.innerHTML = svg(icon);
128
+ button.title = label;
129
+ button.setAttribute("aria-label", label);
130
+ }
131
+ else {
132
+ button.classList.add("squiffy-panel-text-button");
133
+ button.textContent = label;
134
+ }
135
+ button.addEventListener("click", () => open(panel));
136
+ options.buttons.insertBefore(button, first);
137
+ cleanups.push(() => button.remove());
138
+ }
139
+
140
+ function open(panel: Panel) {
141
+ shown = panel;
142
+ heading.textContent = panel.label || panel.passage;
143
+ content.innerHTML = api.renderPassage(panel.passage);
144
+ if (!dialog.open) dialog.showModal();
145
+ }
146
+
147
+ function refresh() {
148
+ for (const [panel, section] of sideSections) {
149
+ section.innerHTML = api.renderPassage(panel.passage);
150
+ // Text that comes out empty, e.g. from an {{#if}}, hides the panel
151
+ section.hidden = !section.textContent?.trim() && !section.querySelector("img, svg, video, canvas, iframe");
152
+ }
153
+ if (aside) aside.hidden = [...sideSections.values()].every(section => section.hidden);
154
+ if (dialog.open && shown) content.innerHTML = api.renderPassage(shown.passage);
155
+ }
156
+
157
+ // Rendered again once whatever changed has finished changing, rather than after every attribute
158
+ let queued = false;
159
+ const queueRefresh = () => {
160
+ if (queued) return;
161
+ queued = true;
162
+ queueMicrotask(() => {
163
+ queued = false;
164
+ if (!disposed) refresh();
165
+ });
166
+ };
167
+ for (const event of ["set", "navigated", "storyUpdated"] as const) {
168
+ cleanups.push(api.on(event, queueRefresh));
169
+ }
170
+ dialog.addEventListener("close", () => { shown = null; });
171
+
172
+ let disposed = false;
173
+ refresh();
174
+
175
+ return {
176
+ refresh,
177
+ open(passage: string) {
178
+ const panel = panels.find(p => p.passage == passage);
179
+ if (panel) open(panel);
180
+ },
181
+ dispose() {
182
+ disposed = true;
183
+ if (dialog.open) dialog.close();
184
+ for (const cleanup of cleanups.splice(0)) cleanup();
185
+ },
186
+ };
187
+ }
@@ -0,0 +1,66 @@
1
+ import { expect, test, describe } from "vitest";
2
+ import { parsePath, readTarget, valueAt, withValueAt } from "./paths.js";
3
+
4
+ describe("parsePath", () => {
5
+ test.each([
6
+ ["score", ["score"]],
7
+ ["my attribute", ["my attribute"]],
8
+ ["hero.hp", ["hero", "hp"]],
9
+ ["inventory.0.name", ["inventory", "0", "name"]],
10
+ ["inventory[0].name", ["inventory", "0", "name"]],
11
+ ["inventory.[0].name", ["inventory", "0", "name"]],
12
+ ["hero[\"max hp\"]", ["hero", "max hp"]],
13
+ ["hero['max hp'].x", ["hero", "max hp", "x"]],
14
+ // Not paths: the whole name is the attribute
15
+ ["a..b", ["a..b"]],
16
+ ["a.", ["a."]],
17
+ [".a", [".a"]],
18
+ ["a[0", ["a[0"]],
19
+ ])("%s", (name, expected) => {
20
+ expect(parsePath(name)).toEqual(expected);
21
+ });
22
+
23
+ test("names that reach the prototype aren't allowed", () => {
24
+ expect(() => parsePath("hero.__proto__.x")).toThrow("__proto__");
25
+ expect(() => parsePath("hero[constructor]")).toThrow("constructor");
26
+ });
27
+ });
28
+
29
+ describe("valueAt and withValueAt", () => {
30
+ test("reads values, and null for anything missing", () => {
31
+ const hero = { hp: 10, items: [{ name: "lamp" }] };
32
+ expect(valueAt(hero, ["items", "0", "name"])).toBe("lamp");
33
+ expect(valueAt(hero, ["items", "1", "name"])).toBeNull();
34
+ expect(valueAt(hero, ["hp", "x"])).toBeNull();
35
+ expect(valueAt(hero, ["toString"])).toBeNull();
36
+ });
37
+
38
+ test("changes a copy, making objects that aren't there", () => {
39
+ const hero = { hp: 10 };
40
+ expect(withValueAt(hero, ["stats", "str"], "hero", 2)).toEqual({ hp: 10, stats: { str: 2 } });
41
+ expect(hero).toEqual({ hp: 10 });
42
+ expect(withValueAt(null, ["hp"], "hero", 1)).toEqual({ hp: 1 });
43
+ expect(withValueAt([1, 2], ["1"], "list", 5)).toEqual([1, 5]);
44
+ });
45
+
46
+ test("can't go through a value that isn't an object", () => {
47
+ expect(() => withValueAt(5, ["hp"], "hero", 1)).toThrow("hero isn't an object, so it has no hp");
48
+ expect(() => withValueAt({ hp: 5 }, ["hp", "max"], "hero", 1)).toThrow("hero.hp isn't an object, so it has no max");
49
+ });
50
+ });
51
+
52
+ describe("readTarget", () => {
53
+ test.each([
54
+ ["gold = 1", { attribute: "gold", segments: [], rest: " = 1" }],
55
+ ["hero.hp += 5", { attribute: "hero", segments: [{ name: "hp" }], rest: " += 5" }],
56
+ ["inventory[i + 1].name = \"x\"", { attribute: "inventory", segments: [{ index: "i + 1" }, { name: "name" }], rest: " = \"x\"" }],
57
+ ["grid[a[0]][\"]\"]", { attribute: "grid", segments: [{ index: "a[0]" }, { index: "\"]\"" }], rest: "" }],
58
+ ])("%s", (text, expected) => {
59
+ expect(readTarget(text)).toEqual(expected);
60
+ });
61
+
62
+ test("isn't a target", () => {
63
+ expect(readTarget("= 1")).toBeNull();
64
+ expect(readTarget("a[0 = 1")).toBeNull();
65
+ });
66
+ });
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
+ }