squiffy-runtime 7.0.0-beta.3 → 7.0.0-beta.5

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.
@@ -1,10 +1,19 @@
1
- // Rewrites infix conditions in {{#if}}, {{#unless}}, {{else if}} and {{else unless}}
2
- // into the equivalent prefix helper calls, before the text reaches Handlebars. e.g.
3
- // {{#if score > 100 and has_key}} -> {{#if (and (gt score 100) has_key)}}
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}})
5
+ // values: {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
6
+ // (also {{inc}} and {{dec}})
7
+ // display: {{= price * 2}} -> {{mul price 2}}
4
8
  //
5
- // Precedence, from tightest to loosest: comparisons, not/!, and/&&, or/||. So "not" applies to
6
- // a whole comparison, as it reads in English: not gender = "male" means not (gender = "male").
7
- // Conditions that don't use any infix operator are passed through unchanged.
9
+ // Precedence, from tightest to loosest: unary minus, * / %, + -, comparisons, not/!, and/&&,
10
+ // or/||. So "not" applies to a whole comparison, as it reads in English: not gender = "male"
11
+ // means not (gender = "male").
12
+ // Expressions that don't use any infix operator are passed through unchanged (except {{= }},
13
+ // which isn't valid Handlebars, so it's always rewritten).
14
+ //
15
+ // "-" and "/" can appear inside Handlebars names and paths (my-score, ../score), so they're only
16
+ // operators at the start of a token: a - b and a -b subtract, but a-b is the attribute "a-b".
8
17
 
9
18
  type TokenType = "op" | "(" | ")" | "value" | "ident";
10
19
 
@@ -27,13 +36,24 @@ const comparisonHelpers: Record<string, string> = {
27
36
  "<=": "lte",
28
37
  };
29
38
 
30
- const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!"];
39
+ const arithmeticHelpers: Record<string, string> = {
40
+ "+": "add",
41
+ "-": "sub",
42
+ "*": "mul",
43
+ "/": "div",
44
+ "%": "mod",
45
+ };
46
+
47
+ const symbolicOps = ["==", "!=", ">=", "<=", "&&", "||", "=", ">", "<", "!", "+", "*", "%", "-", "/"];
31
48
  const keywordOps = ["and", "or", "not"];
32
49
  const literals = ["true", "false", "null", "undefined"];
33
50
 
34
51
  // Characters that end an identifier/path. "[" starts a Handlebars literal segment,
35
52
  // e.g. [my attribute], which may contain any of these.
36
- const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~"]);
53
+ // "-" and "/" aren't here: see above.
54
+ const identTerminators = new Set([..." \t\r\n!\"'()<>=&|{}~+*%"]);
55
+
56
+ const numberPattern = /^-?\d+(\.\d+)?$/;
37
57
 
38
58
  class ExpressionError extends Error {}
39
59
 
@@ -64,7 +84,9 @@ function tokenize(expr: string): Token[] {
64
84
  i = j + 1;
65
85
  continue;
66
86
  }
