squiffy-runtime 6.0.1 → 7.0.0-beta.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/assets.d.ts +3 -0
- package/dist/assets.test.d.ts +1 -0
- package/dist/classes.test.d.ts +1 -0
- package/dist/confirmDialog.d.ts +8 -0
- package/dist/events.d.ts +16 -0
- package/dist/every.d.ts +12 -0
- package/dist/every.test.d.ts +1 -0
- package/dist/helpers.test.d.ts +1 -0
- package/dist/numbers.d.ts +3 -0
- package/dist/panels.d.ts +14 -0
- package/dist/panels.test.d.ts +1 -0
- package/dist/paths.d.ts +15 -0
- package/dist/paths.test.d.ts +1 -0
- package/dist/persistent.test.d.ts +1 -0
- package/dist/playerSettings.d.ts +17 -0
- package/dist/pluginManager.d.ts +2 -1
- package/dist/preview-host.d.ts +33 -0
- package/dist/preview-host.js +125 -0
- package/dist/preview-host.js.map +7 -0
- package/dist/preview-host.test.d.ts +1 -0
- package/dist/preview-html.d.ts +2 -0
- package/dist/preview-html.js +2 -0
- package/dist/preview-protocol.d.ts +69 -0
- package/dist/preview.d.ts +15 -0
- package/dist/preview.main.d.ts +1 -0
- package/dist/preview.test.d.ts +1 -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/scripts.test.d.ts +1 -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 +155 -0
- package/dist/squiffy.preview.html +1631 -0
- package/dist/squiffy.runtime.css +1123 -20
- package/dist/squiffy.runtime.d.ts +13 -1
- package/dist/squiffy.runtime.global.js +146 -76
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +7105 -4681
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +17 -0
- package/dist/storyLists.d.ts +4 -0
- package/dist/storyLists.test.d.ts +1 -0
- package/dist/style.test.d.ts +1 -0
- package/dist/textProcessor.d.ts +27 -0
- package/dist/transitions.test.d.ts +1 -0
- package/dist/types.d.ts +137 -1
- package/dist/types.plugins.d.ts +2 -0
- package/dist/uiLinks.test.d.ts +1 -0
- package/dist/utils.d.ts +2 -1
- package/dist/utils.test.d.ts +1 -0
- package/package.json +25 -11
- package/src/__snapshots__/squiffy.runtime.test.ts.snap +22 -22
- package/src/animation.test.ts +44 -0
- package/src/animation.ts +9 -5
- package/src/assets.test.ts +225 -0
- package/src/assets.ts +92 -0
- package/src/classes.test.ts +201 -0
- package/src/confirmDialog.ts +66 -0
- package/src/events.ts +20 -0
- package/src/every.test.ts +25 -0
- package/src/every.ts +94 -0
- package/src/helpers.test.ts +34 -0
- package/src/numbers.ts +21 -0
- package/src/panels.test.ts +225 -0
- package/src/panels.ts +187 -0
- package/src/paths.test.ts +66 -0
- package/src/paths.ts +155 -0
- package/src/persistent.test.ts +155 -0
- package/src/playerSettings.ts +128 -0
- package/src/pluginManager.ts +6 -1
- package/src/plugins/animate.ts +34 -9
- package/src/plugins/live.ts +18 -5
- package/src/plugins/plugins.test.ts +93 -6
- package/src/plugins/replaceLabel.ts +7 -3
- package/src/preview-host.test.ts +171 -0
- package/src/preview-host.ts +190 -0
- package/src/preview-protocol.ts +79 -0
- package/src/preview.main.ts +34 -0
- package/src/preview.test.ts +367 -0
- package/src/preview.ts +331 -0
- 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/scripts.test.ts +130 -0
- 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 +155 -0
- package/src/squiffy.runtime.css +1123 -20
- package/src/squiffy.runtime.test.ts +2806 -44
- package/src/squiffy.runtime.ts +1130 -64
- package/src/state.ts +172 -11
- package/src/storyLists.test.ts +134 -0
- package/src/storyLists.ts +57 -0
- package/src/style.test.ts +89 -0
- package/src/textProcessor.ts +739 -58
- package/src/transitions.test.ts +343 -0
- package/src/types.plugins.ts +7 -0
- package/src/types.ts +226 -2
- package/src/uiLinks.test.ts +156 -0
- package/src/updater.ts +26 -8
- package/src/utils.test.ts +60 -0
- package/src/utils.ts +46 -14
- package/vite.config.ts +3 -4
- package/vite.preview.config.ts +83 -0
- package/dist/infixExpressions.d.ts +0 -2
- package/src/infixExpressions.test.ts +0 -187
- package/src/infixExpressions.ts +0 -323
- /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// The compiler's list of the runtime's helpers, which its unknown-name warning relies on
|
|
2
|
+
// (squiffy/unknown-name, #526), must have every helper the runtime registers, and no others.
|
|
3
|
+
import { expect, test, vi, beforeEach, afterEach } from "vitest";
|
|
4
|
+
import globalJsdom from "global-jsdom";
|
|
5
|
+
import Handlebars from "handlebars";
|
|
6
|
+
import { init } from "./squiffy.runtime.js";
|
|
7
|
+
import { compile, BUILT_IN_HELPERS } from "squiffy-compiler";
|
|
8
|
+
|
|
9
|
+
let cleanup: () => void;
|
|
10
|
+
|
|
11
|
+
beforeEach(() => {
|
|
12
|
+
cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
vi.restoreAllMocks();
|
|
17
|
+
cleanup();
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
test("the compiler knows every helper the runtime registers", async () => {
|
|
21
|
+
const create = vi.spyOn(Handlebars, "create");
|
|
22
|
+
const result = await compile({ script: "Hello" });
|
|
23
|
+
if (!result.success) throw new Error("Compile failed");
|
|
24
|
+
const story = { ...result.output.story, js: [] } as any;
|
|
25
|
+
await init({ element: document.getElementById("squiffy")!, story, persist: false, storyId: "test", scroll: "none" });
|
|
26
|
+
const registered = new Set<string>();
|
|
27
|
+
for (const created of create.mock.results) {
|
|
28
|
+
for (const name of Object.keys((created.value as typeof Handlebars).helpers)) {
|
|
29
|
+
// The runtime's internal helpers, and Handlebars' for a missing helper
|
|
30
|
+
if (!name.startsWith("__") && name != "helperMissing" && name != "blockHelperMissing") registered.add(name);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
expect([...BUILT_IN_HELPERS].sort(), "Update BUILT_IN_HELPERS in compiler/src/helpers.ts").toEqual([...registered].sort());
|
|
34
|
+
});
|
package/src/numbers.ts
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The rules for turning attribute values into numbers, shared by everything that does arithmetic:
|
|
2
|
+
// the maths helpers ({{add}}, {{sub}} etc., which infix arithmetic is rewritten to), {{inc}} and
|
|
3
|
+
// {{dec}}, and @set's +=, -=, *= and /= (which @inc and @dec compile to).
|
|
4
|
+
//
|
|
5
|
+
// Attributes often hold numbers as text: values from user input, {{set "x" "5"}}, or JavaScript.
|
|
6
|
+
// So text that's a number counts as that number. A blank value (unset, null, false or "") counts
|
|
7
|
+
// as 0, so a counter can start from nothing. Anything else is an error, rather than giving NaN or
|
|
8
|
+
// joining text together.
|
|
9
|
+
|
|
10
|
+
export const isBlank = (v: unknown) => v === undefined || v === null || v === false || v === "";
|
|
11
|
+
|
|
12
|
+
export const isNumeric = (v: unknown) =>
|
|
13
|
+
typeof v === "number" || isBlank(v) || (typeof v === "string" && v.trim() !== "" && !isNaN(Number(v)));
|
|
14
|
+
|
|
15
|
+
// "what" names the operation in the error, e.g. "inc" gives: "inc" needs numbers, but was given "abc"
|
|
16
|
+
export function toNumber(what: string, v: unknown): number {
|
|
17
|
+
if (!isNumeric(v)) {
|
|
18
|
+
throw new Error(`"${what}" needs numbers, but was given ${JSON.stringify(v)}`);
|
|
19
|
+
}
|
|
20
|
+
return isBlank(v) ? 0 : Number(v);
|
|
21
|
+
}
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { expect, test, beforeEach, afterEach } from "vitest";
|
|
2
|
+
import globalJsdom from "global-jsdom";
|
|
3
|
+
import { init } from "./squiffy.runtime.js";
|
|
4
|
+
import { compile as squiffyCompile, PANEL_ICONS as COMPILER_PANEL_ICONS } from "squiffy-compiler";
|
|
5
|
+
import { createPanels } from "./panels.js";
|
|
6
|
+
import { PANEL_ICONS, type Panel, type SquiffyApi } from "./types.js";
|
|
7
|
+
|
|
8
|
+
let cleanup: () => void;
|
|
9
|
+
|
|
10
|
+
beforeEach(() => {
|
|
11
|
+
cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"container\"><div id=\"header\"><button id=\"restart\"></button></div><div id=\"squiffy\"></div></div></body></html>");
|
|
12
|
+
// jsdom has no showModal()
|
|
13
|
+
window.HTMLDialogElement.prototype.showModal = function () { this.setAttribute("open", ""); };
|
|
14
|
+
window.HTMLDialogElement.prototype.close = function () {
|
|
15
|
+
this.removeAttribute("open");
|
|
16
|
+
this.dispatchEvent(new window.Event("close"));
|
|
17
|
+
};
|
|
18
|
+
});
|
|
19
|
+
|
|
20
|
+
afterEach(() => {
|
|
21
|
+
cleanup();
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const script = `[[]]:
|
|
25
|
+
|
|
26
|
+
[status]:
|
|
27
|
+
Gold: {{gold}}
|
|
28
|
+
|
|
29
|
+
[lamp]:
|
|
30
|
+
{{#if lamp}}You have a lamp.{{/if}}
|
|
31
|
+
|
|
32
|
+
[inventory]:
|
|
33
|
+
{{#if lamp}}You have a lamp.{{/if}}{{set "gold" 1000}}{{goto "end"}} Go to [[end]] or [here](b).
|
|
34
|
+
|
|
35
|
+
[[start]]:
|
|
36
|
+
@set gold = 5
|
|
37
|
+
Welcome. [Get the lamp](b, lamp, gold += 10) or go to [[end]].
|
|
38
|
+
|
|
39
|
+
[b]:
|
|
40
|
+
You have it.
|
|
41
|
+
|
|
42
|
+
[[end]]:
|
|
43
|
+
The end.`;
|
|
44
|
+
|
|
45
|
+
const start = async () => {
|
|
46
|
+
const element = document.getElementById("squiffy")!;
|
|
47
|
+
const result = await squiffyCompile({ script });
|
|
48
|
+
if (!result.success) throw new Error("Compile failed");
|
|
49
|
+
const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
|
|
50
|
+
const api = await init({ element, story: { js: js as any, ...result.output.story }, persist: false });
|
|
51
|
+
await api.begin();
|
|
52
|
+
return { api, element };
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const click = async (api: SquiffyApi, element: HTMLElement, text: string) => {
|
|
56
|
+
const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
|
|
57
|
+
.filter(l => l.textContent === text && !l.classList.contains("disabled")).pop()!;
|
|
58
|
+
expect(await api.clickLink(link)).toBe(true);
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
// Lets the panels' queued refresh happen
|
|
62
|
+
const settle = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
63
|
+
|
|
64
|
+
const panelsFor = (api: SquiffyApi, panels: Panel[]) => createPanels(api, {
|
|
65
|
+
panels,
|
|
66
|
+
buttons: document.getElementById("header")!,
|
|
67
|
+
side: document.getElementById("container")!,
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test("renderPassage renders a master section passage with the attributes as they are", async () => {
|
|
71
|
+
const { api } = await start();
|
|
72
|
+
expect(api.renderPassage("status")).toBe("<p>Gold: 5</p>");
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("renderPassage changes nothing, and disables its links", async () => {
|
|
76
|
+
const { api, element } = await start();
|
|
77
|
+
const html = api.renderPassage("inventory");
|
|
78
|
+
expect(api.get("gold")).toBe(5);
|
|
79
|
+
expect(api.get("_section")).toBe("start");
|
|
80
|
+
expect(html).toContain("class=\"squiffy-link link-section disabled\"");
|
|
81
|
+
expect(html).toContain("class=\"squiffy-link link-passage disabled\"");
|
|
82
|
+
// Its {{goto}} isn't followed when the story moves on
|
|
83
|
+
await click(api, element, "Get the lamp");
|
|
84
|
+
expect(api.get("_section")).toBe("start");
|
|
85
|
+
expect(api.get("gold")).toBe(15);
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
test("renderPassage shows an error for a passage that isn't in the master section", async () => {
|
|
89
|
+
const { api } = await start();
|
|
90
|
+
expect(api.renderPassage("b")).toContain("there is no passage called \"b\" in the master section [[]]");
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
test("a side panel is shown beside the story, and rendered again as the story goes on", async () => {
|
|
94
|
+
const { api, element } = await start();
|
|
95
|
+
panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
|
|
96
|
+
const container = document.getElementById("container")!;
|
|
97
|
+
expect(container.classList.contains("squiffy-has-side")).toBe(true);
|
|
98
|
+
const panel = container.querySelector("aside.squiffy-panels-side > section.squiffy-panel")!;
|
|
99
|
+
expect(panel.getAttribute("aria-label")).toBe("Status");
|
|
100
|
+
expect(panel.innerHTML).toBe("<p>Gold: 5</p>");
|
|
101
|
+
|
|
102
|
+
await click(api, element, "Get the lamp");
|
|
103
|
+
await settle();
|
|
104
|
+
expect(panel.innerHTML).toBe("<p>Gold: 15</p>");
|
|
105
|
+
|
|
106
|
+
api.goBack();
|
|
107
|
+
await settle();
|
|
108
|
+
expect(panel.innerHTML).toBe("<p>Gold: 5</p>");
|
|
109
|
+
|
|
110
|
+
// Its button is for narrow screens, where CSS hides the panel
|
|
111
|
+
const button = document.querySelector<HTMLButtonElement>("#header button.squiffy-panel-button")!;
|
|
112
|
+
expect(button.classList.contains("squiffy-panel-side-button")).toBe(true);
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
test("a side panel whose text comes out empty is hidden", async () => {
|
|
116
|
+
const { api, element } = await start();
|
|
117
|
+
panelsFor(api, [{ passage: "lamp", label: "Lamp", position: "side" }]);
|
|
118
|
+
const aside = document.querySelector<HTMLElement>("aside.squiffy-panels-side")!;
|
|
119
|
+
const section = aside.querySelector<HTMLElement>("section")!;
|
|
120
|
+
expect(section.hidden).toBe(true);
|
|
121
|
+
expect(aside.hidden).toBe(true);
|
|
122
|
+
await click(api, element, "Get the lamp");
|
|
123
|
+
await settle();
|
|
124
|
+
expect(section.hidden).toBe(false);
|
|
125
|
+
expect(aside.hidden).toBe(false);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("a button panel's button opens it in a dialog, rendered fresh", async () => {
|
|
129
|
+
const { api, element } = await start();
|
|
130
|
+
panelsFor(api, [{ passage: "status", label: "Status" }, { passage: "inventory", label: "Bag", icon: "bag" }]);
|
|
131
|
+
const buttons = [...document.querySelectorAll<HTMLButtonElement>("#header button")];
|
|
132
|
+
// Before the page's own buttons, in the order they're listed
|
|
133
|
+
expect(buttons.map(b => b.id || b.dataset.passage)).toEqual(["status", "inventory", "restart"]);
|
|
134
|
+
expect(buttons[0].textContent).toBe("Status");
|
|
135
|
+
expect(buttons[0].classList.contains("squiffy-panel-text-button")).toBe(true);
|
|
136
|
+
expect(buttons[1].getAttribute("aria-label")).toBe("Bag");
|
|
137
|
+
expect(buttons[1].querySelector("svg")).not.toBeNull();
|
|
138
|
+
// No side panels, so no aside
|
|
139
|
+
expect(document.querySelector("aside")).toBeNull();
|
|
140
|
+
|
|
141
|
+
buttons[0].click();
|
|
142
|
+
const dialog = document.querySelector<HTMLDialogElement>("dialog.squiffy-panel-dialog")!;
|
|
143
|
+
expect(dialog.hasAttribute("open")).toBe(true);
|
|
144
|
+
expect(dialog.querySelector("h2")!.textContent).toBe("Status");
|
|
145
|
+
expect(dialog.querySelector(".squiffy-panel-dialog-content")!.innerHTML).toBe("<p>Gold: 5</p>");
|
|
146
|
+
// The story's text isn't touched
|
|
147
|
+
expect(element.textContent).not.toContain("Gold:");
|
|
148
|
+
|
|
149
|
+
// While it's open, it follows the story
|
|
150
|
+
api.set("gold", 7);
|
|
151
|
+
await settle();
|
|
152
|
+
expect(dialog.querySelector(".squiffy-panel-dialog-content")!.innerHTML).toBe("<p>Gold: 7</p>");
|
|
153
|
+
|
|
154
|
+
dialog.querySelector<HTMLButtonElement>(".squiffy-panel-dialog-close")!.click();
|
|
155
|
+
expect(dialog.hasAttribute("open")).toBe(false);
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("opening a panel doesn't count as a move", async () => {
|
|
159
|
+
const { api } = await start();
|
|
160
|
+
const panels = panelsFor(api, [{ passage: "status", label: "Status" }]);
|
|
161
|
+
panels.open("status");
|
|
162
|
+
expect(api.canGoBack()).toBe(false);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("without a side element, a side panel only has its button", async () => {
|
|
166
|
+
const { api } = await start();
|
|
167
|
+
createPanels(api, { panels: [{ passage: "status", label: "Status", position: "side" }], buttons: document.getElementById("header")! });
|
|
168
|
+
expect(document.querySelector("aside")).toBeNull();
|
|
169
|
+
const button = document.querySelector<HTMLButtonElement>("button.squiffy-panel-button")!;
|
|
170
|
+
expect(button.classList.contains("squiffy-panel-side-button")).toBe(false);
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
test("dispose takes the panels off the page", async () => {
|
|
174
|
+
const { api } = await start();
|
|
175
|
+
const panels = panelsFor(api, [{ passage: "status", label: "Status", position: "side" }, { passage: "inventory", label: "Bag" }]);
|
|
176
|
+
panels.dispose();
|
|
177
|
+
expect(document.querySelector("aside, dialog, button.squiffy-panel-button")).toBeNull();
|
|
178
|
+
expect(document.getElementById("container")!.classList.contains("squiffy-has-side")).toBe(false);
|
|
179
|
+
expect(document.getElementById("restart")).not.toBeNull();
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
test("the dialog's Close button can be translated", async () => {
|
|
183
|
+
const { api } = await start();
|
|
184
|
+
createPanels(api, { panels: [{ passage: "status", label: "État" }], buttons: document.getElementById("header")!, strings: { close: "Fermer" } });
|
|
185
|
+
expect(document.querySelector(".squiffy-panel-dialog-close")!.getAttribute("aria-label")).toBe("Fermer");
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
test("a hot update renders the panels again", async () => {
|
|
189
|
+
const { api } = await start();
|
|
190
|
+
panelsFor(api, [{ passage: "status", label: "Status", position: "side" }]);
|
|
191
|
+
const result = await squiffyCompile({ script: script.replace("Gold: {{gold}}", "Coins: {{gold}}") });
|
|
192
|
+
if (!result.success) throw new Error("Compile failed");
|
|
193
|
+
const js = result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n")));
|
|
194
|
+
api.update({ js: js as any, ...result.output.story });
|
|
195
|
+
await settle();
|
|
196
|
+
expect(document.querySelector("aside section")!.innerHTML).toBe("<p>Coins: 5</p>");
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
test("the compiler checks for the same icons the runtime has", () => {
|
|
200
|
+
expect([...COMPILER_PANEL_ICONS]).toEqual([...PANEL_ICONS]);
|
|
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
|
+
});
|
package/src/panels.ts
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Panels (#14, #443): passages in the master section that are always to hand, rendered again with
|
|
2
|
+
// the attributes as they are whenever the story moves on, e.g. the player's stats, inventory or
|
|
3
|
+
// a map. A "side" panel is shown beside the story, and a "button" panel is shown in a dialog,
|
|
4
|
+
// opened by a button in the header. Neither is part of the story's text, so they don't count as
|
|
5
|
+
// moves for Back or saved games. On a screen too narrow for a side panel, it has a button too.
|
|
6
|
+
//
|
|
7
|
+
// const panels = createPanels(squiffyApi, {
|
|
8
|
+
// panels: story.panels,
|
|
9
|
+
// buttons: document.getElementById("squiffy-header"),
|
|
10
|
+
// side: document.getElementById("squiffy-container"),
|
|
11
|
+
// });
|
|
12
|
+
|
|
13
|
+
import { PANEL_ICONS, type Panel, type PanelIcon, type SquiffyApi } from "./types.js";
|
|
14
|
+
|
|
15
|
+
export interface PanelsOptions {
|
|
16
|
+
// From the story's squiffy.json "panels" (story.panels)
|
|
17
|
+
panels: Panel[];
|
|
18
|
+
// Where the panels' buttons go: at the start of this element, e.g. the page's header
|
|
19
|
+
buttons: HTMLElement;
|
|
20
|
+
// Where side panels go: an <aside class="squiffy-panels-side"> is added at the end of this
|
|
21
|
+
// element, which gets the class squiffy-has-side, so its CSS can make room. Without it,
|
|
22
|
+
// side panels only have their buttons.
|
|
23
|
+
side?: HTMLElement;
|
|
24
|
+
// The dialog's text, for a story in another language: "close". Anything left out is in English.
|
|
25
|
+
strings?: Partial<Record<string, string>>;
|
|
26
|
+
// Where the dialog goes in the page: the end of the body by default
|
|
27
|
+
container?: HTMLElement;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface Panels {
|
|
31
|
+
// Renders the panels again, e.g. after changing an attribute from outside the story
|
|
32
|
+
refresh: () => void;
|
|
33
|
+
// Opens a panel's dialog, by its passage name
|
|
34
|
+
open: (passage: string) => void;
|
|
35
|
+
// Takes the panels, their buttons and their dialog off the page
|
|
36
|
+
dispose: () => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const ICON_CLOSE = "<path d=\"M18 6 6 18M6 6l12 12\"/>";
|
|
40
|
+
|
|
41
|
+
// Lucide icons (ISC licence), as are the page's other buttons
|
|
42
|
+
const ICONS: Record<PanelIcon, string> = {
|
|
43
|
+
bag: "<path d=\"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z\"/><path d=\"M8 10h8\"/><path d=\"M8 18h8\"/><path d=\"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6\"/><path d=\"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2\"/>",
|
|
44
|
+
person: "<path d=\"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2\"/><circle cx=\"12\" cy=\"7\" r=\"4\"/>",
|
|
45
|
+
map: "<path d=\"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z\"/><path d=\"M15 5.764v15\"/><path d=\"M9 3.236v15\"/>",
|
|
46
|
+
help: "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3\"/><path d=\"M12 17h.01\"/>",
|
|
47
|
+
info: "<circle cx=\"12\" cy=\"12\" r=\"10\"/><path d=\"M12 16v-4\"/><path d=\"M12 8h.01\"/>",
|
|
48
|
+
list: "<path d=\"M3 6h.01M3 12h.01M3 18h.01M8 6h13M8 12h13M8 18h13\"/>",
|
|
49
|
+
book: "<path d=\"M12 7v14\"/><path d=\"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z\"/>",
|
|
50
|
+
star: "<path d=\"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z\"/>",
|
|
51
|
+
heart: "<path d=\"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z\"/>",
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const svg = (paths: string) => `<svg viewBox="0 0 24 24" aria-hidden="true">${paths}</svg>`;
|
|
55
|
+
|
|
56
|
+
let dialogCount = 0;
|
|
57
|
+
|
|
58
|
+
export function createPanels(api: SquiffyApi, options: PanelsOptions): Panels {
|
|
59
|
+
const close = typeof options.strings?.close == "string" ? options.strings.close : "Close";
|
|
60
|
+
const id = `squiffy-panel-${++dialogCount}`;
|
|
61
|
+
const cleanups: (() => void)[] = [];
|
|
62
|
+
|
|
63
|
+
// The dialog that button panels are shown in, one at a time
|
|
64
|
+
const dialog = document.createElement("dialog");
|
|
65
|
+
dialog.className = "squiffy-panel-dialog";
|
|
66
|
+
dialog.setAttribute("aria-labelledby", `${id}-heading`);
|
|
67
|
+
dialog.innerHTML = `
|
|
68
|
+
<div class="squiffy-panel-dialog-header">
|
|
69
|
+
<h2 id="${id}-heading"></h2>
|
|
70
|
+
<button type="button" class="squiffy-panel-dialog-close">${svg(ICON_CLOSE)}</button>
|
|
71
|
+
</div>
|
|
72
|
+
<div class="squiffy-panel squiffy-panel-dialog-content"></div>`;
|
|
73
|
+
const heading = dialog.querySelector("h2")!;
|
|
74
|
+
const closeButton = dialog.querySelector<HTMLButtonElement>(".squiffy-panel-dialog-close")!;
|
|
75
|
+
closeButton.title = close;
|
|
76
|
+
closeButton.setAttribute("aria-label", close);
|
|
77
|
+
closeButton.addEventListener("click", () => dialog.close());
|
|
78
|
+
const content = dialog.querySelector<HTMLDivElement>(".squiffy-panel-dialog-content")!;
|
|
79
|
+
// Clicking the backdrop closes it too
|
|
80
|
+
dialog.addEventListener("click", event => {
|
|
81
|
+
if (event.target === dialog) dialog.close();
|
|
82
|
+
});
|
|
83
|
+
(options.container ?? document.body).appendChild(dialog);
|
|
84
|
+
cleanups.push(() => dialog.remove());
|
|
85
|
+
// The panel the dialog is showing
|
|
86
|
+
let shown: Panel | null = null;
|
|
87
|
+
|
|
88
|
+
const panels = options.panels.filter(panel => panel && typeof panel.passage == "string");
|
|
89
|
+
|
|
90
|
+
// The side panels, beside the story
|
|
91
|
+
const sidePanels = options.side ? panels.filter(panel => panel.position == "side") : [];
|
|
92
|
+
const sideSections = new Map<Panel, HTMLElement>();
|
|
93
|
+
let aside: HTMLElement | null = null;
|
|
94
|
+
if (sidePanels.length && options.side) {
|
|
95
|
+
aside = document.createElement("aside");
|
|
96
|
+
aside.className = "squiffy-panels-side";
|
|
97
|
+
for (const panel of sidePanels) {
|
|
98
|
+
const section = document.createElement("section");
|
|
99
|
+
section.className = "squiffy-panel";
|
|
100
|
+
section.dataset.passage = panel.passage;
|
|
101
|
+
section.setAttribute("aria-label", panel.label || panel.passage);
|
|
102
|
+
aside.appendChild(section);
|
|
103
|
+
sideSections.set(panel, section);
|
|
104
|
+
}
|
|
105
|
+
const side = options.side;
|
|
106
|
+
side.appendChild(aside);
|
|
107
|
+
side.classList.add("squiffy-has-side");
|
|
108
|
+
cleanups.push(() => {
|
|
109
|
+
aside!.remove();
|
|
110
|
+
side.classList.remove("squiffy-has-side");
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// A button for each panel, in the order they're listed, before anything already in the header.
|
|
115
|
+
// A side panel's button is only shown on screens too narrow for the panel.
|
|
116
|
+
const first = options.buttons.firstChild;
|
|
117
|
+
for (const panel of panels) {
|
|
118
|
+
const label = panel.label || panel.passage;
|
|
119
|
+
const button = document.createElement("button");
|
|
120
|
+
button.type = "button";
|
|
121
|
+
button.className = "squiffy-header-button squiffy-panel-button";
|
|
122
|
+
if (panel.position == "side" && sideSections.has(panel)) button.classList.add("squiffy-panel-side-button");
|
|
123
|
+
button.dataset.passage = panel.passage;
|
|
124
|
+
button.setAttribute("aria-haspopup", "dialog");
|
|
125
|
+
const icon = panel.icon && (PANEL_ICONS as readonly string[]).includes(panel.icon) ? ICONS[panel.icon] : null;
|
|
126
|
+
if (icon) {
|
|
127
|
+
button.innerHTML = svg(icon);
|
|
128
|
+
button.title = label;
|
|
129
|
+
button.setAttribute("aria-label", label);
|
|
130
|
+
}
|
|
131
|
+
else {
|
|
132
|
+
button.classList.add("squiffy-panel-text-button");
|
|
133
|
+
button.textContent = label;
|
|
134
|
+
}
|
|
135
|
+
button.addEventListener("click", () => open(panel));
|
|
136
|
+
options.buttons.insertBefore(button, first);
|
|
137
|
+
cleanups.push(() => button.remove());
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function open(panel: Panel) {
|
|
141
|
+
shown = panel;
|
|
142
|
+
heading.textContent = panel.label || panel.passage;
|
|
143
|
+
content.innerHTML = api.renderPassage(panel.passage);
|
|
144
|
+
if (!dialog.open) dialog.showModal();
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function refresh() {
|
|
148
|
+
for (const [panel, section] of sideSections) {
|
|
149
|
+
section.innerHTML = api.renderPassage(panel.passage);
|
|
150
|
+
// Text that comes out empty, e.g. from an {{#if}}, hides the panel
|
|
151
|
+
section.hidden = !section.textContent?.trim() && !section.querySelector("img, svg, video, canvas, iframe");
|
|
152
|
+
}
|
|
153
|
+
if (aside) aside.hidden = [...sideSections.values()].every(section => section.hidden);
|
|
154
|
+
if (dialog.open && shown) content.innerHTML = api.renderPassage(shown.passage);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Rendered again once whatever changed has finished changing, rather than after every attribute
|
|
158
|
+
let queued = false;
|
|
159
|
+
const queueRefresh = () => {
|
|
160
|
+
if (queued) return;
|
|
161
|
+
queued = true;
|
|
162
|
+
queueMicrotask(() => {
|
|
163
|
+
queued = false;
|
|
164
|
+
if (!disposed) refresh();
|
|
165
|
+
});
|
|
166
|
+
};
|
|
167
|
+
for (const event of ["set", "navigated", "storyUpdated"] as const) {
|
|
168
|
+
cleanups.push(api.on(event, queueRefresh));
|
|
169
|
+
}
|
|
170
|
+
dialog.addEventListener("close", () => { shown = null; });
|
|
171
|
+
|
|
172
|
+
let disposed = false;
|
|
173
|
+
refresh();
|
|
174
|
+
|
|
175
|
+
return {
|
|
176
|
+
refresh,
|
|
177
|
+
open(passage: string) {
|
|
178
|
+
const panel = panels.find(p => p.passage == passage);
|
|
179
|
+
if (panel) open(panel);
|
|
180
|
+
},
|
|
181
|
+
dispose() {
|
|
182
|
+
disposed = true;
|
|
183
|
+
if (dialog.open) dialog.close();
|
|
184
|
+
for (const cleanup of cleanups.splice(0)) cleanup();
|
|
185
|
+
},
|
|
186
|
+
};
|
|
187
|
+
}
|
|
@@ -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
|
+
});
|