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
package/src/textProcessor.ts
CHANGED
|
@@ -1,8 +1,50 @@
|
|
|
1
1
|
import * as marked from "marked";
|
|
2
2
|
import Handlebars from "handlebars";
|
|
3
|
-
import { Section, Story } from "./types.js";
|
|
3
|
+
import { Section, Story, TagFilter } from "./types.js";
|
|
4
4
|
import { State } from "./state.js";
|
|
5
|
-
import { rewriteInfixExpressions } from "
|
|
5
|
+
import { rewriteInfixExpressions, rewriteValueExpression, splitSetters } from "squiffy-compiler/infix-expressions";
|
|
6
|
+
import { isNumeric, isBlank, toNumber } from "./numbers.js";
|
|
7
|
+
import { checkSegment, parsePath, valueAt, withValueAt } from "./paths.js";
|
|
8
|
+
import { parseDelay } from "./utils.js";
|
|
9
|
+
import { captureEveryBodies } from "./every.js";
|
|
10
|
+
import { listPassages, listSections, tagsOf } from "./storyLists.js";
|
|
11
|
+
|
|
12
|
+
// The built-in effects for {{#style}} (#453), in squiffy.runtime.css
|
|
13
|
+
const styleEffects = new Set([
|
|
14
|
+
"shake", "shudder", "rumble", "sway", "buoy", "pulse", "fade-in-out", "blink", "flicker",
|
|
15
|
+
"blur", "blurrier", "smear", "mirror", "upside-down",
|
|
16
|
+
"shadow", "emboss", "outline", "condense", "expand", "tall", "flat",
|
|
17
|
+
"double-underline", "wavy-underline", "double-strike", "wavy-strike",
|
|
18
|
+
]);
|
|
19
|
+
|
|
20
|
+
// An embed being shown (#450): its parameters, and the text it wraps, if any
|
|
21
|
+
interface EmbedScope {
|
|
22
|
+
params: Record<string, unknown>;
|
|
23
|
+
content?: () => string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// The comment {{clear}} writes (#524)
|
|
27
|
+
export const CLEAR_MARKER = "squiffy-clear";
|
|
28
|
+
|
|
29
|
+
// What's left of html once everything before its last {{clear}} is taken out, or null if it has none
|
|
30
|
+
export function afterClear(html: string): string | null {
|
|
31
|
+
if (!html.includes(`<!--${CLEAR_MARKER}-->`)) return null;
|
|
32
|
+
const template = document.createElement("template");
|
|
33
|
+
template.innerHTML = html;
|
|
34
|
+
// 128: NodeFilter.SHOW_COMMENT
|
|
35
|
+
const walker = document.createTreeWalker(template.content, 128);
|
|
36
|
+
let last: ChildNode | null = null;
|
|
37
|
+
while (walker.nextNode()) {
|
|
38
|
+
if ((walker.currentNode as Comment).data == CLEAR_MARKER) last = walker.currentNode as ChildNode;
|
|
39
|
+
}
|
|
40
|
+
if (!last) return null;
|
|
41
|
+
// Everything before it, at its own level and in each element it's inside, such as a paragraph
|
|
42
|
+
for (let node: Node | null = last; node && node !== template.content; node = node.parentNode) {
|
|
43
|
+
while (node.previousSibling) node.previousSibling.remove();
|
|
44
|
+
}
|
|
45
|
+
last.remove();
|
|
46
|
+
return template.innerHTML.trim();
|
|
47
|
+
}
|
|
6
48
|
|
|
7
49
|
export class TextProcessor {
|
|
8
50
|
getStory: () => Story;
|
|
@@ -18,61 +60,195 @@ export class TextProcessor {
|
|
|
18
60
|
this.getCurrentSection = currentSection;
|
|
19
61
|
this.handlebars = Handlebars.create();
|
|
20
62
|
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
63
|
+
// {{embed "name"}} shows a section's or passage's text here. It can be given parameters,
|
|
64
|
+
// {{embed "say" who="Ann"}}, which the embedded text reads as {{who}} and which hide any
|
|
65
|
+
// attribute with the same name, and it can wrap text, {{#embed "say"}}Hello!{{/embed}},
|
|
66
|
+
// which the embedded text shows with {{content}} (#450).
|
|
67
|
+
// eslint-disable-next-line @typescript-eslint/no-this-alias
|
|
68
|
+
const processor = this;
|
|
69
|
+
this.handlebars.registerHelper("embed", function (this: unknown, ...args: any[]) {
|
|
70
|
+
const options = args.pop();
|
|
71
|
+
const name = unwrapValue(args[0]);
|
|
72
|
+
const text = processor.embeddedText(name);
|
|
73
|
+
if (text === undefined) return;
|
|
74
|
+
|
|
75
|
+
const params: Record<string, unknown> = Object.create(null);
|
|
76
|
+
for (const [key, value] of Object.entries(options.hash ?? {})) params[key] = unwrapValue(value);
|
|
77
|
+
|
|
78
|
+
// The wrapped text is filled in with the caller's attributes and parameters, not the
|
|
79
|
+
// embedded text's, so it's shown with the scopes as they are here
|
|
80
|
+
const callerScopes = processor.scopes;
|
|
81
|
+
const content = options.fn
|
|
82
|
+
? () => {
|
|
83
|
+
const inner = processor.scopes;
|
|
84
|
+
processor.scopes = callerScopes;
|
|
85
|
+
try {
|
|
86
|
+
return options.fn(this, { data: options.data });
|
|
87
|
+
} finally {
|
|
88
|
+
processor.scopes = inner;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
: undefined;
|
|
92
|
+
|
|
93
|
+
processor.scopes = [...callerScopes, { params, content }];
|
|
94
|
+
try {
|
|
95
|
+
return new Handlebars.SafeString(processor.process(text, true));
|
|
96
|
+
} finally {
|
|
97
|
+
processor.scopes = callerScopes;
|
|
29
98
|
}
|
|
30
99
|
});
|
|
31
100
|
|
|
101
|
+
// Inside an embed that wraps text, that text (#450). A story can have an attribute
|
|
102
|
+
// called content, which {{content}} shows when there's no wrapped text.
|
|
103
|
+
this.handlebars.registerHelper("content", () => {
|
|
104
|
+
const scope = this.scopes[this.scopes.length - 1];
|
|
105
|
+
if (scope?.content) return new Handlebars.SafeString(scope.content());
|
|
106
|
+
if (this.hasAttribute("content")) return this.getAttribute("content");
|
|
107
|
+
return "";
|
|
108
|
+
});
|
|
109
|
+
|
|
32
110
|
this.handlebars.registerHelper("seen", (name: string) => this.state.getSeen(name));
|
|
33
|
-
this.handlebars.registerHelper("
|
|
111
|
+
this.handlebars.registerHelper("visits", (name: string) => this.state.getVisits(name));
|
|
112
|
+
this.handlebars.registerHelper("lastvisited", (name: string) => this.state.getLastVisited(name));
|
|
113
|
+
this.handlebars.registerHelper("get", (attribute: string) => this.getAttribute(attribute));
|
|
34
114
|
this.handlebars.registerHelper("at", (section: string | string[]) => {
|
|
35
|
-
const currentSection = this.
|
|
115
|
+
const currentSection = this.getAttribute("_section");
|
|
36
116
|
if (Array.isArray(section)) {
|
|
37
117
|
return section.includes(currentSection);
|
|
38
118
|
}
|
|
39
119
|
return currentSection === section;
|
|
40
120
|
});
|
|
41
121
|
|
|
42
|
-
// Unwrap SafeString values from subexpressions, but
|
|
122
|
+
// Unwrap SafeString values from subexpressions, but keep lists and objects (#442)
|
|
43
123
|
const unwrapValue = (value: any): any => {
|
|
44
|
-
if (value && typeof value === "object" && typeof value.
|
|
124
|
+
if (value && typeof value === "object" && typeof value.toHTML === "function") {
|
|
45
125
|
return value.toString();
|
|
46
126
|
}
|
|
47
127
|
return value;
|
|
48
128
|
};
|
|
49
129
|
|
|
130
|
+
// {{goto "section"}} and {{goto "section" after=3000}} (#375): the runtime goes there once
|
|
131
|
+
// the section or passage being shown has been written. Only the first one counts.
|
|
132
|
+
this.handlebars.registerHelper("goto", (...args: any[]) => {
|
|
133
|
+
const options = args.pop();
|
|
134
|
+
const section = args.length ? unwrapValue(args[0]) : undefined;
|
|
135
|
+
if (typeof section != "string" || !section || !(section in this.getStory().sections)) {
|
|
136
|
+
return new Handlebars.SafeString(errorHtml("Error in {{goto}}:",
|
|
137
|
+
section === undefined ? "expected a section name, e.g. {{goto \"cave\"}}" : `there is no section called "${section}"`));
|
|
138
|
+
}
|
|
139
|
+
let after = 0;
|
|
140
|
+
if (options.hash.after !== undefined) {
|
|
141
|
+
// A number of milliseconds, or a time like "3s" (#451)
|
|
142
|
+
const delay = parseDelay(unwrapValue(options.hash.after));
|
|
143
|
+
if (delay === null) {
|
|
144
|
+
return new Handlebars.SafeString(errorHtml("Error in {{goto}}:",
|
|
145
|
+
`after= should be a number of milliseconds or a time, e.g. after=3000 or after="3s", not "${options.hash.after}"`));
|
|
146
|
+
}
|
|
147
|
+
after = delay;
|
|
148
|
+
}
|
|
149
|
+
this.goto ??= { section, after };
|
|
150
|
+
return "";
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// {{#every 1000}}...{{/every}} (#451): text that's shown again and again while the player
|
|
154
|
+
// is in the section. This only writes the element: the runtime's timers show the text
|
|
155
|
+
// (see every.ts), first after one delay, as in Twine.
|
|
156
|
+
this.handlebars.registerHelper("every", (...args: any[]) => {
|
|
157
|
+
const options = args.pop();
|
|
158
|
+
const error = (message: string) => new Handlebars.SafeString(errorHtml("Error in {{#every}}:", message));
|
|
159
|
+
const delay = args.length ? parseDelay(unwrapValue(args[0])) : null;
|
|
160
|
+
if (delay === null || delay <= 0) {
|
|
161
|
+
return error(`expected how often to show the text, as a number of milliseconds or a time, e.g. {{#every 1000}} or {{#every "1s"}}${args.length ? `, not "${args[0]}"` : ""}`);
|
|
162
|
+
}
|
|
163
|
+
const body = options.hash.__body;
|
|
164
|
+
if (typeof options.fn != "function" || typeof body != "string") {
|
|
165
|
+
return error("it needs some text to show, e.g. {{#every 1000}}Tick.{{/every}}");
|
|
166
|
+
}
|
|
167
|
+
let attrs = ` data-every="${body}" data-every-delay="${delay}" data-every-count="0"`;
|
|
168
|
+
if (options.hash.times !== undefined) {
|
|
169
|
+
const times = Number(unwrapValue(options.hash.times));
|
|
170
|
+
if (!Number.isInteger(times) || times < 1) {
|
|
171
|
+
return error(`times= should be a whole number of times, e.g. times=10, not "${options.hash.times}"`);
|
|
172
|
+
}
|
|
173
|
+
attrs += ` data-every-times="${times}"`;
|
|
174
|
+
}
|
|
175
|
+
if (options.hash.append) attrs += " data-every-append=\"\"";
|
|
176
|
+
// Text with paragraphs in it is a block, like {{#animate}}'s
|
|
177
|
+
const tag = decodeURIComponent(body).includes("\n\n") ? "div" : "span";
|
|
178
|
+
return new Handlebars.SafeString(`<${tag} class="squiffy-every"${attrs}></${tag}>`);
|
|
179
|
+
});
|
|
180
|
+
|
|
181
|
+
// {{clear}} (#524): like @clear, but it can be in an {{#if}}. It writes a comment that the
|
|
182
|
+
// runtime finds once the text is rendered, and clears the screen before writing what comes after.
|
|
183
|
+
this.handlebars.registerHelper("clear", () => new Handlebars.SafeString(`<!--${CLEAR_MARKER}-->`));
|
|
184
|
+
|
|
185
|
+
// {{stop}} (#451): the {{#every}} whose text this is stops after this time
|
|
186
|
+
this.handlebars.registerHelper("stop", () => {
|
|
187
|
+
this.stopEvery = true;
|
|
188
|
+
return "";
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// {{deactivate "name"}} (#13): the runtime disables the links to that passage on the screen
|
|
192
|
+
// once the section or passage being shown has been written. With no name, it's the passage
|
|
193
|
+
// being shown, e.g. one with @repeat that the player is done with (#104).
|
|
194
|
+
this.handlebars.registerHelper("deactivate", (...args: any[]) => {
|
|
195
|
+
args.pop();
|
|
196
|
+
const names = args.length ? args.map(unwrapValue) : [this.getAttribute("_passage")];
|
|
197
|
+
for (const name of names) {
|
|
198
|
+
if (typeof name != "string" || !name) {
|
|
199
|
+
return new Handlebars.SafeString(errorHtml("Error in {{deactivate}}:",
|
|
200
|
+
args.length ? "expected a passage name, e.g. {{deactivate \"door\"}}" : "{{deactivate}} with no passage name only works in a passage"));
|
|
201
|
+
}
|
|
202
|
+
const sectionPassages = this.getCurrentSection()?.passages;
|
|
203
|
+
const masterPassages = this.getStory().sections[""]?.passages;
|
|
204
|
+
if (!(sectionPassages && name in sectionPassages) && !(masterPassages && name in masterPassages)) {
|
|
205
|
+
return new Handlebars.SafeString(errorHtml("Error in {{deactivate}}:", `there is no passage called "${name}" in this section`));
|
|
206
|
+
}
|
|
207
|
+
this.deactivate.add(name);
|
|
208
|
+
}
|
|
209
|
+
return "";
|
|
210
|
+
});
|
|
211
|
+
|
|
50
212
|
// State modification helpers (side effects, no output)
|
|
51
213
|
// These execute at render time, so they respect {{#if}} conditions
|
|
52
214
|
this.handlebars.registerHelper("set", (attribute: string, value: any) => {
|
|
53
|
-
this.
|
|
215
|
+
this.setAttribute(attribute, unwrapValue(value));
|
|
54
216
|
return "";
|
|
55
217
|
});
|
|
56
218
|
|
|
57
|
-
|
|
58
|
-
|
|
219
|
+
// Captures a value for evaluate()
|
|
220
|
+
this.handlebars.registerHelper("__value", (value: unknown) => {
|
|
221
|
+
this.evaluated = unwrapValue(value);
|
|
59
222
|
return "";
|
|
60
223
|
});
|
|
61
224
|
|
|
62
|
-
this.handlebars.registerHelper("
|
|
63
|
-
|
|
64
|
-
const currentValue = this.state.get(attribute) || 0;
|
|
65
|
-
this.state.set(attribute, currentValue + amount);
|
|
225
|
+
this.handlebars.registerHelper("unset", (attribute: string) => {
|
|
226
|
+
this.setAttribute(attribute, false);
|
|
66
227
|
return "";
|
|
67
228
|
});
|
|
68
229
|
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
230
|
+
// {{forget}} clears the story's persistent attributes (squiffy.json's "persistent", #539),
|
|
231
|
+
// and {{forget "endings" "finished"}} just those
|
|
232
|
+
this.handlebars.registerHelper("forget", (...args: any[]) => {
|
|
233
|
+
args.pop();
|
|
234
|
+
const names = args.map(name => String(unwrapValue(name)));
|
|
235
|
+
this.state.forget(names.length ? names : undefined);
|
|
73
236
|
return "";
|
|
74
237
|
});
|
|
75
238
|
|
|
239
|
+
// {{inc "x"}} adds 1, and {{inc "x" amount}} adds the amount. Handlebars passes its options
|
|
240
|
+
// object last, so the amount is there if there's anything before it.
|
|
241
|
+
const incDecHelper = (name: string, sign: 1 | -1) => {
|
|
242
|
+
this.handlebars.registerHelper(name, (attribute: string, ...args: any[]) => {
|
|
243
|
+
const amount = args.length > 1 ? toNumber(name, unwrapValue(args[0])) : 1;
|
|
244
|
+
const currentValue = toNumber(name, this.getAttribute(attribute));
|
|
245
|
+
this.setAttribute(attribute, currentValue + sign * amount);
|
|
246
|
+
return "";
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
incDecHelper("inc", 1);
|
|
250
|
+
incDecHelper("dec", -1);
|
|
251
|
+
|
|
76
252
|
this.handlebars.registerHelper("and", (...args) => args.slice(0,-1).every(Boolean));
|
|
77
253
|
this.handlebars.registerHelper("or", (...args) => args.slice(0,-1).some(Boolean));
|
|
78
254
|
this.handlebars.registerHelper("not", (v) => !v);
|
|
@@ -82,15 +258,188 @@ export class TextProcessor {
|
|
|
82
258
|
this.handlebars.registerHelper("lt", (a,b) => a < b);
|
|
83
259
|
this.handlebars.registerHelper("gte", (a,b) => a >= b);
|
|
84
260
|
this.handlebars.registerHelper("lte", (a,b) => a <= b);
|
|
261
|
+
// Maths helpers. These are what arithmetic in infix expressions is rewritten to,
|
|
262
|
+
// e.g. {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
|
|
263
|
+
const mathsHelper = (name: string, fn: (a: number, b: number) => number) => {
|
|
264
|
+
this.handlebars.registerHelper(name, (...args) => {
|
|
265
|
+
const values = args.slice(0, -1).map(unwrapValue);
|
|
266
|
+
if (values.length !== 2) {
|
|
267
|
+
throw new Error(`"${name}" needs two values, but was given ${values.length}`);
|
|
268
|
+
}
|
|
269
|
+
return fn(toNumber(name, values[0]), toNumber(name, values[1]));
|
|
270
|
+
});
|
|
271
|
+
};
|
|
272
|
+
// "add" joins text when either value isn't a number (or a string holding one),
|
|
273
|
+
// so name + " the Brave" works, but an attribute holding "5" still adds as 5.
|
|
274
|
+
this.handlebars.registerHelper("add", (...args) => {
|
|
275
|
+
const values = args.slice(0, -1).map(unwrapValue);
|
|
276
|
+
if (values.length !== 2) {
|
|
277
|
+
throw new Error(`"add" needs two values, but was given ${values.length}`);
|
|
278
|
+
}
|
|
279
|
+
const [a, b] = values;
|
|
280
|
+
if (isNumeric(a) && isNumeric(b)) {
|
|
281
|
+
return toNumber("add", a) + toNumber("add", b);
|
|
282
|
+
}
|
|
283
|
+
const text = (v: any) => {
|
|
284
|
+
if (isBlank(v)) return "";
|
|
285
|
+
if (typeof v === "object") {
|
|
286
|
+
throw new Error(`"add" can't add ${Array.isArray(v) ? "a list" : "an object"}`);
|
|
287
|
+
}
|
|
288
|
+
return String(v);
|
|
289
|
+
};
|
|
290
|
+
return text(a) + text(b);
|
|
291
|
+
});
|
|
292
|
+
mathsHelper("sub", (a, b) => a - b);
|
|
293
|
+
mathsHelper("mul", (a, b) => a * b);
|
|
294
|
+
mathsHelper("div", (a, b) => {
|
|
295
|
+
if (b === 0) throw new Error("division by zero");
|
|
296
|
+
return a / b;
|
|
297
|
+
});
|
|
298
|
+
mathsHelper("mod", (a, b) => {
|
|
299
|
+
if (b === 0) throw new Error("division by zero");
|
|
300
|
+
return a % b;
|
|
301
|
+
});
|
|
302
|
+
|
|
303
|
+
// A story can have an attribute with the same name as a helper, such as count or min,
|
|
304
|
+
// which {{count}} on its own would call the helper for, with no values. So the helpers
|
|
305
|
+
// below that need values show the attribute instead, when there is one.
|
|
306
|
+
// Rounding (#446). (round x) rounds to a whole number, and (round x 2) to 2 decimal places.
|
|
307
|
+
// Numbers halfway between round up, as Math.round does, and as Harlowe's (round:) does.
|
|
308
|
+
const roundingHelper = (name: string, fn: (n: number) => number, places: boolean) => {
|
|
309
|
+
this.handlebars.registerHelper(name, (...args) => {
|
|
310
|
+
const values = args.slice(0, -1).map(unwrapValue);
|
|
311
|
+
if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
|
|
312
|
+
if (values.length !== 1 && !(places && values.length === 2)) {
|
|
313
|
+
throw new Error(`"${name}" needs ${places ? "one or two values" : "one value"}, but was given ${values.length}`);
|
|
314
|
+
}
|
|
315
|
+
const n = toNumber(name, values[0]);
|
|
316
|
+
if (values.length === 1) return fn(n);
|
|
317
|
+
const scale = 10 ** toNumber(name, values[1]);
|
|
318
|
+
// toPrecision tidies up floating point errors, so (round 1.005 2) is 1.01, not 1
|
|
319
|
+
return fn(Number((n * scale).toPrecision(15))) / scale;
|
|
320
|
+
});
|
|
321
|
+
};
|
|
322
|
+
roundingHelper("round", Math.round, true);
|
|
323
|
+
roundingHelper("floor", Math.floor, false);
|
|
324
|
+
roundingHelper("ceil", Math.ceil, false);
|
|
325
|
+
roundingHelper("abs", Math.abs, false);
|
|
326
|
+
|
|
327
|
+
// (min a b c) or (min list): the smallest of the values
|
|
328
|
+
const extremeHelper = (name: string, fn: (...values: number[]) => number) => {
|
|
329
|
+
this.handlebars.registerHelper(name, (...args) => {
|
|
330
|
+
let values = args.slice(0, -1).map(unwrapValue);
|
|
331
|
+
if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
|
|
332
|
+
if (values.length === 1 && Array.isArray(values[0])) {
|
|
333
|
+
values = values[0].map(unwrapValue);
|
|
334
|
+
}
|
|
335
|
+
if (values.length === 0) {
|
|
336
|
+
throw new Error(`"${name}" needs at least one value`);
|
|
337
|
+
}
|
|
338
|
+
return fn(...values.map(v => toNumber(name, v)));
|
|
339
|
+
});
|
|
340
|
+
};
|
|
341
|
+
extremeHelper("min", Math.min);
|
|
342
|
+
extremeHelper("max", Math.max);
|
|
343
|
+
|
|
344
|
+
// Text helpers (#446). A blank value (unset, false or "") is empty text, and a number
|
|
345
|
+
// is turned into text.
|
|
346
|
+
const toText = (name: string, v: unknown) => {
|
|
347
|
+
if (isBlank(v)) return "";
|
|
348
|
+
if (typeof v === "object") {
|
|
349
|
+
throw new Error(`"${name}" needs text, but was given ${Array.isArray(v) ? "a list" : "an object"}`);
|
|
350
|
+
}
|
|
351
|
+
return String(v);
|
|
352
|
+
};
|
|
353
|
+
const textHelper = (name: string, fn: (s: string) => string) => {
|
|
354
|
+
this.handlebars.registerHelper(name, (...args) => {
|
|
355
|
+
const values = args.slice(0, -1).map(unwrapValue);
|
|
356
|
+
if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
|
|
357
|
+
if (values.length !== 1) {
|
|
358
|
+
throw new Error(`"${name}" needs one value, but was given ${values.length}`);
|
|
359
|
+
}
|
|
360
|
+
return fn(toText(name, values[0]));
|
|
361
|
+
});
|
|
362
|
+
};
|
|
363
|
+
textHelper("upper", s => s.toUpperCase());
|
|
364
|
+
textHelper("lower", s => s.toLowerCase());
|
|
365
|
+
const capitalise = (s: string) => s.charAt(0).toUpperCase() + s.substring(1);
|
|
366
|
+
textHelper("capitalise", capitalise);
|
|
367
|
+
textHelper("capitalize", capitalise);
|
|
368
|
+
|
|
369
|
+
// {{#once}}...{{else}}...{{/once}} shows its text the first time it's shown, and the
|
|
370
|
+
// {{else}} text (or nothing) after that. Each one remembers for itself, wherever it is:
|
|
371
|
+
// in a section or passage shown again, or in text embedded in several places. Which ones
|
|
372
|
+
// have been shown is in _once, an attribute, so going back undoes it. One with a name,
|
|
373
|
+
// {{#once "warning"}}, shares its memory with the others of that name. firsttime, as
|
|
374
|
+
// Quest has it, is another name for once.
|
|
375
|
+
const once = function (this: unknown, ...args: any[]) {
|
|
376
|
+
const options = args.pop();
|
|
377
|
+
if (typeof options?.fn != "function") {
|
|
378
|
+
throw new Error("once wraps the text to show the first time: {{#once}}...{{/once}}");
|
|
379
|
+
}
|
|
380
|
+
const name = args.length ? unwrapValue(args[0]) : undefined;
|
|
381
|
+
if (args.length && (typeof name != "string" || !name)) {
|
|
382
|
+
throw new Error("the name of a {{#once}} is text, such as {{#once \"warning\"}}");
|
|
383
|
+
}
|
|
384
|
+
const key = name ?? processor.positionKey(options.loc);
|
|
385
|
+
const shown: string[] = processor.state.get("_once") || [];
|
|
386
|
+
if (shown.includes(key)) return options.inverse(this);
|
|
387
|
+
processor.state.set("_once", [...shown, key]);
|
|
388
|
+
return options.fn(this);
|
|
389
|
+
};
|
|
390
|
+
this.handlebars.registerHelper("once", once);
|
|
391
|
+
this.handlebars.registerHelper("firsttime", once);
|
|
392
|
+
|
|
393
|
+
// (cond test a b) is a if test is true, otherwise b (#446). It's what a ? b : c in an
|
|
394
|
+
// expression is rewritten to. Handlebars works out both a and b before calling it, so a
|
|
395
|
+
// helper with side effects, such as (pop "list"), runs whichever is chosen.
|
|
396
|
+
this.handlebars.registerHelper("cond", (...args) => {
|
|
397
|
+
const values = args.slice(0, -1).map(unwrapValue);
|
|
398
|
+
if (values.length === 0 && this.hasAttribute("cond")) return this.getAttribute("cond");
|
|
399
|
+
if (values.length !== 3) {
|
|
400
|
+
throw new Error(`"cond" needs three values, but was given ${values.length}`);
|
|
401
|
+
}
|
|
402
|
+
return values[0] ? values[1] : values[2];
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// a contains b in an expression (#446): whether list a has b in it, text a has the text b
|
|
406
|
+
// in it, or object a has a property called b. Unlike (contains "list" value), which
|
|
407
|
+
// looks up the list by its name, a here is the value itself.
|
|
408
|
+
this.handlebars.registerHelper("__contains", (container: any, value: any) => {
|
|
409
|
+
container = unwrapValue(container);
|
|
410
|
+
value = unwrapValue(value);
|
|
411
|
+
if (Array.isArray(container)) {
|
|
412
|
+
return container.some(item => unwrapValue(item) === value);
|
|
413
|
+
}
|
|
414
|
+
if (isBlank(container)) return false;
|
|
415
|
+
if (typeof container === "object") {
|
|
416
|
+
return Object.prototype.hasOwnProperty.call(container, String(value));
|
|
417
|
+
}
|
|
418
|
+
return String(container).includes(toText("contains", value));
|
|
419
|
+
});
|
|
420
|
+
|
|
85
421
|
this.handlebars.registerHelper("array", function (...args) {
|
|
86
422
|
args.pop(); // remove last argument - options
|
|
87
|
-
return args;
|
|
423
|
+
return args.map(unwrapValue);
|
|
424
|
+
});
|
|
425
|
+
|
|
426
|
+
// An object literal in an expression, e.g. { hp: 10, name: "Ann" } (#442), which
|
|
427
|
+
// compiler/src/infix-expressions.ts rewrites to (__object "hp" 10 "name" "Ann")
|
|
428
|
+
this.handlebars.registerHelper("__object", (...args) => {
|
|
429
|
+
args.pop();
|
|
430
|
+
const result: Record<string, unknown> = {};
|
|
431
|
+
for (let i = 0; i < args.length; i += 2) {
|
|
432
|
+
const key = String(unwrapValue(args[i]));
|
|
433
|
+
checkSegment(key);
|
|
434
|
+
result[key] = unwrapValue(args[i + 1]);
|
|
435
|
+
}
|
|
436
|
+
return result;
|
|
88
437
|
});
|
|
89
438
|
|
|
90
439
|
// Array management helpers
|
|
91
440
|
|
|
92
441
|
this.handlebars.registerHelper("append", (listVar: string, value: any) => {
|
|
93
|
-
const currentArray = this.
|
|
442
|
+
const currentArray = this.getAttribute(listVar) || [];
|
|
94
443
|
const arr = Array.isArray(currentArray) ? [...currentArray] : [currentArray];
|
|
95
444
|
const unwrappedValue = unwrapValue(value);
|
|
96
445
|
if (Array.isArray(unwrappedValue)) {
|
|
@@ -98,12 +447,12 @@ export class TextProcessor {
|
|
|
98
447
|
} else {
|
|
99
448
|
arr.push(unwrappedValue);
|
|
100
449
|
}
|
|
101
|
-
this.
|
|
450
|
+
this.setAttribute(listVar, arr);
|
|
102
451
|
return "";
|
|
103
452
|
});
|
|
104
453
|
|
|
105
454
|
this.handlebars.registerHelper("prepend", (listVar: string, value: any) => {
|
|
106
|
-
const currentArray = this.
|
|
455
|
+
const currentArray = this.getAttribute(listVar) || [];
|
|
107
456
|
const arr = Array.isArray(currentArray) ? [...currentArray] : [currentArray];
|
|
108
457
|
const unwrappedValue = unwrapValue(value);
|
|
109
458
|
if (Array.isArray(unwrappedValue)) {
|
|
@@ -111,23 +460,23 @@ export class TextProcessor {
|
|
|
111
460
|
} else {
|
|
112
461
|
arr.unshift(unwrappedValue);
|
|
113
462
|
}
|
|
114
|
-
this.
|
|
463
|
+
this.setAttribute(listVar, arr);
|
|
115
464
|
return "";
|
|
116
465
|
});
|
|
117
466
|
|
|
118
467
|
this.handlebars.registerHelper("pop", (listVar: string) => {
|
|
119
|
-
const currentArray = this.
|
|
468
|
+
const currentArray = this.getAttribute(listVar) || [];
|
|
120
469
|
if (!Array.isArray(currentArray) || currentArray.length === 0) {
|
|
121
470
|
return "";
|
|
122
471
|
}
|
|
123
472
|
const arr = [...currentArray];
|
|
124
473
|
const item = arr.shift();
|
|
125
|
-
this.
|
|
474
|
+
this.setAttribute(listVar, arr);
|
|
126
475
|
return item;
|
|
127
476
|
});
|
|
128
477
|
|
|
129
478
|
this.handlebars.registerHelper("remove", (listVar: string, value: any) => {
|
|
130
|
-
const currentArray = this.
|
|
479
|
+
const currentArray = this.getAttribute(listVar) || [];
|
|
131
480
|
if (!Array.isArray(currentArray)) {
|
|
132
481
|
return "";
|
|
133
482
|
}
|
|
@@ -136,7 +485,7 @@ export class TextProcessor {
|
|
|
136
485
|
if (index !== -1) {
|
|
137
486
|
const arr = [...currentArray];
|
|
138
487
|
arr.splice(index, 1);
|
|
139
|
-
this.
|
|
488
|
+
this.setAttribute(listVar, arr);
|
|
140
489
|
}
|
|
141
490
|
return "";
|
|
142
491
|
});
|
|
@@ -144,7 +493,7 @@ export class TextProcessor {
|
|
|
144
493
|
this.handlebars.registerHelper("contains", (listOrVar: any, value: any) => {
|
|
145
494
|
let arr: any[];
|
|
146
495
|
if (typeof listOrVar === "string") {
|
|
147
|
-
const stored = this.
|
|
496
|
+
const stored = this.getAttribute(listOrVar);
|
|
148
497
|
arr = Array.isArray(stored) ? stored : [];
|
|
149
498
|
} else if (Array.isArray(listOrVar)) {
|
|
150
499
|
arr = listOrVar;
|
|
@@ -155,45 +504,369 @@ export class TextProcessor {
|
|
|
155
504
|
return arr.some(item => unwrapValue(item) === unwrappedValue);
|
|
156
505
|
});
|
|
157
506
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
507
|
+
// The number of items in an array, or of values in an object
|
|
508
|
+
this.handlebars.registerHelper("length", (...args: any[]) => {
|
|
509
|
+
// The last argument is Handlebars' options
|
|
510
|
+
if (args.length < 2) return 0;
|
|
511
|
+
const listOrVar = args[0];
|
|
512
|
+
const value = typeof listOrVar === "string" ? this.getAttribute(listOrVar) : listOrVar;
|
|
513
|
+
if (Array.isArray(value)) return value.length;
|
|
514
|
+
if (value && typeof value === "object" && !(value instanceof this.handlebars.SafeString)) return Object.keys(value).length;
|
|
515
|
+
return 0;
|
|
516
|
+
});
|
|
517
|
+
|
|
518
|
+
// More helpers for lists (#447). These take the list itself, (join bag), not its name in
|
|
519
|
+
// quotes as append and friends do, and give back a new list rather than changing the
|
|
520
|
+
// attribute, so @set bag = (sort bag) sorts it. A blank value (unset, false or "") is
|
|
521
|
+
// an empty list. Positions start at 0, as with bag[i] and {{@index}}.
|
|
522
|
+
const toList = (name: string, v: unknown): unknown[] => {
|
|
523
|
+
v = unwrapValue(v);
|
|
524
|
+
if (Array.isArray(v)) return v.map(unwrapValue);
|
|
525
|
+
if (isBlank(v)) return [];
|
|
526
|
+
if (typeof v === "string") {
|
|
527
|
+
throw new Error(`"${name}" needs a list, but was given the text "${v}". To use an attribute's list, leave out the quotes: (${name} bag), not (${name} "bag")`);
|
|
528
|
+
}
|
|
529
|
+
throw new Error(`"${name}" needs a list, but was given ${typeof v === "object" ? "an object" : String(v)}`);
|
|
530
|
+
};
|
|
531
|
+
const listHelper = (name: string, min: number, max: number, fn: (values: unknown[]) => unknown) => {
|
|
532
|
+
this.handlebars.registerHelper(name, (...args) => {
|
|
533
|
+
const values = args.slice(0, -1).map(unwrapValue);
|
|
534
|
+
if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
|
|
535
|
+
if (values.length < min || values.length > max) {
|
|
536
|
+
const needs = min === max ? `${min} value${min === 1 ? "" : "s"}` : `${min} to ${max} values`;
|
|
537
|
+
throw new Error(`"${name}" needs ${needs}, but was given ${values.length}`);
|
|
538
|
+
}
|
|
539
|
+
return fn(values);
|
|
540
|
+
});
|
|
541
|
+
};
|
|
542
|
+
// A whole number, for a position or a range
|
|
543
|
+
const toWhole = (name: string, v: unknown) => Math.trunc(toNumber(name, v));
|
|
544
|
+
|
|
545
|
+
// (join bag) is "lamp, key, rope", (join bag " / ") puts " / " between them, and
|
|
546
|
+
// (join bag ", " " and ") is "lamp, key and rope"
|
|
547
|
+
// As a block, {{#join bag ", " " and "}}...{{/join}} shows its text for each item, as
|
|
548
|
+
// {{#each}} does (with this, @index, @first and @last), and puts the separators between
|
|
549
|
+
// them, for lists of links (#525). {{else}} is shown for an empty list.
|
|
550
|
+
const joinTexts = (items: string[], sep: string, lastSep: string | undefined) => {
|
|
551
|
+
if (lastSep === undefined || items.length < 2) return items.join(sep);
|
|
552
|
+
return items.slice(0, -1).join(sep) + lastSep + items[items.length - 1];
|
|
553
|
+
};
|
|
554
|
+
this.handlebars.registerHelper("join", function (this: unknown, ...args: any[]) {
|
|
555
|
+
const options = args.pop();
|
|
556
|
+
const values = args.map(unwrapValue);
|
|
557
|
+
const block = typeof options?.fn === "function";
|
|
558
|
+
if (!block && values.length === 0 && processor.hasAttribute("join")) return processor.getAttribute("join");
|
|
559
|
+
if (values.length < 1 || values.length > 3) {
|
|
560
|
+
throw new Error(`"join" needs 1 to 3 values, but was given ${values.length}`);
|
|
561
|
+
}
|
|
562
|
+
const [list, separator, lastSeparator] = values;
|
|
563
|
+
const sep = separator === undefined ? ", " : toText("join", separator);
|
|
564
|
+
const lastSep = lastSeparator === undefined ? undefined : toText("join", lastSeparator);
|
|
565
|
+
const items = toList("join", list);
|
|
566
|
+
if (!block) return joinTexts(items.map(item => toText("join", item)), sep, lastSep);
|
|
567
|
+
|
|
568
|
+
if (items.length === 0) return options.inverse(this);
|
|
569
|
+
const escape = Handlebars.Utils.escapeExpression;
|
|
570
|
+
const texts = items.map((item, index) => {
|
|
571
|
+
const data = Handlebars.createFrame(options.data ?? {});
|
|
572
|
+
data.index = index;
|
|
573
|
+
data.first = index === 0;
|
|
574
|
+
data.last = index === items.length - 1;
|
|
575
|
+
return String(options.fn(item, { data, blockParams: [item, index] }));
|
|
576
|
+
});
|
|
577
|
+
return joinTexts(texts, escape(sep), lastSep === undefined ? undefined : escape(lastSep));
|
|
578
|
+
});
|
|
579
|
+
|
|
580
|
+
// Numbers go before text, in order, and text is in alphabetical order, ignoring case,
|
|
581
|
+
// with numbers inside it in order too ("item 2" before "item 10")
|
|
582
|
+
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
|
|
583
|
+
listHelper("sort", 1, 1, ([list]) => toList("sort", list).sort((a, b) => {
|
|
584
|
+
const aNum = typeof a === "number", bNum = typeof b === "number";
|
|
585
|
+
if (aNum && bNum) return (a as number) - (b as number);
|
|
586
|
+
if (aNum !== bNum) return aNum ? -1 : 1;
|
|
587
|
+
return collator.compare(toText("sort", a), toText("sort", b));
|
|
588
|
+
}));
|
|
589
|
+
|
|
590
|
+
listHelper("shuffle", 1, 1, ([list]) => {
|
|
591
|
+
const items = toList("shuffle", list);
|
|
592
|
+
for (let i = items.length - 1; i > 0; i--) {
|
|
593
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
594
|
+
[items[i], items[j]] = [items[j], items[i]];
|
|
595
|
+
}
|
|
596
|
+
return items;
|
|
597
|
+
});
|
|
598
|
+
|
|
599
|
+
// (slice bag 1 3) is the items from position 1 up to, but not including, 3, and
|
|
600
|
+
// (slice bag 1) is the rest from position 1. A negative position counts from the end,
|
|
601
|
+
// so (slice bag -2) is the last two. It takes part of some text in the same way.
|
|
602
|
+
listHelper("slice", 2, 3, ([container, start, end]) => {
|
|
603
|
+
const from = toWhole("slice", start), to = end === undefined ? undefined : toWhole("slice", end);
|
|
604
|
+
return typeof container === "string" ? container.slice(from, to) : toList("slice", container).slice(from, to);
|
|
605
|
+
});
|
|
606
|
+
|
|
607
|
+
// The first or last item, or nothing for an empty list
|
|
608
|
+
listHelper("first", 1, 1, ([list]) => toList("first", list)[0] ?? "");
|
|
609
|
+
listHelper("last", 1, 1, ([list]) => toList("last", list).slice(-1)[0] ?? "");
|
|
610
|
+
|
|
611
|
+
// Where a value is in a list (from 0), or where some text is in text, or -1 if it isn't
|
|
612
|
+
listHelper("indexof", 2, 2, ([container, value]) => {
|
|
613
|
+
if (typeof container === "string") return container.indexOf(toText("indexof", value));
|
|
614
|
+
return toList("indexof", container).indexOf(value);
|
|
615
|
+
});
|
|
616
|
+
|
|
617
|
+
// How many times a value is in a list, or some text is in text
|
|
618
|
+
listHelper("count", 2, 2, ([container, value]) => {
|
|
619
|
+
if (typeof container === "string") {
|
|
620
|
+
const text = toText("count", value);
|
|
621
|
+
return text === "" ? 0 : container.split(text).length - 1;
|
|
622
|
+
}
|
|
623
|
+
return toList("count", container).filter(item => item === value).length;
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
// (range 1 5) is the list 1, 2, 3, 4, 5, and (range 5 1) counts down
|
|
627
|
+
listHelper("range", 2, 2, ([from, to]) => {
|
|
628
|
+
const start = toWhole("range", from), end = toWhole("range", to);
|
|
629
|
+
if (Math.abs(end - start) >= 10000) {
|
|
630
|
+
throw new Error(`"range" can make a list of up to 10,000 numbers, but was asked for ${Math.abs(end - start) + 1}`);
|
|
167
631
|
}
|
|
168
|
-
|
|
632
|
+
const step = end >= start ? 1 : -1;
|
|
633
|
+
const result: number[] = [];
|
|
634
|
+
for (let n = start; n !== end + step; n += step) result.push(n);
|
|
635
|
+
return result;
|
|
636
|
+
});
|
|
637
|
+
|
|
638
|
+
// (passages) lists the current section's passages and the master section's, (passages
|
|
639
|
+
// "carriage") a section's ("" for the master section's), and (sections) the story's
|
|
640
|
+
// sections, leaving out @1, @last and @after. tagged="passenger" lists only those with
|
|
641
|
+
// that @tag, and untagged="settled" leaves out those with it. (tags "name") is a
|
|
642
|
+
// passage's or section's tags (#527). Like the list helpers, with nothing given, they're
|
|
643
|
+
// the attribute with the same name if there is one.
|
|
644
|
+
const filterOf = (options: any): TagFilter => ({
|
|
645
|
+
tagged: unwrapValue(options.hash?.tagged), untagged: unwrapValue(options.hash?.untagged),
|
|
646
|
+
});
|
|
647
|
+
const storyListHelper = (name: string, max: number, fn: (values: unknown[], options: any) => unknown) => {
|
|
648
|
+
this.handlebars.registerHelper(name, (...args) => {
|
|
649
|
+
const options = args.pop();
|
|
650
|
+
const values = args.map(unwrapValue);
|
|
651
|
+
if (!values.length && !Object.keys(options.hash ?? {}).length && this.hasAttribute(name)) return this.getAttribute(name);
|
|
652
|
+
if (values.length > max) {
|
|
653
|
+
throw new Error(`"${name}" needs ${max ? `at most ${max} value` : "no values"}, but was given ${values.length}`);
|
|
654
|
+
}
|
|
655
|
+
return fn(values, options);
|
|
656
|
+
});
|
|
657
|
+
};
|
|
658
|
+
storyListHelper("passages", 1, ([section], options) =>
|
|
659
|
+
listPassages(this.getStory(), section === undefined ? undefined : String(section), this.getAttribute("_section"), filterOf(options)));
|
|
660
|
+
storyListHelper("sections", 0, (_, options) => listSections(this.getStory(), filterOf(options)));
|
|
661
|
+
storyListHelper("tags", 1, ([name]) => {
|
|
662
|
+
const current = this.getAttribute("_section");
|
|
663
|
+
return name === undefined ? [...(this.getStory().sections[current]?.tags ?? [])] : tagsOf(this.getStory(), String(name), current);
|
|
169
664
|
});
|
|
170
665
|
|
|
171
|
-
const
|
|
666
|
+
const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&").replace(/"/g, """);
|
|
667
|
+
|
|
668
|
+
// A link's text and setters can have {{...}} in them, such as [[Drop the {{this}}]](drop,
|
|
669
|
+
// item = "{{this}}") inside an {{#each}}. They're filled in where the link is, so they see
|
|
670
|
+
// the loop's item. Setters aren't HTML, so their values aren't escaped.
|
|
671
|
+
const linkTemplates = new Map<string, HandlebarsTemplateDelegate>();
|
|
672
|
+
const fillIn = (text: unknown, context: unknown, options: any, escape: boolean) => {
|
|
673
|
+
if (typeof text != "string" || !text.includes("{{")) return text;
|
|
674
|
+
const key = (escape ? "h:" : "t:") + text;
|
|
675
|
+
let template = linkTemplates.get(key);
|
|
676
|
+
if (!template) {
|
|
677
|
+
template = this.handlebars.compile(rewriteInfixExpressions(text), { compat: true, noEscape: !escape });
|
|
678
|
+
linkTemplates.set(key, template);
|
|
679
|
+
}
|
|
680
|
+
return template(context, { data: options.data });
|
|
681
|
+
};
|
|
682
|
+
|
|
683
|
+
const addAdditionalParameters = (context: unknown, options: any) => {
|
|
172
684
|
let result = "";
|
|
173
|
-
const setters = options.hash.set as string || "";
|
|
685
|
+
const setters = fillIn(options.hash.set as string || "", context, options, false) as string;
|
|
174
686
|
if (setters) {
|
|
175
|
-
|
|
687
|
+
// With expressions, a setter can have commas inside quotes, e.g. greeting = "Hi, there"
|
|
688
|
+
const list = this.getStory().expressions ? splitSetters(setters) : setters.split(",").map(s => s.trim());
|
|
689
|
+
result += ` data-set="${escapeAttr(JSON.stringify(list))}"`;
|
|
176
690
|
}
|
|
177
691
|
return result;
|
|
178
692
|
};
|
|
179
693
|
|
|
180
|
-
|
|
694
|
+
// Handlebars passes the context a helper is used in (inside an {{#each}}, the item) as this
|
|
695
|
+
this.handlebars.registerHelper("section", function (this: unknown, section: string, options) {
|
|
696
|
+
const text = fillIn(options.hash.text as string || section, this, options, true);
|
|
697
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-section" data-section="${escapeAttr(section)}"${addAdditionalParameters(this, options)} role="link" tabindex="0">${text}</a>`);
|
|
698
|
+
});
|
|
699
|
+
|
|
700
|
+
this.handlebars.registerHelper("passage", function (this: unknown, passage: string, options) {
|
|
701
|
+
const text = fillIn(options.hash.text as string || passage, this, options, true);
|
|
702
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${escapeAttr(passage)}"${addAdditionalParameters(this, options)} role="link" tabindex="0">${text}</a>`);
|
|
703
|
+
});
|
|
704
|
+
|
|
705
|
+
// {{restart}} and {{saves}} (#452): links that restart the story, asking first unless
|
|
706
|
+
// confirm=false, and open the Saved games dialog, like the page's own buttons
|
|
707
|
+
this.handlebars.registerHelper("restart", function (this: unknown, options) {
|
|
708
|
+
const text = fillIn(options.hash.text as string || processor.strings.restart, this, options, true);
|
|
709
|
+
const confirm = options.hash.confirm === false || options.hash.confirm === "false" ? " data-confirm=\"false\"" : "";
|
|
710
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-restart" data-handler="restart"${confirm} role="link" tabindex="0">${text}</a>`);
|
|
711
|
+
});
|
|
712
|
+
|
|
713
|
+
this.handlebars.registerHelper("saves", function (this: unknown, options) {
|
|
714
|
+
const text = fillIn(options.hash.text as string || processor.strings.saves, this, options, true);
|
|
715
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-saves" data-handler="saves" role="link" tabindex="0">${text}</a>`);
|
|
716
|
+
});
|
|
181
717
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
718
|
+
// {{settings}} (#452): a link that opens the Settings dialog, where the player changes the
|
|
719
|
+
// story's settings (squiffy.json's "settings")
|
|
720
|
+
this.handlebars.registerHelper("settings", function (this: unknown, options) {
|
|
721
|
+
const text = fillIn(options.hash.text as string || processor.strings.settings, this, options, true);
|
|
722
|
+
return new Handlebars.SafeString(`<a class="squiffy-link link-settings" data-handler="settings" role="link" tabindex="0">${text}</a>`);
|
|
185
723
|
});
|
|
186
724
|
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
725
|
+
// {{#style "warning"}}...{{/style}} (#453) gives the text it wraps one or more classes, for
|
|
726
|
+
// the story's own CSS or the built-in effects (shudder, blur, ...: .squiffy-style.shudder
|
|
727
|
+
// in squiffy.runtime.css). Text with blank lines in it is a block, so it gets a div.
|
|
728
|
+
this.handlebars.registerHelper("style", function (this: unknown, ...args: any[]) {
|
|
729
|
+
const options = args.pop();
|
|
730
|
+
// String(): text that's only one helper, such as an {{#every}}, comes back as the helper's
|
|
731
|
+
// SafeString
|
|
732
|
+
const content = typeof options?.fn == "function" ? String(options.fn(this)) : "";
|
|
733
|
+
const classes = args.flatMap(a => String(unwrapValue(a) ?? "").split(/\s+/)).filter(c => c.length > 0);
|
|
734
|
+
// An element has one animation and one transform, so a second effect would replace the
|
|
735
|
+
// first. Each effect after the first goes on an element of its own inside it, where
|
|
736
|
+
// they add up.
|
|
737
|
+
const extraEffects = classes.filter(c => styleEffects.has(c)).slice(1);
|
|
738
|
+
const outer = classes.filter(c => !extraEffects.includes(c));
|
|
739
|
+
const isBlock = content.includes("\n\n");
|
|
740
|
+
const tag = isBlock ? "div" : "span";
|
|
741
|
+
// The blank lines around a block's content let Markdown in it be rendered inside the div
|
|
742
|
+
let html = isBlock ? `\n\n${content.trim()}\n\n` : content;
|
|
743
|
+
for (const c of [...extraEffects].reverse()) {
|
|
744
|
+
html = `<${tag} class="squiffy-style ${escapeAttr(c)}">${html}</${tag}>`;
|
|
745
|
+
}
|
|
746
|
+
return new Handlebars.SafeString(`<${tag} class="${escapeAttr(["squiffy-style", ...outer].join(" "))}">${html}</${tag}>`);
|
|
747
|
+
});
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// The default text of {{restart}}, {{saves}} and {{settings}} links, which the runtime sets
|
|
751
|
+
// from the page's strings
|
|
752
|
+
strings = { restart: "Restart", saves: "Saved games", settings: "Settings" };
|
|
753
|
+
|
|
754
|
+
// Evaluates an expression, such as gold + price * 2, with the same rules and helpers as
|
|
755
|
+
// {{#if}} and {{set}}. Throws if it isn't valid, or a helper fails.
|
|
756
|
+
evaluate(expression: string): unknown {
|
|
757
|
+
let template = this.expressionCache.get(expression);
|
|
758
|
+
if (!template) {
|
|
759
|
+
template = this.handlebars.compile(`{{__value ${rewriteValueExpression(expression)}}}`);
|
|
760
|
+
this.expressionCache.set(expression, template);
|
|
761
|
+
}
|
|
762
|
+
this.evaluated = undefined;
|
|
763
|
+
template(this.context());
|
|
764
|
+
return this.evaluated;
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Where a {{goto}} asked to go. The runtime clears it before showing a section or passage, and
|
|
768
|
+
// follows it afterwards.
|
|
769
|
+
goto: { section: string; after: number } | null = null;
|
|
770
|
+
// The passages whose links a {{deactivate}} asked to disable. Like goto, the runtime clears it
|
|
771
|
+
// before showing a section or passage, and acts on it afterwards.
|
|
772
|
+
deactivate = new Set<string>();
|
|
773
|
+
// Set by a {{stop}} in an {{#every}}'s text (#451). The runtime clears it before showing the
|
|
774
|
+
// text, and checks it afterwards.
|
|
775
|
+
stopEvery = false;
|
|
776
|
+
|
|
777
|
+
// The embeds being shown, innermost last (#450). Each embed's text sees its own parameters
|
|
778
|
+
// and the story's attributes, but not the parameters of the embed it's inside.
|
|
779
|
+
private scopes: EmbedScope[] = [];
|
|
780
|
+
|
|
781
|
+
// The text {{embed "name"}} shows: a passage in the current section, or a section
|
|
782
|
+
private embeddedText(name: unknown): string | undefined {
|
|
783
|
+
if (typeof name != "string") return undefined;
|
|
784
|
+
const currentSection = this.getCurrentSection();
|
|
785
|
+
if (currentSection.passages && Object.prototype.hasOwnProperty.call(currentSection.passages, name)) {
|
|
786
|
+
return currentSection.passages[name].text || "";
|
|
787
|
+
}
|
|
788
|
+
const story = this.getStory();
|
|
789
|
+
if (Object.prototype.hasOwnProperty.call(story.sections, name)) {
|
|
790
|
+
return story.sections[name].text || "";
|
|
791
|
+
}
|
|
792
|
+
return undefined;
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
// The parameters of the embed being shown, if any
|
|
796
|
+
private get params(): Record<string, unknown> | undefined {
|
|
797
|
+
return this.scopes[this.scopes.length - 1]?.params;
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
private isParam(attribute: string) {
|
|
801
|
+
const params = this.params;
|
|
802
|
+
return !!params && Object.prototype.hasOwnProperty.call(params, parsePath(attribute)[0]);
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// Attributes, as the text being shown sees them: inside an embed, its parameters come first.
|
|
806
|
+
// A name can be a path, such as hero.hp, as for State.
|
|
807
|
+
hasAttribute(attribute: string) {
|
|
808
|
+
return this.isParam(attribute) || this.state.has(attribute);
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
getAttribute(attribute: string): any {
|
|
812
|
+
if (this.isParam(attribute)) {
|
|
813
|
+
const [name, ...inside] = parsePath(attribute);
|
|
814
|
+
return structuredClone(valueAt(this.params![name], inside));
|
|
815
|
+
}
|
|
816
|
+
return this.state.get(attribute);
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
// Setting a parameter changes it for the rest of that embed only. Anything else is the story's.
|
|
820
|
+
setAttribute(attribute: string, value: any) {
|
|
821
|
+
if (this.isParam(attribute)) {
|
|
822
|
+
const [name, ...inside] = parsePath(attribute);
|
|
823
|
+
if (typeof value === "undefined") value = true;
|
|
824
|
+
this.params![name] = inside.length ? withValueAt(this.params![name], inside, name, value) : structuredClone(value);
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
this.state.set(attribute, value);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
// What a template's names are looked up in: the story's attributes, with the parameters of
|
|
831
|
+
// the embed being shown in front of them
|
|
832
|
+
private context(): Record<string, any> {
|
|
833
|
+
const store = this.state.getStore();
|
|
834
|
+
const params = this.params;
|
|
835
|
+
if (!params || !Object.keys(params).length) return store;
|
|
836
|
+
const isParam = (prop: string | symbol) => typeof prop == "string" && Object.prototype.hasOwnProperty.call(params, prop);
|
|
837
|
+
return new Proxy({} as Record<string, any>, {
|
|
838
|
+
get: (_, prop) => isParam(prop) ? structuredClone(params[prop as string]) : Reflect.get(store, prop),
|
|
839
|
+
has: (_, prop) => isParam(prop) || Reflect.has(store, prop),
|
|
840
|
+
ownKeys: () => [...new Set([...Object.keys(params), ...Reflect.ownKeys(store)])],
|
|
841
|
+
getOwnPropertyDescriptor: (_, prop) => isParam(prop)
|
|
842
|
+
? { enumerable: true, configurable: true, value: structuredClone(params[prop as string]) }
|
|
843
|
+
: Reflect.getOwnPropertyDescriptor(store, prop),
|
|
190
844
|
});
|
|
191
845
|
}
|
|
192
846
|
|
|
847
|
+
// The texts being processed, innermost last: a section's or passage's, and any it embeds
|
|
848
|
+
private processing: string[] = [];
|
|
849
|
+
|
|
850
|
+
// Identifies a place in the text being processed, for a {{#once}} to remember itself by: a
|
|
851
|
+
// hash of the text, and where in it the block starts. A name that starts with a space can't
|
|
852
|
+
// be the name an author gave one.
|
|
853
|
+
private positionKey(loc?: { start: { line: number; column: number } }): string {
|
|
854
|
+
const text = this.processing[this.processing.length - 1] ?? "";
|
|
855
|
+
let hash = 5381;
|
|
856
|
+
for (let i = 0; i < text.length; i++) hash = ((hash * 33) ^ text.charCodeAt(i)) >>> 0;
|
|
857
|
+
return ` ${hash.toString(36)}:${loc?.start.line ?? 0}:${loc?.start.column ?? 0}`;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
private expressionCache = new Map<string, HandlebarsTemplateDelegate>();
|
|
861
|
+
// Where the __value helper puts the value of the expression being evaluated
|
|
862
|
+
private evaluated: unknown;
|
|
863
|
+
|
|
193
864
|
process(text: string, inline: boolean) {
|
|
865
|
+
this.processing.push(text);
|
|
194
866
|
try {
|
|
195
|
-
|
|
196
|
-
|
|
867
|
+
// compat: inside an {{#each}}, a name that isn't one of the item's looks for an attribute
|
|
868
|
+
const template = this.handlebars.compile(rewriteInfixExpressions(captureEveryBodies(text)), { compat: true });
|
|
869
|
+
text = template(this.context());
|
|
197
870
|
|
|
198
871
|
if (inline) {
|
|
199
872
|
return marked.parseInline(text, { async: false }).trim();
|
|
@@ -204,7 +877,15 @@ export class TextProcessor {
|
|
|
204
877
|
} catch (e) {
|
|
205
878
|
const errorMessage = e instanceof Error ? e.message : String(e);
|
|
206
879
|
console.error("Squiffy template error:", errorMessage);
|
|
207
|
-
return
|
|
880
|
+
return errorHtml("Template error:", errorMessage);
|
|
881
|
+
} finally {
|
|
882
|
+
this.processing.pop();
|
|
208
883
|
}
|
|
209
884
|
}
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
// The block that shows an error in the story's output
|
|
888
|
+
export function errorHtml(label: string, message: string) {
|
|
889
|
+
const escape = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
890
|
+
return `<div class="squiffy-error" style="color: red; background: #ffe0e0; padding: 8px; border: 1px solid red; margin: 4px 0; font-family: monospace; white-space: pre-wrap;"><strong>${escape(label)}</strong> ${escape(message)}</div>`;
|
|
210
891
|
}
|