squiffy-runtime 7.0.0-beta.5 → 7.0.0-beta.6

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 (45) hide show
  1. package/dist/events.d.ts +1 -0
  2. package/dist/panels.d.ts +14 -0
  3. package/dist/panels.test.d.ts +1 -0
  4. package/dist/preview-host.d.ts +2 -1
  5. package/dist/preview-host.js +4 -1
  6. package/dist/preview-host.js.map +2 -2
  7. package/dist/preview-html.js +1 -1
  8. package/dist/preview-protocol.d.ts +4 -0
  9. package/dist/saveSlots.d.ts +16 -0
  10. package/dist/saves.test.d.ts +1 -0
  11. package/dist/savesDialog.d.ts +43 -0
  12. package/dist/savesDialog.test.d.ts +1 -0
  13. package/dist/squiffy.page.css +46 -22
  14. package/dist/squiffy.preview.html +604 -108
  15. package/dist/squiffy.runtime.css +468 -8
  16. package/dist/squiffy.runtime.d.ts +9 -1
  17. package/dist/squiffy.runtime.global.js +113 -72
  18. package/dist/squiffy.runtime.global.js.map +1 -1
  19. package/dist/squiffy.runtime.js +4154 -3534
  20. package/dist/squiffy.runtime.js.map +1 -1
  21. package/dist/state.d.ts +2 -0
  22. package/dist/textProcessor.d.ts +1 -0
  23. package/dist/types.d.ts +30 -0
  24. package/package.json +3 -3
  25. package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
  26. package/src/events.ts +1 -0
  27. package/src/panels.test.ts +201 -0
  28. package/src/panels.ts +187 -0
  29. package/src/preview-host.test.ts +5 -1
  30. package/src/preview-host.ts +9 -3
  31. package/src/preview-protocol.ts +6 -2
  32. package/src/preview.test.ts +68 -3
  33. package/src/preview.ts +74 -13
  34. package/src/saveSlots.ts +159 -0
  35. package/src/saves.test.ts +199 -0
  36. package/src/savesDialog.test.ts +290 -0
  37. package/src/savesDialog.ts +499 -0
  38. package/src/squiffy.page.css +46 -22
  39. package/src/squiffy.runtime.css +468 -8
  40. package/src/squiffy.runtime.test.ts +375 -4
  41. package/src/squiffy.runtime.ts +227 -10
  42. package/src/state.ts +18 -4
  43. package/src/textProcessor.ts +50 -9
  44. package/src/types.ts +54 -1
  45. package/vite.preview.config.ts +7 -0
@@ -31,10 +31,12 @@ describe("preview host", () => {
31
31
  ]);
32
32
 
33
33
  host.update("x");
34
+ host.update("y", ["body { color: red; }"]);
34
35
  host.restart();
35
36
  host.back();
36
37
  expect(sent.slice(2)).toEqual([
37
38
  { channel: PREVIEW_CHANNEL, type: "update", js: "x" },
39
+ { channel: PREVIEW_CHANNEL, type: "update", js: "y", css: ["body { color: red; }"] },
38
40
  { channel: PREVIEW_CHANNEL, type: "restart" },
39
41
  { channel: PREVIEW_CHANNEL, type: "back" },
40
42
  ]);
