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
package/src/preview.ts CHANGED
@@ -2,8 +2,10 @@
2
2
  // page itself (preview.main.ts) connects this to postMessage; it's separate so it can be tested.
3
3
 
4
4
  import { init } from "./squiffy.runtime.js";
5
+ import { createPanels, type Panels } from "./panels.js";
6
+ import { createSettingsDialog, SETTINGS_ICON, type SettingsDialog } from "./settingsDialog.js";
5
7
  import type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory } from "./preview-protocol.js";
6
- import type { SquiffyApi, Story } from "./types.js";
8
+ import type { Panel, PlayerSetting, SquiffyApi, Story } from "./types.js";
7
9
 
8
10
  export interface PreviewOptions {
9
11
  // Where to show the story
@@ -12,6 +14,8 @@ export interface PreviewOptions {
12
14
  // Loads a compiled story module. By default it's imported from a blob URL, so story
13
15
  // JavaScript runs without new Function (and so without unsafe-eval in a CSP).
14
16
  loadModule?(js: string): Promise<{ story: Story }>;
17
+ // Reloads the page, for a "reload" message
18
+ reload?(): void;
15
19
  }
16
20
 
17
21
  const mimeTypes: Record<string, string> = {
@@ -27,6 +31,10 @@ const mimeType = (path: string) => mimeTypes[path.substring(path.lastIndexOf("."
27
31
 
28
32
  const normalisePath = (path: string) => path.replace(/^(\.\/)+/, "");
29
33
 
34
+ // The url()s in a story's stylesheet that are paths, rather than web addresses, data: URIs and the like
35
+ const CSS_URL = /url\(\s*(?:"((?:[^"\\\n]|\\.)*)"|'((?:[^'\\\n]|\\.)*)'|([^)"'\s]*))\s*\)/gi;
36
+ const isRelativeUrl = (url: string) => url != "" && !/^(?:[a-z][a-z\d+.-]*:|\/|#)/i.test(url);
37
+
30
38
  async function importFromBlob(js: string): Promise<{ story: Story }> {
31
39
  const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
32
40
  try {
@@ -47,11 +55,36 @@ function errorMessage(error: unknown): PreviewMessage {
47
55
  export function createPreview(options: PreviewOptions) {
48
56
  const loadModule = options.loadModule ?? importFromBlob;
49
57
  let api: SquiffyApi | undefined;
58
+ // The story's panels (squiffy.json's "panels"), shown as on the published page: their buttons
59
+ // in a bar above the story, and side panels beside it if the preview is wide enough
60
+ let panels: Panels | undefined;
61
+ let panelsJson = "";
62
+ let panelButtons: HTMLElement | undefined;
63
+ // The Settings button (#452), after the panels' buttons, for a story with "settings"
64
+ let settingsButton: HTMLButtonElement | undefined;
65
+ let settingsDialog: SettingsDialog | undefined;
66
+ let panelSide: HTMLElement | undefined;
67
+ // The runtime puts the story's classes (@class, {{addclass}}, settings such as
68
+ // setting-textSize-Large) on the element it's given, which here is inside the header and side
69
+ // panels' layout. They're copied to the preview's own element, which is #squiffy as on a
70
+ // published page, so stylesheets with rules such as div#squiffy.dark work here too.
71
+ let classObserver: MutationObserver | undefined;
72
+ let mirroredClasses: string[] = [];
73
+ // The host's mute button (#444), which carries on to the next story loaded
74
+ let muted = false;
75
+ let usesSound = false;
50
76
  // Each load gets a new number, so a slow load that's been replaced doesn't start
51
77
  let loadCount = 0;
52
78
  const assetUrls = new Map<string, string>();
53
79
  const objectUrls: string[] = [];
54
- const injected: Element[] = [];
80
+ // The story's own stylesheets and scripts
81
+ let styles: HTMLStyleElement[] = [];
82
+ // Their text as the host sent it, before withAssetUrls
83
+ let styleTexts: string[] = [];
84
+ let scripts: HTMLScriptElement[] = [];
85
+ // Sets the theme. It's added before any of the story's own stylesheets, so they can override it.
86
+ const themeStyle = document.createElement("style");
87
+ document.head.appendChild(themeStyle);
55
88
 
56
89
  const send = (message: PreviewMessage) => {
57
90
  try {
@@ -63,6 +96,19 @@ export function createPreview(options: PreviewOptions) {
63
96
  }
64
97
  };
65
98
 
99
+ // Whether the story's stylesheets set color-scheme themselves: if they do, the story looks the
100
+ // same whichever theme the preview is set to
101
+ function themeIsFixed(): boolean {
102
+ const theme = themeStyle.textContent;
103
+ const schemeFor = (scheme: string) => {
104
+ themeStyle.textContent = `:root { color-scheme: ${scheme}; }`;
105
+ return getComputedStyle(document.documentElement).getPropertyValue("color-scheme");
106
+ };
107
+ const fixed = schemeFor("light") == schemeFor("dark");
108
+ themeStyle.textContent = theme;
109
+ return fixed;
110
+ }
111
+
66
112
  const resolveAssetUrl = (path: string) => assetUrls.get(normalisePath(path)) ?? path;
67
113
 
68
114
  function setAssets(assets: PreviewAssets) {
@@ -77,16 +123,41 @@ export function createPreview(options: PreviewOptions) {
77
123
  objectUrls.push(url);
78
124
  assetUrls.set(normalisePath(path), url);
79
125
  }
126
+ // The stylesheets' url()s, such as their fonts, may now be different files
127
+ styles.forEach((style, i) => { style.textContent = withAssetUrls(styleTexts[i]); });
80
128
  }
81
129
 
82
- async function addStoryFiles(story: PreviewStory) {
83
- for (const element of injected.splice(0)) element.remove();
84
- for (const css of story.css ?? []) {
130
+ // A stylesheet with its url()s, which are paths from the story's folder, swapped for the
131
+ // assets' URLs. One that isn't an asset is left as it is.
132
+ const withAssetUrls = (css: string) => css.replace(CSS_URL, (match, double?: string, single?: string, bare?: string) => {
133
+ const url = (double ?? single ?? bare ?? "").trim();
134
+ const resolved = isRelativeUrl(url) ? assetUrls.get(normalisePath(url)) : undefined;
135
+ return resolved ? `url("${resolved}")` : match;
136
+ });
137
+
138
+ // Replaces the story's stylesheets, where the old ones were, so they stay before its scripts
139
+ // (which may add styles of their own). Returns false if they haven't changed.
140
+ function setStyles(css: string[]): boolean {
141
+ if (css.length == styleTexts.length && css.every((text, i) => styleTexts[i] == text)) return false;
142
+ const before = styles[0] ?? scripts[0] ?? null;
143
+ const added = css.map(text => {
85
144
  const style = document.createElement("style");
86
- style.textContent = css;
87
- document.head.appendChild(style);
88
- injected.push(style);
89
- }
145
+ style.textContent = withAssetUrls(text);
146
+ document.head.insertBefore(style, before);
147
+ return style;
148
+ });
149
+ for (const style of styles) style.remove();
150
+ styles = added;
151
+ styleTexts = [...css];
152
+ return true;
153
+ }
154
+
155
+ async function addStoryFiles(story: PreviewStory) {
156
+ for (const element of [...styles, ...scripts]) element.remove();
157
+ styles = [];
158
+ styleTexts = [];
159
+ scripts = [];
160
+ setStyles(story.css ?? []);
90
161
  for (const js of story.scripts ?? []) {
91
162
  const script = document.createElement("script");
92
163
  const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
@@ -96,21 +167,48 @@ export function createPreview(options: PreviewOptions) {
96
167
  document.head.appendChild(script);
97
168
  });
98
169
  URL.revokeObjectURL(url);
99
- injected.push(script);
170
+ scripts.push(script);
171
+ }
172
+ }
173
+
174
+ function mirrorClasses(from: HTMLElement | undefined) {
175
+ const classes = from ? [...from.classList].filter(c => c != "squiffy-preview-story") : [];
176
+ for (const c of mirroredClasses) {
177
+ if (!classes.includes(c)) options.element.classList.remove(c);
100
178
  }
179
+ for (const c of classes) options.element.classList.add(c);
180
+ mirroredClasses = classes;
101
181
  }
102
182
 
103
183
  async function load(message: Extract<HostMessage, { type: "load" }>) {
104
184
  const thisLoad = ++loadCount;
185
+ api?.dispose();
105
186
  api = undefined;
187
+ classObserver?.disconnect();
188
+ classObserver = undefined;
189
+ mirrorClasses(undefined);
106
190
  options.element.innerHTML = "";
107
191
  await addStoryFiles(message.story);
108
192
  const { story } = await loadModule(message.story.js);
109
193
  if (thisLoad != loadCount) return;
194
+ send({ type: "themeFixed", fixed: themeIsFixed() });
110
195
 
196
+ panels?.dispose();
197
+ panels = undefined;
198
+ panelsJson = "";
199
+ settingsDialog?.element.remove();
200
+ settingsDialog = undefined;
201
+ settingsButton = undefined;
202
+ panelButtons = document.createElement("div");
203
+ panelButtons.className = "squiffy-preview-header";
204
+ panelSide = document.createElement("div");
205
+ panelSide.className = "squiffy-preview-body";
111
206
  const container = document.createElement("div");
112
207
  container.className = "squiffy-preview-story";
113
- options.element.appendChild(container);
208
+ panelSide.appendChild(container);
209
+ options.element.append(panelButtons, panelSide);
210
+ classObserver = new MutationObserver(() => mirrorClasses(container));
211
+ classObserver.observe(container, { attributes: true, attributeFilter: ["class"] });
114
212
 
115
213
  const newApi = await init({
116
214
  element: container,
@@ -128,12 +226,62 @@ export function createPreview(options: PreviewOptions) {
128
226
  newApi.on("navigated", e => {
129
227
  if (thisLoad == loadCount) send({ type: "navigated", ...e });
130
228
  });
229
+ newApi.on("sound", () => {
230
+ if (thisLoad == loadCount && !usesSound) {
231
+ usesSound = true;
232
+ send({ type: "usesSound", usesSound });
233
+ }
234
+ });
235
+ newApi.setMuted(muted);
236
+ usesSound = newApi.usesSound();
237
+ send({ type: "usesSound", usesSound });
131
238
  api = newApi;
239
+ setPanels(story.panels);
240
+ setSettingsButton(story.settings);
132
241
  send({ type: "canGoBackChanged", canGoBack: false });
133
242
  await newApi.begin(message.startAt);
243
+ // Now, rather than waiting for the observer, so they're there when the host hears it's loaded
244
+ if (thisLoad == loadCount) mirrorClasses(container);
134
245
  if (thisLoad == loadCount) send({ type: "loaded" });
135
246
  }
136
247
 
248
+ // Shows the story's panels, or shows them again if they've changed
249
+ function setPanels(list: Panel[] | undefined) {
250
+ const json = JSON.stringify(list ?? []);
251
+ if (!api || !panelButtons || json == panelsJson) return;
252
+ panelsJson = json;
253
+ panels?.dispose();
254
+ panels = list?.length ? createPanels(api, { panels: list, buttons: panelButtons, side: panelSide }) : undefined;
255
+ }
256
+
257
+ // Shows the Settings button if the story has settings
258
+ function setSettingsButton(list: PlayerSetting[] | undefined) {
259
+ if (!api || !panelButtons) return;
260
+ if (!list?.length) {
261
+ settingsButton?.remove();
262
+ settingsButton = undefined;
263
+ return;
264
+ }
265
+ if (settingsButton) {
266
+ panelButtons.appendChild(settingsButton);
267
+ return;
268
+ }
269
+ const button = document.createElement("button");
270
+ button.type = "button";
271
+ button.className = "squiffy-header-button squiffy-settings-button";
272
+ button.title = "Settings";
273
+ button.setAttribute("aria-label", "Settings");
274
+ button.setAttribute("aria-haspopup", "dialog");
275
+ button.innerHTML = SETTINGS_ICON;
276
+ button.addEventListener("click", () => {
277
+ if (!api) return;
278
+ settingsDialog ??= createSettingsDialog(api);
279
+ settingsDialog.open();
280
+ });
281
+ panelButtons.appendChild(button);
282
+ settingsButton = button;
283
+ }
284
+
137
285
  async function receive(message: HostMessage) {
138
286
  try {
139
287
  switch (message.type) {
@@ -141,7 +289,15 @@ export function createPreview(options: PreviewOptions) {
141
289
  await load(message);
142
290
  break;
143
291
  case "update":
144
- if (api) api.update((await loadModule(message.js)).story);
292
+ if (!api) break;
293
+ // A stylesheet can change whether the story sets its own color-scheme
294
+ if (message.css && setStyles(message.css)) send({ type: "themeFixed", fixed: themeIsFixed() });
295
+ {
296
+ const { story } = await loadModule(message.js);
297
+ api.update(story);
298
+ setPanels(story.panels);
299
+ setSettingsButton(story.settings);
300
+ }
145
301
  break;
146
302
  case "restart":
147
303
  api?.restart();
@@ -152,6 +308,16 @@ export function createPreview(options: PreviewOptions) {
152
308
  case "assets":
153
309
  setAssets(message.assets);
154
310
  break;
311
+ case "muted":
312
+ muted = message.muted;
313
+ api?.setMuted(muted);
314
+ break;
315
+ case "reload":
316
+ options.reload?.();
317
+ break;
318
+ case "theme":
319
+ themeStyle.textContent = message.theme == "system" ? "" : `:root { color-scheme: ${message.theme}; }`;
320
+ break;
155
321
  }
156
322
  }
157
323
  catch (error) {
@@ -0,0 +1,159 @@
1
+ import type { SavedGame } from "./types.js";
2
+
3
+ // A player's saved games for one story, which the Saved games dialog lists. Each has an id, and
4
+ // an optional name the player gave it.
5
+ export interface SaveSlot {
6
+ id: number;
7
+ name: string | null;
8
+ save: SavedGame;
9
+ }
10
+
11
+ export interface SaveSlots {
12
+ // Newest first
13
+ list(): Promise<SaveSlot[]>;
14
+ get(id: number): Promise<SaveSlot | null>;
15
+ // Saves to a new slot
16
+ add(save: SavedGame, name: string | null): Promise<SaveSlot>;
17
+ // Replaces a slot's save, keeping its name
18
+ overwrite(id: number, save: SavedGame): Promise<void>;
19
+ // A null or empty name makes the save unnamed again
20
+ rename(id: number, name: string | null): Promise<void>;
21
+ delete(id: number): Promise<void>;
22
+ }
23
+
24
+ interface SlotRecord {
25
+ key: string;
26
+ id: number;
27
+ name: string | null;
28
+ save: SavedGame;
29
+ }
30
+
31
+ const DATABASE = "squiffy-saves";
32
+ const STORE = "saves";
33
+
34
+ const newestFirst = (a: SaveSlot, b: SaveSlot) =>
35
+ b.save.savedAt.localeCompare(a.save.savedAt) || b.id - a.id;
36
+
37
+ const toSlot = (record: SlotRecord): SaveSlot => ({ id: record.id, name: record.name, save: record.save });
38
+
39
+ const cleanName = (name: string | null) => name?.trim() || null;
40
+
41
+ function request<T>(req: IDBRequest<T>): Promise<T> {
42
+ return new Promise((resolve, reject) => {
43
+ req.onsuccess = () => resolve(req.result);
44
+ req.onerror = () => reject(req.error);
45
+ });
46
+ }
47
+
48
+ function done(tx: IDBTransaction): Promise<void> {
49
+ return new Promise((resolve, reject) => {
50
+ tx.oncomplete = () => resolve();
51
+ tx.onerror = () => reject(tx.error);
52
+ tx.onabort = () => reject(tx.error);
53
+ });
54
+ }
55
+
56
+ // Saved games kept in the browser's IndexedDB, under key, so each story has its own. IndexedDB
57
+ // rather than localStorage, as a save has all the text on screen, and localStorage only holds a
58
+ // few megabytes for everything on the site.
59
+ export function indexedDbSaveSlots(key: string): SaveSlots {
60
+ let database: Promise<IDBDatabase> | undefined;
61
+
62
+ const open = () => database ??= new Promise((resolve, reject) => {
63
+ const req = indexedDB.open(DATABASE, 1);
64
+ req.onupgradeneeded = () => {
65
+ req.result.createObjectStore(STORE, { keyPath: ["key", "id"] });
66
+ };
67
+ req.onsuccess = () => resolve(req.result);
68
+ req.onerror = () => {
69
+ database = undefined;
70
+ reject(req.error);
71
+ };
72
+ });
73
+
74
+ const range = () => IDBKeyRange.bound([key, -Infinity], [key, Infinity]);
75
+
76
+ const transaction = async (mode: IDBTransactionMode) =>
77
+ (await open()).transaction(STORE, mode).objectStore(STORE);
78
+
79
+ const get = async (id: number): Promise<SlotRecord | undefined> =>
80
+ request((await transaction("readonly")).get([key, id]) as IDBRequest<SlotRecord | undefined>);
81
+
82
+ const put = async (record: SlotRecord) => {
83
+ const store = await transaction("readwrite");
84
+ store.put(record);
85
+ await done(store.transaction);
86
+ };
87
+
88
+ // Asks the browser not to clear the saves when it's short of space. It may say no.
89
+ let persistRequested = false;
90
+ const requestPersistence = () => {
91
+ if (persistRequested) return;
92
+ persistRequested = true;
93
+ navigator.storage?.persist?.().catch(() => {});
94
+ };
95
+
96
+ return {
97
+ async list() {
98
+ const records = await request((await transaction("readonly")).getAll(range()) as IDBRequest<SlotRecord[]>);
99
+ return records.map(toSlot).sort(newestFirst);
100
+ },
101
+ async get(id) {
102
+ const record = await get(id);
103
+ return record ? toSlot(record) : null;
104
+ },
105
+ async add(save, name) {
106
+ const keys = await request((await transaction("readonly")).getAllKeys(range()));
107
+ const id = keys.reduce<number>((max, k) => Math.max(max, (k as [string, number])[1]), 0) + 1;
108
+ const record = { key, id, name: cleanName(name), save };
109
+ await put(record);
110
+ requestPersistence();
111
+ return toSlot(record);
112
+ },
113
+ async overwrite(id, save) {
114
+ const record = await get(id);
115
+ await put({ key, id, name: record?.name ?? null, save });
116
+ },
117
+ async rename(id, name) {
118
+ const record = await get(id);
119
+ if (record) await put({ ...record, name: cleanName(name) });
120
+ },
121
+ async delete(id) {
122
+ const store = await transaction("readwrite");
123
+ store.delete([key, id]);
124
+ await done(store.transaction);
125
+ },
126
+ };
127
+ }
128
+
129
+ // Saved games kept in memory, which are gone when the page is: for tests, and somewhere to save
130
+ // when IndexedDB isn't there
131
+ export function memorySaveSlots(): SaveSlots {
132
+ const slots = new Map<number, SaveSlot>();
133
+ let nextId = 1;
134
+ const copy = (slot: SaveSlot): SaveSlot => structuredClone(slot);
135
+ return {
136
+ async list() {
137
+ return [...slots.values()].map(copy).sort(newestFirst);
138
+ },
139
+ async get(id) {
140
+ const slot = slots.get(id);
141
+ return slot ? copy(slot) : null;
142
+ },
143
+ async add(save, name) {
144
+ const slot = { id: nextId++, name: cleanName(name), save: structuredClone(save) };
145
+ slots.set(slot.id, slot);
146
+ return copy(slot);
147
+ },
148
+ async overwrite(id, save) {
149
+ slots.set(id, { id, name: slots.get(id)?.name ?? null, save: structuredClone(save) });
150
+ },
151
+ async rename(id, name) {
152
+ const slot = slots.get(id);
153
+ if (slot) slot.name = cleanName(name);
154
+ },
155
+ async delete(id) {
156
+ slots.delete(id);
157
+ },
158
+ };
159
+ }
@@ -0,0 +1,199 @@
1
+ import { expect, test, beforeEach, afterEach, beforeAll, vi } from "vitest";
2
+ import globalJsdom from "global-jsdom";
3
+ import { init } from "./squiffy.runtime.js";
4
+ import { compile as squiffyCompile } from "squiffy-compiler";
5
+ import type { SavedGame } from "./types.js";
6
+
7
+ beforeAll(() => {
8
+ vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
9
+ });
10
+
11
+ let cleanup: () => void;
12
+
13
+ beforeEach(() => {
14
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
15
+ });
16
+
17
+ afterEach(() => {
18
+ localStorage.clear();
19
+ cleanup();
20
+ });
21
+
22
+ const script = `[[a]]:
23
+ @set score = 1
24
+ Welcome to the start. Go to [[b]] or read [more].
25
+
26
+ [more]:
27
+ More text.
28
+
29
+ [[b]]:
30
+ @set score = 2
31
+ You are in b. Go to [[c]].
32
+
33
+ [[c]]:
34
+ @set score = 3
35
+ You are in c.`;
36
+
37
+ const compileStory = async (text: string, projectId?: string) => {
38
+ const result = await squiffyCompile({ script: text, projectId });
39
+ if (!result.success) throw new Error("Compile failed");
40
+ const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
41
+ return { js: js as any, ...result.output.story };
42
+ };
43
+
44
+ const start = async (options: { projectId?: string; persist?: boolean; text?: string } = {}) => {
45
+ const element = document.getElementById("squiffy")!;
46
+ element.innerHTML = "";
47
+ const story = await compileStory(options.text ?? script, options.projectId);
48
+ const api = await init({ element, story, persist: options.persist ?? false });
49
+ await api.begin();
50
+ return { api, element };
51
+ };
52
+
53
+ const click = async (api: Awaited<ReturnType<typeof start>>["api"], element: HTMLElement, text: string) => {
54
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
55
+ .filter(l => l.textContent === text && !l.classList.contains("disabled")).pop();
56
+ if (!link) throw new Error(`No link "${text}"`);
57
+ expect(await api.clickLink(link)).toBe(true);
58
+ };
59
+
60
+ test("getSave gives where the player is, what they were reading, and every attribute", async () => {
61
+ const { api, element } = await start({ projectId: "story-1" });
62
+ await click(api, element, "b");
63
+ const save = api.getSave();
64
+ expect(save.format).toBe("squiffy-save");
65
+ expect(save.version).toBe(1);
66
+ expect(save.storyId).toBe("story-1");
67
+ expect(save.section).toBe("b");
68
+ expect(save.passage).toBeNull();
69
+ expect(save.summary).toBe("You are in b. Go to c.");
70
+ expect(save.state.score).toBe(2);
71
+ expect(save.state._output).toContain("You are in b.");
72
+ expect(new Date(save.savedAt).getTime()).not.toBeNaN();
73
+ // It's JSON
74
+ expect(JSON.parse(JSON.stringify(save))).toEqual(save);
75
+ });
76
+
77
+ test("the summary is a heading the section starts with, or its paragraphs with spaces between", async () => {
78
+ const withHeading = await start({ text: "# Day One\n\nYou start work." });
79
+ expect(withHeading.api.getSave().summary).toBe("Day One");
80
+ const paragraphs = await start({ text: "First.\n\nSecond.<br>Third." });
81
+ expect(paragraphs.api.getSave().summary).toBe("First. Second. Third.");
82
+ });
83
+
84
+ test("a long summary is cut at a word", async () => {
85
+ const long = "word ".repeat(40).trim();
86
+ const { api } = await start({ text: long });
87
+ const summary = api.getSave().summary;
88
+ expect(summary.endsWith("word…")).toBe(true);
89
+ expect(summary.length).toBeLessThanOrEqual(101);
90
+ });
91
+
92
+ test("loadSave puts the game back as it was, and Back still works", async () => {
93
+ const { api, element } = await start();
94
+ await click(api, element, "b");
95
+ const save = JSON.parse(JSON.stringify(api.getSave())) as SavedGame;
96
+
97
+ await click(api, element, "c");
98
+ expect(api.get("score")).toBe(3);
99
+
100
+ const navigated = vi.fn();
101
+ const canGoBackChanged = vi.fn();
102
+ api.on("navigated", navigated);
103
+ api.on("canGoBackChanged", canGoBackChanged);
104
+ expect(await api.loadSave(save)).toEqual({ success: true });
105
+
106
+ expect(api.get("score")).toBe(2);
107
+ expect(api.get("_section")).toBe("b");
108
+ expect(element.textContent).toContain("You are in b.");
109
+ expect(element.textContent).not.toContain("You are in c.");
110
+ expect(navigated).toHaveBeenCalledWith({ section: "b" });
111
+ expect(canGoBackChanged).toHaveBeenCalledWith({ canGoBack: true });
112
+
113
+ // Carries on from there
114
+ await click(api, element, "c");
115
+ expect(api.get("score")).toBe(3);
116
+
117
+ // And goes back through the loaded game's history
118
+ api.goBack();
119
+ api.goBack();
120
+ expect(api.get("_section")).toBe("a");
121
+ expect(api.get("score")).toBe(1);
122
+ expect(api.canGoBack()).toBe(false);
123
+ });
124
+
125
+ test("loadSave keeps passages", async () => {
126
+ const { api, element } = await start();
127
+ await click(api, element, "more");
128
+ const save = api.getSave();
129
+ expect(save.passage).toBe("more");
130
+ await click(api, element, "b");
131
+
132
+ await api.loadSave(save);
133
+ expect(element.textContent).toContain("More text.");
134
+ expect(api.get("_passage")).toBe("more");
135
+ api.goBack();
136
+ expect(element.textContent).not.toContain("More text.");
137
+ });
138
+
139
+ test("a loaded game replaces the automatic save", async () => {
140
+ const { api, element } = await start({ persist: true });
141
+ await click(api, element, "b");
142
+ const save = api.getSave();
143
+ await click(api, element, "c");
144
+ await api.loadSave(save);
145
+
146
+ // A new page carries on from the loaded game
147
+ const again = await start({ persist: true });
148
+ expect(again.api.get("_section")).toBe("b");
149
+ expect(again.api.get("score")).toBe(2);
150
+ expect(again.element.textContent).not.toContain("You are in c.");
151
+ });
152
+
153
+ test("attributes set after the save are gone once it's loaded", async () => {
154
+ const { api, element } = await start({ persist: true });
155
+ const save = api.getSave();
156
+ api.set("extra", "yes");
157
+ await click(api, element, "b");
158
+ await api.loadSave(save);
159
+ expect(api.get("extra")).toBeNull();
160
+ expect(Object.keys(localStorage).some(key => key.endsWith("-extra"))).toBe(false);
161
+ });
162
+
163
+ test("a save from a different story isn't loaded", async () => {
164
+ const { api, element } = await start({ projectId: "story-1" });
165
+ const save = { ...api.getSave(), storyId: "story-2" };
166
+ await click(api, element, "b");
167
+ expect(await api.loadSave(save)).toEqual({ success: false, error: "wrongStory" });
168
+ expect(api.get("_section")).toBe("b");
169
+ });
170
+
171
+ test("a save from a story with no id, or into one, is loaded", async () => {
172
+ const { api, element } = await start({ projectId: "story-1" });
173
+ const save = { ...api.getSave(), storyId: null };
174
+ await click(api, element, "b");
175
+ expect(await api.loadSave(save)).toEqual({ success: true });
176
+ expect(api.get("_section")).toBe("a");
177
+
178
+ const other = await start();
179
+ expect(await other.api.loadSave({ ...save, storyId: "story-1" })).toEqual({ success: true });
180
+ });
181
+
182
+ test("something that isn't a save isn't loaded", async () => {
183
+ const { api } = await start();
184
+ const save = api.getSave();
185
+ for (const bad of [null, "text", {}, { ...save, format: "other" }, { ...save, version: 2 }, { ...save, state: {} }]) {
186
+ expect(await api.loadSave(bad as any)).toEqual({ success: false, error: "notASave" });
187
+ }
188
+ });
189
+
190
+ test("a save whose section has gone starts the story again, keeping its attributes", async () => {
191
+ const { api, element } = await start();
192
+ await click(api, element, "b");
193
+ const save = api.getSave();
194
+ const changed = await start({ text: "[[a]]:\nNew start. Go to [[z]].\n\n[[z]]:\nZ." });
195
+ expect(await changed.api.loadSave(save)).toEqual({ success: true });
196
+ expect(changed.api.get("_section")).toBe("a");
197
+ expect(changed.element.textContent).toContain("New start.");
198
+ expect(changed.element.textContent).not.toContain("You are in b.");
199
+ });