squiffy-runtime 7.0.0-beta.2 → 7.0.0-beta.4

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.
@@ -2,7 +2,8 @@ import * as marked from "marked";
2
2
  import Handlebars from "handlebars";
3
3
  import { Section, Story } from "./types.js";
4
4
  import { State } from "./state.js";
5
- import { rewriteInfixExpressions } from "./infixExpressions.js";
5
+ import { rewriteInfixExpressions, rewriteValueExpression, splitSetters } from "./infixExpressions.js";
6
+ import { isNumeric, isBlank, toNumber } from "./numbers.js";
6
7
 
7
8
  export class TextProcessor {
8
9
  getStory: () => Story;
@@ -54,24 +55,29 @@ export class TextProcessor {
54
55
  return "";
55
56
  });
56
57
 
57
- this.handlebars.registerHelper("unset", (attribute: string) => {
58
- this.state.set(attribute, false);
58
+ // Captures a value for evaluate()
59
+ this.handlebars.registerHelper("__value", (value: unknown) => {
60
+ this.evaluated = unwrapValue(value);
59
61
  return "";
60
62
  });
61
63
 
62
- this.handlebars.registerHelper("inc", (attribute: string, options: any) => {
63
- const amount = typeof options === "number" ? options : 1;
64
- const currentValue = this.state.get(attribute) || 0;
65
- this.state.set(attribute, currentValue + amount);
64
+ this.handlebars.registerHelper("unset", (attribute: string) => {
65
+ this.state.set(attribute, false);
66
66
  return "";
67
67
  });
68
68
 
69
- this.handlebars.registerHelper("dec", (attribute: string, options: any) => {
70
- const amount = typeof options === "number" ? options : 1;
71
- const currentValue = this.state.get(attribute) || 0;
72
- this.state.set(attribute, currentValue - amount);
73
- return "";
74
- });
69
+ // {{inc "x"}} adds 1, and {{inc "x" amount}} adds the amount. Handlebars passes its options
70
+ // object last, so the amount is there if there's anything before it.
71
+ const incDecHelper = (name: string, sign: 1 | -1) => {
72
+ this.handlebars.registerHelper(name, (attribute: string, ...args: any[]) => {
73
+ const amount = args.length > 1 ? toNumber(name, unwrapValue(args[0])) : 1;
74
+ const currentValue = toNumber(name, this.state.get(attribute));
75
+ this.state.set(attribute, currentValue + sign * amount);
76
+ return "";
77
+ });
78
+ };
79
+ incDecHelper("inc", 1);
80
+ incDecHelper("dec", -1);
75
81
 
76
82
  this.handlebars.registerHelper("and", (...args) => args.slice(0,-1).every(Boolean));
77
83
  this.handlebars.registerHelper("or", (...args) => args.slice(0,-1).some(Boolean));
@@ -82,6 +88,48 @@ export class TextProcessor {
82
88
  this.handlebars.registerHelper("lt", (a,b) => a < b);
83
89
  this.handlebars.registerHelper("gte", (a,b) => a >= b);
84
90
  this.handlebars.registerHelper("lte", (a,b) => a <= b);
91
+ // Maths helpers. These are what arithmetic in infix expressions is rewritten to,
92
+ // e.g. {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
93
+ const mathsHelper = (name: string, fn: (a: number, b: number) => number) => {
94
+ this.handlebars.registerHelper(name, (...args) => {
95
+ const values = args.slice(0, -1).map(unwrapValue);
96
+ if (values.length !== 2) {
97
+ throw new Error(`"${name}" needs two values, but was given ${values.length}`);
98
+ }
99
+ return fn(toNumber(name, values[0]), toNumber(name, values[1]));
100
+ });
101
+ };
102
+ // "add" joins text when either value isn't a number (or a string holding one),
103
+ // so name + " the Brave" works, but an attribute holding "5" still adds as 5.
104
+ this.handlebars.registerHelper("add", (...args) => {
105
+ const values = args.slice(0, -1).map(unwrapValue);
106
+ if (values.length !== 2) {
107
+ throw new Error(`"add" needs two values, but was given ${values.length}`);
108
+ }
109
+ const [a, b] = values;
110
+ if (isNumeric(a) && isNumeric(b)) {
111
+ return toNumber("add", a) + toNumber("add", b);
112
+ }
113
+ const text = (v: any) => {
114
+ if (isBlank(v)) return "";
115
+ if (typeof v === "object") {
116
+ throw new Error(`"add" can't add ${Array.isArray(v) ? "a list" : "an object"}`);
117
+ }
118
+ return String(v);
119
+ };
120
+ return text(a) + text(b);
121
+ });
122
+ mathsHelper("sub", (a, b) => a - b);
123
+ mathsHelper("mul", (a, b) => a * b);
124
+ mathsHelper("div", (a, b) => {
125
+ if (b === 0) throw new Error("division by zero");
126
+ return a / b;
127
+ });
128
+ mathsHelper("mod", (a, b) => {
129
+ if (b === 0) throw new Error("division by zero");
130
+ return a % b;
131
+ });
132
+
85
133
  this.handlebars.registerHelper("array", function (...args) {
86
134
  args.pop(); // remove last argument - options
87
135
  return args;
@@ -168,17 +216,19 @@ export class TextProcessor {
168
216
  return arr.length;
169
217
  });
170
218
 
219
+ const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
220
+
171
221
  const addAdditionalParameters = (options: any) => {
172
222
  let result = "";
173
223
  const setters = options.hash.set as string || "";
174
224
  if (setters) {
175
- result += ` data-set='${JSON.stringify(setters.split(",").map(s => s.trim()))}'`;
225
+ // With expressions, a setter can have commas inside quotes, e.g. greeting = "Hi, there"
226
+ const list = this.getStory().expressions ? splitSetters(setters) : setters.split(",").map(s => s.trim());
227
+ result += ` data-set="${escapeAttr(JSON.stringify(list))}"`;
176
228
  }
177
229
  return result;
178
230
  };
179
231
 
180
- const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
181
-
182
232
  this.handlebars.registerHelper("section", (section: string, options) => {
183
233
  const text = options.hash.text as string || section;
184
234
  return new Handlebars.SafeString(`<a class="squiffy-link link-section" data-section="${escapeAttr(section)}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
@@ -190,6 +240,23 @@ export class TextProcessor {
190
240
  });
191
241
  }
192
242
 
243
+ // Evaluates an expression, such as gold + price * 2, with the same rules and helpers as
244
+ // {{#if}} and {{set}}. Throws if it isn't valid, or a helper fails.
245
+ evaluate(expression: string): unknown {
246
+ let template = this.expressionCache.get(expression);
247
+ if (!template) {
248
+ template = this.handlebars.compile(`{{__value ${rewriteValueExpression(expression)}}}`);
249
+ this.expressionCache.set(expression, template);
250
+ }
251
+ this.evaluated = undefined;
252
+ template(this.state.getStore());
253
+ return this.evaluated;
254
+ }
255
+
256
+ private expressionCache = new Map<string, HandlebarsTemplateDelegate>();
257
+ // Where the __value helper puts the value of the expression being evaluated
258
+ private evaluated: unknown;
259
+
193
260
  process(text: string, inline: boolean) {
194
261
  try {
195
262
  const template = this.handlebars.compile(rewriteInfixExpressions(text));
@@ -204,7 +271,13 @@ export class TextProcessor {
204
271
  } catch (e) {
205
272
  const errorMessage = e instanceof Error ? e.message : String(e);
206
273
  console.error("Squiffy template error:", errorMessage);
207
- 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>Template error:</strong> ${errorMessage}</div>`;
274
+ return errorHtml("Template error:", errorMessage);
208
275
  }
209
276
  }
277
+ }
278
+
279
+ // The block that shows an error in the story's output
280
+ export function errorHtml(label: string, message: string) {
281
+ const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
282
+ 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
283
  }
package/src/types.ts CHANGED
@@ -79,6 +79,9 @@ export interface Story {
79
79
  start: string;
80
80
  id?: string | null;
81
81
  uiJsIndex?: number;
82
+ // Whether @set and link setters take expressions, with the same rules as {{#if}}: attributes
83
+ // by name, and text in quotes. True for a story with a squiffy.json (#373).
84
+ expressions?: boolean;
82
85
  sections: Record<string, Section>;
83
86
  }
84
87