@@ -61,7 +63,7 @@ describe("preview host", () => {
61
63
  const { channel, receive } = fakeChannel();
62
64
  const handlers = {
63
65
  onReady: vi.fn(), onLoaded: vi.fn(), onAttributeSet: vi.fn(), onCanGoBackChanged: vi.fn(),
64
- onNavigated: vi.fn(), onRuntimeError: vi.fn(),
66
+ onNavigated: vi.fn(), onThemeFixed: vi.fn(), onRuntimeError: vi.fn(),
65
67
  };
66
68
  const host = createPreviewHost(channel, handlers);
67
69
  receive({ type: "navigated", section: "not ours" });
@@ -73,6 +75,7 @@ describe("preview host", () => {
73
75
  { type: "attributeSet", name: "score", value: 2 },
74
76
  { type: "canGoBackChanged", canGoBack: true },
75
77
  { type: "navigated", section: "s", passage: "p" },
78
+ { type: "themeFixed", fixed: true },
76
79
  { type: "runtimeError", message: "oops", stack: "at x" },
77
80
  ]) {
78
81
  receive({ channel: PREVIEW_CHANNEL, ...message });
@@ -83,6 +86,7 @@ describe("preview host", () => {
83
86
  expect(handlers.onCanGoBackChanged).toHaveBeenCalledWith(true);
84
87
  expect(handlers.onNavigated).toHaveBeenCalledOnce();
85
88
  expect(handlers.onNavigated).toHaveBeenCalledWith("s", "p");
89
+ expect(handlers.onThemeFixed).toHaveBeenCalledWith(true);
86
90
  expect(handlers.onRuntimeError).toHaveBeenCalledWith("oops", "at x");
87
91
 
88
92
  host.dispose();
@@ -31,6 +31,8 @@ export interface PreviewHandlers {
31
31
  onAttributeSet?(name: string, value: unknown): void;
32
32
  onCanGoBackChanged?(canGoBack: boolean): void;
33
33
  onNavigated?(section: string, passage?: string): void;
34
+ // Whether the story's own CSS sets its color-scheme, so setTheme() makes no difference
35
+ onThemeFixed?(fixed: boolean): void;
34
36
  onRuntimeError?(message: string, stack?: string): void;
35
37
  }
36
38
 
@@ -39,8 +41,9 @@ export interface PreviewHost {
39
41
  readonly ready: Promise<void>;
40
42
  // Starts a story, replacing any that's running
41
43
  load(story: PreviewStory, options?: { startAt?: StartAt }): void;
42
- // Hot-updates the running story, keeping its state
43
- update(js: string): void;
44
+ // Hot-updates the running story, keeping its state. css, if given, replaces the story's own
45
+ // stylesheets; its scripts only change with load().
46
+ update(js: string, css?: string[]): void;
44
47
  restart(): void;
45
48
  back(): void;
46
49
  // Sets the assets the story can use. Send these before load().
@@ -112,6 +115,9 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
112
115
  case "navigated":
113
116
  handlers.onNavigated?.(message.section, message.passage);
114
117
  break;
118
+ case "themeFixed":
119
+ handlers.onThemeFixed?.(message.fixed);
120
+ break;
115
121
  case "runtimeError":
116
122
  handlers.onRuntimeError?.(message.message, message.stack);
117
123
  break;
@@ -121,7 +127,7 @@ export function createPreviewHost(channel: PreviewChannel, handlers: PreviewHand
121
127
  return {
122
128
  ready,
123
129
  load: (story, options = {}) => send({ type: "load", story, ...(options.startAt ? { startAt: options.startAt } : {}) }),
124
- update: js => send({ type: "update", js }),
130
+ update: (js, css) => send({ type: "update", js, ...(css ? { css } : {}) }),
125
131
  restart: () => send({ type: "restart" }),
126
132
  back: () => send({ type: "back" }),
127
133
  setAssets: assets => send({ type: "assets", assets }),
@@ -33,8 +33,9 @@ export type PreviewTheme = "light" | "dark" | "system";
33
33
  export type HostMessage =
34
34
  // Starts a story, replacing any that's running. Send assets first.
35
35
  | { type: "load"; story: PreviewStory; startAt?: StartAt }
36
- // Hot-updates the running story, keeping its state
37
- | { type: "update"; js: string }
36
+ // Hot-updates the running story, keeping its state. css, if given, replaces the story's own
37
+ // stylesheets. Its scripts can't be replaced in a running story: that needs a load.
38
+ | { type: "update"; js: string; css?: string[] }
38
39
  | { type: "restart" }
39
40
  | { type: "back" }
40
41
  // Replaces the assets the story can use
@@ -48,6 +49,9 @@ export type PreviewMessage =
48
49
  | { type: "ready" }
49
50
  // A story from a load message has started
50
51
  | { type: "loaded" }
52
+ // Whether the story's own CSS sets its color-scheme, e.g. ":root { color-scheme: light; }",
53
+ // so the theme message makes no difference. Sent each time a story is loaded, before "loaded".
54
+ | { type: "themeFixed"; fixed: boolean }
51
55
  // An attribute was set. Internal attributes, whose names start with "_", aren't sent.
52
56
  | { type: "attributeSet"; name: string; value: unknown }
53
57
  | { type: "canGoBackChanged"; canGoBack: boolean }
@@ -3,7 +3,7 @@ import globalJsdom from "global-jsdom";
3
3
  import { compile } from "squiffy-compiler";
4
4
  import { createPreview } from "./preview.js";
5
5
  import type { PreviewMessage } from "./preview-protocol.js";
6
- import type { Story } from "./types.js";
6
+ import type { Panel, Story } from "./types.js";
7
7
 
8
8
  beforeAll(() => {
9
9
  vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
@@ -31,8 +31,8 @@ afterEach(() => {
31
31
  });
32
32
 
33
33
  // The compiled story module, as a host would send it
34
- const compileJs = async (script: string) => {
35
- const result = await compile({ script });
34
+ const compileJs = async (script: string, panels?: Panel[]) => {
35
+ const result = await compile({ script, panels });
36
36
  if (!result.success) throw new Error("Compile failed");
37
37
  return result.getJs();
38
38
  };
@@ -70,6 +70,7 @@ describe("preview", () => {
70
70
 
71
71
  expect(element.textContent).toContain("Welcome.");
72
72
  expect(messages).toEqual([
73
+ { type: "themeFixed", fixed: false },
73
74
  { type: "canGoBackChanged", canGoBack: false },
74
75
  // The story-wide turn count (#377), which isn't internal, so it's reported
75
76
  { type: "attributeSet", name: "turns", value: 0 },
@@ -83,6 +84,8 @@ describe("preview", () => {
83
84
  await vi.waitFor(() => expect(messages.some(m => m.type == "navigated")).toBe(true));
84
85
  expect(messages).toEqual([
85
86
  { type: "attributeSet", name: "turns", value: 1 },
87
+ // Where the player was before (#56), which isn't internal either
88
+ { type: "attributeSet", name: "previous", value: "start" },
86
89
  { type: "attributeSet", name: "looked", value: true },
87
90
  { type: "canGoBackChanged", canGoBack: true },
88
91
  { type: "navigated", section: "start", passage: "look" },
@@ -142,6 +145,35 @@ describe("preview", () => {
142
145
  expect(element.textContent).toContain("Welcome.");
143
146
  });
144
147
 
148
+ test("hot updates replace the story's stylesheets, keeping its state", async () => {
149
+ const { preview, element, messages } = setUp();
150
+ const js = await compileJs(script);
151
+ const styles = () => [...document.head.querySelectorAll("style")].map(s => s.textContent);
152
+ const fixed = () => messages.filter(m => m.type == "themeFixed");
153
+ await preview.receive({ type: "load", story: { js, css: ["body { color: red; }", "p { margin: 0; }"] } });
154
+ element.querySelector<HTMLElement>("a[data-section='cellar']")!.click();
155
+ await vi.waitFor(() => expect(element.textContent).toContain("It's dark"));
156
+
157
+ messages.length = 0;
158
+ await preview.receive({ type: "update", js, css: ["body { color: blue; }"] });
159
+ // After the preview's own (empty) theme style
160
+ expect(styles()).toEqual(["", "body { color: blue; }"]);
161
+ expect(element.textContent).toContain("It's dark");
162
+ expect(fixed()).toEqual([{ type: "themeFixed", fixed: false }]);
163
+
164
+ // A stylesheet that sets color-scheme
165
+ messages.length = 0;
166
+ await preview.receive({ type: "update", js, css: [":root { color-scheme: light; }"] });
167
+ expect(fixed()).toEqual([{ type: "themeFixed", fixed: true }]);
168
+
169
+ // The same stylesheets again, or none given, change nothing
170
+ messages.length = 0;
171
+ await preview.receive({ type: "update", js, css: [":root { color-scheme: light; }"] });
172
+ await preview.receive({ type: "update", js });
173
+ expect(styles()).toEqual(["", ":root { color-scheme: light; }"]);
174
+ expect(fixed()).toEqual([]);
175
+ });
176
+
145
177
  test("adds the story's stylesheets, replacing the previous story's", async () => {
146
178
  const { preview } = setUp();
147
179
  const js = await compileJs(script);
@@ -163,6 +195,39 @@ describe("preview", () => {
163
195
  expect(styles()[0]).toBe("");
164
196
  });
165
197
 
198
+ test("says whether the story's stylesheets set its color-scheme", async () => {
199
+ const { preview, messages } = setUp();
200
+ const js = await compileJs(script);
201
+ const fixed = () => messages.filter(m => m.type == "themeFixed");
202
+
203
+ await preview.receive({ type: "theme", theme: "dark" });
204
+ await preview.receive({ type: "load", story: { js, css: ["body { color: red; }"] } });
205
+ expect(fixed()).toEqual([{ type: "themeFixed", fixed: false }]);
206
+
207
+ messages.length = 0;
208
+ await preview.receive({ type: "load", story: { js, css: [":root { color-scheme: light; }"] } });
209
+ expect(fixed()).toEqual([{ type: "themeFixed", fixed: true }]);
210
+ // Finding out doesn't change the theme the host set
211
+ expect(document.head.querySelector("style")!.textContent).toBe(":root { color-scheme: dark; }");
212
+ });
213
+
214
+ test("shows the story's panels, and shows them again when they change", async () => {
215
+ const { preview, element } = setUp();
216
+ const panelScript = "[[]]:\n\n[status]:\nScore: {{score}}\n\n" + script;
217
+ await preview.receive({ type: "load", story: { js: await compileJs(panelScript, [{ passage: "status", label: "Status", position: "side" }]) } });
218
+ expect(element.querySelector(".squiffy-preview-header button.squiffy-panel-button")!.textContent).toBe("Status");
219
+ expect(element.querySelector(".squiffy-preview-body > aside section")!.innerHTML).toBe("<p>Score: 1</p>");
220
+
221
+ await preview.receive({ type: "update", js: await compileJs(panelScript, [{ passage: "status", label: "Score" }]) });
222
+ expect(element.querySelector("aside")).toBeNull();
223
+ expect([...element.querySelectorAll("button.squiffy-panel-button")].map(b => b.textContent)).toEqual(["Score"]);
224
+
225
+ // A new story has no panels left over
226
+ await preview.receive({ type: "load", story: { js: await compileJs(script) } });
227
+ expect(element.querySelector("button.squiffy-panel-button")).toBeNull();
228
+ expect(document.querySelectorAll("dialog.squiffy-panel-dialog")).toHaveLength(0);
229
+ });
230
+
166
231
  test("reports errors", async () => {
167
232
  const messages: PreviewMessage[] = [];
168
233
  const preview = createPreview({
package/src/preview.ts CHANGED
@@ -2,8 +2,9 @@
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";
5
6
  import type { HostMessage, PreviewAssets, PreviewMessage, PreviewStory } from "./preview-protocol.js";
6
- import type { SquiffyApi, Story } from "./types.js";
7
+ import type { Panel, SquiffyApi, Story } from "./types.js";
7
8
 
8
9
  export interface PreviewOptions {
9
10
  // Where to show the story
@@ -47,11 +48,19 @@ function errorMessage(error: unknown): PreviewMessage {
47
48
  export function createPreview(options: PreviewOptions) {
48
49
  const loadModule = options.loadModule ?? importFromBlob;
49
50
  let api: SquiffyApi | undefined;
51
+ // The story's panels (squiffy.json's "panels"), shown as on the published page: their buttons
52
+ // in a bar above the story, and side panels beside it if the preview is wide enough
53
+ let panels: Panels | undefined;
54
+ let panelsJson = "";
55
+ let panelButtons: HTMLElement | undefined;
56
+ let panelSide: HTMLElement | undefined;
50
57
  // Each load gets a new number, so a slow load that's been replaced doesn't start
51
58
  let loadCount = 0;
52
59
  const assetUrls = new Map<string, string>();
53
60
  const objectUrls: string[] = [];
54
- const injected: Element[] = [];
61
+ // The story's own stylesheets and scripts
62
+ let styles: HTMLStyleElement[] = [];
63
+ let scripts: HTMLScriptElement[] = [];
55
64
  // Sets the theme. It's added before any of the story's own stylesheets, so they can override it.
56
65
  const themeStyle = document.createElement("style");
57
66
  document.head.appendChild(themeStyle);
@@ -66,6 +75,19 @@ export function createPreview(options: PreviewOptions) {
66
75
  }
67
76
  };
68
77
 
78
+ // Whether the story's stylesheets set color-scheme themselves: if they do, the story looks the
79
+ // same whichever theme the preview is set to
80
+ function themeIsFixed(): boolean {
81
+ const theme = themeStyle.textContent;
82
+ const schemeFor = (scheme: string) => {
83
+ themeStyle.textContent = `:root { color-scheme: ${scheme}; }`;
84
+ return getComputedStyle(document.documentElement).getPropertyValue("color-scheme");
85
+ };
86
+ const fixed = schemeFor("light") == schemeFor("dark");
87
+ themeStyle.textContent = theme;
88
+ return fixed;
89
+ }
90
+
69
91
  const resolveAssetUrl = (path: string) => assetUrls.get(normalisePath(path)) ?? path;
70
92
 
71
93
  function setAssets(assets: PreviewAssets) {
@@ -82,14 +104,27 @@ export function createPreview(options: PreviewOptions) {
82
104
  }
83
105
  }
84
106
 
85
- async function addStoryFiles(story: PreviewStory) {
86
- for (const element of injected.splice(0)) element.remove();
87
- for (const css of story.css ?? []) {
107
+ // Replaces the story's stylesheets, where the old ones were, so they stay before its scripts
108
+ // (which may add styles of their own). Returns false if they haven't changed.
109
+ function setStyles(css: string[]): boolean {
110
+ if (css.length == styles.length && css.every((text, i) => styles[i].textContent == text)) return false;
111
+ const before = styles[0] ?? scripts[0] ?? null;
112
+ const added = css.map(text => {
88
113
  const style = document.createElement("style");
89
- style.textContent = css;
90
- document.head.appendChild(style);
91
- injected.push(style);
92
- }
114
+ style.textContent = text;
115
+ document.head.insertBefore(style, before);
116
+ return style;
117
+ });
118
+ for (const style of styles) style.remove();
119
+ styles = added;
120
+ return true;
121
+ }
122
+
123
+ async function addStoryFiles(story: PreviewStory) {
124
+ for (const element of [...styles, ...scripts]) element.remove();
125
+ styles = [];
126
+ scripts = [];
127
+ setStyles(story.css ?? []);
93
128
  for (const js of story.scripts ?? []) {
94
129
  const script = document.createElement("script");
95
130
  const url = URL.createObjectURL(new Blob([js], { type: "text/javascript" }));
@@ -99,7 +134,7 @@ export function createPreview(options: PreviewOptions) {
99
134
  document.head.appendChild(script);
100
135
  });
101
136
  URL.revokeObjectURL(url);
102
- injected.push(script);
137
+ scripts.push(script);
103
138
  }
104
139
  }
105
140
 
@@ -110,10 +145,19 @@ export function createPreview(options: PreviewOptions) {
110
145
  await addStoryFiles(message.story);
111
146
  const { story } = await loadModule(message.story.js);
112
147
  if (thisLoad != loadCount) return;
113
-
148
+ send({ type: "themeFixed", fixed: themeIsFixed() });
149
+
150
+ panels?.dispose();
151
+ panels = undefined;
152
+ panelsJson = "";
153
+ panelButtons = document.createElement("div");
154
+ panelButtons.className = "squiffy-preview-header";
155
+ panelSide = document.createElement("div");
156
+ panelSide.className = "squiffy-preview-body";
114
157
  const container = document.createElement("div");
115
158
  container.className = "squiffy-preview-story";
116
- options.element.appendChild(container);
159
+ panelSide.appendChild(container);
160
+ options.element.append(panelButtons, panelSide);
117
161
 
118
162
  const newApi = await init({
119
163
  element: container,
@@ -132,11 +176,21 @@ export function createPreview(options: PreviewOptions) {
132
176
  if (thisLoad == loadCount) send({ type: "navigated", ...e });
133
177
  });
134
178
  api = newApi;
179
+ setPanels(story.panels);
135
180
  send({ type: "canGoBackChanged", canGoBack: false });
136
181
  await newApi.begin(message.startAt);
137
182
  if (thisLoad == loadCount) send({ type: "loaded" });
138
183
  }
139
184
 
185
+ // Shows the story's panels, or shows them again if they've changed
186
+ function setPanels(list: Panel[] | undefined) {
187
+ const json = JSON.stringify(list ?? []);
188
+ if (!api || !panelButtons || json == panelsJson) return;
189
+ panelsJson = json;
190
+ panels?.dispose();
191
+ panels = list?.length ? createPanels(api, { panels: list, buttons: panelButtons, side: panelSide }) : undefined;
192
+ }
193
+
140
194
  async function receive(message: HostMessage) {
141
195
  try {
142
196
  switch (message.type) {
@@ -144,7 +198,14 @@ export function createPreview(options: PreviewOptions) {
144
198
  await load(message);
145
199
  break;
146
200
  case "update":
147
- if (api) api.update((await loadModule(message.js)).story);
201
+ if (!api) break;
202
+ // A stylesheet can change whether the story sets its own color-scheme
203
+ if (message.css && setStyles(message.css)) send({ type: "themeFixed", fixed: themeIsFixed() });
204
+ {
205
+ const { story } = await loadModule(message.js);
206
+ api.update(story);
207
+ setPanels(story.panels);
208
+ }
148
209
  break;
149
210
  case "restart":
150
211
  api?.restart();
@@ -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
+ }