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,499 @@
1
+ import type { SavedGame, SquiffyApi } from "./types.js";
2
+ import { indexedDbSaveSlots, memorySaveSlots, type SaveSlot, type SaveSlots } from "./saveSlots.js";
3
+
4
+ // The dialog's text in English. The published page passes in squiffy.json's "strings", which
5
+ // use the same names (see PAGE_STRINGS in the compiler). [name] and [time] are filled in.
6
+ export const SAVES_STRINGS = {
7
+ saves: "Saved games",
8
+ saveName: "Name (optional)",
9
+ save: "Save",
10
+ noSaves: "No saved games yet.",
11
+ savedGame: "Saved game",
12
+ savedToday: "Today, [time]",
13
+ savedYesterday: "Yesterday, [time]",
14
+ load: "Load",
15
+ loadConfirm: "Load \"[name]\"? You'll lose anything you've done since you last saved.",
16
+ saveOptions: "Options for [name]",
17
+ overwrite: "Overwrite",
18
+ overwriteConfirm: "Overwrite \"[name]\"?",
19
+ rename: "Rename",
20
+ newName: "New name",
21
+ saveToFile: "Save to file",
22
+ loadFromFile: "Load from file",
23
+ delete: "Delete",
24
+ deleteConfirm: "Delete \"[name]\"? This can't be undone.",
25
+ cancel: "Cancel",
26
+ close: "Close",
27
+ wrongStory: "This saved game is for a different story.",
28
+ notASave: "This file isn't a saved game.",
29
+ cantSave: "The game couldn't be saved. Try Save to file instead.",
30
+ };
31
+
32
+ export type SavesStringName = keyof typeof SAVES_STRINGS;
33
+
34
+ export interface SavesDialogOptions {
35
+ // Where the player's saves are kept. By default, in the browser's IndexedDB under `key`.
36
+ slots?: SaveSlots;
37
+ // Which story the saves are for, when `slots` isn't given: the page's path by default
38
+ key?: string;
39
+ // The dialog's text, for a story in another language. Anything left out is in English.
40
+ strings?: Partial<Record<string, string>>;
41
+ // The name Save to file gives the file, before ".squiffy-save": the page's title by default
42
+ fileName?: string;
43
+ // Where the dialog goes in the page: the end of the body by default
44
+ container?: HTMLElement;
45
+ }
46
+
47
+ export interface SavesDialog {
48
+ element: HTMLDialogElement;
49
+ open: () => Promise<void>;
50
+ close: () => void;
51
+ }
52
+
53
+ export const SAVE_FILE_EXTENSION = ".squiffy-save";
54
+
55
+ const ICON_CLOSE = "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M18 6 6 18M6 6l12 12\"/></svg>";
56
+ const ICON_OPTIONS = "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><circle cx=\"5\" cy=\"12\" r=\"1\"/><circle cx=\"12\" cy=\"12\" r=\"1\"/><circle cx=\"19\" cy=\"12\" r=\"1\"/></svg>";
57
+ const ICON_DOWNLOAD = "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M7 10l5 5 5-5M12 15V3\"/></svg>";
58
+ const ICON_UPLOAD = "<svg viewBox=\"0 0 24 24\" aria-hidden=\"true\"><path d=\"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4M17 8l-5-5-5 5M12 3v12\"/></svg>";
59
+
60
+ let dialogCount = 0;
61
+
62
+ // "Today, 12:57", "Yesterday, 21:14", or the date and time for anything older
63
+ export function formatSaveTime(savedAt: string, strings: Record<SavesStringName, string> = SAVES_STRINGS, now = new Date()) {
64
+ const date = new Date(savedAt);
65
+ if (isNaN(date.getTime())) return "";
66
+ const time = date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" });
67
+ const startOfDay = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime();
68
+ const daysAgo = Math.round((startOfDay(now) - startOfDay(date)) / 86400000);
69
+ if (daysAgo === 0) return strings.savedToday.replace("[time]", time);
70
+ if (daysAgo === 1) return strings.savedYesterday.replace("[time]", time);
71
+ const day = date.toLocaleDateString(undefined, {
72
+ day: "numeric", month: "short",
73
+ ...(date.getFullYear() !== now.getFullYear() ? { year: "numeric" } : {}),
74
+ });
75
+ return `${day}, ${time}`;
76
+ }
77
+
78
+ // The Saved games dialog: saves the game into a list of saves, which the player can load,
79
+ // overwrite, rename, save to a file or delete, and saves to and loads from a file. It's added to
80
+ // the page hidden, and open() shows it.
81
+ export function createSavesDialog(api: SquiffyApi, options: SavesDialogOptions = {}): SavesDialog {
82
+ const strings: Record<SavesStringName, string> = { ...SAVES_STRINGS };
83
+ for (const name of Object.keys(SAVES_STRINGS) as SavesStringName[]) {
84
+ const value = options.strings?.[name];
85
+ if (typeof value == "string") strings[name] = value;
86
+ }
87
+ const slots = options.slots ?? (typeof indexedDB != "undefined"
88
+ ? indexedDbSaveSlots(options.key ?? window.location.pathname)
89
+ : memorySaveSlots());
90
+ const id = `squiffy-saves-${++dialogCount}`;
91
+
92
+ const dialog = document.createElement("dialog");
93
+ dialog.className = "squiffy-saves";
94
+ dialog.setAttribute("aria-labelledby", `${id}-heading`);
95
+ dialog.innerHTML = `
96
+ <div class="squiffy-saves-header">
97
+ <h2 id="${id}-heading"></h2>
98
+ <button type="button" class="squiffy-saves-icon-button" data-close>${ICON_CLOSE}</button>
99
+ </div>
100
+ <p class="squiffy-saves-error" role="alert" hidden></p>
101
+ <form class="squiffy-saves-new">
102
+ <input type="text" autocomplete="off">
103
+ <button type="submit" class="squiffy-saves-button squiffy-saves-primary"></button>
104
+ </form>
105
+ <ul class="squiffy-saves-list"></ul>
106
+ <div class="squiffy-saves-footer">
107
+ <button type="button" class="squiffy-saves-link" data-save-to-file>${ICON_DOWNLOAD}<span></span></button>
108
+ <button type="button" class="squiffy-saves-link" data-load-from-file>${ICON_UPLOAD}<span></span></button>
109
+ <input type="file" accept="${SAVE_FILE_EXTENSION},.json,application/json" hidden>
110
+ </div>
111
+ <div class="squiffy-saves-footer-confirm"></div>`;
112
+
113
+ const $ = <T extends Element>(selector: string) => dialog.querySelector<T>(selector)!;
114
+ $("h2").textContent = strings.saves;
115
+ const closeButton = $<HTMLButtonElement>("[data-close]");
116
+ closeButton.title = strings.close;
117
+ closeButton.setAttribute("aria-label", strings.close);
118
+ const error = $<HTMLParagraphElement>(".squiffy-saves-error");
119
+ const form = $<HTMLFormElement>("form");
120
+ const nameInput = $<HTMLInputElement>("form input");
121
+ nameInput.placeholder = strings.saveName;
122
+ nameInput.setAttribute("aria-label", strings.saveName);
123
+ $("form button").textContent = strings.save;
124
+ const list = $<HTMLUListElement>(".squiffy-saves-list");
125
+ $("[data-save-to-file] span").textContent = strings.saveToFile;
126
+ $("[data-load-from-file] span").textContent = strings.loadFromFile;
127
+ const fileInput = $<HTMLInputElement>("input[type=file]");
128
+ const footerConfirm = $<HTMLDivElement>(".squiffy-saves-footer-confirm");
129
+
130
+ (options.container ?? document.body).appendChild(dialog);
131
+
132
+ // Whether the player has done anything since they last saved or loaded, which loading a save
133
+ // would lose. Squiffy saves automatically too, but that doesn't count: loading replaces it.
134
+ // That's anything since the start of the story (which may be a game restored from earlier),
135
+ // unless they've saved or loaded since. It's worked out when it's needed, as the dialog can be
136
+ // made before the story begins.
137
+ let savedOrLoaded = false;
138
+ api.on("navigated", () => { savedOrLoaded = false; });
139
+ const unsaved = () => !savedOrLoaded && api.canGoBack();
140
+
141
+ let saves: SaveSlot[] = [];
142
+ // Closes whatever's open inside the dialog (a question, a save's menu, or a rename), so
143
+ // Escape can close that before it closes the dialog
144
+ let cancelOpen: (() => void) | null = null;
145
+
146
+ const showError = (message: string) => {
147
+ error.textContent = message;
148
+ error.hidden = false;
149
+ };
150
+ const hideError = () => {
151
+ error.hidden = true;
152
+ };
153
+
154
+ const titleOf = (slot: SaveSlot) => slot.name || slot.save.summary || strings.savedGame;
155
+
156
+ const metaOf = (slot: SaveSlot) =>
157
+ [formatSaveTime(slot.save.savedAt, strings), slot.name && slot.save.summary].filter(Boolean).join(" · ");
158
+
159
+ const rowOf = (slotId: number) => list.querySelector<HTMLLIElement>(`[data-slot="${slotId}"]`);
160
+
161
+ function render() {
162
+ list.replaceChildren();
163
+ if (!saves.length) {
164
+ const empty = document.createElement("li");
165
+ empty.className = "squiffy-saves-empty";
166
+ empty.textContent = strings.noSaves;
167
+ list.appendChild(empty);
168
+ return;
169
+ }
170
+ for (const slot of saves) {
171
+ const title = titleOf(slot);
172
+ const row = document.createElement("li");
173
+ row.className = "squiffy-saves-row";
174
+ row.dataset.slot = String(slot.id);
175
+ row.innerHTML = `
176
+ <div class="squiffy-saves-line">
177
+ <div class="squiffy-saves-info">
178
+ <div class="squiffy-saves-title" id="${id}-title-${slot.id}"></div>
179
+ <div class="squiffy-saves-meta"></div>
180
+ </div>
181
+ <button type="button" class="squiffy-saves-button" data-action="load" aria-describedby="${id}-title-${slot.id}"></button>
182
+ <div class="squiffy-saves-options">
183
+ <button type="button" class="squiffy-saves-icon-button" data-action="options" aria-haspopup="menu" aria-expanded="false" aria-controls="${id}-menu-${slot.id}">${ICON_OPTIONS}</button>
184
+ <div class="squiffy-saves-menu" id="${id}-menu-${slot.id}" role="menu" hidden>
185
+ <button type="button" role="menuitem" data-action="overwrite"></button>
186
+ <button type="button" role="menuitem" data-action="rename"></button>
187
+ <button type="button" role="menuitem" data-action="download"></button>
188
+ <button type="button" role="menuitem" data-action="delete" class="squiffy-saves-danger"></button>
189
+ </div>
190
+ </div>
191
+ </div>`;
192
+ const q = (selector: string) => row.querySelector<HTMLElement>(selector)!;
193
+ q(".squiffy-saves-title").textContent = title;
194
+ const meta = metaOf(slot);
195
+ if (meta) q(".squiffy-saves-meta").textContent = meta;
196
+ else q(".squiffy-saves-meta").remove();
197
+ q("[data-action=load]").textContent = strings.load;
198
+ const options = q("[data-action=options]");
199
+ options.title = strings.saveOptions.replace("[name]", title);
200
+ options.setAttribute("aria-label", options.title);
201
+ q("[data-action=overwrite]").textContent = strings.overwrite;
202
+ q("[data-action=rename]").textContent = strings.rename;
203
+ q("[data-action=download]").textContent = strings.saveToFile;
204
+ q("[data-action=delete]").textContent = strings.delete;
205
+ list.appendChild(row);
206
+ }
207
+ }
208
+
209
+ async function refresh() {
210
+ try {
211
+ saves = await slots.list();
212
+ }
213
+ catch {
214
+ saves = [];
215
+ showError(strings.cantSave);
216
+ }
217
+ render();
218
+ }
219
+
220
+ // Asks a question inside the dialog, under `container`, rather than with confirm(). Resolves
221
+ // true if the player goes ahead.
222
+ function confirmInDialog(container: HTMLElement, message: string, actionLabel: string, danger = false) {
223
+ cancelOpen?.();
224
+ const box = document.createElement("div");
225
+ box.className = "squiffy-saves-confirm";
226
+ box.setAttribute("role", "group");
227
+ box.innerHTML = `<p id="${id}-confirm"></p>
228
+ <div class="squiffy-saves-confirm-buttons">
229
+ <button type="button" class="squiffy-saves-button" data-answer="no"></button>
230
+ <button type="button" class="squiffy-saves-button ${danger ? "squiffy-saves-danger-button" : "squiffy-saves-primary"}" data-answer="yes" aria-describedby="${id}-confirm"></button>
231
+ </div>`;
232
+ box.setAttribute("aria-labelledby", `${id}-confirm`);
233
+ box.querySelector("p")!.textContent = message;
234
+ const no = box.querySelector<HTMLButtonElement>("[data-answer=no]")!;
235
+ const yes = box.querySelector<HTMLButtonElement>("[data-answer=yes]")!;
236
+ no.textContent = strings.cancel;
237
+ yes.textContent = actionLabel;
238
+ container.appendChild(box);
239
+ return new Promise<boolean>(resolve => {
240
+ const finish = (answer: boolean) => {
241
+ cancelOpen = null;
242
+ box.remove();
243
+ resolve(answer);
244
+ };
245
+ cancelOpen = () => finish(false);
246
+ no.addEventListener("click", () => finish(false));
247
+ yes.addEventListener("click", () => finish(true));
248
+ yes.focus();
249
+ });
250
+ }
251
+
252
+ // A save's menu goes in the top layer as a popover, where the browser has them, so the list
253
+ // scrolling doesn't cut it off. It's under its ⋯ button, or above it if there's no room below.
254
+ const popovers = typeof HTMLElement.prototype.showPopover == "function";
255
+
256
+ function showMenu(menu: HTMLElement, button: HTMLElement) {
257
+ if (!popovers) {
258
+ menu.hidden = false;
259
+ return;
260
+ }
261
+ menu.hidden = false;
262
+ menu.popover = "manual";
263
+ menu.showPopover();
264
+ const rect = button.getBoundingClientRect();
265
+ const { width, height } = menu.getBoundingClientRect();
266
+ const below = rect.bottom + 4;
267
+ menu.style.top = `${below + height > window.innerHeight - 8 ? Math.max(8, rect.top - 4 - height) : below}px`;
268
+ menu.style.left = `${Math.max(8, Math.min(rect.right - width, window.innerWidth - 8 - width))}px`;
269
+ }
270
+
271
+ function hideMenu(menu: HTMLElement) {
272
+ if (popovers && menu.matches(":popover-open")) menu.hidePopover();
273
+ menu.hidden = true;
274
+ }
275
+
276
+ // A save's menu, opened by its ⋯ button
277
+ function openMenu(button: HTMLElement) {
278
+ const menu = document.getElementById(button.getAttribute("aria-controls")!)!;
279
+ const wasOpen = button.getAttribute("aria-expanded") == "true";
280
+ cancelOpen?.();
281
+ if (wasOpen) return;
282
+ showMenu(menu, button);
283
+ button.setAttribute("aria-expanded", "true");
284
+ const items = [...menu.querySelectorAll<HTMLElement>("[role=menuitem]")];
285
+ items[0].focus();
286
+
287
+ const close = (focusButton: boolean) => {
288
+ cancelOpen = null;
289
+ hideMenu(menu);
290
+ button.setAttribute("aria-expanded", "false");
291
+ menu.removeEventListener("keydown", onKey);
292
+ dialog.removeEventListener("pointerdown", onPointerDown);
293
+ if (focusButton) button.focus();
294
+ };
295
+ const onKey = (e: KeyboardEvent) => {
296
+ const index = items.indexOf(document.activeElement as HTMLElement);
297
+ const next = ({ ArrowDown: index + 1, ArrowUp: index - 1, Home: 0, End: items.length - 1 } as Record<string, number>)[e.key];
298
+ if (next !== undefined) {
299
+ e.preventDefault();
300
+ items[(next + items.length) % items.length].focus();
301
+ }
302
+ else if (e.key == "Tab") {
303
+ close(false);
304
+ }
305
+ };
306
+ const onPointerDown = (e: PointerEvent) => {
307
+ const target = e.target as Node;
308
+ if (!menu.contains(target) && !button.contains(target)) close(false);
309
+ };
310
+ menu.addEventListener("keydown", onKey);
311
+ dialog.addEventListener("pointerdown", onPointerDown);
312
+ cancelOpen = () => close(true);
313
+ }
314
+
315
+ // Turns a save's title into a text box. Enter or leaving the box keeps the new name (an empty
316
+ // one makes the save unnamed again), and Escape keeps the old one.
317
+ function startRename(slot: SaveSlot) {
318
+ const title = rowOf(slot.id)?.querySelector(".squiffy-saves-title");
319
+ if (!title) return;
320
+ const input = document.createElement("input");
321
+ input.type = "text";
322
+ input.className = "squiffy-saves-rename";
323
+ input.autocomplete = "off";
324
+ input.value = slot.name ?? "";
325
+ input.placeholder = titleOf(slot);
326
+ input.setAttribute("aria-label", strings.newName);
327
+ title.replaceWith(input);
328
+ input.focus();
329
+ input.select();
330
+
331
+ let finished = false;
332
+ const finish = async (keep: boolean) => {
333
+ if (finished) return;
334
+ finished = true;
335
+ cancelOpen = null;
336
+ const name = input.value.trim() || null;
337
+ if (keep && name !== slot.name) {
338
+ await slots.rename(slot.id, name).catch(() => showError(strings.cantSave));
339
+ }
340
+ await refresh();
341
+ rowOf(slot.id)?.querySelector<HTMLElement>("[data-action=load]")?.focus();
342
+ };
343
+ cancelOpen = () => { finish(false); };
344
+ input.addEventListener("keydown", e => {
345
+ if (e.key == "Enter") {
346
+ e.preventDefault();
347
+ finish(true);
348
+ }
349
+ });
350
+ input.addEventListener("blur", () => finish(true));
351
+ }
352
+
353
+ function fileName() {
354
+ const name = (options.fileName ?? document.title).replace(/[\\/:*?"<>|]+/g, "").replace(/\s+/g, " ").trim();
355
+ return (name || "story") + SAVE_FILE_EXTENSION;
356
+ }
357
+
358
+ function download(save: SavedGame) {
359
+ const url = URL.createObjectURL(new Blob([JSON.stringify(save)], { type: "application/json" }));
360
+ const link = document.createElement("a");
361
+ link.href = url;
362
+ link.download = fileName();
363
+ dialog.appendChild(link);
364
+ link.click();
365
+ link.remove();
366
+ setTimeout(() => URL.revokeObjectURL(url), 0);
367
+ }
368
+
369
+ async function load(save: unknown) {
370
+ const result = await api.loadSave(save as SavedGame);
371
+ if (!result.success) {
372
+ showError(strings[result.error]);
373
+ return;
374
+ }
375
+ savedOrLoaded = true;
376
+ dialog.close();
377
+ }
378
+
379
+ // Escape closes whatever's open in the dialog first
380
+ dialog.addEventListener("cancel", e => {
381
+ if (cancelOpen) {
382
+ e.preventDefault();
383
+ cancelOpen();
384
+ }
385
+ });
386
+
387
+ closeButton.addEventListener("click", () => dialog.close());
388
+
389
+ form.addEventListener("submit", async e => {
390
+ e.preventDefault();
391
+ hideError();
392
+ cancelOpen?.();
393
+ try {
394
+ await slots.add(api.getSave(), nameInput.value);
395
+ savedOrLoaded = true;
396
+ nameInput.value = "";
397
+ }
398
+ catch {
399
+ showError(strings.cantSave);
400
+ }
401
+ await refresh();
402
+ nameInput.focus();
403
+ });
404
+
405
+ list.addEventListener("click", async e => {
406
+ const button = (e.target as Element).closest<HTMLElement>("[data-action]");
407
+ const row = button?.closest<HTMLLIElement>("[data-slot]");
408
+ if (!button || !row) return;
409
+ const slot = saves.find(s => s.id === Number(row.dataset.slot));
410
+ if (!slot) return;
411
+ const action = button.dataset.action;
412
+ if (action == "options") {
413
+ openMenu(button);
414
+ return;
415
+ }
416
+ if (button.getAttribute("role") == "menuitem") cancelOpen?.();
417
+ hideError();
418
+ const title = titleOf(slot);
419
+
420
+ if (action == "load") {
421
+ if (unsaved() && !await confirmInDialog(row, strings.loadConfirm.replace("[name]", title), strings.load)) {
422
+ button.focus();
423
+ return;
424
+ }
425
+ const latest = await slots.get(slot.id).catch(() => null);
426
+ if (latest) await load(latest.save);
427
+ }
428
+ else if (action == "overwrite") {
429
+ if (!await confirmInDialog(row, strings.overwriteConfirm.replace("[name]", title), strings.overwrite)) return;
430
+ try {
431
+ await slots.overwrite(slot.id, api.getSave());
432
+ savedOrLoaded = true;
433
+ }
434
+ catch {
435
+ showError(strings.cantSave);
436
+ }
437
+ await refresh();
438
+ rowOf(slot.id)?.querySelector<HTMLElement>("[data-action=load]")?.focus();
439
+ }
440
+ else if (action == "rename") {
441
+ startRename(slot);
442
+ }
443
+ else if (action == "download") {
444
+ download(slot.save);
445
+ }
446
+ else if (action == "delete") {
447
+ if (!await confirmInDialog(row, strings.deleteConfirm.replace("[name]", title), strings.delete, true)) return;
448
+ await slots.delete(slot.id).catch(() => showError(strings.cantSave));
449
+ await refresh();
450
+ nameInput.focus();
451
+ }
452
+ });
453
+
454
+ $("[data-save-to-file]").addEventListener("click", () => {
455
+ hideError();
456
+ download(api.getSave());
457
+ savedOrLoaded = true;
458
+ });
459
+
460
+ $("[data-load-from-file]").addEventListener("click", () => {
461
+ hideError();
462
+ fileInput.click();
463
+ });
464
+
465
+ fileInput.addEventListener("change", async () => {
466
+ const file = fileInput.files?.[0];
467
+ fileInput.value = "";
468
+ if (!file) return;
469
+ let save: unknown;
470
+ try {
471
+ save = JSON.parse(await file.text());
472
+ }
473
+ catch {
474
+ showError(strings.notASave);
475
+ return;
476
+ }
477
+ if (unsaved() && !await confirmInDialog(footerConfirm, strings.loadConfirm.replace("[name]", file.name), strings.load)) {
478
+ return;
479
+ }
480
+ await load(save);
481
+ });
482
+
483
+ return {
484
+ element: dialog,
485
+ async open() {
486
+ hideError();
487
+ cancelOpen?.();
488
+ nameInput.value = "";
489
+ // Shown straight away, so the player can type a name while the saves are listed
490
+ if (!dialog.open) dialog.showModal();
491
+ nameInput.focus();
492
+ await refresh();
493
+ },
494
+ close() {
495
+ cancelOpen?.();
496
+ dialog.close();
497
+ },
498
+ };
499
+ }
@@ -0,0 +1,130 @@
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 { SquiffyScriptApi, Story } from "./types.js";
6
+
7
+ // The story's own scripts (#528): the squiffy:ready event, and what it gives them
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
+ localStorage.clear();
17
+ cleanup();
18
+ });
19
+
20
+ const compile = async (script: string): Promise<Story> => {
21
+ const result = await squiffyCompile({ script, expressions: true });
22
+ if (!result.success) throw new Error("Compile failed");
23
+ return {
24
+ js: result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n"))) as any,
25
+ ...result.output.story,
26
+ };
27
+ };
28
+
29
+ const script = `[[start]]:
30
+ @set score = 1
31
+ Hello. [[Next]](kitchen) [look]
32
+
33
+ [look]:
34
+ @set looked = true
35
+ A look.
36
+
37
+ [[kitchen]]:
38
+ @set score = 2
39
+ The kitchen.`;
40
+
41
+ // A script's listener, as on a published page: on document, before the story is set up
42
+ const listen = () => {
43
+ const ready: SquiffyScriptApi[] = [];
44
+ document.addEventListener("squiffy:ready", event => {
45
+ ready.push((event as CustomEvent<SquiffyScriptApi>).detail);
46
+ });
47
+ return ready;
48
+ };
49
+
50
+ const link = (text: string) => Array.from(document.querySelectorAll<HTMLElement>("a.squiffy-link"))
51
+ .reverse().find(a => a.textContent == text)!;
52
+
53
+ test("squiffy:ready bubbles to document before the story begins, so a script hears the first section", async () => {
54
+ const ready = listen();
55
+ const element = document.getElementById("squiffy")!;
56
+ const api = await init({ element, story: await compile(script) });
57
+ expect(ready).toHaveLength(1);
58
+ expect(ready[0].element).toBe(element);
59
+
60
+ const navigated: unknown[] = [];
61
+ ready[0].on("navigated", e => navigated.push(e));
62
+ await api.begin();
63
+ expect(navigated).toEqual([{ section: "start" }]);
64
+
65
+ await api.clickLink(link("look"));
66
+ await api.clickLink(link("Next"));
67
+ expect(navigated).toEqual([{ section: "start" }, { section: "start", passage: "look" }, { section: "kitchen" }]);
68
+ });
69
+
70
+ test("a script hears about going back and restarting, and can stop listening", async () => {
71
+ const ready = listen();
72
+ const api = await init({ element: document.getElementById("squiffy")!, story: await compile(script), scroll: "element" });
73
+ const sections: string[] = [];
74
+ const stop = ready[0].on("navigated", e => sections.push(e.section));
75
+ await api.begin();
76
+ await api.clickLink(link("Next"));
77
+ api.goBack();
78
+ api.restart();
79
+ await new Promise(resolve => setTimeout(resolve, 0));
80
+ expect(sections).toEqual(["start", "kitchen", "start", "start"]);
81
+
82
+ stop();
83
+ await api.clickLink(link("Next"));
84
+ expect(sections).toHaveLength(4);
85
+ });
86
+
87
+ test("a script can read and set attributes, go to a section, and see what's been seen", async () => {
88
+ const ready = listen();
89
+ const api = await init({ element: document.getElementById("squiffy")!, story: await compile(script) });
90
+ const squiffy = ready[0];
91
+ const set: unknown[] = [];
92
+ squiffy.on("set", e => { if (!e.attribute.startsWith("_")) set.push(e); });
93
+ await api.begin();
94
+ expect(squiffy.get("score")).toBe(1);
95
+ expect(set).toContainEqual({ attribute: "score", value: 1 });
96
+
97
+ squiffy.set("gold", 5);
98
+ expect(api.get("gold")).toBe(5);
99
+
100
+ await api.clickLink(link("look"));
101
+ expect(squiffy.story.seen("look")).toBe(true);
102
+ expect(squiffy.story.visits("kitchen")).toBe(0);
103
+ expect(squiffy.story.passages()).toEqual(["look"]);
104
+ expect(squiffy.story.sections()).toEqual(["start", "kitchen"]);
105
+ await squiffy.story.go("kitchen");
106
+ expect(api.get("_section")).toBe("kitchen");
107
+ expect(squiffy.get("score")).toBe(2);
108
+ });
109
+
110
+ test("a script can read a player setting, and hear when it changes", async () => {
111
+ const ready = listen();
112
+ const story = await compile(script);
113
+ story.settings = [{ name: "effects", label: "Effects", type: "toggle", default: true }];
114
+ const api = await init({ element: document.getElementById("squiffy")!, story });
115
+ const squiffy = ready[0];
116
+ const changed: unknown[] = [];
117
+ squiffy.on("settingChanged", e => changed.push(e));
118
+ expect(squiffy.getSetting("effects")).toBe(true);
119
+ api.setSetting("effects", false);
120
+ expect(squiffy.getSetting("effects")).toBe(false);
121
+ expect(changed).toEqual([{ name: "effects", value: false }]);
122
+ });
123
+
124
+ test("a script can only listen for the story's own events, not the page's", async () => {
125
+ const ready = listen();
126
+ await init({ element: document.getElementById("squiffy")!, story: await compile(script) });
127
+ expect(() => ready[0].on("restartRequested" as any, () => {})).toThrow(/can't listen for "restartRequested"/);
128
+ // It isn't something the API has, such as begin() or dispose()
129
+ expect("begin" in ready[0]).toBe(false);
130
+ });