squiffy-runtime 7.0.0-beta.6 → 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.
Files changed (80) hide show
  1. package/dist/assets.d.ts +1 -0
  2. package/dist/classes.test.d.ts +1 -0
  3. package/dist/confirmDialog.d.ts +8 -0
  4. package/dist/events.d.ts +11 -0
  5. package/dist/every.d.ts +12 -0
  6. package/dist/every.test.d.ts +1 -0
  7. package/dist/paths.d.ts +15 -0
  8. package/dist/paths.test.d.ts +1 -0
  9. package/dist/playerSettings.d.ts +17 -0
  10. package/dist/preview-host.d.ts +2 -0
  11. package/dist/preview-host.js +10 -0
  12. package/dist/preview-host.js.map +2 -2
  13. package/dist/preview-html.js +1 -1
  14. package/dist/preview-protocol.d.ts +6 -0
  15. package/dist/settings.test.d.ts +1 -0
  16. package/dist/settingsDialog.d.ts +17 -0
  17. package/dist/skill.test.d.ts +1 -0
  18. package/dist/sound.d.ts +35 -0
  19. package/dist/sound.test.d.ts +1 -0
  20. package/dist/squiffy.page.css +14 -3
  21. package/dist/squiffy.preview.html +680 -82
  22. package/dist/squiffy.runtime.css +531 -1
  23. package/dist/squiffy.runtime.d.ts +5 -1
  24. package/dist/squiffy.runtime.global.js +117 -96
  25. package/dist/squiffy.runtime.global.js.map +1 -1
  26. package/dist/squiffy.runtime.js +5728 -4520
  27. package/dist/squiffy.runtime.js.map +1 -1
  28. package/dist/state.d.ts +4 -1
  29. package/dist/style.test.d.ts +1 -0
  30. package/dist/textProcessor.d.ts +16 -0
  31. package/dist/transitions.test.d.ts +1 -0
  32. package/dist/types.d.ts +54 -0
  33. package/dist/uiLinks.test.d.ts +1 -0
  34. package/dist/utils.d.ts +1 -0
  35. package/dist/utils.test.d.ts +1 -0
  36. package/package.json +3 -3
  37. package/src/__snapshots__/squiffy.runtime.test.ts.snap +10 -10
  38. package/src/animation.test.ts +44 -0
  39. package/src/animation.ts +9 -5
  40. package/src/assets.test.ts +1 -3
  41. package/src/assets.ts +1 -1
  42. package/src/classes.test.ts +201 -0
  43. package/src/confirmDialog.ts +66 -0
  44. package/src/events.ts +18 -0
  45. package/src/every.test.ts +25 -0
  46. package/src/every.ts +94 -0
  47. package/src/panels.test.ts +24 -0
  48. package/src/paths.test.ts +66 -0
  49. package/src/paths.ts +155 -0
  50. package/src/playerSettings.ts +128 -0
  51. package/src/plugins/animate.ts +16 -3
  52. package/src/plugins/live.ts +10 -4
  53. package/src/plugins/plugins.test.ts +51 -6
  54. package/src/preview-host.test.ts +22 -0
  55. package/src/preview-host.ts +15 -0
  56. package/src/preview-protocol.ts +9 -1
  57. package/src/preview.test.ts +114 -3
  58. package/src/preview.ts +97 -3
  59. package/src/settings.test.ts +233 -0
  60. package/src/settingsDialog.ts +160 -0
  61. package/src/skill.test.ts +67 -0
  62. package/src/sound.test.ts +273 -0
  63. package/src/sound.ts +207 -0
  64. package/src/squiffy.page.css +14 -3
  65. package/src/squiffy.runtime.css +531 -1
  66. package/src/squiffy.runtime.test.ts +1130 -17
  67. package/src/squiffy.runtime.ts +600 -38
  68. package/src/state.ts +45 -10
  69. package/src/style.test.ts +89 -0
  70. package/src/textProcessor.ts +484 -35
  71. package/src/transitions.test.ts +302 -0
  72. package/src/types.ts +79 -0
  73. package/src/uiLinks.test.ts +156 -0
  74. package/src/updater.ts +26 -8
  75. package/src/utils.test.ts +60 -0
  76. package/src/utils.ts +44 -14
  77. package/dist/infixExpressions.d.ts +0 -6
  78. package/src/infixExpressions.test.ts +0 -379
  79. package/src/infixExpressions.ts +0 -488
  80. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -2,8 +2,23 @@ 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, rewriteValueExpression, splitSetters } from "./infixExpressions.js";
5
+ import { rewriteInfixExpressions, rewriteValueExpression, splitSetters } from "squiffy-compiler/infix-expressions";
6
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
+
11
+ // The built-in effects for {{#style}} (#453), in squiffy.runtime.css
12
+ const styleEffects = new Set([
13
+ "shake", "shudder", "rumble", "sway", "buoy", "pulse", "fade-in-out", "blink", "flicker",
14
+ "blur", "blurrier", "smear", "mirror", "upside-down",
15
+ ]);
16
+
17
+ // An embed being shown (#450): its parameters, and the text it wraps, if any
18
+ interface EmbedScope {
19
+ params: Record<string, unknown>;
20
+ content?: () => string;
21
+ }
7
22
 