67
- const op = symbolicOps.find(o => expr.startsWith(o, i));
87
+ // A "-" before a digit starts a negative number, as before (the parser treats
88
+ // a -1 as a - 1 where it needs an operator)
89
+ const op = symbolicOps.find(o => expr.startsWith(o, i) && !(o === "-" && /\d/.test(expr[i + 1] ?? "")));
68
90
  if (op) {
69
91
  tokens.push({ type: "op", text: op });
70
92
  i += op.length;
@@ -87,7 +109,7 @@ function tokenize(expr: string): Token[] {
87
109
  const word = expr.slice(i, j);
88
110
  if (keywordOps.includes(word)) {
89
111
  tokens.push({ type: "op", text: word });
90
- } else if (literals.includes(word) || /^-?\d+(\.\d+)?$/.test(word)) {
112
+ } else if (literals.includes(word) || numberPattern.test(word)) {
91
113
  tokens.push({ type: "value", text: word });
92
114
  } else {
93
115
  tokens.push({ type: "ident", text: word });
@@ -123,6 +145,28 @@ class Parser {
123
145
  return token ? `'${token.text}'` : "end of expression";
124
146
  }
125
147
 
148
+ // A value: an expression with nothing after it
149
+ parseExpression(): Node {
150
+ const result = this.parseOr();
151
+ if (this.peek()) {
152
+ throw new ExpressionError(`unexpected ${this.describe(this.peek())}`);
153
+ }
154
+ return result;
155
+ }
156
+
157
+ // Arguments to a helper: `count` plain values (e.g. the attribute name), then an expression
158
+ parseArguments(count: number): Node[] {
159
+ const result: Node[] = [];
160
+ for (let i = 0; i < count; i++) {
161
+ result.push(this.parsePrimary());
162
+ }
163
+ if (!this.peek()) {
164
+ throw new ExpressionError("expected a value");
165
+ }
166
+ result.push(this.parseExpression());
167
+ return result;
168
+ }
169
+
126
170
  // Top level: an expression, optionally followed by hash arguments (e.g. includeZero=true)
127
171
  parseCondition(): Node[] {
128
172
  const result = [this.parseOr()];
@@ -176,7 +220,7 @@ class Parser {
176
220
  }
177
221
 
178
222
  private parseComparison(): Node {
179
- const left = this.parsePrimary();
223
+ const left = this.parseAdditive();
180
224
  const opToken = this.peek();
181
225
  if (opToken?.type !== "op" || !(opToken.text in comparisonHelpers)) {
182
226
  return left;
@@ -185,7 +229,7 @@ class Parser {
185
229
  if (!this.peek()) {
186
230
  throw new ExpressionError(`expected a value after '${opToken.text}'`);
187
231
  }
188
- const right = this.parsePrimary();
232
+ const right = this.parseAdditive();
189
233
  const following = this.peek();
190
234
  if (following?.type === "op" && following.text in comparisonHelpers) {
191
235
  throw new ExpressionError(`comparisons can't be chained (at '${following.text}'), use "and" to combine them`);
@@ -194,6 +238,49 @@ class Parser {
194
238
  return { kind: "call", name: comparisonHelpers[opToken.text], args: [left, right] };
195
239
  }
196
240
 
241
+ private parseAdditive(): Node {
242
+ return this.parseArithmetic(["+", "-"], () => this.parseMultiplicative());
243
+ }
244
+
245
+ private parseMultiplicative(): Node {
246
+ return this.parseArithmetic(["*", "/", "%"], () => this.parseUnary());
247
+ }
248
+
249
+ // Left-associative, so a - b - c is (a - b) - c
250
+ private parseArithmetic(ops: string[], parseOperand: () => Node): Node {
251
+ let left = parseOperand();
252
+ for (;;) {
253
+ let op: string;
254
+ const token = this.peek();
255
+ if (this.isOp(token, ...ops)) {
256
+ op = this.next().text;
257
+ if (!this.peek()) {
258
+ throw new ExpressionError(`expected a value after '${op}'`);
259
+ }
260
+ } else if (ops.includes("-") && token?.type === "value" && token.text.startsWith("-") && numberPattern.test(token.text)) {
261
+ // a -1 means a - 1. Split the negative number into the operator and the number.
262
+ op = "-";
263
+ this.tokens[this.pos] = { type: "value", text: token.text.slice(1) };
264
+ } else {
265
+ return left;
266
+ }
267
+ this.usedInfix = true;
268
+ left = { kind: "call", name: arithmeticHelpers[op], args: [left, parseOperand()] };
269
+ }
270
+ }
271
+
272
+ private parseUnary(): Node {
273
+ if (this.isOp(this.peek(), "-")) {
274
+ this.next();
275
+ if (!this.peek()) {
276
+ throw new ExpressionError("expected a value after '-'");
277
+ }
278
+ this.usedInfix = true;
279
+ return { kind: "call", name: "sub", args: [{ kind: "raw", text: "0" }, this.parseUnary()] };
280
+ }
281
+ return this.parsePrimary();
282
+ }
283
+
197
284
  private parsePrimary(): Node {
198
285
  const token = this.peek();
199
286
  if (token?.type === "ident" || token?.type === "value") {
@@ -247,34 +334,105 @@ function emit(node: Node): string {
247
334
  return `(${node.name} ${node.args.map(emit).join(" ")})`;
248
335
  }
249
336
 
250
- // Rewrites a single condition. Returns null if it doesn't use infix syntax.
251
- export function rewriteInfixCondition(condition: string): string | null {
252
- let tokens: Token[];
253
- try {
254
- tokens = tokenize(condition);
255
- } catch {
256
- // Leave anything we can't tokenize for Handlebars to report
257
- return null;
258
- }
259
- const hasOperators = tokens.some(t => t.type === "op");
260
- const parser = new Parser(tokens);
261
- let nodes: Node[];
337
+ // "value" is a whole expression whose value is used, e.g. the right-hand side of @set
338
+ type Mode = "condition" | "arguments" | "display" | "value";
339
+
340
+ // Parses `text` and returns the rewritten nodes, or null if it should be left alone: it
341
+ // doesn't use infix syntax, or it can't be parsed and has no operators (which leaves malformed
342
+ // prefix syntax for Handlebars to report).
343
+ function rewrite(text: string, mode: Mode, label: string): Node[] | null {
344
+ // Whether errors are always reported, and the result always returned, rather than leaving
345
+ // anything that isn't infix syntax for Handlebars
346
+ const strict = mode === "display" || mode === "value";
347
+ // Errors are thrown after the try/catch blocks, as new errors with the expression in the message
262
348
  let error: ExpressionError | null = null;
349
+ let tokens: Token[] = [];
263
350
  try {
264
- nodes = parser.parseCondition();
351
+ tokens = tokenize(text);
265
352
  } catch (e) {
266
- if (!hasOperators || !(e instanceof ExpressionError)) return null;
353
+ // Leave anything we can't tokenize for Handlebars to report, except {{= }}
354
+ if (!strict || !(e instanceof ExpressionError)) return null;
267
355
  error = e;
268
- nodes = [];
356
+ }
357
+ const hasOperators = tokens.some(t => t.type === "op");
358
+ const parser = new Parser(tokens);
359
+ let nodes: Node[] = [];
360
+ if (!error) {
361
+ try {
362
+ nodes = mode === "condition" ? parser.parseCondition()
363
+ : mode === "arguments" ? parser.parseArguments(1)
364
+ : [parser.parseExpression()];
365
+ } catch (e) {
366
+ if (!(e instanceof ExpressionError) || (!hasOperators && !strict)) return null;
367
+ error = e;
368
+ }
269
369
  }
270
370
  if (error) {
271
- throw new Error(`Invalid condition "${condition.trim()}": ${error.message}`);
371
+ throw new Error(`Invalid ${label} "${text.trim()}": ${error.message}`);
272
372
  }
273
- if (!parser.usedInfix) return null;
274
- return nodes.map(emit).join(" ");
373
+ if (!parser.usedInfix && !strict) return null;
374
+ return nodes;
375
+ }
376
+
377
+ // Rewrites a single condition. Returns null if it doesn't use infix syntax.
378
+ export function rewriteInfixCondition(condition: string): string | null {
379
+ const nodes = rewrite(condition, "condition", "condition");
380
+ return nodes && nodes.map(emit).join(" ");
275
381
  }
276
382
 
277
- const blockStart = /(\\*)\{\{(~?\s*)(#if|#unless|else\s+if|else\s+unless)(?=[\s(!])/g;
383
+ // Rewrites the arguments to {{set}}, {{inc}} or {{dec}}: an attribute name, then an expression.
384
+ // Returns null if the expression doesn't use infix syntax.
385
+ export function rewriteInfixArguments(args: string): string | null {
386
+ const nodes = rewrite(args, "arguments", "expression");
387
+ return nodes && nodes.map(emit).join(" ");
388
+ }
389
+
390
+ // Rewrites the expression in {{= expression}} into the contents of a mustache tag, i.e. a
391
+ // helper call without the outer parentheses, or an attribute name.
392
+ export function rewriteDisplayExpression(expression: string): string {
393
+ const node = rewrite(expression, "display", "expression")![0];
394
+ if (node.kind === "call") {
395
+ return `${node.name} ${node.args.map(emit).join(" ")}`;
396
+ }
397
+ if (literals.includes(node.text) || numberPattern.test(node.text) || /^["']/.test(node.text)) {
398
+ throw new Error(`Invalid expression "${expression.trim()}": expected an attribute or a calculation`);
399
+ }
400
+ return node.text;
401
+ }
402
+
403
+ // Rewrites an expression whose value is used (the right-hand side of @set and link setters, when a
404
+ // story uses expressions there) into a Handlebars value: a helper call in parentheses, an
405
+ // attribute name or a literal. Throws if it isn't a valid expression.
406
+ export function rewriteValueExpression(expression: string): string {
407
+ return emit(rewrite(expression, "value", "expression")![0]);
408
+ }
409
+
410
+ // Splits a list of link setters on the commas between them, but not on commas inside quotes or
411
+ // parentheses: greeting = "Hi, there", gold -= price is two setters.
412
+ export function splitSetters(setters: string): string[] {
413
+ const result: string[] = [];
414
+ let depth = 0;
415
+ let quote: string | null = null;
416
+ let start = 0;
417
+ for (let i = 0; i < setters.length; i++) {
418
+ const c = setters[i];
419
+ if (quote) {
420
+ if (c === "\\") i++;
421
+ else if (c === quote) quote = null;
422
+ }
423
+ else if (c === "\"" || c === "'") quote = c;
424
+ else if (c === "(") depth++;
425
+ else if (c === ")") depth = Math.max(0, depth - 1);
426
+ else if (c === "," && depth === 0) {
427
+ result.push(setters.slice(start, i));
428
+ start = i + 1;
429
+ }
430
+ }
431
+ result.push(setters.slice(start));
432
+ return result.map(s => s.trim()).filter(s => s !== "");
433
+ }
434
+
435
+ const tagStart = /(\\*)\{\{(~?\s*)(?:(#if|#unless|else\s+if|else\s+unless)(?=[\s(!])|(set|inc|dec)(?=\s)|(=))/g;
278
436
 
279
437
  // Finds the end of a mustache tag starting at `from`, skipping over quoted strings.
280
438
  // Returns the index of the closing "}}" (or "~}}"), or -1.
@@ -301,9 +459,9 @@ export function rewriteInfixExpressions(text: string): string {
301
459
 
302
460
  let result = "";
303
461
  let last = 0;
304
- blockStart.lastIndex = 0;
462
+ tagStart.lastIndex = 0;
305
463
  let match: RegExpExecArray | null;
306
- while ((match = blockStart.exec(text)) !== null) {
464
+ while ((match = tagStart.exec(text)) !== null) {
307
465
  // An odd number of backslashes escapes the mustache
308
466
  if (match[1].length % 2 === 1) continue;
309
467
 
@@ -311,13 +469,20 @@ export function rewriteInfixExpressions(text: string): string {
311
469
  const argEnd = findTagEnd(text, argStart);
312
470
  if (argEnd === -1) break;
313
471
 
314
- const condition = text.slice(argStart, argEnd);
315
- const rewritten = rewriteInfixCondition(condition);
316
- if (rewritten !== null) {
317
- result += text.slice(last, argStart) + " " + rewritten;
472
+ const args = text.slice(argStart, argEnd);
473
+ if (match[5]) {
474
+ // {{= expression}}: replace the "=" too
475
+ const tagOpen = match.index + match[1].length;
476
+ result += text.slice(last, tagOpen) + "{{" + match[2] + rewriteDisplayExpression(args);
318
477
  last = argEnd;
478
+ } else {
479
+ const rewritten = match[3] ? rewriteInfixCondition(args) : rewriteInfixArguments(args);
480
+ if (rewritten !== null) {
481
+ result += text.slice(last, argStart) + " " + rewritten;
482
+ last = argEnd;
483
+ }
319
484
  }
320
- blockStart.lastIndex = argEnd;
485
+ tagStart.lastIndex = argEnd;
321
486
  }
322
487
  return result + text.slice(last);
323
488
  }
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
+ }
@@ -220,6 +220,48 @@ Your score is {{#label "score"}}0{{/label}}.
220
220
  expect(labelSpans[0].classList.contains("fade-in")).toBe(false);
221
221
  });
222
222
 
223
+ test("Replace plugin: replaces the latest label, in a section visited again after the screen is cleared", async () => {
224
+ const script = `
225
+ [[]]:
226
+ @clear
227
+
228
+ [[room]]:
229
+ The box is {{#label "box"}}closed{{/label}}. [Open it](open) or [[go out]](outside).
230
+
231
+ [open]:
232
+ {{#replace "box"}}open{{/replace}}
233
+
234
+ [[outside]]:
235
+ You're outside. [[Go back in]](room)
236
+ `;
237
+
238
+ const { squiffyApi, element } = await initScript(script);
239
+ await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='outside']")!);
240
+ await squiffyApi.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='room']")!);
241
+
242
+ expect(element.querySelectorAll(".squiffy-label-box").length).toBe(2);
243
+ const links = element.querySelectorAll<HTMLElement>("a.squiffy-link[data-passage='open']");
244
+ await squiffyApi.clickLink(links[links.length - 1]);
245
+ const labels = element.querySelectorAll(".squiffy-label-box");
246
+ expect(labels[0].textContent).toBe("closed");
247
+ expect(labels[1].textContent).toBe("open");
248
+ });
249
+
250
+ test("Replace plugin: replace with only a label in it", async () => {
251
+ const script = `
252
+ The box is {{#label "box"}}closed{{/label}}. [Open it](open)
253
+
254
+ [open]:
255
+ {{#replace "box"}}{{#label "lid"}}open{{/label}}{{/replace}}
256
+ `;
257
+
258
+ const { squiffyApi, element } = await initScript(script);
259
+ await squiffyApi.clickLink(findPassageLink(element, "open")!);
260
+
261
+ expect(element.querySelector(".squiffy-label-box")?.innerHTML).toBe("<span class=\"squiffy-label-lid\">open</span>");
262
+ expect(element.querySelector(".squiffy-error")).toBeNull();
263
+ });
264
+
223
265
  // ===== RotateSequencePlugin Tests =====
224
266
 
225
267
  test("Sequence plugin: click through sequence", async () => {
@@ -11,8 +11,12 @@ export function ReplaceLabel() : SquiffyPlugin {
11
11
  return new Handlebars.SafeString(`<span class="squiffy-label-${name}">${options.fn(this)}</span>`);
12
12
  });
13
13
  squiffy.registerHelper("replace", function(this: any, name: string, options) {
14
- const result = options.fn(this);
15
- const element = squiffy.outputElement.querySelector<HTMLElement>(`.squiffy-label-${name}`);
14
+ // A block that's only another helper, such as {{#label}}, gives that helper's SafeString
15
+ const result = String(options.fn(this));
16
+ // The latest label with the name: when a section is visited again, or the screen's been
17
+ // cleared, earlier ones can still be in the output (in the clear stack, hidden)
18
+ const labels = squiffy.outputElement.querySelectorAll<HTMLElement>(`.squiffy-label-${name}`);
19
+ const element = labels[labels.length - 1];
16
20
  if (element) {
17
21
  const isBlock = result.includes("\n\n");
18
22
  const html = isBlock
@@ -71,6 +71,8 @@ describe("preview", () => {
71
71
  expect(element.textContent).toContain("Welcome.");
72
72
  expect(messages).toEqual([
73
73
  { type: "canGoBackChanged", canGoBack: false },
74
+ // The story-wide turn count (#377), which isn't internal, so it's reported
75
+ { type: "attributeSet", name: "turns", value: 0 },
74
76
  { type: "attributeSet", name: "score", value: 1 },
75
77
  { type: "navigated", section: "start" },
76
78
  { type: "loaded" },
@@ -80,6 +82,7 @@ describe("preview", () => {
80
82
  element.querySelector<HTMLElement>("a[data-passage='look']")!.click();
81
83
  await vi.waitFor(() => expect(messages.some(m => m.type == "navigated")).toBe(true));
82
84
  expect(messages).toEqual([
85
+ { type: "attributeSet", name: "turns", value: 1 },
83
86
  { type: "attributeSet", name: "looked", value: true },
84
87
  { type: "canGoBackChanged", canGoBack: true },
85
88
  { type: "navigated", section: "start", passage: "look" },
@@ -99,7 +99,7 @@ select.squiffy-invalid:focus
99
99
  box-shadow: 0 0 0 0.2rem color-mix(in srgb, var(--squiffy-error) 50%, transparent);
100
100
  }
101
101
 
102
- /* Header button styles: the Restart button */
102
+ /* Header button styles: the Back and Restart buttons */
103
103
  button.squiffy-header-button
104
104
  {
105
105
  color: var(--squiffy-muted);
@@ -114,12 +114,19 @@ button.squiffy-header-button
114
114
  transition: color 0.2s ease-in-out, text-decoration-color 0.2s ease-in-out;
115
115
  }
116
116
 
117
- button.squiffy-header-button:hover
117
+ button.squiffy-header-button:hover:not(:disabled)
118
118
  {
119
119
  color: var(--squiffy-text);
120
120
  text-decoration-color: currentColor;
121
121
  }
122
122
 
123
+ /* The Back button, when there's nothing to go back to */
124
+ button.squiffy-header-button:disabled
125
+ {
126
+ cursor: default;
127
+ opacity: 0.5;
128
+ }
129
+
123
130
  /* Output block spacing */
124
131
  div.squiffy-output-block:not(:last-child),
125
132
  div.squiffy-output-passage:not(:last-child),