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,5 +1,6 @@
1
1
  import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt } from "./types.js";
2
- import { TextProcessor } from "./textProcessor.js";
2
+ import { TextProcessor, errorHtml } from "./textProcessor.js";
3
+ import { toNumber } from "./numbers.js";
3
4
  import { Emitter, SquiffyEventMap } from "./events.js";
4
5
  import { State } from "./state.js";
5
6
  import { updateStory } from "./updater.js";
@@ -23,9 +24,18 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
23
24
  let scrollPosition = 0;
24
25
  // Set when the screen is cleared, so the next scroll goes up to the top of the new screen (#54)
25
26
  let scrollToTop = false;
27
+ // Errors from setting attributes (e.g. @set gold += abc), shown at the start of the next text
28
+ // written. A link's setters run before the next section has anywhere to show them.
29
+ const pendingErrors: string[] = [];
26
30
  const emitter = new Emitter<SquiffyEventMap>();
27
31
  const transitions: (() => Promise<void>)[] = [];
28
32
  let runningTransitions = false;
33
+ // A {{goto ... after=}} waiting to happen (#375)
34
+ let gotoTimer: ReturnType<typeof setTimeout> | undefined;
35
+ // {{goto}}s followed one after another without the player doing anything, so a loop can't hang
36
+ // the browser
37
+ let gotoHops = 0;
38
+ const MAX_GOTO_HOPS = 100;
29
39
 
30
40
  async function handleLink(link: HTMLElement): Promise<boolean> {
31
41
  if (runningTransitions) return false;
@@ -42,6 +52,12 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
42
52
  const passage = link.getAttribute("data-passage");
43
53
  const section = link.getAttribute("data-section");
44
54
 
55
+ if (passage !== null || section !== null) {
56
+ gotoHops = 0;
57
+ // The story-wide turn count (#377). A {{goto}} isn't a turn, as the player didn't click it.
58
+ set("turns", (get("turns") || 0) + 1);
59
+ }
60
+
45
61
  if (passage !== null) {
46
62
  disableLink(link);
47
63
  set("_turncount", get("_turncount") + 1);
@@ -109,8 +125,56 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
109
125
  }
110
126
  if (!load()) {
111
127
  await go(story.start);
128
+ return;
129
+ }
130
+ // Saved while waiting for a {{goto}}, so carry on waiting
131
+ const element = currentPassageElement ?? currentSectionElement;
132
+ const section = element?.getAttribute("data-goto");
133
+ if (section && section in story.sections) {
134
+ await followGoto({ section, after: Number(element.getAttribute("data-goto-after") || 0) });
112
135
  }
113
136
  }
137
+
138
+ function cancelGoto() {
139
+ clearTimeout(gotoTimer);
140
+ gotoTimer = undefined;
141
+ textProcessor.goto = null;
142
+ }
143
+
144
+ // Takes the {{goto}} from the text just shown, if there was one, and marks the section or
145
+ // passage element with it, so that going back skips it, and loading resumes it.
146
+ function takeGoto(element: HTMLElement) {
147
+ const pending = textProcessor.goto;
148
+ textProcessor.goto = null;
149
+ if (pending) {
150
+ element.setAttribute("data-goto", pending.section);
151
+ if (pending.after) element.setAttribute("data-goto-after", String(pending.after));
152
+ }
153
+ return pending;
154
+ }
155
+
156
+ async function followGoto(pending: { section: string; after: number } | null) {
157
+ if (!pending) return;
158
+ if (pending.after > 0) {
159
+ gotoTimer = setTimeout(() => {
160
+ gotoTimer = undefined;
161
+ gotoHops = 0;
162
+ void go(pending.section);
163
+ }, pending.after);
164
+ return;
165
+ }
166
+ if (++gotoHops > MAX_GOTO_HOPS) {
167
+ gotoHops = 0;
168
+ const element = currentPassageElement ?? currentSectionElement;
169
+ element.removeAttribute("data-goto");
170
+ const message = `stopped after ${MAX_GOTO_HOPS} in a row without the player clicking anything, going to "${pending.section}". Is there a loop?`;
171
+ console.error("Squiffy error in {{goto}}:", message);
172
+ element.insertAdjacentHTML("beforeend", errorHtml("Error in {{goto}}:", message));
173
+ save();
174
+ return;
175
+ }
176
+ await go(pending.section);
177
+ }
114
178
 