8
23
  export class TextProcessor {
9
24
  getStory: () => Story;
@@ -19,31 +34,67 @@ export class TextProcessor {
19
34
  this.getCurrentSection = currentSection;
20
35
  this.handlebars = Handlebars.create();
21
36
 
22
- this.handlebars.registerHelper("embed", (name: string) => {
23
- const currentSection = this.getCurrentSection();
24
- if (currentSection.passages && name in currentSection.passages) {
25
- return new Handlebars.SafeString(this.process(currentSection.passages[name].text || "", true));
26
- }
27
- const story = this.getStory();
28
- if (name in story.sections) {
29
- return new Handlebars.SafeString(this.process(story.sections[name].text || "", true));
37
+ // {{embed "name"}} shows a section's or passage's text here. It can be given parameters,
38
+ // {{embed "say" who="Ann"}}, which the embedded text reads as {{who}} and which hide any
39
+ // attribute with the same name, and it can wrap text, {{#embed "say"}}Hello!{{/embed}},
40
+ // which the embedded text shows with {{content}} (#450).
41
+ // eslint-disable-next-line @typescript-eslint/no-this-alias
42
+ const processor = this;
43
+ this.handlebars.registerHelper("embed", function (this: unknown, ...args: any[]) {
44
+ const options = args.pop();
45
+ const name = unwrapValue(args[0]);
46
+ const text = processor.embeddedText(name);
47
+ if (text === undefined) return;
48
+
49
+ const params: Record<string, unknown> = Object.create(null);
50
+ for (const [key, value] of Object.entries(options.hash ?? {})) params[key] = unwrapValue(value);
51
+
52
+ // The wrapped text is filled in with the caller's attributes and parameters, not the
53
+ // embedded text's, so it's shown with the scopes as they are here
54
+ const callerScopes = processor.scopes;
55
+ const content = options.fn
56
+ ? () => {
57
+ const inner = processor.scopes;
58
+ processor.scopes = callerScopes;
59
+ try {
60
+ return options.fn(this, { data: options.data });
61
+ } finally {
62
+ processor.scopes = inner;
63
+ }
64
+ }
65
+ : undefined;
66
+
67
+ processor.scopes = [...callerScopes, { params, content }];
68
+ try {
69
+ return new Handlebars.SafeString(processor.process(text, true));
70
+ } finally {
71
+ processor.scopes = callerScopes;
30
72
  }
31
73
  });
32
74
 
75
+ // Inside an embed that wraps text, that text (#450). A story can have an attribute
76
+ // called content, which {{content}} shows when there's no wrapped text.
77
+ this.handlebars.registerHelper("content", () => {
78
+ const scope = this.scopes[this.scopes.length - 1];
79
+ if (scope?.content) return new Handlebars.SafeString(scope.content());
80
+ if (this.hasAttribute("content")) return this.getAttribute("content");
81
+ return "";
82
+ });
83
+
33
84
  this.handlebars.registerHelper("seen", (name: string) => this.state.getSeen(name));
34
85
  this.handlebars.registerHelper("visits", (name: string) => this.state.getVisits(name));
35
- this.handlebars.registerHelper("get", (attribute: string) => this.state.get(attribute));
86
+ this.handlebars.registerHelper("get", (attribute: string) => this.getAttribute(attribute));
36
87
  this.handlebars.registerHelper("at", (section: string | string[]) => {
37
- const currentSection = this.state.get("_section");
88
+ const currentSection = this.getAttribute("_section");
38
89
  if (Array.isArray(section)) {
39
90
  return section.includes(currentSection);
40
91
  }
41
92
  return currentSection === section;
42
93
  });
43
94
 
44
- // Unwrap SafeString values from subexpressions, but preserve arrays
95
+ // Unwrap SafeString values from subexpressions, but keep lists and objects (#442)
45
96
  const unwrapValue = (value: any): any => {
46
- if (value && typeof value === "object" && typeof value.toString === "function" && !Array.isArray(value)) {
97
+ if (value && typeof value === "object" && typeof value.toHTML === "function") {
47
98
  return value.toString();
48
99
  }
49
100
  return value;
@@ -60,22 +111,58 @@ export class TextProcessor {
60
111
  }
61
112
  let after = 0;
62
113
  if (options.hash.after !== undefined) {
63
- after = Number(unwrapValue(options.hash.after));
64
- if (!Number.isFinite(after) || after < 0) {
114
+ // A number of milliseconds, or a time like "3s" (#451)
115
+ const delay = parseDelay(unwrapValue(options.hash.after));
116
+ if (delay === null) {
65
117
  return new Handlebars.SafeString(errorHtml("Error in {{goto}}:",
66
- `after= should be a number of milliseconds, e.g. after=3000, not "${options.hash.after}"`));
118
+ `after= should be a number of milliseconds or a time, e.g. after=3000 or after="3s", not "${options.hash.after}"`));
67
119
  }
120
+ after = delay;
68
121
  }
69
122
  this.goto ??= { section, after };
70
123
  return "";
71
124
  });
72
125
 
126
+ // {{#every 1000}}...{{/every}} (#451): text that's shown again and again while the player
127
+ // is in the section. This only writes the element: the runtime's timers show the text
128
+ // (see every.ts), first after one delay, as in Twine.
129
+ this.handlebars.registerHelper("every", (...args: any[]) => {
130
+ const options = args.pop();
131
+ const error = (message: string) => new Handlebars.SafeString(errorHtml("Error in {{#every}}:", message));
132
+ const delay = args.length ? parseDelay(unwrapValue(args[0])) : null;
133
+ if (delay === null || delay <= 0) {
134
+ 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]}"` : ""}`);
135
+ }
136
+ const body = options.hash.__body;
137
+ if (typeof options.fn != "function" || typeof body != "string") {
138
+ return error("it needs some text to show, e.g. {{#every 1000}}Tick.{{/every}}");
139
+ }
140
+ let attrs = ` data-every="${body}" data-every-delay="${delay}" data-every-count="0"`;
141
+ if (options.hash.times !== undefined) {
142
+ const times = Number(unwrapValue(options.hash.times));
143
+ if (!Number.isInteger(times) || times < 1) {
144
+ return error(`times= should be a whole number of times, e.g. times=10, not "${options.hash.times}"`);
145
+ }
146
+ attrs += ` data-every-times="${times}"`;
147
+ }
148
+ if (options.hash.append) attrs += " data-every-append=\"\"";
149
+ // Text with paragraphs in it is a block, like {{#animate}}'s
150
+ const tag = decodeURIComponent(body).includes("\n\n") ? "div" : "span";
151
+ return new Handlebars.SafeString(`<${tag} class="squiffy-every"${attrs}></${tag}>`);
152
+ });
153
+
154
+ // {{stop}} (#451): the {{#every}} whose text this is stops after this time
155
+ this.handlebars.registerHelper("stop", () => {
156
+ this.stopEvery = true;
157
+ return "";
158
+ });
159
+
73
160
  // {{deactivate "name"}} (#13): the runtime disables the links to that passage on the screen
74
161
  // once the section or passage being shown has been written. With no name, it's the passage
75
162
  // being shown, e.g. one with @repeat that the player is done with (#104).
76
163
  this.handlebars.registerHelper("deactivate", (...args: any[]) => {
77
164
  args.pop();
78
- const names = args.length ? args.map(unwrapValue) : [this.state.get("_passage")];
165
+ const names = args.length ? args.map(unwrapValue) : [this.getAttribute("_passage")];
79
166
  for (const name of names) {
80
167
  if (typeof name != "string" || !name) {
81
168
  return new Handlebars.SafeString(errorHtml("Error in {{deactivate}}:",
@@ -94,7 +181,7 @@ export class TextProcessor {
94
181
  // State modification helpers (side effects, no output)
95
182
  // These execute at render time, so they respect {{#if}} conditions
96
183
  this.handlebars.registerHelper("set", (attribute: string, value: any) => {
97
- this.state.set(attribute, unwrapValue(value));
184
+ this.setAttribute(attribute, unwrapValue(value));
98
185
  return "";
99
186
  });
100
187
 
@@ -105,7 +192,7 @@ export class TextProcessor {
105
192
  });
106
193
 
107
194
  this.handlebars.registerHelper("unset", (attribute: string) => {
108
- this.state.set(attribute, false);
195
+ this.setAttribute(attribute, false);
109
196
  return "";
110
197
  });
111
198
 
@@ -114,8 +201,8 @@ export class TextProcessor {
114
201
  const incDecHelper = (name: string, sign: 1 | -1) => {
115
202
  this.handlebars.registerHelper(name, (attribute: string, ...args: any[]) => {
116
203
  const amount = args.length > 1 ? toNumber(name, unwrapValue(args[0])) : 1;
117
- const currentValue = toNumber(name, this.state.get(attribute));
118
- this.state.set(attribute, currentValue + sign * amount);
204
+ const currentValue = toNumber(name, this.getAttribute(attribute));
205
+ this.setAttribute(attribute, currentValue + sign * amount);
119
206
  return "";
120
207
  });
121
208
  };
@@ -173,15 +260,146 @@ export class TextProcessor {
173
260
  return a % b;
174
261
  });
175
262
 
263
+ // A story can have an attribute with the same name as a helper, such as count or min,
264
+ // which {{count}} on its own would call the helper for, with no values. So the helpers
265
+ // below that need values show the attribute instead, when there is one.
266
+ // Rounding (#446). (round x) rounds to a whole number, and (round x 2) to 2 decimal places.
267
+ // Numbers halfway between round up, as Math.round does, and as Harlowe's (round:) does.
268
+ const roundingHelper = (name: string, fn: (n: number) => number, places: boolean) => {
269
+ this.handlebars.registerHelper(name, (...args) => {
270
+ const values = args.slice(0, -1).map(unwrapValue);
271
+ if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
272
+ if (values.length !== 1 && !(places && values.length === 2)) {
273
+ throw new Error(`"${name}" needs ${places ? "one or two values" : "one value"}, but was given ${values.length}`);
274
+ }
275
+ const n = toNumber(name, values[0]);
276
+ if (values.length === 1) return fn(n);
277
+ const scale = 10 ** toNumber(name, values[1]);
278
+ // toPrecision tidies up floating point errors, so (round 1.005 2) is 1.01, not 1
279
+ return fn(Number((n * scale).toPrecision(15))) / scale;
280
+ });
281
+ };
282
+ roundingHelper("round", Math.round, true);
283
+ roundingHelper("floor", Math.floor, false);
284
+ roundingHelper("ceil", Math.ceil, false);
285
+ roundingHelper("abs", Math.abs, false);
286
+
287
+ // (min a b c) or (min list): the smallest of the values
288
+ const extremeHelper = (name: string, fn: (...values: number[]) => number) => {
289
+ this.handlebars.registerHelper(name, (...args) => {
290
+ let values = args.slice(0, -1).map(unwrapValue);
291
+ if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
292
+ if (values.length === 1 && Array.isArray(values[0])) {
293
+ values = values[0].map(unwrapValue);
294
+ }
295
+ if (values.length === 0) {
296
+ throw new Error(`"${name}" needs at least one value`);
297
+ }
298
+ return fn(...values.map(v => toNumber(name, v)));
299
+ });
300
+ };
301
+ extremeHelper("min", Math.min);
302
+ extremeHelper("max", Math.max);
303
+
304
+ // Text helpers (#446). A blank value (unset, false or "") is empty text, and a number
305
+ // is turned into text.
306
+ const toText = (name: string, v: unknown) => {
307
+ if (isBlank(v)) return "";
308
+ if (typeof v === "object") {
309
+ throw new Error(`"${name}" needs text, but was given ${Array.isArray(v) ? "a list" : "an object"}`);
310
+ }
311
+ return String(v);
312
+ };
313
+ const textHelper = (name: string, fn: (s: string) => string) => {
314
+ this.handlebars.registerHelper(name, (...args) => {
315
+ const values = args.slice(0, -1).map(unwrapValue);
316
+ if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
317
+ if (values.length !== 1) {
318
+ throw new Error(`"${name}" needs one value, but was given ${values.length}`);
319
+ }
320
+ return fn(toText(name, values[0]));
321
+ });
322
+ };
323
+ textHelper("upper", s => s.toUpperCase());
324
+ textHelper("lower", s => s.toLowerCase());
325
+ const capitalise = (s: string) => s.charAt(0).toUpperCase() + s.substring(1);
326
+ textHelper("capitalise", capitalise);
327
+ textHelper("capitalize", capitalise);
328
+
329
+ // {{#once}}...{{else}}...{{/once}} shows its text the first time it's shown, and the
330
+ // {{else}} text (or nothing) after that. Each one remembers for itself, wherever it is:
331
+ // in a section or passage shown again, or in text embedded in several places. Which ones
332
+ // have been shown is in _once, an attribute, so going back undoes it. One with a name,
333
+ // {{#once "warning"}}, shares its memory with the others of that name. firsttime, as
334
+ // Quest has it, is another name for once.
335
+ const once = function (this: unknown, ...args: any[]) {
336
+ const options = args.pop();
337
+ if (typeof options?.fn != "function") {
338
+ throw new Error("once wraps the text to show the first time: {{#once}}...{{/once}}");
339
+ }
340
+ const name = args.length ? unwrapValue(args[0]) : undefined;
341
+ if (args.length && (typeof name != "string" || !name)) {
342
+ throw new Error("the name of a {{#once}} is text, such as {{#once \"warning\"}}");
343
+ }
344
+ const key = name ?? processor.positionKey(options.loc);
345
+ const shown: string[] = processor.state.get("_once") || [];
346
+ if (shown.includes(key)) return options.inverse(this);
347
+ processor.state.set("_once", [...shown, key]);
348
+ return options.fn(this);
349
+ };
350
+ this.handlebars.registerHelper("once", once);
351
+ this.handlebars.registerHelper("firsttime", once);
352
+
353
+ // (cond test a b) is a if test is true, otherwise b (#446). It's what a ? b : c in an
354
+ // expression is rewritten to. Handlebars works out both a and b before calling it, so a
355
+ // helper with side effects, such as (pop "list"), runs whichever is chosen.
356
+ this.handlebars.registerHelper("cond", (...args) => {
357
+ const values = args.slice(0, -1).map(unwrapValue);
358
+ if (values.length === 0 && this.hasAttribute("cond")) return this.getAttribute("cond");
359
+ if (values.length !== 3) {
360
+ throw new Error(`"cond" needs three values, but was given ${values.length}`);
361
+ }
362
+ return values[0] ? values[1] : values[2];
363
+ });
364
+
365
+ // a contains b in an expression (#446): whether list a has b in it, text a has the text b
366
+ // in it, or object a has a property called b. Unlike (contains "list" value), which
367
+ // looks up the list by its name, a here is the value itself.
368
+ this.handlebars.registerHelper("__contains", (container: any, value: any) => {
369
+ container = unwrapValue(container);
370
+ value = unwrapValue(value);
371
+ if (Array.isArray(container)) {
372
+ return container.some(item => unwrapValue(item) === value);
373
+ }
374
+ if (isBlank(container)) return false;
375
+ if (typeof container === "object") {
376
+ return Object.prototype.hasOwnProperty.call(container, String(value));
377
+ }
378
+ return String(container).includes(toText("contains", value));
379
+ });
380
+
176
381
  this.handlebars.registerHelper("array", function (...args) {
177
382
  args.pop(); // remove last argument - options
178
- return args;
383
+ return args.map(unwrapValue);
384
+ });
385
+
386
+ // An object literal in an expression, e.g. { hp: 10, name: "Ann" } (#442), which
387
+ // compiler/src/infix-expressions.ts rewrites to (__object "hp" 10 "name" "Ann")
388
+ this.handlebars.registerHelper("__object", (...args) => {
389
+ args.pop();
390
+ const result: Record<string, unknown> = {};
391
+ for (let i = 0; i < args.length; i += 2) {
392
+ const key = String(unwrapValue(args[i]));
393
+ checkSegment(key);
394
+ result[key] = unwrapValue(args[i + 1]);
395
+ }
396
+ return result;
179
397
  });
180
398
 
181
399
  // Array management helpers
182
400
 
183
401
  this.handlebars.registerHelper("append", (listVar: string, value: any) => {
184
- const currentArray = this.state.get(listVar) || [];
402
+ const currentArray = this.getAttribute(listVar) || [];
185
403
  const arr = Array.isArray(currentArray) ? [...currentArray] : [currentArray];
186
404
  const unwrappedValue = unwrapValue(value);
187
405
  if (Array.isArray(unwrappedValue)) {
@@ -189,12 +407,12 @@ export class TextProcessor {
189
407
  } else {
190
408
  arr.push(unwrappedValue);
191
409
  }
192
- this.state.set(listVar, arr);
410
+ this.setAttribute(listVar, arr);
193
411
  return "";
194
412
  });
195
413
 
196
414
  this.handlebars.registerHelper("prepend", (listVar: string, value: any) => {
197
- const currentArray = this.state.get(listVar) || [];
415
+ const currentArray = this.getAttribute(listVar) || [];
198
416
  const arr = Array.isArray(currentArray) ? [...currentArray] : [currentArray];
199
417
  const unwrappedValue = unwrapValue(value);
200
418
  if (Array.isArray(unwrappedValue)) {
@@ -202,23 +420,23 @@ export class TextProcessor {
202
420
  } else {
203
421
  arr.unshift(unwrappedValue);
204
422
  }
205
- this.state.set(listVar, arr);
423
+ this.setAttribute(listVar, arr);
206
424
  return "";
207
425
  });
208
426
 
209
427
  this.handlebars.registerHelper("pop", (listVar: string) => {
210
- const currentArray = this.state.get(listVar) || [];
428
+ const currentArray = this.getAttribute(listVar) || [];
211
429
  if (!Array.isArray(currentArray) || currentArray.length === 0) {
212
430
  return "";
213
431
  }
214
432
  const arr = [...currentArray];
215
433
  const item = arr.shift();
216
- this.state.set(listVar, arr);
434
+ this.setAttribute(listVar, arr);
217
435
  return item;
218
436
  });
219
437
 
220
438
  this.handlebars.registerHelper("remove", (listVar: string, value: any) => {
221
- const currentArray = this.state.get(listVar) || [];
439
+ const currentArray = this.getAttribute(listVar) || [];
222
440
  if (!Array.isArray(currentArray)) {
223
441
  return "";
224
442
  }
@@ -227,7 +445,7 @@ export class TextProcessor {
227
445
  if (index !== -1) {
228
446
  const arr = [...currentArray];
229
447
  arr.splice(index, 1);
230
- this.state.set(listVar, arr);
448
+ this.setAttribute(listVar, arr);
231
449
  }
232
450
  return "";
233
451
  });
@@ -235,7 +453,7 @@ export class TextProcessor {
235
453
  this.handlebars.registerHelper("contains", (listOrVar: any, value: any) => {
236
454
  let arr: any[];
237
455
  if (typeof listOrVar === "string") {
238
- const stored = this.state.get(listOrVar);
456
+ const stored = this.getAttribute(listOrVar);
239
457
  arr = Array.isArray(stored) ? stored : [];
240
458
  } else if (Array.isArray(listOrVar)) {
241
459
  arr = listOrVar;
@@ -249,7 +467,7 @@ export class TextProcessor {
249
467
  this.handlebars.registerHelper("length", (listOrVar: any) => {
250
468
  let arr: any[];
251
469
  if (typeof listOrVar === "string") {
252
- const stored = this.state.get(listOrVar);
470
+ const stored = this.getAttribute(listOrVar);
253
471
  arr = Array.isArray(stored) ? stored : [];
254
472
  } else if (Array.isArray(listOrVar)) {
255
473
  arr = listOrVar;
@@ -259,6 +477,100 @@ export class TextProcessor {
259
477
  return arr.length;
260
478
  });
261
479
 
480
+ // More helpers for lists (#447). These take the list itself, (join bag), not its name in
481
+ // quotes as append and friends do, and give back a new list rather than changing the
482
+ // attribute, so @set bag = (sort bag) sorts it. A blank value (unset, false or "") is
483
+ // an empty list. Positions start at 0, as with bag[i] and {{@index}}.
484
+ const toList = (name: string, v: unknown): unknown[] => {
485
+ v = unwrapValue(v);
486
+ if (Array.isArray(v)) return v.map(unwrapValue);
487
+ if (isBlank(v)) return [];
488
+ if (typeof v === "string") {
489
+ 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")`);
490
+ }
491
+ throw new Error(`"${name}" needs a list, but was given ${typeof v === "object" ? "an object" : String(v)}`);
492
+ };
493
+ const listHelper = (name: string, min: number, max: number, fn: (values: unknown[]) => unknown) => {
494
+ this.handlebars.registerHelper(name, (...args) => {
495
+ const values = args.slice(0, -1).map(unwrapValue);
496
+ if (values.length === 0 && this.hasAttribute(name)) return this.getAttribute(name);
497
+ if (values.length < min || values.length > max) {
498
+ const needs = min === max ? `${min} value${min === 1 ? "" : "s"}` : `${min} to ${max} values`;
499
+ throw new Error(`"${name}" needs ${needs}, but was given ${values.length}`);
500
+ }
501
+ return fn(values);
502
+ });
503
+ };
504
+ // A whole number, for a position or a range
505
+ const toWhole = (name: string, v: unknown) => Math.trunc(toNumber(name, v));
506
+
507
+ // (join bag) is "lamp, key, rope", (join bag " / ") puts " / " between them, and
508
+ // (join bag ", " " and ") is "lamp, key and rope"
509
+ listHelper("join", 1, 3, ([list, separator, lastSeparator]) => {
510
+ const items = toList("join", list).map(item => toText("join", item));
511
+ const sep = separator === undefined ? ", " : toText("join", separator);
512
+ if (lastSeparator === undefined || items.length < 2) return items.join(sep);
513
+ return items.slice(0, -1).join(sep) + toText("join", lastSeparator) + items[items.length - 1];
514
+ });
515
+
516
+ // Numbers go before text, in order, and text is in alphabetical order, ignoring case,
517
+ // with numbers inside it in order too ("item 2" before "item 10")
518
+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
519
+ listHelper("sort", 1, 1, ([list]) => toList("sort", list).sort((a, b) => {
520
+ const aNum = typeof a === "number", bNum = typeof b === "number";
521
+ if (aNum && bNum) return (a as number) - (b as number);
522
+ if (aNum !== bNum) return aNum ? -1 : 1;
523
+ return collator.compare(toText("sort", a), toText("sort", b));
524
+ }));
525
+
526
+ listHelper("shuffle", 1, 1, ([list]) => {
527
+ const items = toList("shuffle", list);
528
+ for (let i = items.length - 1; i > 0; i--) {
529
+ const j = Math.floor(Math.random() * (i + 1));
530
+ [items[i], items[j]] = [items[j], items[i]];
531
+ }
532
+ return items;
533
+ });
534
+
535
+ // (slice bag 1 3) is the items from position 1 up to, but not including, 3, and
536
+ // (slice bag 1) is the rest from position 1. A negative position counts from the end,
537
+ // so (slice bag -2) is the last two. It takes part of some text in the same way.
538
+ listHelper("slice", 2, 3, ([container, start, end]) => {
539
+ const from = toWhole("slice", start), to = end === undefined ? undefined : toWhole("slice", end);
540
+ return typeof container === "string" ? container.slice(from, to) : toList("slice", container).slice(from, to);
541
+ });
542
+
543
+ // The first or last item, or nothing for an empty list
544
+ listHelper("first", 1, 1, ([list]) => toList("first", list)[0] ?? "");
545
+ listHelper("last", 1, 1, ([list]) => toList("last", list).slice(-1)[0] ?? "");
546
+
547
+ // Where a value is in a list (from 0), or where some text is in text, or -1 if it isn't
548
+ listHelper("indexof", 2, 2, ([container, value]) => {
549
+ if (typeof container === "string") return container.indexOf(toText("indexof", value));
550
+ return toList("indexof", container).indexOf(value);
551
+ });
552
+
553
+ // How many times a value is in a list, or some text is in text
554
+ listHelper("count", 2, 2, ([container, value]) => {
555
+ if (typeof container === "string") {
556
+ const text = toText("count", value);
557
+ return text === "" ? 0 : container.split(text).length - 1;
558
+ }
559
+ return toList("count", container).filter(item => item === value).length;
560
+ });
561
+
562
+ // (range 1 5) is the list 1, 2, 3, 4, 5, and (range 5 1) counts down
563
+ listHelper("range", 2, 2, ([from, to]) => {
564
+ const start = toWhole("range", from), end = toWhole("range", to);
565
+ if (Math.abs(end - start) >= 10000) {
566
+ throw new Error(`"range" can make a list of up to 10,000 numbers, but was asked for ${Math.abs(end - start) + 1}`);
567
+ }
568
+ const step = end >= start ? 1 : -1;
569
+ const result: number[] = [];
570
+ for (let n = start; n !== end + step; n += step) result.push(n);
571
+ return result;
572
+ });
573
+
262
574
  const escapeAttr = (s: unknown) => String(s).replace(/&/g, "&amp;").replace(/"/g, "&quot;");
263
575
 
264
576
  // A link's text and setters can have {{...}} in them, such as [[Drop the {{this}}]](drop,
@@ -297,8 +609,56 @@ export class TextProcessor {
297
609
  const text = fillIn(options.hash.text as string || passage, this, options, true);
298
610
  return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${escapeAttr(passage)}"${addAdditionalParameters(this, options)} role="link" tabindex="0">${text}</a>`);
299
611
  });
612
+
613
+ // {{restart}} and {{saves}} (#452): links that restart the story, asking first unless
614
+ // confirm=false, and open the Saved games dialog, like the page's own buttons
615
+ this.handlebars.registerHelper("restart", function (this: unknown, options) {
616
+ const text = fillIn(options.hash.text as string || processor.strings.restart, this, options, true);
617
+ const confirm = options.hash.confirm === false || options.hash.confirm === "false" ? " data-confirm=\"false\"" : "";
618
+ return new Handlebars.SafeString(`<a class="squiffy-link link-restart" data-handler="restart"${confirm} role="link" tabindex="0">${text}</a>`);
619
+ });
620
+
621
+ this.handlebars.registerHelper("saves", function (this: unknown, options) {
622
+ const text = fillIn(options.hash.text as string || processor.strings.saves, this, options, true);
623
+ return new Handlebars.SafeString(`<a class="squiffy-link link-saves" data-handler="saves" role="link" tabindex="0">${text}</a>`);
624
+ });
625
+
626
+ // {{settings}} (#452): a link that opens the Settings dialog, where the player changes the
627
+ // story's settings (squiffy.json's "settings")
628
+ this.handlebars.registerHelper("settings", function (this: unknown, options) {
629
+ const text = fillIn(options.hash.text as string || processor.strings.settings, this, options, true);
630
+ return new Handlebars.SafeString(`<a class="squiffy-link link-settings" data-handler="settings" role="link" tabindex="0">${text}</a>`);
631
+ });
632
+
633
+ // {{#style "warning"}}...{{/style}} (#453) gives the text it wraps one or more classes, for
634
+ // the story's own CSS or the built-in effects (shudder, blur, ...: .squiffy-style.shudder
635
+ // in squiffy.runtime.css). Text with blank lines in it is a block, so it gets a div.
636
+ this.handlebars.registerHelper("style", function (this: unknown, ...args: any[]) {
637
+ const options = args.pop();
638
+ // String(): text that's only one helper, such as an {{#every}}, comes back as the helper's
639
+ // SafeString
640
+ const content = typeof options?.fn == "function" ? String(options.fn(this)) : "";
641
+ const classes = args.flatMap(a => String(unwrapValue(a) ?? "").split(/\s+/)).filter(c => c.length > 0);
642
+ // An element has one animation and one transform, so a second effect would replace the
643
+ // first. Each effect after the first goes on an element of its own inside it, where
644
+ // they add up.
645
+ const extraEffects = classes.filter(c => styleEffects.has(c)).slice(1);
646
+ const outer = classes.filter(c => !extraEffects.includes(c));
647
+ const isBlock = content.includes("\n\n");
648
+ const tag = isBlock ? "div" : "span";
649
+ // The blank lines around a block's content let Markdown in it be rendered inside the div
650
+ let html = isBlock ? `\n\n${content.trim()}\n\n` : content;
651
+ for (const c of [...extraEffects].reverse()) {
652
+ html = `<${tag} class="squiffy-style ${escapeAttr(c)}">${html}</${tag}>`;
653
+ }
654
+ return new Handlebars.SafeString(`<${tag} class="${escapeAttr(["squiffy-style", ...outer].join(" "))}">${html}</${tag}>`);
655
+ });
300
656
  }
301
657
 
658
+ // The default text of {{restart}}, {{saves}} and {{settings}} links, which the runtime sets
659
+ // from the page's strings
660
+ strings = { restart: "Restart", saves: "Saved games", settings: "Settings" };
661
+
302
662
  // Evaluates an expression, such as gold + price * 2, with the same rules and helpers as
303
663
  // {{#if}} and {{set}}. Throws if it isn't valid, or a helper fails.
304
664
  evaluate(expression: string): unknown {
@@ -308,7 +668,7 @@ export class TextProcessor {
308
668
  this.expressionCache.set(expression, template);
309
669
  }
310
670
  this.evaluated = undefined;
311
- template(this.state.getStore());
671
+ template(this.context());
312
672
  return this.evaluated;
313
673
  }
314
674
 
@@ -318,16 +678,103 @@ export class TextProcessor {
318
678
  // The passages whose links a {{deactivate}} asked to disable. Like goto, the runtime clears it
319
679
  // before showing a section or passage, and acts on it afterwards.
320
680
  deactivate = new Set<string>();
681
+ // Set by a {{stop}} in an {{#every}}'s text (#451). The runtime clears it before showing the
682
+ // text, and checks it afterwards.
683
+ stopEvery = false;
684
+
685
+ // The embeds being shown, innermost last (#450). Each embed's text sees its own parameters
686
+ // and the story's attributes, but not the parameters of the embed it's inside.
687
+ private scopes: EmbedScope[] = [];
688
+
689
+ // The text {{embed "name"}} shows: a passage in the current section, or a section
690
+ private embeddedText(name: unknown): string | undefined {
691
+ if (typeof name != "string") return undefined;
692
+ const currentSection = this.getCurrentSection();
693
+ if (currentSection.passages && Object.prototype.hasOwnProperty.call(currentSection.passages, name)) {
694
+ return currentSection.passages[name].text || "";
695
+ }
696
+ const story = this.getStory();
697
+ if (Object.prototype.hasOwnProperty.call(story.sections, name)) {
698
+ return story.sections[name].text || "";
699
+ }
700
+ return undefined;
701
+ }
702
+
703
+ // The parameters of the embed being shown, if any
704
+ private get params(): Record<string, unknown> | undefined {
705
+ return this.scopes[this.scopes.length - 1]?.params;
706
+ }
707
+
708
+ private isParam(attribute: string) {
709
+ const params = this.params;
710
+ return !!params && Object.prototype.hasOwnProperty.call(params, parsePath(attribute)[0]);
711
+ }
712
+
713
+ // Attributes, as the text being shown sees them: inside an embed, its parameters come first.
714
+ // A name can be a path, such as hero.hp, as for State.
715
+ hasAttribute(attribute: string) {
716
+ return this.isParam(attribute) || this.state.has(attribute);
717
+ }
718
+
719
+ getAttribute(attribute: string): any {
720
+ if (this.isParam(attribute)) {
721
+ const [name, ...inside] = parsePath(attribute);
722
+ return structuredClone(valueAt(this.params![name], inside));
723
+ }
724
+ return this.state.get(attribute);
725
+ }
726
+
727
+ // Setting a parameter changes it for the rest of that embed only. Anything else is the story's.
728
+ setAttribute(attribute: string, value: any) {
729
+ if (this.isParam(attribute)) {
730
+ const [name, ...inside] = parsePath(attribute);
731
+ if (typeof value === "undefined") value = true;
732
+ this.params![name] = inside.length ? withValueAt(this.params![name], inside, name, value) : structuredClone(value);
733
+ return;
734
+ }
735
+ this.state.set(attribute, value);
736
+ }
737
+
738
+ // What a template's names are looked up in: the story's attributes, with the parameters of
739
+ // the embed being shown in front of them
740
+ private context(): Record<string, any> {
741
+ const store = this.state.getStore();
742
+ const params = this.params;
743
+ if (!params || !Object.keys(params).length) return store;
744
+ const isParam = (prop: string | symbol) => typeof prop == "string" && Object.prototype.hasOwnProperty.call(params, prop);
745
+ return new Proxy({} as Record<string, any>, {
746
+ get: (_, prop) => isParam(prop) ? structuredClone(params[prop as string]) : Reflect.get(store, prop),
747
+ has: (_, prop) => isParam(prop) || Reflect.has(store, prop),
748
+ ownKeys: () => [...new Set([...Object.keys(params), ...Reflect.ownKeys(store)])],
749
+ getOwnPropertyDescriptor: (_, prop) => isParam(prop)
750
+ ? { enumerable: true, configurable: true, value: structuredClone(params[prop as string]) }
751
+ : Reflect.getOwnPropertyDescriptor(store, prop),
752
+ });
753
+ }
754
+
755
+ // The texts being processed, innermost last: a section's or passage's, and any it embeds
756
+ private processing: string[] = [];
757
+
758
+ // Identifies a place in the text being processed, for a {{#once}} to remember itself by: a
759
+ // hash of the text, and where in it the block starts. A name that starts with a space can't
760
+ // be the name an author gave one.
761
+ private positionKey(loc?: { start: { line: number; column: number } }): string {
762
+ const text = this.processing[this.processing.length - 1] ?? "";
763
+ let hash = 5381;
764
+ for (let i = 0; i < text.length; i++) hash = ((hash * 33) ^ text.charCodeAt(i)) >>> 0;
765
+ return ` ${hash.toString(36)}:${loc?.start.line ?? 0}:${loc?.start.column ?? 0}`;
766
+ }
321
767
 
322
768
  private expressionCache = new Map<string, HandlebarsTemplateDelegate>();
323
769
  // Where the __value helper puts the value of the expression being evaluated
324
770
  private evaluated: unknown;
325
771
 
326
772
  process(text: string, inline: boolean) {
773
+ this.processing.push(text);
327
774
  try {
328
775
  // compat: inside an {{#each}}, a name that isn't one of the item's looks for an attribute
329
- const template = this.handlebars.compile(rewriteInfixExpressions(text), { compat: true });
330
- text = template(this.state.getStore());
776
+ const template = this.handlebars.compile(rewriteInfixExpressions(captureEveryBodies(text)), { compat: true });
777
+ text = template(this.context());
331
778
 
332
779
  if (inline) {
333
780
  return marked.parseInline(text, { async: false }).trim();
@@ -339,6 +786,8 @@ export class TextProcessor {
339
786
  const errorMessage = e instanceof Error ? e.message : String(e);
340
787
  console.error("Squiffy template error:", errorMessage);
341
788
  return errorHtml("Template error:", errorMessage);
789
+ } finally {
790
+ this.processing.pop();
342
791
  }
343
792
  }
344
793
  }