squiffy-runtime 7.0.0-beta.7 → 7.0.0-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/confirmDialog.d.ts +8 -0
- package/dist/events.d.ts +10 -0
- package/dist/every.d.ts +12 -0
- package/dist/every.test.d.ts +1 -0
- package/dist/playerSettings.d.ts +17 -0
- package/dist/preview-html.js +1 -1
- package/dist/settings.test.d.ts +1 -0
- package/dist/settingsDialog.d.ts +17 -0
- package/dist/squiffy.page.css +4 -1
- package/dist/squiffy.preview.html +673 -83
- package/dist/squiffy.runtime.css +531 -1
- package/dist/squiffy.runtime.d.ts +5 -1
- package/dist/squiffy.runtime.global.js +106 -85
- package/dist/squiffy.runtime.global.js.map +1 -1
- package/dist/squiffy.runtime.js +4743 -4157
- package/dist/squiffy.runtime.js.map +1 -1
- package/dist/state.d.ts +1 -0
- package/dist/style.test.d.ts +1 -0
- package/dist/textProcessor.d.ts +8 -0
- package/dist/transitions.test.d.ts +1 -0
- package/dist/types.d.ts +43 -0
- package/dist/uiLinks.test.d.ts +1 -0
- package/dist/utils.d.ts +1 -0
- package/dist/utils.test.d.ts +1 -0
- package/package.json +3 -3
- package/src/animation.test.ts +44 -0
- package/src/animation.ts +7 -3
- package/src/confirmDialog.ts +66 -0
- package/src/events.ts +17 -0
- package/src/every.test.ts +25 -0
- package/src/every.ts +94 -0
- package/src/panels.test.ts +24 -0
- package/src/playerSettings.ts +128 -0
- package/src/plugins/animate.ts +9 -0
- package/src/plugins/live.ts +3 -1
- package/src/plugins/plugins.test.ts +17 -0
- package/src/preview.test.ts +53 -3
- package/src/preview.ts +60 -1
- package/src/settings.test.ts +233 -0
- package/src/settingsDialog.ts +160 -0
- package/src/squiffy.page.css +4 -1
- package/src/squiffy.runtime.css +531 -1
- package/src/squiffy.runtime.test.ts +613 -16
- package/src/squiffy.runtime.ts +372 -19
- package/src/state.ts +16 -1
- package/src/style.test.ts +89 -0
- package/src/textProcessor.ts +141 -6
- package/src/transitions.test.ts +302 -0
- package/src/types.ts +56 -0
- package/src/uiLinks.test.ts +156 -0
- package/src/utils.test.ts +60 -0
- package/src/utils.ts +44 -14
- package/dist/infixExpressions.d.ts +0 -7
- package/src/infixExpressions.test.ts +0 -516
- package/src/infixExpressions.ts +0 -672
- /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
package/src/infixExpressions.ts
DELETED
|
@@ -1,672 +0,0 @@
|
|
|
1
|
-
// Rewrites infix expressions into the equivalent prefix helper calls, before the text reaches
|
|
2
|
-
// Handlebars. They're accepted in:
|
|
3
|
-
// conditions: {{#if score > 100 and has_key}} -> {{#if (and (gt score 100) has_key)}}
|
|
4
|
-
// (also {{#unless}}, {{else if}} and {{else unless}}, and what {{#each}} and
|
|
5
|
-
// {{#with}} go through: {{#each (range 1 (count + 1))}} (#447))
|
|
6
|
-
// values: {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
|
|
7
|
-
// (also {{inc}} and {{dec}}, and {{append}}, {{prepend}} and {{remove}})
|
|
8
|
-
// display: {{= price * 2}} -> {{mul price 2}}
|
|
9
|
-
//
|
|
10
|
-
// Two operators work on values rather than numbers (#446):
|
|
11
|
-
// bag contains "key" -> (__contains bag "key") (lists, text and objects)
|
|
12
|
-
// hp > 0 ? "alive" : "dead" -> (cond (gt hp 0) "alive" "dead")
|
|
13
|
-
//
|
|
14
|
-
// Precedence, from tightest to loosest: unary minus, * / %, + -, comparisons (and contains),
|
|
15
|
-
// not/!, and/&&, or/||, and then ? :. So "not" applies to a whole comparison, as it reads in English: not gender = "male"
|
|
16
|
-
// means not (gender = "male").
|
|
17
|
-
// Expressions that don't use any infix operator are passed through unchanged (except {{= }},
|
|
18
|
-
// which isn't valid Handlebars, so it's always rewritten).
|
|
19
|
-
//
|
|
20
|
-
// "-" and "/" can appear inside Handlebars names and paths (my-score, ../score), so they're only
|
|
21
|
-
// operators at the start of a token: a - b and a -b subtract, but a-b is the attribute "a-b".
|
|
22
|
-
//
|
|
23
|
-
// Objects and lists (#442):
|
|
24
|
-
// { hp: 10, name: "Ann" } -> (__object "hp" 10 "name" "Ann")
|
|
25
|
-
// [1, 2, 3] -> (array 1 2 3)
|
|
26
|
-
// inventory[i].name -> (lookup (lookup inventory i) "name")
|
|
27
|
-
// hero.hp needs no rewriting: it's a Handlebars path. A "[" at the start of a value is a list if
|
|
28
|
-
// it's empty, or has a comma in it, or starts with a literal value; otherwise it's a Handlebars
|
|
29
|
-
// name that isn't a plain word, such as [my attribute], as before. A list of one attribute is
|
|
30
|
-
// written (array name).
|
|
31
|
-
|
|
32
|
-
// "index" is a "[" straight after a value, and "[" one that starts a list
|
|
33
|
-
type TokenType = "op" | "(" | ")" | "value" | "ident" | "index" | "[" | "]" | "{" | "}" | ":" | ",";
|
|
34
|
-
|
|
35
|
-
interface Token {
|
|
36
|
-
type: TokenType;
|
|
37
|
-
text: string;
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
type Node =
|
|
41
|
-
| { kind: "raw", text: string }
|
|
42
|
-
| { kind: "call", name: string, args: Node[] };
|
|
43
|
-
|
|
44
|
-
const punctuation = new Set(["{", "}", ":", ",", "]"]);
|
|
45
|
-
|
|
46
|
-
const comparisonHelpers: Record<string, string> = {
|
|
47
|
-
"=": "eq",
|
|
48
|
-
"==": "eq",
|
|
49
|
-
"!=": "ne",
|
|
50
|
-
">": "gt",
|
|
51
|
-
"<": "lt",
|
|
52
|
-
">=": "gte",
|
|
53
|
-
"<=": "lte",
|
|
54
|
-
// a contains b (#446): see the __contains helper
|
|
55
|
-
"contains": "__contains",
|
|
56
|
-
};
|
|
57
|
-
|
|
58
|
-
const arithmeticHelpers: Record<string, string> = {
|
|
59
|
-
"+": "add",
|
|
60
|
-
"-": "sub",
|
|
61
|
-
"*": "mul",
|
|
62
|
-
"/": "div",
|
|
63
|
-
"%": "mod",
|
|
64
|
-
};
|
|
65
|
-
|
|
66
|
-
const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!", "+", "*", "%", "-", "/", "?"];
|
|
67
|
-
const keywordOps = ["and", "or", "not"];
|
|
68
|
-
const literals = ["true", "false", "null", "undefined"];
|
|
69
|
-
|
|
70
|
-
// Characters that end an identifier/path. "[" starts a Handlebars literal segment,
|
|
71
|
-
// e.g. [my attribute], which may contain any of these.
|
|
72
|
-
// "-" and "/" aren't here: see above.
|
|
73
|
-
const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~+*%:,]?"]);
|
|
74
|
-
|
|
75
|
-
const numberPattern = /^-?\d+(\.\d+)?$/;
|
|
76
|
-
|
|
77
|
-
class ExpressionError extends Error {}
|
|
78
|
-
|
|
79
|
-
// Whether the "[" at `open`, at the start of a value, starts a list rather than a Handlebars name
|
|
80
|
-
// like [my attribute]: it's empty, or it has a comma in it, or it starts with a literal value
|
|
81
|
-
function startsList(expr: string, open: number): boolean {
|
|
82
|
-
const after = expr.substring(open + 1).trimStart();
|
|
83
|
-
if (/^[\]"'{[(\d-]/.test(after)) return true;
|
|
84
|
-
const close = expr.indexOf("]", open);
|
|
85
|
-
return close !== -1 && expr.substring(open, close).includes(",");
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
// Whether a token can be the end of a value, so that what follows it is an operator
|
|
89
|
-
function endsValue(token: Token | undefined) {
|
|
90
|
-
return token?.type === "ident" || token?.type === "value" || token?.type === ")" || token?.type === "]" || token?.type === "}";
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
function tokenize(expr: string): Token[] {
|
|
94
|
-
const tokens: Token[] = [];
|
|
95
|
-
let i = 0;
|
|
96
|
-
while (i < expr.length) {
|
|
97
|
-
const c = expr[i];
|
|
98
|
-
if (/\s/.test(c)) {
|
|
99
|
-
i++;
|
|
100
|
-
continue;
|
|
101
|
-
}
|
|
102
|
-
if (c === "(" || c === ")" || punctuation.has(c)) {
|
|
103
|
-
tokens.push({ type: c as TokenType, text: c });
|
|
104
|
-
i++;
|
|
105
|
-
continue;
|
|
106
|
-
}
|
|
107
|
-
if (c === "\"" || c === "'") {
|
|
108
|
-
let j = i + 1;
|
|
109
|
-
while (j < expr.length && expr[j] !== c) {
|
|
110
|
-
if (expr[j] === "\\") j++;
|
|
111
|
-
j++;
|
|
112
|
-
}
|
|
113
|
-
if (j >= expr.length) {
|
|
114
|
-
throw new ExpressionError("unterminated string");
|
|
115
|
-
}
|
|
116
|
-
tokens.push({ type: "value", text: expr.slice(i, j + 1) });
|
|
117
|
-
i = j + 1;
|
|
118
|
-
continue;
|
|
119
|
-
}
|
|
120
|
-
// A "[" straight after a value is an index, as in inventory[0] or inventory[i][j]
|
|
121
|
-
if (c === "[" && /[\w\])]/.test(expr[i - 1] ?? "")) {
|
|
122
|
-
tokens.push({ type: "index", text: c });
|
|
123
|
-
i++;
|
|
124
|
-
continue;
|
|
125
|
-
}
|
|
126
|
-
if (c === "[" && startsList(expr, i)) {
|
|
127
|
-
tokens.push({ type: "[", text: c });
|
|
128
|
-
i++;
|
|
129
|
-
continue;
|
|
130
|
-
}
|
|
131
|
-
// A "-" before a digit starts a negative number, as before (the parser treats
|
|
132
|
-
// a -1 as a - 1 where it needs an operator)
|
|
133
|
-
const op = symbolicOps.find(o => expr.startsWith(o, i) && !(o === "-" && /\d/.test(expr[i + 1] ?? "")));
|
|
134
|
-
if (op) {
|
|
135
|
-
tokens.push({ type: "op", text: op });
|
|
136
|
-
i += op.length;
|
|
137
|
-
continue;
|
|
138
|
-
}
|
|
139
|
-
let j = i;
|
|
140
|
-
while (j < expr.length && !identTerminators.has(expr[j])) {
|
|
141
|
-
// A "[" straight after a name is an index, as in inventory[0]. After "." or "/", or at
|
|
142
|
-
// the start, it's a Handlebars name, as in inventory.[0] or [my attribute].
|
|
143
|
-
if (expr[j] === "[" && j > i && expr[j - 1] !== "." && expr[j - 1] !== "/") {
|
|
144
|
-
break;
|
|
145
|
-
}
|
|
146
|
-
if (expr[j] === "[") {
|
|
147
|
-
const close = expr.indexOf("]", j);
|
|
148
|
-
if (close === -1) {
|
|
149
|
-
throw new ExpressionError("missing ']'");
|
|
150
|
-
}
|
|
151
|
-
j = close;
|
|
152
|
-
}
|
|
153
|
-
j++;
|
|
154
|
-
}
|
|
155
|
-
if (j === i) {
|
|
156
|
-
throw new ExpressionError(`unexpected '${c}'`);
|
|
157
|
-
}
|
|
158
|
-
const word = expr.slice(i, j);
|
|
159
|
-
if (keywordOps.includes(word) || (word === "contains" && endsValue(tokens[tokens.length - 1]))) {
|
|
160
|
-
// "contains" is only an operator after a value, so (contains "bag" "key") is still
|
|
161
|
-
// the helper
|
|
162
|
-
tokens.push({ type: "op", text: word });
|
|
163
|
-
} else if (literals.includes(word) || numberPattern.test(word)) {
|
|
164
|
-
tokens.push({ type: "value", text: word });
|
|
165
|
-
} else {
|
|
166
|
-
tokens.push({ type: "ident", text: word });
|
|
167
|
-
}
|
|
168
|
-
i = j;
|
|
169
|
-
}
|
|
170
|
-
return tokens;
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
class Parser {
|
|
174
|
-
private pos = 0;
|
|
175
|
-
usedInfix = false;
|
|
176
|
-
|
|
177
|
-
constructor(private tokens: Token[]) {}
|
|
178
|
-
|
|
179
|
-
private peek(offset = 0): Token | undefined {
|
|
180
|
-
return this.tokens[this.pos + offset];
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
private next(): Token {
|
|
184
|
-
return this.tokens[this.pos++];
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
private isOp(token: Token | undefined, ...ops: string[]) {
|
|
188
|
-
return token?.type === "op" && ops.includes(token.text);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
private startsPrimary(token: Token | undefined) {
|
|
192
|
-
return token?.type === "ident" || token?.type === "value" || token?.type === "(" || token?.type === "[" || token?.type === "{";
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
private describe(token: Token | undefined) {
|
|
196
|
-
return token ? `'${token.text}'` : "end of expression";
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
// A value: an expression with nothing after it
|
|
200
|
-
parseExpression(): Node {
|
|
201
|
-
const result = this.parseConditional();
|
|
202
|
-
if (this.peek()) {
|
|
203
|
-
throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
|
|
204
|
-
}
|
|
205
|
-
return result;
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
// Arguments to a helper: `count` plain values (e.g. the attribute name), then an expression
|
|
209
|
-
parseArguments(count: number): Node[] {
|
|
210
|
-
const result: Node[] = [];
|
|
211
|
-
for (let i = 0; i < count; i++) {
|
|
212
|
-
result.push(this.parsePrimary());
|
|
213
|
-
}
|
|
214
|
-
if (!this.peek()) {
|
|
215
|
-
throw new ExpressionError("expected a value");
|
|
216
|
-
}
|
|
217
|
-
result.push(this.parseExpression());
|
|
218
|
-
return result;
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
// {{embed}}'s arguments (#450): the name, then parameters, each of which can be an expression,
|
|
222
|
-
// e.g. {{embed "say" who=name hp=hp - 1}}
|
|
223
|
-
parseEmbed(): Node[] {
|
|
224
|
-
const result = [this.parsePrimary()];
|
|
225
|
-
while (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
|
|
226
|
-
const key = this.next().text;
|
|
227
|
-
this.next(); // "="
|
|
228
|
-
if (!this.peek()) {
|
|
229
|
-
throw new ExpressionError(`expected a value after '${key}='`);
|
|
230
|
-
}
|
|
231
|
-
result.push({ kind: "raw", text: `${key}=${emit(this.parseConditional())}` });
|
|
232
|
-
}
|
|
233
|
-
if (this.peek()) {
|
|
234
|
-
throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
|
|
235
|
-
}
|
|
236
|
-
return result;
|
|
237
|
-
}
|
|
238
|
-
|
|
239
|
-
// Top level: an expression, optionally followed by hash arguments (e.g. includeZero=true)
|
|
240
|
-
parseCondition(): Node[] {
|
|
241
|
-
const result = [this.parseConditional()];
|
|
242
|
-
while (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
|
|
243
|
-
result.push(this.parseHashPair());
|
|
244
|
-
}
|
|
245
|
-
if (this.peek()) {
|
|
246
|
-
throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
|
|
247
|
-
}
|
|
248
|
-
return result;
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
private parseHashPair(): Node {
|
|
252
|
-
const key = this.next().text;
|
|
253
|
-
this.next(); // "="
|
|
254
|
-
return { kind: "raw", text: `${key}=${emit(this.parsePrimary())}` };
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
// test ? a : b (#446), the loosest of all, and right-associative, so a ? b : c ? d : e
|
|
258
|
-
// is a ? b : (c ? d : e)
|
|
259
|
-
private parseConditional(): Node {
|
|
260
|
-
const test = this.parseOr();
|
|
261
|
-
if (!this.isOp(this.peek(), "?")) return test;
|
|
262
|
-
this.next();
|
|
263
|
-
if (!this.peek()) {
|
|
264
|
-
throw new ExpressionError("expected a value after '?'");
|
|
265
|
-
}
|
|
266
|
-
const ifTrue = this.parseConditional();
|
|
267
|
-
this.expect(":");
|
|
268
|
-
if (!this.peek()) {
|
|
269
|
-
throw new ExpressionError("expected a value after ':'");
|
|
270
|
-
}
|
|
271
|
-
const ifFalse = this.parseConditional();
|
|
272
|
-
this.usedInfix = true;
|
|
273
|
-
return { kind: "call", name: "cond", args: [test, ifTrue, ifFalse] };
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
private parseOr(): Node {
|
|
277
|
-
return this.parseChain(["or", "||"], "or", () => this.parseAnd());
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
private parseAnd(): Node {
|
|
281
|
-
return this.parseChain(["and", "&&"], "and", () => this.parseNot());
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
private parseChain(ops: string[], helper: string, parseOperand: () => Node): Node {
|
|
285
|
-
const operands = [parseOperand()];
|
|
286
|
-
while (this.isOp(this.peek(), ...ops)) {
|
|
287
|
-
const op = this.next().text;
|
|
288
|
-
if (!this.peek()) {
|
|
289
|
-
throw new ExpressionError(`expected a value after '${op}'`);
|
|
290
|
-
}
|
|
291
|
-
operands.push(parseOperand());
|
|
292
|
-
}
|
|
293
|
-
if (operands.length === 1) return operands[0];
|
|
294
|
-
this.usedInfix = true;
|
|
295
|
-
return { kind: "call", name: helper, args: operands };
|
|
296
|
-
}
|
|
297
|
-
|
|
298
|
-
private parseNot(): Node {
|
|
299
|
-
if (this.isOp(this.peek(), "not", "!")) {
|
|
300
|
-
const op = this.next().text;
|
|
301
|
-
if (!this.peek()) {
|
|
302
|
-
throw new ExpressionError(`expected a value after '${op}'`);
|
|
303
|
-
}
|
|
304
|
-
this.usedInfix = true;
|
|
305
|
-
return { kind: "call", name: "not", args: [this.parseNot()] };
|
|
306
|
-
}
|
|
307
|
-
return this.parseComparison();
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
private parseComparison(): Node {
|
|
311
|
-
const left = this.parseAdditive();
|
|
312
|
-
const opToken = this.peek();
|
|
313
|
-
if (opToken?.type !== "op" || !(opToken.text in comparisonHelpers)) {
|
|
314
|
-
return left;
|
|
315
|
-
}
|
|
316
|
-
this.next();
|
|
317
|
-
if (!this.peek()) {
|
|
318
|
-
throw new ExpressionError(`expected a value after '${opToken.text}'`);
|
|
319
|
-
}
|
|
320
|
-
const right = this.parseAdditive();
|
|
321
|
-
const following = this.peek();
|
|
322
|
-
if (following?.type === "op" && following.text in comparisonHelpers) {
|
|
323
|
-
throw new ExpressionError(`comparisons can't be chained (at '${following.text}'), use "and" to combine them`);
|
|
324
|
-
}
|
|
325
|
-
this.usedInfix = true;
|
|
326
|
-
return { kind: "call", name: comparisonHelpers[opToken.text], args: [left, right] };
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
private parseAdditive(): Node {
|
|
330
|
-
return this.parseArithmetic(["+", "-"], () => this.parseMultiplicative());
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
private parseMultiplicative(): Node {
|
|
334
|
-
return this.parseArithmetic(["*", "/", "%"], () => this.parseUnary());
|
|
335
|
-
}
|
|
336
|
-
|
|
337
|
-
// Left-associative, so a - b - c is (a - b) - c
|
|
338
|
-
private parseArithmetic(ops: string[], parseOperand: () => Node): Node {
|
|
339
|
-
let left = parseOperand();
|
|
340
|
-
for (;;) {
|
|
341
|
-
let op: string;
|
|
342
|
-
const token = this.peek();
|
|
343
|
-
if (this.isOp(token, ...ops)) {
|
|
344
|
-
op = this.next().text;
|
|
345
|
-
if (!this.peek()) {
|
|
346
|
-
throw new ExpressionError(`expected a value after '${op}'`);
|
|
347
|
-
}
|
|
348
|
-
} else if (ops.includes("-") && token?.type === "value" && token.text.startsWith("-") && numberPattern.test(token.text)) {
|
|
349
|
-
// a -1 means a - 1. Split the negative number into the operator and the number.
|
|
350
|
-
op = "-";
|
|
351
|
-
this.tokens[this.pos] = { type: "value", text: token.text.slice(1) };
|
|
352
|
-
} else {
|
|
353
|
-
return left;
|
|
354
|
-
}
|
|
355
|
-
this.usedInfix = true;
|
|
356
|
-
left = { kind: "call", name: arithmeticHelpers[op], args: [left, parseOperand()] };
|
|
357
|
-
}
|
|
358
|
-
}
|
|
359
|
-
|
|
360
|
-
private parseUnary(): Node {
|
|
361
|
-
if (this.isOp(this.peek(), "-")) {
|
|
362
|
-
this.next();
|
|
363
|
-
if (!this.peek()) {
|
|
364
|
-
throw new ExpressionError("expected a value after '-'");
|
|
365
|
-
}
|
|
366
|
-
this.usedInfix = true;
|
|
367
|
-
return { kind: "call", name: "sub", args: [{ kind: "raw", text: "0" }, this.parseUnary()] };
|
|
368
|
-
}
|
|
369
|
-
return this.parsePrimary();
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// A value, then any [index] or .name after it, e.g. inventory[i].name
|
|
373
|
-
private parsePrimary(): Node {
|
|
374
|
-
let node = this.parseAtom();
|
|
375
|
-
for (;;) {
|
|
376
|
-
const token = this.peek();
|
|
377
|
-
if (token?.type === "index") {
|
|
378
|
-
this.next();
|
|
379
|
-
const index = this.parseConditional();
|
|
380
|
-
this.expect("]");
|
|
381
|
-
this.usedInfix = true;
|
|
382
|
-
node = { kind: "call", name: "lookup", args: [node, index] };
|
|
383
|
-
}
|
|
384
|
-
else if (token?.type === "ident" && token.text.startsWith(".") && this.tokens[this.pos - 1]?.type === "]") {
|
|
385
|
-
// .name after an index: a name, or Handlebars' .[name]
|
|
386
|
-
this.next();
|
|
387
|
-
for (const part of token.text.substring(1).split(".")) {
|
|
388
|
-
const name = /^\[(.*)\]$/.exec(part)?.[1] ?? part;
|
|
389
|
-
if (!name) throw new ExpressionError(`unexpected '${token.text}'`);
|
|
390
|
-
node = { kind: "call", name: "lookup", args: [node, { kind: "raw", text: JSON.stringify(name) }] };
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
else {
|
|
394
|
-
return node;
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
}
|
|
398
|
-
|
|
399
|
-
private expect(type: TokenType) {
|
|
400
|
-
if (this.peek()?.type !== type) {
|
|
401
|
-
throw new ExpressionError(`expected '${type}' but found ${this.describe(this.peek())}`);
|
|
402
|
-
}
|
|
403
|
-
this.next();
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
// { name: value, ... } (#442)
|
|
407
|
-
private parseObject(): Node {
|
|
408
|
-
const args: Node[] = [];
|
|
409
|
-
while (this.peek()?.type !== "}") {
|
|
410
|
-
const key = this.next();
|
|
411
|
-
if (!key) throw new ExpressionError("expected '}' but found end of expression");
|
|
412
|
-
if ((key.type === "ident" || key.type === "value") && /^\w+$/.test(key.text)) {
|
|
413
|
-
args.push({ kind: "raw", text: `"${key.text}"` });
|
|
414
|
-
} else if (key.type === "value" && /^["']/.test(key.text)) {
|
|
415
|
-
args.push({ kind: "raw", text: key.text });
|
|
416
|
-
} else {
|
|
417
|
-
throw new ExpressionError(`expected a name in the object, e.g. { hp: 10 }, but found '${key.text}'`);
|
|
418
|
-
}
|
|
419
|
-
this.expect(":");
|
|
420
|
-
args.push(this.parseConditional());
|
|
421
|
-
if (this.peek()?.type !== ",") break;
|
|
422
|
-
this.next();
|
|
423
|
-
}
|
|
424
|
-
this.expect("}");
|
|
425
|
-
this.usedInfix = true;
|
|
426
|
-
return { kind: "call", name: "__object", args };
|
|
427
|
-
}
|
|
428
|
-
|
|
429
|
-
// [value, ...] (#442)
|
|
430
|
-
private parseList(): Node {
|
|
431
|
-
const args: Node[] = [];
|
|
432
|
-
while (this.peek()?.type !== "]") {
|
|
433
|
-
if (!this.peek()) throw new ExpressionError("expected ']' but found end of expression");
|
|
434
|
-
args.push(this.parseConditional());
|
|
435
|
-
if (this.peek()?.type !== ",") break;
|
|
436
|
-
this.next();
|
|
437
|
-
}
|
|
438
|
-
this.expect("]");
|
|
439
|
-
this.usedInfix = true;
|
|
440
|
-
return { kind: "call", name: "array", args };
|
|
441
|
-
}
|
|
442
|
-
|
|
443
|
-
private parseAtom(): Node {
|
|
444
|
-
const token = this.peek();
|
|
445
|
-
if (token?.type === "{") {
|
|
446
|
-
this.next();
|
|
447
|
-
return this.parseObject();
|
|
448
|
-
}
|
|
449
|
-
if (token?.type === "[") {
|
|
450
|
-
this.next();
|
|
451
|
-
return this.parseList();
|
|
452
|
-
}
|
|
453
|
-
if (token?.type === "ident" || token?.type === "value") {
|
|
454
|
-
this.next();
|
|
455
|
-
return { kind: "raw", text: token.text };
|
|
456
|
-
}
|
|
457
|
-
if (token?.type === "(") {
|
|
458
|
-
this.next();
|
|
459
|
-
const node = this.isHelperCall() ? this.parseHelperCall() : this.parseConditional();
|
|
460
|
-
if (this.peek()?.type !== ")") {
|
|
461
|
-
throw new ExpressionError(`expected ')' but found ${this.describe(this.peek())}`);
|
|
462
|
-
}
|
|
463
|
-
this.next();
|
|
464
|
-
return node;
|
|
465
|
-
}
|
|
466
|
-
if (this.isOp(token, "not", "!")) {
|
|
467
|
-
const example = token?.text === "!" ? "!value" : "not value";
|
|
468
|
-
throw new ExpressionError(`'${token?.text}' must be inside parentheses here, e.g. (${example})`);
|
|
469
|
-
}
|
|
470
|
-
if (token?.type === "op") {
|
|
471
|
-
throw new ExpressionError(`expected a value before '${token.text}'`);
|
|
472
|
-
}
|
|
473
|
-
throw new ExpressionError(token ? `unexpected ${this.describe(token)}` : "expected a value");
|
|
474
|
-
}
|
|
475
|
-
|
|
476
|
-
// Inside parentheses, decide between an existing prefix helper call like (seen "intro")
|
|
477
|
-
// or (and a b), and an infix group like (score > 100).
|
|
478
|
-
private isHelperCall() {
|
|
479
|
-
const first = this.peek();
|
|
480
|
-
const second = this.peek(1);
|
|
481
|
-
if (this.isOp(first, "and", "or")) return true;
|
|
482
|
-
return first?.type === "ident" && this.startsPrimary(second);
|
|
483
|
-
}
|
|
484
|
-
|
|
485
|
-
private parseHelperCall(): Node {
|
|
486
|
-
const name = this.next().text;
|
|
487
|
-
const args: Node[] = [];
|
|
488
|
-
while (this.peek() && this.peek()?.type !== ")") {
|
|
489
|
-
if (this.peek()?.type === "ident" && this.isOp(this.peek(1), "=")) {
|
|
490
|
-
args.push(this.parseHashPair());
|
|
491
|
-
} else {
|
|
492
|
-
args.push(this.parsePrimary());
|
|
493
|
-
}
|
|
494
|
-
}
|
|
495
|
-
return { kind: "call", name, args };
|
|
496
|
-
}
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
function emit(node: Node): string {
|
|
500
|
-
if (node.kind === "raw") return node.text;
|
|
501
|
-
return `(${node.name} ${node.args.map(emit).join(" ")})`;
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
// "value" is a whole expression whose value is used, e.g. the right-hand side of @set
|
|
505
|
-
type Mode = "condition" | "arguments" | "embed" | "display" | "value";
|
|
506
|
-
|
|
507
|
-
// Parses `text` and returns the rewritten nodes, or null if it should be left alone: it
|
|
508
|
-
// doesn't use infix syntax, or it can't be parsed and has no operators (which leaves malformed
|
|
509
|
-
// prefix syntax for Handlebars to report).
|
|
510
|
-
function rewrite(text: string, mode: Mode, label: string): Node[] | null {
|
|
511
|
-
// Whether errors are always reported, and the result always returned, rather than leaving
|
|
512
|
-
// anything that isn't infix syntax for Handlebars
|
|
513
|
-
const strict = mode === "display" || mode === "value";
|
|
514
|
-
// Errors are thrown after the try/catch blocks, as new errors with the expression in the message
|
|
515
|
-
let error: ExpressionError | null = null;
|
|
516
|
-
let tokens: Token[] = [];
|
|
517
|
-
try {
|
|
518
|
-
tokens = tokenize(text);
|
|
519
|
-
} catch (e) {
|
|
520
|
-
// Leave anything we can't tokenize for Handlebars to report, except {{= }}
|
|
521
|
-
if (!strict || !(e instanceof ExpressionError)) return null;
|
|
522
|
-
error = e;
|
|
523
|
-
}
|
|
524
|
-
const hasOperators = tokens.some(t => t.type === "op" || t.type === "index" || t.type === "[" || t.type === "{");
|
|
525
|
-
const parser = new Parser(tokens);
|
|
526
|
-
let nodes: Node[] = [];
|
|
527
|
-
if (!error) {
|
|
528
|
-
try {
|
|
529
|
-
nodes = mode === "condition" ? parser.parseCondition()
|
|
530
|
-
: mode === "arguments" ? parser.parseArguments(1)
|
|
531
|
-
: mode === "embed" ? parser.parseEmbed()
|
|
532
|
-
: [parser.parseExpression()];
|
|
533
|
-
} catch (e) {
|
|
534
|
-
if (!(e instanceof ExpressionError) || (!hasOperators && !strict)) return null;
|
|
535
|
-
error = e;
|
|
536
|
-
}
|
|
537
|
-
}
|
|
538
|
-
if (error) {
|
|
539
|
-
throw new Error(`Invalid ${label} "${text.trim()}": ${error.message}`);
|
|
540
|
-
}
|
|
541
|
-
if (!parser.usedInfix && !strict) return null;
|
|
542
|
-
return nodes;
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
// Rewrites a single condition. Returns null if it doesn't use infix syntax.
|
|
546
|
-
export function rewriteInfixCondition(condition: string): string | null {
|
|
547
|
-
const nodes = rewrite(condition, "condition", "condition");
|
|
548
|
-
return nodes && nodes.map(emit).join(" ");
|
|
549
|
-
}
|
|
550
|
-
|
|
551
|
-
// Rewrites the arguments to {{set}}, {{inc}}, {{dec}}, {{append}}, {{prepend}} or {{remove}}: an
|
|
552
|
-
// attribute name, then an expression.
|
|
553
|
-
// Returns null if the expression doesn't use infix syntax.
|
|
554
|
-
export function rewriteInfixArguments(args: string): string | null {
|
|
555
|
-
const nodes = rewrite(args, "arguments", "expression");
|
|
556
|
-
return nodes && nodes.map(emit).join(" ");
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
// Rewrites the arguments to {{embed}}: a name, then parameters whose values can be expressions
|
|
560
|
-
// (#450). Returns null if they don't use infix syntax.
|
|
561
|
-
export function rewriteInfixEmbed(args: string): string | null {
|
|
562
|
-
const nodes = rewrite(args, "embed", "embed");
|
|
563
|
-
return nodes && nodes.map(emit).join(" ");
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// Rewrites the expression in {{= expression}} into the contents of a mustache tag, i.e. a
|
|
567
|
-
// helper call without the outer parentheses, or an attribute name.
|
|
568
|
-
export function rewriteDisplayExpression(expression: string): string {
|
|
569
|
-
const node = rewrite(expression, "display", "expression")![0];
|
|
570
|
-
if (node.kind === "call") {
|
|
571
|
-
return `${node.name} ${node.args.map(emit).join(" ")}`;
|
|
572
|
-
}
|
|
573
|
-
if (literals.includes(node.text) || numberPattern.test(node.text) || /^["']/.test(node.text)) {
|
|
574
|
-
throw new Error(`Invalid expression "${expression.trim()}": expected an attribute or a calculation`);
|
|
575
|
-
}
|
|
576
|
-
return node.text;
|
|
577
|
-
}
|
|
578
|
-
|
|
579
|
-
// Rewrites an expression whose value is used (the right-hand side of @set and link setters, when a
|
|
580
|
-
// story uses expressions there) into a Handlebars value: a helper call in parentheses, an
|
|
581
|
-
// attribute name or a literal. Throws if it isn't a valid expression.
|
|
582
|
-
export function rewriteValueExpression(expression: string): string {
|
|
583
|
-
return emit(rewrite(expression, "value", "expression")![0]);
|
|
584
|
-
}
|
|
585
|
-
|
|
586
|
-
// Splits a list of link setters on the commas between them, but not on commas inside quotes or
|
|
587
|
-
// brackets: greeting = "Hi, there", gold -= price is two setters, and so is
|
|
588
|
-
// hero = { hp: 10, name: "Ann" }, gold = 0.
|
|
589
|
-
export function splitSetters(setters: string): string[] {
|
|
590
|
-
const result: string[] = [];
|
|
591
|
-
let depth = 0;
|
|
592
|
-
let quote: string | null = null;
|
|
593
|
-
let start = 0;
|
|
594
|
-
for (let i = 0; i < setters.length; i++) {
|
|
595
|
-
const c = setters[i];
|
|
596
|
-
if (quote) {
|
|
597
|
-
if (c === "\\") i++;
|
|
598
|
-
else if (c === quote) quote = null;
|
|
599
|
-
}
|
|
600
|
-
else if (c === "\"" || c === "'") quote = c;
|
|
601
|
-
else if (c === "(" || c === "[" || c === "{") depth++;
|
|
602
|
-
else if (c === ")" || c === "]" || c === "}") depth = Math.max(0, depth - 1);
|
|
603
|
-
else if (c === "," && depth === 0) {
|
|
604
|
-
result.push(setters.slice(start, i));
|
|
605
|
-
start = i + 1;
|
|
606
|
-
}
|
|
607
|
-
}
|
|
608
|
-
result.push(setters.slice(start));
|
|
609
|
-
return result.map(s => s.trim()).filter(s => s !== "");
|
|
610
|
-
}
|
|
611
|
-
|
|
612
|
-
const tagStart = /(\\*)\{\{(~?\s*)(?:(#if|#unless|#each|#with|else\s+if|else\s+unless)(?=[\s(!])|(set|inc|dec|append|prepend|remove)(?=\s)|(=)|(#?embed)(?=\s))/g;
|
|
613
|
-
|
|
614
|
-
// Finds the end of a mustache tag starting at `from`, skipping over quoted strings and objects,
|
|
615
|
-
// such as {{set "hero" { hp: 10 }}}. Returns the index of the closing "}}" (or "~}}"), or -1.
|
|
616
|
-
function findTagEnd(text: string, from: number): number {
|
|
617
|
-
let quote: string | null = null;
|
|
618
|
-
let braces = 0;
|
|
619
|
-
for (let i = from; i < text.length; i++) {
|
|
620
|
-
const c = text[i];
|
|
621
|
-
if (quote) {
|
|
622
|
-
if (c === "\\") i++;
|
|
623
|
-
else if (c === quote) quote = null;
|
|
624
|
-
} else if (c === "\"" || c === "'") {
|
|
625
|
-
quote = c;
|
|
626
|
-
} else if (c === "{") {
|
|
627
|
-
braces++;
|
|
628
|
-
} else if (c === "}" && braces > 0) {
|
|
629
|
-
braces--;
|
|
630
|
-
} else if (text.startsWith("~}}", i)) {
|
|
631
|
-
return i;
|
|
632
|
-
} else if (text.startsWith("}}", i)) {
|
|
633
|
-
return i;
|
|
634
|
-
}
|
|
635
|
-
}
|
|
636
|
-
return -1;
|
|
637
|
-
}
|
|
638
|
-
|
|
639
|
-
export function rewriteInfixExpressions(text: string): string {
|
|
640
|
-
if (!text.includes("{{")) return text;
|
|
641
|
-
|
|
642
|
-
let result = "";
|
|
643
|
-
let last = 0;
|
|
644
|
-
tagStart.lastIndex = 0;
|
|
645
|
-
let match: RegExpExecArray | null;
|
|
646
|
-
while ((match = tagStart.exec(text)) !== null) {
|
|
647
|
-
// An odd number of backslashes escapes the mustache
|
|
648
|
-
if (match[1].length % 2 === 1) continue;
|
|
649
|
-
|
|
650
|
-
const argStart = match.index + match[0].length;
|
|
651
|
-
const argEnd = findTagEnd(text, argStart);
|
|
652
|
-
if (argEnd === -1) break;
|
|
653
|
-
|
|
654
|
-
const args = text.slice(argStart, argEnd);
|
|
655
|
-
if (match[5]) {
|
|
656
|
-
// {{= expression}}: replace the "=" too
|
|
657
|
-
const tagOpen = match.index + match[1].length;
|
|
658
|
-
result += text.slice(last, tagOpen) + "{{" + match[2] + rewriteDisplayExpression(args);
|
|
659
|
-
last = argEnd;
|
|
660
|
-
} else {
|
|
661
|
-
const rewritten = match[3] ? rewriteInfixCondition(args)
|
|
662
|
-
: match[6] ? rewriteInfixEmbed(args)
|
|
663
|
-
: rewriteInfixArguments(args);
|
|
664
|
-
if (rewritten !== null) {
|
|
665
|
-
result += text.slice(last, argStart) + " " + rewritten;
|
|
666
|
-
last = argEnd;
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
tagStart.lastIndex = argEnd;
|
|
670
|
-
}
|
|
671
|
-
return result + text.slice(last);
|
|
672
|
-
}
|
|
File without changes
|