115
179
  async function processLink(link: HTMLElement) {
116
180
  animation.runLinkAnimation(link);
@@ -124,7 +188,67 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
124
188
  }
125
189
  }
126
190
 
191
+ // Runs a setter from @set or a link, e.g. gold += 5. An error leaves the attribute as it was,
192
+ // and is shown with the next text written.
127
193
  function setAttribute(expr: string) {
194
+ try {
195
+ if (story.expressions) {
196
+ setWithExpression(expr);
197
+ }
198
+ else {
199
+ setWithoutExpression(expr);
200
+ }
201
+ }
202
+ catch (e) {
203
+ const message = e instanceof Error ? e.message : String(e);
204
+ console.error(`Squiffy error in "${expr}":`, message);
205
+ pendingErrors.push(errorHtml(`Error in "${expr}":`, message));
206
+ }
207
+ }
208
+
209
+ // +=, -=, *= and /=, which only work on numbers (#374)
210
+ function operate(lhs: string, op: string, amountValue: unknown) {
211
+ const what = op + "=";
212
+ const amount = toNumber(what, amountValue);
213
+ let value = toNumber(what, get(lhs));
214
+ if (op == "+") value += amount;
215
+ if (op == "-") value -= amount;
216
+ if (op == "*") value *= amount;
217
+ if (op == "/") value /= amount;
218
+ set(lhs, value);
219
+ }
220
+
221
+ // A story with a squiffy.json (#373): the right-hand side is an expression, with the same rules
222
+ // as {{#if}}, e.g. weapon = "sword", gold = gold + price * 2, rich = gold > 100.
223
+ function setWithExpression(expr: string) {
224
+ const textMatch = /^(\w+)\s*:=(.*)$/.exec(expr);
225
+ if (textMatch) {
226
+ // Text with {{...}} processed, as before
227
+ set(textMatch[1], ui.processText(textMatch[2], true));
228
+ return;
229
+ }
230
+ const match = /^(\w+)\s*([+\-*/]?)=(?!=)(.*)$/.exec(expr);
231
+ if (match) {
232
+ const [, lhs, op, rhs] = match;
233
+ const value = textProcessor.evaluate(rhs);
234
+ if (op) {
235
+ operate(lhs, op, value);
236
+ }
237
+ else {
238
+ set(lhs, value);
239
+ }
240
+ return;
241
+ }
242
+ const flagMatch = /^(not\s+)?(\w+)$/.exec(expr.trim());
243
+ if (!flagMatch) {
244
+ throw new Error("expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key");
245
+ }
246
+ set(flagMatch[2], !flagMatch[1]);
247
+ }
248
+
249
+ // A story without a squiffy.json, as in Squiffy 6: the right-hand side is a number, true,
250
+ // false, @attribute, or else text
251
+ function setWithoutExpression(expr: string) {
128
252
  expr = expr.replace(/^(\w*\s*):=(.*)$/, (_, name, value) => (name + "=" + ui.processText(value, true)));
129
253
  const setRegex = /^([\w]*)\s*=\s*(.*)$/;
130
254
  const setMatch = setRegex.exec(expr);
@@ -151,24 +275,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
151
275
  if (incDecMatch) {
152
276
  const lhs = incDecMatch[1];
153
277
  const op = incDecMatch[2];
154
- let rhs = incDecMatch[3];
155
- if (rhs.startsWith("@")) rhs = get(rhs.substring(1));
156
- const rhsNumeric = parseFloat(rhs);
157
- let value = get(lhs);
158
- if (value === null) value = 0;
159
- if (op == "+") {
160
- value += rhsNumeric;
161
- }
162
- if (op == "-") {
163
- value -= rhsNumeric;
164
- }
165
- if (op == "*") {
166
- value *= rhsNumeric;
167
- }
168
- if (op == "/") {
169
- value /= rhsNumeric;
170
- }
171
- set(lhs, value);
278
+ const rhsText = incDecMatch[3].trim();
279
+ operate(lhs, op, rhsText.startsWith("@") ? get(rhsText.substring(1)) : rhsText);
172
280
  }
173
281
  else {
174
282
  let value = true;
@@ -182,10 +290,14 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
182
290
  }
183
291
 
184
292
  async function go(sectionName: string) {
293
+ cancelGoto();
185
294
  const oldCanGoBack = canGoBack();
186
295
  currentSection = story.sections[sectionName];
187
296
  if (!currentSection) return;
188
297
  set("_section", sectionName);
298
+ // The story-wide turn count starts at 0 (#377), in a new story or one saved before it existed.
299
+ // It isn't a change the player made, so it isn't undone.
300
+ if (get("turns") === null) state.setInternal("turns", 0, false);
189
301
  state.setSeen(sectionName);
190
302
  const master = story.sections[""];
191
303
  if (master?.clear || currentSection.clear) {
@@ -213,6 +325,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
213
325
  setupInputValidation(currentSectionElement);
214
326
 
215
327
  set("_turncount", 0);
328
+ const pending = takeGoto(currentSectionElement);
216
329
  writeUndoLog();
217
330
  save();
218
331
 
@@ -221,6 +334,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
221
334
  emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
222
335
  }
223
336
  emitter.emit("navigated", { section: sectionName });
337
+ await followGoto(pending);
224
338
  }
225
339
 
226
340
  function runJs(index: number, extra: any = null) {
@@ -235,6 +349,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
235
349
  story: {
236
350
  go: go,
237
351
  seen: (sectionOrPassage: string) => state.getSeen(sectionOrPassage),
352
+ visits: (sectionOrPassage: string) => state.getVisits(sectionOrPassage),
238
353
  },
239
354
  element: outputElementContainer,
240
355
  import: imports,
@@ -274,6 +389,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
274
389
  }
275
390
 
276
391
  async function showPassage(passageName: string) {
392
+ cancelGoto();
277
393
  const oldCanGoBack = canGoBack();
278
394
  let passage = currentSection.passages && currentSection.passages[passageName];
279
395
  const masterSection = story.sections[""];
@@ -335,6 +451,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
335
451
  // Setup validation for any inputs added by passages
336
452
  setupInputValidation(currentSectionElement);
337
453
 
454
+ const pending = takeGoto(currentPassageElement!);
338
455
  writeUndoLog();
339
456
  save();
340
457
  const newCanGoBack = canGoBack();
@@ -342,6 +459,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
342
459
  emitter.emit("canGoBackChanged", { canGoBack: newCanGoBack });
343
460
  }
344
461
  emitter.emit("navigated", { section: get("_section"), passage: passageName });
462
+ await followGoto(pending);
345
463
  }
