squiffy-runtime 7.0.0-beta.6 → 7.0.0-beta.8
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/assets.d.ts +1 -0
- package/dist/classes.test.d.ts +1 -0
- package/dist/confirmDialog.d.ts +8 -0
- package/dist/events.d.ts +11 -0
- package/dist/every.d.ts +12 -0
- package/dist/every.test.d.ts +1 -0
- package/dist/paths.d.ts +15 -0
- package/dist/paths.test.d.ts +1 -0
- package/dist/playerSettings.d.ts +17 -0
- package/dist/preview-host.d.ts +2 -0
- package/dist/preview-host.js +10 -0
- package/dist/preview-host.js.map +2 -2
- package/dist/preview-html.js +1 -1
- package/dist/preview-protocol.d.ts +6 -0
- package/dist/settings.test.d.ts +1 -0
- package/dist/settingsDialog.d.ts +17 -0
- package/dist/skill.test.d.ts +1 -0
- package/dist/sound.d.ts +35 -0
- package/dist/sound.test.d.ts +1 -0
- package/dist/squiffy.page.css +14 -3
- package/dist/squiffy.preview.html +680 -82
- package/dist/squiffy.runtime.css +531 -1
- package/dist/squiffy.runtime.d.ts +5 -1
- package/dist/squiffy.runtime.global.js +117 -96
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +5728 -4520
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +4 -1
- package/dist/style.test.d.ts +1 -0
- package/dist/textProcessor.d.ts +16 -0
- package/dist/transitions.test.d.ts +1 -0
- package/dist/types.d.ts +54 -0
- package/dist/uiLinks.test.d.ts +1 -0
- package/dist/utils.d.ts +1 -0
- package/dist/utils.test.d.ts +1 -0
- package/package.json +3 -3
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
- package/src/animation.test.ts +44 -0
- package/src/animation.ts +9 -5
- package/src/assets.test.ts +1 -3
- package/src/assets.ts +1 -1
- package/src/classes.test.ts +201 -0
- package/src/confirmDialog.ts +66 -0
- package/src/events.ts +18 -0
- package/src/every.test.ts +25 -0
- package/src/every.ts +94 -0
- package/src/panels.test.ts +24 -0
- package/src/paths.test.ts +66 -0
- package/src/paths.ts +155 -0
- package/src/playerSettings.ts +128 -0
- package/src/plugins/animate.ts +16 -3
- package/src/plugins/live.ts +10 -4
- package/src/plugins/plugins.test.ts +51 -6
- package/src/preview-host.test.ts +22 -0
- package/src/preview-host.ts +15 -0
- package/src/preview-protocol.ts +9 -1
- package/src/preview.test.ts +114 -3
- package/src/preview.ts +97 -3
- package/src/settings.test.ts +233 -0
- package/src/settingsDialog.ts +160 -0
- package/src/skill.test.ts +67 -0
- package/src/sound.test.ts +273 -0
- package/src/sound.ts +207 -0
- package/src/squiffy.page.css +14 -3
- package/src/squiffy.runtime.css +531 -1
- package/src/squiffy.runtime.test.ts +1130 -17
- package/src/squiffy.runtime.ts +600 -38
- package/src/state.ts +45 -10
- package/src/style.test.ts +89 -0
- package/src/textProcessor.ts +484 -35
- package/src/transitions.test.ts +302 -0
- package/src/types.ts +79 -0
- package/src/uiLinks.test.ts +156 -0
- package/src/updater.ts +26 -8
- package/src/utils.test.ts +60 -0
- package/src/utils.ts +44 -14
- package/dist/infixExpressions.d.ts +0 -6
- package/src/infixExpressions.test.ts +0 -379
- package/src/infixExpressions.ts +0 -488
- /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// A question for the player, such as "Are you sure you want to restart?", in a dialog that looks
|
|
2
|
+
// like the rest of the page, in place of the browser's confirm()
|
|
3
|
+
|
|
4
|
+
export interface ConfirmDialogOptions {
|
|
5
|
+
message: string;
|
|
6
|
+
// The button that goes ahead, e.g. "Restart"
|
|
7
|
+
confirm: string;
|
|
8
|
+
// "Cancel" by default
|
|
9
|
+
cancel?: string;
|
|
10
|
+
// Whether going ahead loses something, which colours its button as a warning
|
|
11
|
+
danger?: boolean;
|
|
12
|
+
// Where the dialog goes in the page: the end of the body by default
|
|
13
|
+
container?: HTMLElement;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
let dialogCount = 0;
|
|
17
|
+
|
|
18
|
+
// Shows the question, and resolves true if the player goes ahead. Escape, Cancel and clicking
|
|
19
|
+
// outside the dialog all resolve false. The dialog is taken off the page once it's answered.
|
|
20
|
+
export function confirmDialog(options: ConfirmDialogOptions): Promise<boolean> {
|
|
21
|
+
const id = `squiffy-confirm-${++dialogCount}`;
|
|
22
|
+
const dialog = document.createElement("dialog");
|
|
23
|
+
dialog.className = "squiffy-confirm";
|
|
24
|
+
dialog.setAttribute("role", "alertdialog");
|
|
25
|
+
dialog.setAttribute("aria-labelledby", `${id}-message`);
|
|
26
|
+
dialog.innerHTML = `
|
|
27
|
+
<p id="${id}-message"></p>
|
|
28
|
+
<div class="squiffy-confirm-buttons">
|
|
29
|
+
<button type="button" class="squiffy-confirm-button" data-answer="no"></button>
|
|
30
|
+
<button type="button" class="squiffy-confirm-button ${options.danger ? "squiffy-confirm-danger" : "squiffy-confirm-primary"}" data-answer="yes"></button>
|
|
31
|
+
</div>`;
|
|
32
|
+
dialog.querySelector("p")!.textContent = options.message;
|
|
33
|
+
const no = dialog.querySelector<HTMLButtonElement>("[data-answer=no]")!;
|
|
34
|
+
const yes = dialog.querySelector<HTMLButtonElement>("[data-answer=yes]")!;
|
|
35
|
+
no.textContent = options.cancel ?? "Cancel";
|
|
36
|
+
yes.textContent = options.confirm;
|
|
37
|
+
(options.container ?? document.body).appendChild(dialog);
|
|
38
|
+
|
|
39
|
+
return new Promise<boolean>(resolve => {
|
|
40
|
+
let answered = false;
|
|
41
|
+
const finish = (answer: boolean) => {
|
|
42
|
+
if (answered) return;
|
|
43
|
+
answered = true;
|
|
44
|
+
if (dialog.open) dialog.close();
|
|
45
|
+
dialog.remove();
|
|
46
|
+
resolve(answer);
|
|
47
|
+
};
|
|
48
|
+
no.addEventListener("click", () => finish(false));
|
|
49
|
+
yes.addEventListener("click", () => finish(true));
|
|
50
|
+
// Escape
|
|
51
|
+
dialog.addEventListener("cancel", e => {
|
|
52
|
+
e.preventDefault();
|
|
53
|
+
finish(false);
|
|
54
|
+
});
|
|
55
|
+
dialog.addEventListener("close", () => finish(false));
|
|
56
|
+
// A click on the backdrop is on the dialog itself, outside its content
|
|
57
|
+
dialog.addEventListener("click", e => {
|
|
58
|
+
if (e.target !== dialog) return;
|
|
59
|
+
const rect = dialog.getBoundingClientRect();
|
|
60
|
+
const inside = e.clientX >= rect.left && e.clientX <= rect.right && e.clientY >= rect.top && e.clientY <= rect.bottom;
|
|
61
|
+
if (!inside) finish(false);
|
|
62
|
+
});
|
|
63
|
+
dialog.showModal();
|
|
64
|
+
yes.focus();
|
|
65
|
+
});
|
|
66
|
+
}
|
package/src/events.ts
CHANGED
|
@@ -5,7 +5,20 @@ export type SquiffyEventMap = {
|
|
|
5
5
|
set: { attribute: string, value: any }; // an attribute was set
|
|
6
6
|
canGoBackChanged: { canGoBack: boolean }; // whether the "back" button should be enabled
|
|
7
7
|
navigated: { section: string, passage?: string }; // a section or passage was shown, or Back went to one
|
|
8
|
+
sound: Record<string, never>; // music or a sound started playing (#444), even if it's muted
|
|
8
9
|
storyUpdated: Record<string, never>; // update() changed the story, e.g. after an edit in the editor
|
|
10
|
+
// A {{restart}} link was clicked (#452). With a handler, the page does the restarting, asking
|
|
11
|
+
// first if confirm is true. Without one, the runtime asks in its own dialog.
|
|
12
|
+
restartRequested: { confirm: boolean };
|
|
13
|
+
// A {{saves}} link was clicked (#452). With a handler, the page opens its Saved games dialog.
|
|
14
|
+
// Without one, the runtime opens one of its own.
|
|
15
|
+
savesRequested: Record<string, never>;
|
|
16
|
+
// A {{settings}} link was clicked (#452). With a handler, the page opens its Settings dialog.
|
|
17
|
+
// Without one, the runtime opens one of its own.
|
|
18
|
+
settingsRequested: Record<string, never>;
|
|
19
|
+
// The player changed a setting (#452). Putting them back to their defaults raises it for each
|
|
20
|
+
// one that changes.
|
|
21
|
+
settingChanged: { name: string, value: unknown };
|
|
9
22
|
};
|
|
10
23
|
|
|
11
24
|
export type SquiffyEventHandler<E extends keyof SquiffyEventMap> =
|
|
@@ -32,6 +45,11 @@ export class Emitter<Events extends Record<string, any>> {
|
|
|
32
45
|
return off;
|
|
33
46
|
}
|
|
34
47
|
|
|
48
|
+
// Whether anything is listening for the event
|
|
49
|
+
has<E extends keyof Events>(event: E) {
|
|
50
|
+
return (this.listeners.get(event)?.size ?? 0) > 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
35
53
|
emit<E extends keyof Events>(event: E, payload: Events[E]) {
|
|
36
54
|
this.listeners.get(event)?.forEach(h => {
|
|
37
55
|
try { (h as any)(payload); } catch (err) {
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { expect, test } from "vitest";
|
|
2
|
+
import { captureEveryBodies } from "./every.js";
|
|
3
|
+
|
|
4
|
+
const body = (text: string) => `__body="${encodeURIComponent(text)}"`;
|
|
5
|
+
|
|
6
|
+
test("captureEveryBodies copies each {{#every}}'s text into it (#451)", () => {
|
|
7
|
+
expect(captureEveryBodies("A {{#every 1000}}Tick {{n}}{{/every}} B"))
|
|
8
|
+
.toBe(`A {{#every 1000 ${body("Tick {{n}}")}}}Tick {{n}}{{/every}} B`);
|
|
9
|
+
expect(captureEveryBodies("{{~#every 1000 times=2~}}x{{~/every~}}"))
|
|
10
|
+
.toBe(`{{~#every 1000 times=2 ${body("x")}~}}x{{~/every~}}`);
|
|
11
|
+
expect(captureEveryBodies("{{#every \"1s\"}}\"quoted}}\"{{/every}}"))
|
|
12
|
+
.toBe(`{{#every "1s" ${body("\"quoted}}\"")}}}"quoted}}"{{/every}}`);
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
test("captureEveryBodies handles {{#every}} inside {{#every}}", () => {
|
|
16
|
+
const inner = "{{#every 500}}in{{/every}}";
|
|
17
|
+
expect(captureEveryBodies(`{{#every 1000}}out ${inner}{{/every}}`))
|
|
18
|
+
.toBe(`{{#every 1000 ${body(`out ${inner}`)}}}out {{#every 500 ${body("in")}}}in{{/every}}{{/every}}`);
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
test("captureEveryBodies leaves other text alone", () => {
|
|
22
|
+
for (const text of ["no tags", "{{#if a}}x{{/if}}", "\\{{#every 1000}}x{{/every}}", "{{#everything}}x{{/everything}}"]) {
|
|
23
|
+
expect(captureEveryBodies(text)).toBe(text);
|
|
24
|
+
}
|
|
25
|
+
});
|
package/src/every.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// {{#every 1000}}...{{/every}} (#451): text shown again and again, every so often, while the
|
|
2
|
+
// player is in the section. Each time, its text is worked out again and replaces what it showed
|
|
3
|
+
// before (or, with append=true, is added after it), until a {{stop}} inside it, times= ticks, or
|
|
4
|
+
// the player moving on to another section.
|
|
5
|
+
//
|
|
6
|
+
// The text is kept in the page, so a saved game, going back and the editor's preview can start
|
|
7
|
+
// it again: before the text is compiled, captureEveryBodies() copies each {{#every}}'s text into a
|
|
8
|
+
// hidden __body= parameter, which the helper puts in the element it writes.
|
|
9
|
+
|
|
10
|
+
import { findTagEnd } from "squiffy-compiler/infix-expressions";
|
|
11
|
+
|
|
12
|
+
const everyTag = /(\\*)\{\{~?\s*(?:(#every)(?=[\s}~])|(\/every)\s*~?\}\})/g;
|
|
13
|
+
|
|
14
|
+
// Adds __body="..." to each {{#every}}, with the text between it and its {{/every}}, encoded so
|
|
15
|
+
// that it can't end the string or the tag
|
|
16
|
+
export function captureEveryBodies(text: string): string {
|
|
17
|
+
if (!text.includes("#every")) return text;
|
|
18
|
+
const insertions: { at: number; text: string }[] = [];
|
|
19
|
+
const open: { tagEnd: number; bodyStart: number }[] = [];
|
|
20
|
+
everyTag.lastIndex = 0;
|
|
21
|
+
let match: RegExpExecArray | null;
|
|
22
|
+
while ((match = everyTag.exec(text)) !== null) {
|
|
23
|
+
// An odd number of backslashes escapes the mustache
|
|
24
|
+
if (match[1].length % 2 === 1) continue;
|
|
25
|
+
if (match[2]) {
|
|
26
|
+
const tagEnd = findTagEnd(text, match.index + match[0].length);
|
|
27
|
+
if (tagEnd === -1) break;
|
|
28
|
+
const bodyStart = text.indexOf("}}", tagEnd) + 2;
|
|
29
|
+
// With no delay, it's left for the helper to report, as __body= would be the delay
|
|
30
|
+
const hasDelay = text.slice(match.index + match[0].length, tagEnd).trim() !== "";
|
|
31
|
+
open.push({ tagEnd: hasDelay ? tagEnd : -1, bodyStart });
|
|
32
|
+
everyTag.lastIndex = bodyStart;
|
|
33
|
+
} else {
|
|
34
|
+
const start = open.pop();
|
|
35
|
+
if (!start) continue;
|
|
36
|
+
if (start.tagEnd === -1) continue;
|
|
37
|
+
const body = text.slice(start.bodyStart, match.index + match[1].length);
|
|
38
|
+
insertions.push({ at: start.tagEnd, text: ` __body="${encodeURIComponent(body)}"` });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
insertions.sort((a, b) => b.at - a.at);
|
|
42
|
+
for (const { at, text: insert } of insertions) {
|
|
43
|
+
text = text.slice(0, at) + insert + text.slice(at);
|
|
44
|
+
}
|
|
45
|
+
return text;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const everySelector = ".squiffy-every:not([data-every-stopped])";
|
|
49
|
+
|
|
50
|
+
// A tick's timer function is marked, so that the CLI's --play can tell a story that's only
|
|
51
|
+
// repeating some text from one that's still moving on by itself
|
|
52
|
+
export const EVERY_TICK = "squiffyEvery";
|
|
53
|
+
|
|
54
|
+
// The timers for the {{#every}}s in the current section. sync() starts a timer for each one that
|
|
55
|
+
// hasn't got one, and stops those that aren't there any more.
|
|
56
|
+
export class EveryTimers {
|
|
57
|
+
private timers = new Map<HTMLElement, ReturnType<typeof setTimeout>>();
|
|
58
|
+
|
|
59
|
+
// tick: shows the text again. It returns false if it can't yet, e.g. while a transition is
|
|
60
|
+
// running, so it's tried again a little later.
|
|
61
|
+
constructor(private getRoot: () => HTMLElement | undefined, private tick: (el: HTMLElement) => boolean) {}
|
|
62
|
+
|
|
63
|
+
sync() {
|
|
64
|
+
const root = this.getRoot();
|
|
65
|
+
const active = new Set(root?.isConnected ? root.querySelectorAll<HTMLElement>(everySelector) : []);
|
|
66
|
+
for (const [el, timer] of this.timers) {
|
|
67
|
+
if (!active.has(el)) {
|
|
68
|
+
clearTimeout(timer);
|
|
69
|
+
this.timers.delete(el);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
for (const el of active) {
|
|
73
|
+
if (!this.timers.has(el)) this.schedule(el, Number(el.getAttribute("data-every-delay")) || 0);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
stopAll() {
|
|
78
|
+
for (const timer of this.timers.values()) clearTimeout(timer);
|
|
79
|
+
this.timers.clear();
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
private schedule(el: HTMLElement, ms: number) {
|
|
83
|
+
const fn = () => {
|
|
84
|
+
this.timers.delete(el);
|
|
85
|
+
if (!this.tick(el)) {
|
|
86
|
+
this.schedule(el, 50);
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
this.sync();
|
|
90
|
+
};
|
|
91
|
+
(fn as unknown as Record<string, boolean>)[EVERY_TICK] = true;
|
|
92
|
+
this.timers.set(el, setTimeout(fn, ms));
|
|
93
|
+
}
|
|
94
|
+
}
|
package/src/panels.test.ts
CHANGED
|
@@ -199,3 +199,27 @@ test("a hot update renders the panels again", async () => {
|
|
|
199
199
|
test("the compiler checks for the same icons the runtime has", () => {
|
|
200
200
|
expect([...COMPILER_PANEL_ICONS]).toEqual([...PANEL_ICONS]);
|
|
201
201
|
});
|
|
202
|
+
|
|
203
|
+
test("shows the attributes of a game restored when the page loads", async () => {
|
|
204
|
+
const element = document.getElementById("squiffy")!;
|
|
205
|
+
const result = await squiffyCompile({ script });
|
|
206
|
+
if (!result.success) throw new Error("Compile failed");
|
|
207
|
+
const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
|
|
208
|
+
const story = { js: js as any, ...result.output.story };
|
|
209
|
+
|
|
210
|
+
const first = await init({ element, story, persist: true, storyId: "panels-restore" });
|
|
211
|
+
await first.begin();
|
|
212
|
+
await click(first, element, "Get the lamp");
|
|
213
|
+
expect(first.get("gold")).toBe(15);
|
|
214
|
+
|
|
215
|
+
// The page again, as it does it: the panels first, then the story begins, from the saved game
|
|
216
|
+
document.getElementById("container")!.querySelector("aside")?.remove();
|
|
217
|
+
element.innerHTML = "";
|
|
218
|
+
const api = await init({ element, story, persist: true, storyId: "panels-restore" });
|
|
219
|
+
panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
|
|
220
|
+
await api.begin();
|
|
221
|
+
await settle();
|
|
222
|
+
|
|
223
|
+
expect(document.querySelector("aside.squiffy-panels-side")!.textContent).toContain("Gold: 15");
|
|
224
|
+
localStorage.clear();
|
|
225
|
+
});
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { expect, test, describe } from "vitest";
|
|
2
|
+
import { parsePath, readTarget, valueAt, withValueAt } from "./paths.js";
|
|
3
|
+
|
|
4
|
+
describe("parsePath", () => {
|
|
5
|
+
test.each([
|
|
6
|
+
["score", ["score"]],
|
|
7
|
+
["my attribute", ["my attribute"]],
|
|
8
|
+
["hero.hp", ["hero", "hp"]],
|
|
9
|
+
["inventory.0.name", ["inventory", "0", "name"]],
|
|
10
|
+
["inventory[0].name", ["inventory", "0", "name"]],
|
|
11
|
+
["inventory.[0].name", ["inventory", "0", "name"]],
|
|
12
|
+
["hero[\"max hp\"]", ["hero", "max hp"]],
|
|
13
|
+
["hero['max hp'].x", ["hero", "max hp", "x"]],
|
|
14
|
+
// Not paths: the whole name is the attribute
|
|
15
|
+
["a..b", ["a..b"]],
|
|
16
|
+
["a.", ["a."]],
|
|
17
|
+
[".a", [".a"]],
|
|
18
|
+
["a[0", ["a[0"]],
|
|
19
|
+
])("%s", (name, expected) => {
|
|
20
|
+
expect(parsePath(name)).toEqual(expected);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("names that reach the prototype aren't allowed", () => {
|
|
24
|
+
expect(() => parsePath("hero.__proto__.x")).toThrow("__proto__");
|
|
25
|
+
expect(() => parsePath("hero[constructor]")).toThrow("constructor");
|
|
26
|
+
});
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
describe("valueAt and withValueAt", () => {
|
|
30
|
+
test("reads values, and null for anything missing", () => {
|
|
31
|
+
const hero = { hp: 10, items: [{ name: "lamp" }] };
|
|
32
|
+
expect(valueAt(hero, ["items", "0", "name"])).toBe("lamp");
|
|
33
|
+
expect(valueAt(hero, ["items", "1", "name"])).toBeNull();
|
|
34
|
+
expect(valueAt(hero, ["hp", "x"])).toBeNull();
|
|
35
|
+
expect(valueAt(hero, ["toString"])).toBeNull();
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
test("changes a copy, making objects that aren't there", () => {
|
|
39
|
+
const hero = { hp: 10 };
|
|
40
|
+
expect(withValueAt(hero, ["stats", "str"], "hero", 2)).toEqual({ hp: 10, stats: { str: 2 } });
|
|
41
|
+
expect(hero).toEqual({ hp: 10 });
|
|
42
|
+
expect(withValueAt(null, ["hp"], "hero", 1)).toEqual({ hp: 1 });
|
|
43
|
+
expect(withValueAt([1, 2], ["1"], "list", 5)).toEqual([1, 5]);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("can't go through a value that isn't an object", () => {
|
|
47
|
+
expect(() => withValueAt(5, ["hp"], "hero", 1)).toThrow("hero isn't an object, so it has no hp");
|
|
48
|
+
expect(() => withValueAt({ hp: 5 }, ["hp", "max"], "hero", 1)).toThrow("hero.hp isn't an object, so it has no max");
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("readTarget", () => {
|
|
53
|
+
test.each([
|
|
54
|
+
["gold = 1", { attribute: "gold", segments: [], rest: " = 1" }],
|
|
55
|
+
["hero.hp += 5", { attribute: "hero", segments: [{ name: "hp" }], rest: " += 5" }],
|
|
56
|
+
["inventory[i + 1].name = \"x\"", { attribute: "inventory", segments: [{ index: "i + 1" }, { name: "name" }], rest: " = \"x\"" }],
|
|
57
|
+
["grid[a[0]][\"]\"]", { attribute: "grid", segments: [{ index: "a[0]" }, { index: "\"]\"" }], rest: "" }],
|
|
58
|
+
])("%s", (text, expected) => {
|
|
59
|
+
expect(readTarget(text)).toEqual(expected);
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
test("isn't a target", () => {
|
|
63
|
+
expect(readTarget("= 1")).toBeNull();
|
|
64
|
+
expect(readTarget("a[0 = 1")).toBeNull();
|
|
65
|
+
});
|
|
66
|
+
});
|
package/src/paths.ts
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// Values inside objects and lists (#442). An attribute can hold an object, such as
|
|
2
|
+
// { hp: 10, name: "Ann" }, or a list, and a path names a value inside it:
|
|
3
|
+
//
|
|
4
|
+
// hero.hp the hp of the object in the attribute hero
|
|
5
|
+
// inventory.0.name the name of the first item in the list inventory
|
|
6
|
+
// inventory[0].name the same
|
|
7
|
+
// hero["max hp"] a name that isn't a plain word
|
|
8
|
+
//
|
|
9
|
+
// squiffy.get, squiffy.set, {{set}}, {{inc}}, {{live}} and the like take a path as text, with
|
|
10
|
+
// these rules. Setters (@set hero.hp = 10) can also use another attribute as an index,
|
|
11
|
+
// inventory[i].name, which runtime/src/squiffy.runtime.ts reads with readTarget.
|
|
12
|
+
|
|
13
|
+
// Names that would reach an object's prototype rather than a value in it
|
|
14
|
+
const forbidden = new Set(["__proto__", "prototype", "constructor"]);
|
|
15
|
+
|
|
16
|
+
export function checkSegment(segment: string) {
|
|
17
|
+
if (forbidden.has(segment)) {
|
|
18
|
+
throw new Error(`"${segment}" can't be used as a name inside an object`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// The segments of a path, e.g. ["inventory", "0", "name"] for inventory[0].name. A name with no
|
|
23
|
+
// "." or "[" is a whole attribute name, and so is one that isn't a path at all, such as "a..b".
|
|
24
|
+
export function parsePath(name: string): string[] {
|
|
25
|
+
if (!name.includes(".") && !name.includes("[")) return [name];
|
|
26
|
+
const root = /^[^.[\]]+/.exec(name);
|
|
27
|
+
if (!root) return [name];
|
|
28
|
+
const segments: string[] = [root[0]];
|
|
29
|
+
let i = root[0].length;
|
|
30
|
+
while (i < name.length) {
|
|
31
|
+
if (name[i] === ".") {
|
|
32
|
+
// inventory.0.name, or Handlebars' inventory.[0].name
|
|
33
|
+
if (name[i + 1] === "[") {
|
|
34
|
+
i++;
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const segment = /^[^.[\]]+/.exec(name.substring(i + 1));
|
|
38
|
+
if (!segment) return [name];
|
|
39
|
+
segments.push(segment[0]);
|
|
40
|
+
i += 1 + segment[0].length;
|
|
41
|
+
}
|
|
42
|
+
else if (name[i] === "[") {
|
|
43
|
+
const close = name.indexOf("]", i);
|
|
44
|
+
if (close === -1) return [name];
|
|
45
|
+
let segment = name.substring(i + 1, close).trim();
|
|
46
|
+
const quoted = /^(["'])(.*)\1$/.exec(segment);
|
|
47
|
+
if (quoted) segment = quoted[2];
|
|
48
|
+
segments.push(segment);
|
|
49
|
+
i = close + 1;
|
|
50
|
+
}
|
|
51
|
+
else {
|
|
52
|
+
return [name];
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
segments.forEach(checkSegment);
|
|
56
|
+
return segments;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const isContainer = (value: unknown): value is Record<string, unknown> =>
|
|
60
|
+
typeof value === "object" && value !== null;
|
|
61
|
+
|
|
62
|
+
// The value at a path inside a value, or null if there's nothing there
|
|
63
|
+
export function valueAt(value: unknown, segments: string[]): unknown {
|
|
64
|
+
for (const segment of segments) {
|
|
65
|
+
if (!isContainer(value) || !Object.prototype.hasOwnProperty.call(value, segment)) return null;
|
|
66
|
+
value = value[segment];
|
|
67
|
+
}
|
|
68
|
+
return value ?? null;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// A copy of root with the value at the path inside it changed. Objects that aren't there yet are
|
|
72
|
+
// made, so @set hero.hp = 10 works before hero has been set. Throws if the path goes through a
|
|
73
|
+
// value that isn't an object or a list, such as a number.
|
|
74
|
+
export function withValueAt(root: unknown, segments: string[], name: string, value: unknown): unknown {
|
|
75
|
+
const result = isContainer(root) ? structuredClone(root) : root === null || root === undefined ? {} : null;
|
|
76
|
+
if (result === null) {
|
|
77
|
+
throw new Error(`${name} isn't an object, so it has no ${segments[0]}`);
|
|
78
|
+
}
|
|
79
|
+
let container: Record<string, unknown> = result;
|
|
80
|
+
let path = name;
|
|
81
|
+
segments.forEach((segment, i) => {
|
|
82
|
+
checkSegment(segment);
|
|
83
|
+
if (i === segments.length - 1) {
|
|
84
|
+
container[segment] = value;
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
path += "." + segment;
|
|
88
|
+
let next = Object.prototype.hasOwnProperty.call(container, segment) ? container[segment] : undefined;
|
|
89
|
+
if (next === undefined || next === null) {
|
|
90
|
+
next = {};
|
|
91
|
+
container[segment] = next;
|
|
92
|
+
}
|
|
93
|
+
if (!isContainer(next)) {
|
|
94
|
+
throw new Error(`${path} isn't an object, so it has no ${segments[i + 1]}`);
|
|
95
|
+
}
|
|
96
|
+
container = next;
|
|
97
|
+
});
|
|
98
|
+
return result;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// The target of a setter, e.g. hero.hp in hero.hp += 5 or inventory[i].name in
|
|
102
|
+
// inventory[i].name = "lamp": the attribute, then each name or index after it. An index is an
|
|
103
|
+
// expression, which the runtime works out when the setter runs.
|
|
104
|
+
export type TargetSegment = { name: string } | { index: string };
|
|
105
|
+
|
|
106
|
+
export interface Target {
|
|
107
|
+
attribute: string;
|
|
108
|
+
segments: TargetSegment[];
|
|
109
|
+
// Everything after the target, e.g. " += 5"
|
|
110
|
+
rest: string;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Reads a setter's target from the start of a setter, or returns null if it doesn't start with an
|
|
114
|
+
// attribute name. Whitespace before it is skipped.
|
|
115
|
+
export function readTarget(text: string): Target | null {
|
|
116
|
+
const start = /^\s*(\w+)/.exec(text);
|
|
117
|
+
if (!start) return null;
|
|
118
|
+
const segments: TargetSegment[] = [];
|
|
119
|
+
let i = start[0].length;
|
|
120
|
+
for (;;) {
|
|
121
|
+
const name = /^\.(\w+)/.exec(text.substring(i));
|
|
122
|
+
if (name) {
|
|
123
|
+
segments.push({ name: name[1] });
|
|
124
|
+
i += name[0].length;
|
|
125
|
+
continue;
|
|
126
|
+
}
|
|
127
|
+
if (text[i] !== "[") break;
|
|
128
|
+
const close = findClose(text, i);
|
|
129
|
+
if (close === -1) return null;
|
|
130
|
+
segments.push({ index: text.substring(i + 1, close) });
|
|
131
|
+
i = close + 1;
|
|
132
|
+
}
|
|
133
|
+
return { attribute: start[1], segments, rest: text.substring(i) };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// The index of the "]" that closes the "[" at `open`, skipping quoted text and brackets inside it,
|
|
137
|
+
// or -1
|
|
138
|
+
function findClose(text: string, open: number): number {
|
|
139
|
+
let depth = 0;
|
|
140
|
+
let quote: string | null = null;
|
|
141
|
+
for (let i = open; i < text.length; i++) {
|
|
142
|
+
const c = text[i];
|
|
143
|
+
if (quote) {
|
|
144
|
+
if (c === "\\") i++;
|
|
145
|
+
else if (c === quote) quote = null;
|
|
146
|
+
}
|
|
147
|
+
else if (c === "\"" || c === "'") quote = c;
|
|
148
|
+
else if (c === "[" || c === "(" || c === "{") depth++;
|
|
149
|
+
else if (c === "]" || c === ")" || c === "}") {
|
|
150
|
+
depth--;
|
|
151
|
+
if (depth === 0) return c === "]" ? i : -1;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return -1;
|
|
155
|
+
}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
// Player settings (#452): options from squiffy.json's "settings" that the player can change at any
|
|
2
|
+
// time, such as text size or content warnings. The story reads them as settings.name. They're the
|
|
3
|
+
// player's, not the game's, so they aren't attributes: going back, restarting and loading a saved
|
|
4
|
+
// game leave them as they are. They're kept for the story in localStorage, like Mute.
|
|
5
|
+
|
|
6
|
+
import type { PlayerSetting, SettingValue } from "./types.js";
|
|
7
|
+
|
|
8
|
+
export class PlayerSettings {
|
|
9
|
+
// The values the player has changed, by name. A setting that isn't here has its default.
|
|
10
|
+
private values: Record<string, SettingValue> = {};
|
|
11
|
+
|
|
12
|
+
constructor(private getDefinitions: () => PlayerSetting[], private storageKey?: string) {
|
|
13
|
+
if (!storageKey) return;
|
|
14
|
+
try {
|
|
15
|
+
const saved = JSON.parse(localStorage.getItem(storageKey) ?? "{}");
|
|
16
|
+
if (saved && typeof saved == "object" && !Array.isArray(saved)) this.values = saved;
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// Nothing saved, or storage that can't be read: every setting has its default
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
definitions() {
|
|
24
|
+
return this.getDefinitions().filter(setting => setting && typeof setting.name == "string");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
private find(name: string) {
|
|
28
|
+
return this.definitions().find(setting => setting.name == name);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// Whether the story has any settings, which is when it reads settings.name as a setting
|
|
32
|
+
any() {
|
|
33
|
+
return this.definitions().length > 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
get(name: string): SettingValue | null {
|
|
37
|
+
const setting = this.find(name);
|
|
38
|
+
if (!setting) return null;
|
|
39
|
+
const value = Object.prototype.hasOwnProperty.call(this.values, name) ? this.values[name] : undefined;
|
|
40
|
+
return value !== undefined && isValid(setting, value) ? value : defaultValue(setting);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Every setting's value, by name: the "settings" the story reads
|
|
44
|
+
all(): Record<string, SettingValue> {
|
|
45
|
+
return Object.fromEntries(this.definitions().map(setting => [setting.name, this.get(setting.name)!]));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Returns whether the value changed. One the setting can't have is ignored.
|
|
49
|
+
set(name: string, value: SettingValue): boolean {
|
|
50
|
+
const setting = this.find(name);
|
|
51
|
+
if (!setting) return false;
|
|
52
|
+
const coerced = coerce(setting, value);
|
|
53
|
+
if (coerced === null || coerced === this.get(name)) return false;
|
|
54
|
+
this.values[name] = coerced;
|
|
55
|
+
this.store();
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
reset() {
|
|
60
|
+
this.values = {};
|
|
61
|
+
this.store();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// The classes the settings put on the story's element, so the story's CSS can use them: a
|
|
65
|
+
// toggle's name while it's on (setting-warnings), and a list's or range's name and value
|
|
66
|
+
// (setting-textSize-Large)
|
|
67
|
+
classes(): string[] {
|
|
68
|
+
const classes: string[] = [];
|
|
69
|
+
for (const setting of this.definitions()) {
|
|
70
|
+
const value = this.get(setting.name);
|
|
71
|
+
if (setting.type == "toggle") {
|
|
72
|
+
if (value === true) classes.push(`setting-${setting.name}`);
|
|
73
|
+
}
|
|
74
|
+
else if (value !== null) {
|
|
75
|
+
classes.push(`setting-${setting.name}-${String(value).replace(/[^A-Za-z0-9_-]+/g, "-")}`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return classes;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
private store() {
|
|
82
|
+
if (!this.storageKey) return;
|
|
83
|
+
try {
|
|
84
|
+
if (Object.keys(this.values).length) localStorage.setItem(this.storageKey, JSON.stringify(this.values));
|
|
85
|
+
else localStorage.removeItem(this.storageKey);
|
|
86
|
+
}
|
|
87
|
+
catch {
|
|
88
|
+
// Storage that's full or turned off: the setting lasts until the page is closed
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function defaultValue(setting: PlayerSetting): SettingValue {
|
|
94
|
+
switch (setting.type) {
|
|
95
|
+
case "toggle": return setting.default ?? false;
|
|
96
|
+
case "list": return setting.default ?? setting.options[0]?.value ?? "";
|
|
97
|
+
case "range": return setting.default ?? setting.min;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function isValid(setting: PlayerSetting, value: unknown) {
|
|
102
|
+
return coerce(setting, value) === value;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// The value as the setting has it, e.g. "true" for a toggle is true and "3" for a range is 3, or
|
|
106
|
+
// null if the setting can't have it. A range's value is kept within min and max, on a step.
|
|
107
|
+
function coerce(setting: PlayerSetting, value: unknown): SettingValue | null {
|
|
108
|
+
switch (setting.type) {
|
|
109
|
+
case "toggle":
|
|
110
|
+
if (typeof value == "boolean") return value;
|
|
111
|
+
if (value === "true") return true;
|
|
112
|
+
if (value === "false") return false;
|
|
113
|
+
return null;
|
|
114
|
+
case "list": {
|
|
115
|
+
const text = typeof value == "string" || typeof value == "number" || typeof value == "boolean" ? String(value) : null;
|
|
116
|
+
return text !== null && setting.options.some(option => option.value === text) ? text : null;
|
|
117
|
+
}
|
|
118
|
+
case "range": {
|
|
119
|
+
const n = typeof value == "number" ? value : typeof value == "string" && value.trim() ? Number(value) : NaN;
|
|
120
|
+
if (!Number.isFinite(n)) return null;
|
|
121
|
+
const clamped = Math.min(setting.max, Math.max(setting.min, n));
|
|
122
|
+
if (!setting.step) return clamped;
|
|
123
|
+
const stepped = setting.min + Math.round((clamped - setting.min) / setting.step) * setting.step;
|
|
124
|
+
// Without the rounding errors of adding up steps such as 0.1
|
|
125
|
+
return Number(Math.min(setting.max, stepped).toFixed(10));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
package/src/plugins/animate.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import { PluginHost, SquiffyPlugin } from "../types.plugins.js";
|
|
2
2
|
import Handlebars from "handlebars";
|
|
3
3
|
import * as marked from "marked";
|
|
4
|
+
import { parseDelay } from "../utils.js";
|
|
5
|
+
|
|
6
|
+
// The parameters to the built-in animations that are times
|
|
7
|
+
const timeParameters = ["start", "interval", "duration", "fadeDuration"];
|
|
4
8
|
|
|
5
9
|
export function AnimatePlugin(): SquiffyPlugin {
|
|
6
10
|
let squiffy: PluginHost;
|
|
@@ -79,9 +83,13 @@ export function AnimatePlugin(): SquiffyPlugin {
|
|
|
79
83
|
if (oldLink.classList.contains("disabled")) {
|
|
80
84
|
link.classList.add("disabled");
|
|
81
85
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
86
|
+
// tabindex, and which click or {{deactivate}} disabled it, so going back
|
|
87
|
+
// enables the right links
|
|
88
|
+
for (const attr of ["tabindex", "data-clicked", "data-deactivated-by"]) {
|
|
89
|
+
const value = oldLink.getAttribute(attr);
|
|
90
|
+
if (value !== null) {
|
|
91
|
+
link.setAttribute(attr, value);
|
|
92
|
+
}
|
|
85
93
|
}
|
|
86
94
|
});
|
|
87
95
|
};
|
|
@@ -128,6 +136,11 @@ export function AnimatePlugin(): SquiffyPlugin {
|
|
|
128
136
|
content,
|
|
129
137
|
...options.hash,
|
|
130
138
|
};
|
|
139
|
+
// Times can be written like "1.5s" as well as in milliseconds (#451)
|
|
140
|
+
for (const key of timeParameters) {
|
|
141
|
+
const delay = parseDelay(dataset[key]);
|
|
142
|
+
if (delay !== null) dataset[key] = delay;
|
|
143
|
+
}
|
|
131
144
|
|
|
132
145
|
const attrs = Object.entries(dataset)
|
|
133
146
|
.map(([key, value]) =>
|