squiffy-runtime 7.0.0-beta.4 → 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.
- package/dist/events.d.ts +1 -0
- package/dist/panels.d.ts +14 -0
- package/dist/panels.test.d.ts +1 -0
- package/dist/preview-host.d.ts +2 -1
- package/dist/preview-host.js +4 -1
- package/dist/preview-host.js.map +2 -2
- package/dist/preview-html.js +1 -1
- package/dist/preview-protocol.d.ts +4 -0
- package/dist/saveSlots.d.ts +16 -0
- package/dist/saves.test.d.ts +1 -0
- package/dist/savesDialog.d.ts +43 -0
- package/dist/savesDialog.test.d.ts +1 -0
- package/dist/squiffy.page.css +46 -22
- package/dist/squiffy.preview.html +612 -109
- package/dist/squiffy.runtime.css +476 -9
- package/dist/squiffy.runtime.d.ts +9 -1
- package/dist/squiffy.runtime.global.js +113 -72
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +4146 -3460
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +4 -0
- package/dist/textProcessor.d.ts +5 -0
- package/dist/types.d.ts +32 -0
- package/package.json +3 -3
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +21 -21
- package/src/events.ts +1 -0
- package/src/panels.test.ts +201 -0
- package/src/panels.ts +187 -0
- package/src/plugins/plugins.test.ts +42 -0
- package/src/plugins/replaceLabel.ts +6 -2
- package/src/preview-host.test.ts +5 -1
- package/src/preview-host.ts +9 -3
- package/src/preview-protocol.ts +6 -2
- package/src/preview.test.ts +71 -3
- package/src/preview.ts +74 -13
- package/src/saveSlots.ts +159 -0
- package/src/saves.test.ts +199 -0
- package/src/savesDialog.test.ts +290 -0
- package/src/savesDialog.ts +499 -0
- package/src/squiffy.page.css +46 -22
- package/src/squiffy.runtime.css +476 -9
- package/src/squiffy.runtime.test.ts +890 -4
- package/src/squiffy.runtime.ts +322 -17
- package/src/state.ts +34 -4
- package/src/textProcessor.ts +76 -9
- package/src/types.ts +57 -1
- package/vite.preview.config.ts +7 -0
package/src/saveSlots.ts
ADDED
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,290 @@
|
|
|
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 { createSavesDialog, formatSaveTime } from "./savesDialog.js";
|
|
6
|
+
import { memorySaveSlots, type SaveSlots } from "./saveSlots.js";
|
|
7
|
+
import type { SquiffyApi } from "./types.js";
|
|
8
|
+
|
|
9
|
+
beforeAll(() => {
|
|
10
|
+
vi.stubGlobal("crypto", { randomUUID: () => "00000000-0000-0000-0000-000000000000" });
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
let cleanup: () => void;
|
|
14
|
+
|
|
15
|
+
beforeEach(() => {
|
|
16
|
+
cleanup = globalJsdom("<!DOCTYPE html><html><head><title>My Story</title></head><body><div id=\"squiffy\"></div></body></html>");
|
|
17
|
+
// jsdom has no showModal()
|
|
18
|
+
window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", ""); };
|
|
19
|
+
window.HTMLDialogElement.prototype.close = function () { this.removeAttribute("open"); };
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
afterEach(() => {
|
|
23
|
+
localStorage.clear();
|
|
24
|
+
cleanup();
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const script = `[[a]]:
|
|
28
|
+
Welcome to the start. Go to [[b]].
|
|
29
|
+
|
|
30
|
+
[[b]]:
|
|
31
|
+
You are in b. Go to [[c]].
|
|
32
|
+
|
|
33
|
+
[[c]]:
|
|
34
|
+
You are in c.`;
|
|
35
|
+
|
|
36
|
+
const start = async () => {
|
|
37
|
+
const element = document.getElementById("squiffy")!;
|
|
38
|
+
const result = await squiffyCompile({ script, projectId: "story-1" });
|
|
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
|
+
const api = await init({ element, story: { js: js as any, ...result.output.story }, persist: false });
|
|
42
|
+
await api.begin();
|
|
43
|
+
return { api, element };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const click = async (api: SquiffyApi, element: HTMLElement, text: string) => {
|
|
47
|
+
const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
|
|
48
|
+
.filter(l => l.textContent === text && !l.classList.contains("disabled")).pop()!;
|
|
49
|
+
expect(await api.clickLink(link)).toBe(true);
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
// Lets the dialog's async handlers finish
|
|
53
|
+
const settle = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
54
|
+
|
|
55
|
+
const setup = async (slots: SaveSlots = memorySaveSlots()) => {
|
|
56
|
+
const { api, element } = await start();
|
|
57
|
+
const dialog = createSavesDialog(api, { slots });
|
|
58
|
+
await dialog.open();
|
|
59
|
+
const el = dialog.element;
|
|
60
|
+
const q = <T extends HTMLElement = HTMLElement>(selector: string) => el.querySelector<T>(selector)!;
|
|
61
|
+
const rows = () => [...el.querySelectorAll<HTMLElement>(".squiffy-saves-row")].map(row => ({
|
|
62
|
+
title: row.querySelector(".squiffy-saves-title")?.textContent,
|
|
63
|
+
meta: row.querySelector(".squiffy-saves-meta")?.textContent ?? "",
|
|
64
|
+
}));
|
|
65
|
+
const save = async (name = "") => {
|
|
66
|
+
q<HTMLInputElement>("form input").value = name;
|
|
67
|
+
q<HTMLFormElement>("form").requestSubmit();
|
|
68
|
+
await settle();
|
|
69
|
+
};
|
|
70
|
+
const row = (index: number) => el.querySelectorAll<HTMLElement>(".squiffy-saves-row")[index];
|
|
71
|
+
const pick = async (index: number, action: string) => {
|
|
72
|
+
row(index).querySelector<HTMLElement>(`[data-action=${action}]`)!.click();
|
|
73
|
+
await settle();
|
|
74
|
+
};
|
|
75
|
+
const answer = async (yes: boolean) => {
|
|
76
|
+
el.querySelector<HTMLElement>(`.squiffy-saves-confirm [data-answer=${yes ? "yes" : "no"}]`)!.click();
|
|
77
|
+
await settle();
|
|
78
|
+
await settle();
|
|
79
|
+
};
|
|
80
|
+
return { api, element, dialog, el, q, rows, save, row, pick, answer, slots };
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
test("it opens with no saves, on the name box", async () => {
|
|
84
|
+
const { el, q } = await setup();
|
|
85
|
+
expect(el.open).toBe(true);
|
|
86
|
+
expect(q("h2").textContent).toBe("Saved games");
|
|
87
|
+
expect(q(".squiffy-saves-empty").textContent).toBe("No saved games yet.");
|
|
88
|
+
expect(document.activeElement).toBe(q("form input"));
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("saving adds a save, titled by its name or the text the player was reading, newest first", async () => {
|
|
92
|
+
const { api, element, rows, save } = await setup();
|
|
93
|
+
await save();
|
|
94
|
+
await click(api, element, "b");
|
|
95
|
+
await save(" Before c ");
|
|
96
|
+
expect(rows()).toEqual([
|
|
97
|
+
{ title: "Before c", meta: expect.stringMatching(/^Today, .* · You are in b\. Go to c\.$/) },
|
|
98
|
+
{ title: "Welcome to the start. Go to b.", meta: expect.stringMatching(/^Today, /) },
|
|
99
|
+
]);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("loading a save asks first if there's progress since the last save, then closes", async () => {
|
|
103
|
+
const { api, element, el, save, pick, answer } = await setup();
|
|
104
|
+
await save();
|
|
105
|
+
await click(api, element, "b");
|
|
106
|
+
|
|
107
|
+
await pick(0, "load");
|
|
108
|
+
expect(el.querySelector(".squiffy-saves-confirm p")!.textContent)
|
|
109
|
+
.toBe("Load \"Welcome to the start. Go to b.\"? You'll lose anything you've done since you last saved.");
|
|
110
|
+
await answer(false);
|
|
111
|
+
expect(api.get("_section")).toBe("b");
|
|
112
|
+
expect(el.open).toBe(true);
|
|
113
|
+
|
|
114
|
+
await pick(0, "load");
|
|
115
|
+
await answer(true);
|
|
116
|
+
expect(api.get("_section")).toBe("a");
|
|
117
|
+
expect(el.open).toBe(false);
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
test("loading straight after saving doesn't ask", async () => {
|
|
121
|
+
const { api, element, el, save, pick } = await setup();
|
|
122
|
+
await click(api, element, "b");
|
|
123
|
+
await save();
|
|
124
|
+
await pick(0, "load");
|
|
125
|
+
await settle();
|
|
126
|
+
expect(el.querySelector(".squiffy-saves-confirm")).toBeNull();
|
|
127
|
+
expect(el.open).toBe(false);
|
|
128
|
+
expect(api.get("_section")).toBe("b");
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("a dialog made before the story begins still asks before losing a restored game", async () => {
|
|
132
|
+
const element = document.getElementById("squiffy")!;
|
|
133
|
+
const result = await squiffyCompile({ script, projectId: "story-1" });
|
|
134
|
+
if (!result.success) throw new Error("Compile failed");
|
|
135
|
+
const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
|
|
136
|
+
const story = { js: js as any, ...result.output.story };
|
|
137
|
+
const first = await init({ element, story, persist: true });
|
|
138
|
+
await first.begin();
|
|
139
|
+
await click(first, element, "b");
|
|
140
|
+
|
|
141
|
+
// A new page: the dialog is made first, as the published page does
|
|
142
|
+
element.innerHTML = "";
|
|
143
|
+
const api = await init({ element, story, persist: true });
|
|
144
|
+
const slots = memorySaveSlots();
|
|
145
|
+
await slots.add(api.getSave(), "Start");
|
|
146
|
+
const dialog = createSavesDialog(api, { slots });
|
|
147
|
+
await api.begin();
|
|
148
|
+
await dialog.open();
|
|
149
|
+
dialog.element.querySelector<HTMLElement>("[data-action=load]")!.click();
|
|
150
|
+
await settle();
|
|
151
|
+
expect(dialog.element.querySelector(".squiffy-saves-confirm")).not.toBeNull();
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("a save's menu opens and closes, and Escape closes it before the dialog", async () => {
|
|
155
|
+
const { el, save, row, pick } = await setup();
|
|
156
|
+
await save();
|
|
157
|
+
const button = row(0).querySelector<HTMLElement>("[data-action=options]")!;
|
|
158
|
+
expect(button.getAttribute("aria-label")).toBe("Options for Welcome to the start. Go to b.");
|
|
159
|
+
const menu = row(0).querySelector<HTMLElement>("[role=menu]")!;
|
|
160
|
+
expect(menu.hidden).toBe(true);
|
|
161
|
+
|
|
162
|
+
await pick(0, "options");
|
|
163
|
+
expect(menu.hidden).toBe(false);
|
|
164
|
+
expect(button.getAttribute("aria-expanded")).toBe("true");
|
|
165
|
+
expect(document.activeElement?.textContent).toBe("Overwrite");
|
|
166
|
+
menu.dispatchEvent(new window.KeyboardEvent("keydown", { key: "ArrowDown", bubbles: true }));
|
|
167
|
+
expect(document.activeElement?.textContent).toBe("Rename");
|
|
168
|
+
|
|
169
|
+
const cancel = new window.Event("cancel", { cancelable: true });
|
|
170
|
+
el.dispatchEvent(cancel);
|
|
171
|
+
expect(cancel.defaultPrevented).toBe(true);
|
|
172
|
+
expect(menu.hidden).toBe(true);
|
|
173
|
+
expect(document.activeElement).toBe(button);
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
test("overwrite replaces a save with the game as it is now, keeping its name", async () => {
|
|
177
|
+
const { api, element, rows, save, pick, answer } = await setup();
|
|
178
|
+
await save("Mine");
|
|
179
|
+
await click(api, element, "b");
|
|
180
|
+
await pick(0, "overwrite");
|
|
181
|
+
await answer(true);
|
|
182
|
+
expect(rows()).toEqual([{ title: "Mine", meta: expect.stringContaining("You are in b.") }]);
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
test("rename changes a save's name, and an empty name makes it unnamed again", async () => {
|
|
186
|
+
const { el, rows, save, row, pick } = await setup();
|
|
187
|
+
await save("Old");
|
|
188
|
+
await pick(0, "rename");
|
|
189
|
+
let input = row(0).querySelector<HTMLInputElement>("input")!;
|
|
190
|
+
expect(input.value).toBe("Old");
|
|
191
|
+
input.value = "New";
|
|
192
|
+
input.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter" }));
|
|
193
|
+
await settle();
|
|
194
|
+
await settle();
|
|
195
|
+
expect(rows()[0].title).toBe("New");
|
|
196
|
+
|
|
197
|
+
await pick(0, "rename");
|
|
198
|
+
input = row(0).querySelector<HTMLInputElement>("input")!;
|
|
199
|
+
input.value = " ";
|
|
200
|
+
input.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Enter" }));
|
|
201
|
+
await settle();
|
|
202
|
+
await settle();
|
|
203
|
+
expect(rows()[0].title).toBe("Welcome to the start. Go to b.");
|
|
204
|
+
expect(el.querySelector(".squiffy-saves-rename")).toBeNull();
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
test("delete asks first", async () => {
|
|
208
|
+
const { el, rows, save, pick, answer } = await setup();
|
|
209
|
+
await save("Mine");
|
|
210
|
+
await pick(0, "delete");
|
|
211
|
+
expect(el.querySelector(".squiffy-saves-confirm p")!.textContent).toBe("Delete \"Mine\"? This can't be undone.");
|
|
212
|
+
await answer(false);
|
|
213
|
+
expect(rows()).toHaveLength(1);
|
|
214
|
+
await pick(0, "delete");
|
|
215
|
+
await answer(true);
|
|
216
|
+
expect(rows()).toHaveLength(0);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test("Save to file downloads the game as a .squiffy-save named after the page", async () => {
|
|
220
|
+
const { api, q } = await setup();
|
|
221
|
+
const blobs: Blob[] = [];
|
|
222
|
+
URL.createObjectURL = (blob: Blob) => { blobs.push(blob); return "blob:x"; };
|
|
223
|
+
URL.revokeObjectURL = () => {};
|
|
224
|
+
let downloaded = "";
|
|
225
|
+
window.HTMLAnchorElement.prototype.click = function () { downloaded = this.download; };
|
|
226
|
+
q("[data-save-to-file]").click();
|
|
227
|
+
expect(downloaded).toBe("My Story.squiffy-save");
|
|
228
|
+
expect(JSON.parse(await blobs[0].text())).toEqual({ ...api.getSave(), savedAt: expect.any(String) });
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
test("Load from file loads a save, and says so when the file isn't one or is for another story", async () => {
|
|
232
|
+
const { api, element, el, q } = await setup();
|
|
233
|
+
await click(api, element, "b");
|
|
234
|
+
const save = api.getSave();
|
|
235
|
+
await click(api, element, "c");
|
|
236
|
+
|
|
237
|
+
const input = q<HTMLInputElement>("input[type=file]");
|
|
238
|
+
const choose = async (text: string) => {
|
|
239
|
+
Object.defineProperty(input, "files", { configurable: true, value: [new window.File([text], "game.squiffy-save")] });
|
|
240
|
+
input.dispatchEvent(new window.Event("change"));
|
|
241
|
+
await settle();
|
|
242
|
+
await settle();
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
await choose("not json");
|
|
246
|
+
expect(q(".squiffy-saves-error").hidden).toBe(false);
|
|
247
|
+
expect(q(".squiffy-saves-error").textContent).toBe("This file isn't a saved game.");
|
|
248
|
+
|
|
249
|
+
await choose(JSON.stringify({ ...save, storyId: "another" }));
|
|
250
|
+
// Progress since the last save, so it asks first
|
|
251
|
+
el.querySelector<HTMLElement>(".squiffy-saves-confirm [data-answer=yes]")!.click();
|
|
252
|
+
await settle();
|
|
253
|
+
await settle();
|
|
254
|
+
expect(q(".squiffy-saves-error").textContent).toBe("This saved game is for a different story.");
|
|
255
|
+
expect(api.get("_section")).toBe("c");
|
|
256
|
+
|
|
257
|
+
await choose(JSON.stringify(save));
|
|
258
|
+
el.querySelector<HTMLElement>(".squiffy-saves-confirm [data-answer=yes]")!.click();
|
|
259
|
+
await settle();
|
|
260
|
+
await settle();
|
|
261
|
+
expect(api.get("_section")).toBe("b");
|
|
262
|
+
expect(el.open).toBe(false);
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
test("a store that fails says the game couldn't be saved", async () => {
|
|
266
|
+
const slots = memorySaveSlots();
|
|
267
|
+
slots.add = () => Promise.reject(new Error("full"));
|
|
268
|
+
const { q, save, rows } = await setup(slots);
|
|
269
|
+
await save();
|
|
270
|
+
expect(q(".squiffy-saves-error").textContent).toBe("The game couldn't be saved. Try Save to file instead.");
|
|
271
|
+
expect(rows()).toHaveLength(0);
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
test("the text can be translated", async () => {
|
|
275
|
+
const { api } = await start();
|
|
276
|
+
const dialog = createSavesDialog(api, { slots: memorySaveSlots(), strings: { saves: "Parties sauvegardées", save: "Sauvegarder", unknown: "x" } });
|
|
277
|
+
await dialog.open();
|
|
278
|
+
expect(dialog.element.querySelector("h2")!.textContent).toBe("Parties sauvegardées");
|
|
279
|
+
expect(dialog.element.querySelector("form button")!.textContent).toBe("Sauvegarder");
|
|
280
|
+
expect(dialog.element.querySelector(".squiffy-saves-empty")!.textContent).toBe("No saved games yet.");
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
test("formatSaveTime", () => {
|
|
284
|
+
const now = new Date(2026, 10, 18, 20, 0);
|
|
285
|
+
expect(formatSaveTime(new Date(2026, 10, 18, 9, 5).toISOString(), undefined, now)).toMatch(/^Today, /);
|
|
286
|
+
expect(formatSaveTime(new Date(2026, 10, 17, 9, 5).toISOString(), undefined, now)).toMatch(/^Yesterday, /);
|
|
287
|
+
expect(formatSaveTime(new Date(2026, 10, 1, 9, 5).toISOString(), undefined, now)).toMatch(/^1 Nov|^Nov 1/);
|
|
288
|
+
expect(formatSaveTime(new Date(2025, 10, 1, 9, 5).toISOString(), undefined, now)).toContain("2025");
|
|
289
|
+
expect(formatSaveTime("nonsense")).toBe("");
|
|
290
|
+
});
|