346
464
 
347
465
  async function processAttributes(attributes: string[]) {
@@ -351,6 +469,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
351
469
  }
352
470
 
353
471
  function restart() {
472
+ cancelGoto();
354
473
  state.reset();
355
474
  // TODO: This feels like the wrong way of triggering location.reload()
356
475
  // - should be a separate setting to the scroll setting.
@@ -496,7 +615,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
496
615
  write: (text: string, source: string) => {
497
616
  scrollPosition = outputElement.scrollHeight;
498
617
 
499
- const html = ui.renderHtml(text, false).trim();
618
+ const html = pendingErrors.splice(0).join("") + ui.renderHtml(text, false).trim();
500
619
 
501
620
  // Previously, we skipped the rest of this if "html" came back as an empty string.
502
621
  // But, we _do_ always want the block to be created, in the editor at least - as the
@@ -638,7 +757,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
638
757
  }
639
758
 
640
759
  function canGoBack() {
641
- return getHistoryCount() > 1;
760
+ // Sections and passages that went somewhere else with {{goto}} are skipped by goBack(), so
761
+ // they don't count, unless it's the current one, still waiting for its after= delay
762
+ const current = currentPassageElement ?? currentSectionElement;
763
+ const redirected = [...outputElement.querySelectorAll("[data-goto]")].filter(el => el !== current).length;
764
+ return getHistoryCount() - redirected > 1;
642
765
  }
643
766
 
644
767
  function goBack() {
@@ -648,6 +771,24 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
648
771
  return;
649
772
  }
650
773
 
774
+ cancelGoto();
775
+ // Undo back to the section or passage the player clicked through to, not one that went
776
+ // somewhere else with {{goto}}
777
+ do {
778
+ undoLast();
779
+ } while ((currentPassageElement ?? currentSectionElement).hasAttribute("data-goto") && getHistoryCount() > 1);
780
+ // The attributes were saved as they were undone, so save the output to match. Otherwise a saved
781
+ // game would come back with the text that was undone.
782
+ save();
783
+
784
+ if (!canGoBack()) {
785
+ emitter.emit("canGoBackChanged", { canGoBack: false });
786
+ }
787
+ const passage = currentPassageElement?.getAttribute("data-passage");
788
+ emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
789
+ }
790
+
791
+ function undoLast() {
651
792
  const clearStack = getClearStack();
652
793
 
653
794
  if (currentPassageElement) {
@@ -707,12 +848,6 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
707
848
  setCurrentPassageElement();
708
849
  enableInputs(currentSectionElement);
709
850
  }
710
-
711
- if (!canGoBack()) {
712
- emitter.emit("canGoBackChanged", { canGoBack: false });
713
- }
714
- const passage = currentPassageElement?.getAttribute("data-passage");
715
- emitter.emit("navigated", passage ? { section: get("_section"), passage } : { section: get("_section") });
716
851
  }
717
852
 
718
853
  // We create a separate div inside the passed-in element. This allows us to clear the text output, but
@@ -827,6 +962,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
827
962
  clickLink: handleLink,
828
963
  update: update,
829
964
  goBack: goBack,
965
+ canGoBack: canGoBack,
830
966
  on: (e, h) => emitter.on(e, h),
831
967
  off: (e, h) => emitter.off(e, h),
832
968
  once: (e, h) => emitter.once(e, h),
package/src/state.ts CHANGED
@@ -107,9 +107,15 @@ export class State {
107
107
  }
108
108
  }
109
109
 
110
+ // Records a visit to a section or passage: adds it to _seen_sections, and counts it in
111
+ // _visits (#377). Both are attributes, so going back undoes them.
110
112
  setSeen(sectionName: string) {
111
113
  let seenSections = this.get("_seen_sections");
112
114
  if (!seenSections) seenSections = [];
115
+ const visits = this.get("_visits") || {};
116
+ // A save from before _visits has the name in _seen_sections with no count: that's one visit
117
+ visits[sectionName] = this.getVisitsFrom(visits, seenSections, sectionName) + 1;
118
+ this.set("_visits", visits);
113
119
  if (seenSections.indexOf(sectionName) == -1) {
114
120
  seenSections.push(sectionName);
115
121
  this.set("_seen_sections", seenSections);
@@ -121,4 +127,14 @@ export class State {
121
127
  if (!seenSections) return false;
122
128
  return (seenSections.indexOf(sectionName) > -1);
123
129
  }
130
+
131
+ // How many times a section or passage has been visited, or 0 if it hasn't
132
+ getVisits(sectionName: string): number {
133
+ return this.getVisitsFrom(this.get("_visits") || {}, this.get("_seen_sections") || [], sectionName);
134
+ }
135
+
136
+ private getVisitsFrom(visits: Record<string, number>, seenSections: string[], sectionName: string): number {
137
+ if (Object.prototype.hasOwnProperty.call(visits, sectionName)) return visits[sectionName];
138
+ return seenSections.indexOf(sectionName) > -1 ? 1 : 0;
139
+ }
124
140
  }
@@ -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;
@@ -30,6 +31,7 @@ export class TextProcessor {
30
31
  });
31
32
 
32
33
  this.handlebars.registerHelper("seen", (name: string) => this.state.getSeen(name));
34
+ this.handlebars.registerHelper("visits", (name: string) => this.state.getVisits(name));
33
35
  this.handlebars.registerHelper("get", (attribute: string) => this.state.get(attribute));
34
36
  this.handlebars.registerHelper("at", (section: string | string[]) => {
35
37
  const currentSection = this.state.get("_section");
@@ -47,6 +49,27 @@ export class TextProcessor {
47
49
  return value;
48
50
  };
49
51
 
52
+ // {{goto "section"}} and {{goto "section" after=3000}} (#375): the runtime goes there once
53
+ // the section or passage being shown has been written. Only the first one counts.
54
+ this.handlebars.registerHelper("goto", (...args: any[]) => {
55
+ const options = args.pop();
56
+ const section = args.length ? unwrapValue(args[0]) : undefined;
57
+ if (typeof section != "string" || !section || !(section in this.getStory().sections)) {
58
+ return new Handlebars.SafeString(errorHtml("Error in {{goto}}:",
59
+ section === undefined ? "expected a section name, e.g. {{goto \"cave\"}}" : `there is no section called "${section}"`));
60
+ }
61
+ let after = 0;
62
+ if (options.hash.after !== undefined) {
63
+ after = Number(unwrapValue(options.hash.after));
64
+ if (!Number.isFinite(after) || after < 0) {
65
+ return new Handlebars.SafeString(errorHtml("Error in {{goto}}:",
66
+ `after= should be a number of milliseconds, e.g. after=3000, not "${options.hash.after}"`));
67
+ }
68
+ }
69
+ this.goto ??= { section, after };
70
+ return "";
71
+ });
72
+
50
73
  // State modification helpers (side effects, no output)
51
74
  // These execute at render time, so they respect {{#if}} conditions
52
75
  this.handlebars.registerHelper("set", (attribute: string, value: any) => {
@@ -54,24 +77,29 @@ export class TextProcessor {
54
77
  return "";
55
78
  });
56
79
 
57
- this.handlebars.registerHelper("unset", (attribute: string) => {
58
- this.state.set(attribute, false);
80
+ // Captures a value for evaluate()
81
+ this.handlebars.registerHelper("__value", (value: unknown) => {
82
+ this.evaluated = unwrapValue(value);
59
83
  return "";
60
84
  });
61
85
 
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);
86
+ this.handlebars.registerHelper("unset", (attribute: string) => {
87
+ this.state.set(attribute, false);
66
88
  return "";
67
89
  });
68
90
 
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
- });
91
+ // {{inc "x"}} adds 1, and {{inc "x" amount}} adds the amount. Handlebars passes its options
92
+ // object last, so the amount is there if there's anything before it.
93
+ const incDecHelper = (name: string, sign: 1 | -1) => {
94
+ this.handlebars.registerHelper(name, (attribute: string, ...args: any[]) => {
95
+ const amount = args.length > 1 ? toNumber(name, unwrapValue(args[0])) : 1;
96
+ const currentValue = toNumber(name, this.state.get(attribute));
97
+ this.state.set(attribute, currentValue + sign * amount);
98
+ return "";
99
+ });
100
+ };
101
+ incDecHelper("inc", 1);
102
+ incDecHelper("dec", -1);
75
103
 
76
104
  this.handlebars.registerHelper("and", (...args) => args.slice(0,-1).every(Boolean));
77
105
  this.handlebars.registerHelper("or", (...args) => args.slice(0,-1).some(Boolean));
@@ -82,6 +110,48 @@ export class TextProcessor {
82
110
  this.handlebars.registerHelper("lt", (a,b) => a < b);
83
111
  this.handlebars.registerHelper("gte", (a,b) => a >= b);
84
112
  this.handlebars.registerHelper("lte", (a,b) => a <= b);
113
+ // Maths helpers. These are what arithmetic in infix expressions is rewritten to,
114
+ // e.g. {{set "gold" gold + price * 2}} -> {{set "gold" (add gold (mul price 2))}}
115
+ const mathsHelper = (name: string, fn: (a: number, b: number) => number) => {
116
+ this.handlebars.registerHelper(name, (...args) => {
117
+ const values = args.slice(0, -1).map(unwrapValue);
118
+ if (values.length !== 2) {
119
+ throw new Error(`"${name}" needs two values, but was given ${values.length}`);
120
+ }
121
+ return fn(toNumber(name, values[0]), toNumber(name, values[1]));
122
+ });
123
+ };
124
+ // "add" joins text when either value isn't a number (or a string holding one),
125
+ // so name + " the Brave" works, but an attribute holding "5" still adds as 5.
126
+ this.handlebars.registerHelper("add", (...args) => {
127
+ const values = args.slice(0, -1).map(unwrapValue);
128
+ if (values.length !== 2) {
129
+ throw new Error(`"add" needs two values, but was given ${values.length}`);
130
+ }
131
+ const [a, b] = values;
132
+ if (isNumeric(a) && isNumeric(b)) {
133
+ return toNumber("add", a) + toNumber("add", b);
134
+ }
135
+ const text = (v: any) => {
136
+ if (isBlank(v)) return "";
137
+ if (typeof v === "object") {
138
+ throw new Error(`"add" can't add ${Array.isArray(v) ? "a list" : "an object"}`);
139
+ }
140
+ return String(v);
141
+ };
142
+ return text(a) + text(b);
143
+ });
144
+ mathsHelper("sub", (a, b) => a - b);
145
+ mathsHelper("mul", (a, b) => a * b);
146
+ mathsHelper("div", (a, b) => {
147
+ if (b === 0) throw new Error("division by zero");
148
+ return a / b;
149
+ });
150
+ mathsHelper("mod", (a, b) => {
151
+ if (b === 0) throw new Error("division by zero");
152
+ return a % b;
153
+ });
154
+
85
155
  this.handlebars.registerHelper("array", function (...args) {
86
156
  args.pop(); // remove last argument - options
87
157
  return args;
@@ -168,17 +238,19 @@ export class TextProcessor {
168
238
  return arr.length;
169
239
  });
170
240
 
241
+ const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
242
+
171
243
  const addAdditionalParameters = (options: any) => {
172
244
  let result = "";
173
245
  const setters = options.hash.set as string || "";
174
246
  if (setters) {
175
- result += ` data-set='${JSON.stringify(setters.split(",").map(s => s.trim()))}'`;
247
+ // With expressions, a setter can have commas inside quotes, e.g. greeting = "Hi, there"
248
+ const list = this.getStory().expressions ? splitSetters(setters) : setters.split(",").map(s => s.trim());
249
+ result += ` data-set="${escapeAttr(JSON.stringify(list))}"`;
176
250
  }
177
251
  return result;
178
252
  };
179
253
 
180
- const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
181
-
182
254
  this.handlebars.registerHelper("section", (section: string, options) => {
183
255
  const text = options.hash.text as string || section;
184
256
  return new Handlebars.SafeString(`<a class="squiffy-link link-section" data-section="${escapeAttr(section)}"${addAdditionalParameters(options)} role="link" tabindex="0">${text}</a>`);
@@ -190,6 +262,27 @@ export class TextProcessor {
190
262
  });
191
263
  }
192
264
 
265
+ // Evaluates an expression, such as gold + price * 2, with the same rules and helpers as
266
+ // {{#if}} and {{set}}. Throws if it isn't valid, or a helper fails.
267
+ evaluate(expression: string): unknown {
268
+ let template = this.expressionCache.get(expression);
269
+ if (!template) {
270
+ template = this.handlebars.compile(`{{__value ${rewriteValueExpression(expression)}}}`);
271
+ this.expressionCache.set(expression, template);
272
+ }
273
+ this.evaluated = undefined;
274
+ template(this.state.getStore());
275
+ return this.evaluated;
276
+ }
277
+
278
+ // Where a {{goto}} asked to go. The runtime clears it before showing a section or passage, and
279
+ // follows it afterwards.
280
+ goto: { section: string; after: number } | null = null;
281
+
282
+ private expressionCache = new Map<string, HandlebarsTemplateDelegate>();
283
+ // Where the __value helper puts the value of the expression being evaluated
284
+ private evaluated: unknown;
285
+
193
286
  process(text: string, inline: boolean) {
194
287
  try {
195
288
  const template = this.handlebars.compile(rewriteInfixExpressions(text));
@@ -204,7 +297,13 @@ export class TextProcessor {
204
297
  } catch (e) {
205
298
  const errorMessage = e instanceof Error ? e.message : String(e);
206
299
  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>`;
300
+ return errorHtml("Template error:", errorMessage);
208
301
  }
209
302
  }
303
+ }
304
+
305
+ // The block that shows an error in the story's output
306
+ export function errorHtml(label: string, message: string) {
307
+ const escape = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
308
+ 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
309
  }
package/src/types.ts CHANGED
@@ -39,6 +39,8 @@ export interface SquiffyApi {
39
39
  clickLink: (link: HTMLElement) => Promise<boolean>;
40
40
  update: (story: Story) => void;
41
41
  goBack: () => void;
42
+ // Whether goBack() would go anywhere, e.g. to enable a Back button. canGoBackChanged says when it changes.
43
+ canGoBack: () => boolean;
42
44
 
43
45
  on<E extends keyof SquiffyEventMap>(
44
46
  event: E,
@@ -67,6 +69,7 @@ interface SquiffyJsFunctionApi {
67
69
  story: {
68
70
  go: (section: string) => void;
69
71
  seen: (sectionOrPassage: string) => boolean;
72
+ visits: (sectionOrPassage: string) => number;
70
73
  };
71
74
  }
72
75
 
@@ -79,6 +82,9 @@ export interface Story {
79
82
  start: string;
80
83
  id?: string | null;
81
84
  uiJsIndex?: number;
85
+ // Whether @set and link setters take expressions, with the same rules as {{#if}}: attributes
86
+ // by name, and text in quotes. True for a story with a squiffy.json (#373).
87
+ expressions?: boolean;
82
88
  sections: Record<string, Section>;
83
89
  }
84
90