squiffy-runtime 6.0.1 → 7.0.0-beta.11

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 (117) hide show
  1. package/dist/assets.d.ts +3 -0
  2. package/dist/assets.test.d.ts +1 -0
  3. package/dist/classes.test.d.ts +1 -0
  4. package/dist/confirmDialog.d.ts +8 -0
  5. package/dist/events.d.ts +16 -0
  6. package/dist/every.d.ts +12 -0
  7. package/dist/every.test.d.ts +1 -0
  8. package/dist/helpers.test.d.ts +1 -0
  9. package/dist/numbers.d.ts +3 -0
  10. package/dist/panels.d.ts +14 -0
  11. package/dist/panels.test.d.ts +1 -0
  12. package/dist/paths.d.ts +15 -0
  13. package/dist/paths.test.d.ts +1 -0
  14. package/dist/persistent.test.d.ts +1 -0
  15. package/dist/playerSettings.d.ts +17 -0
  16. package/dist/pluginManager.d.ts +2 -1
  17. package/dist/preview-host.d.ts +33 -0
  18. package/dist/preview-host.js +125 -0
  19. package/dist/preview-host.js.map +7 -0
  20. package/dist/preview-host.test.d.ts +1 -0
  21. package/dist/preview-html.d.ts +2 -0
  22. package/dist/preview-html.js +2 -0
  23. package/dist/preview-protocol.d.ts +69 -0
  24. package/dist/preview.d.ts +15 -0
  25. package/dist/preview.main.d.ts +1 -0
  26. package/dist/preview.test.d.ts +1 -0
  27. package/dist/saveSlots.d.ts +16 -0
  28. package/dist/saves.test.d.ts +1 -0
  29. package/dist/savesDialog.d.ts +43 -0
  30. package/dist/savesDialog.test.d.ts +1 -0
  31. package/dist/scripts.test.d.ts +1 -0
  32. package/dist/settings.test.d.ts +1 -0
  33. package/dist/settingsDialog.d.ts +17 -0
  34. package/dist/skill.test.d.ts +1 -0
  35. package/dist/sound.d.ts +35 -0
  36. package/dist/sound.test.d.ts +1 -0
  37. package/dist/squiffy.page.css +155 -0
  38. package/dist/squiffy.preview.html +1631 -0
  39. package/dist/squiffy.runtime.css +1123 -20
  40. package/dist/squiffy.runtime.d.ts +13 -1
  41. package/dist/squiffy.runtime.global.js +146 -76
  42. package/dist/squiffy.runtime.global.js.map +1 -1
  43. package/dist/squiffy.runtime.js +7105 -4681
  44. package/dist/squiffy.runtime.js.map +1 -1
  45. package/dist/state.d.ts +17 -0
  46. package/dist/storyLists.d.ts +4 -0
  47. package/dist/storyLists.test.d.ts +1 -0
  48. package/dist/style.test.d.ts +1 -0
  49. package/dist/textProcessor.d.ts +27 -0
  50. package/dist/transitions.test.d.ts +1 -0
  51. package/dist/types.d.ts +137 -1
  52. package/dist/types.plugins.d.ts +2 -0
  53. package/dist/uiLinks.test.d.ts +1 -0
  54. package/dist/utils.d.ts +2 -1
  55. package/dist/utils.test.d.ts +1 -0
  56. package/package.json +25 -11
  57. package/src/__snapshots__/squiffy.runtime.test.ts.snap +22 -22
  58. package/src/animation.test.ts +44 -0
  59. package/src/animation.ts +9 -5
  60. package/src/assets.test.ts +225 -0
  61. package/src/assets.ts +92 -0
  62. package/src/classes.test.ts +201 -0
  63. package/src/confirmDialog.ts +66 -0
  64. package/src/events.ts +20 -0
  65. package/src/every.test.ts +25 -0
  66. package/src/every.ts +94 -0
  67. package/src/helpers.test.ts +34 -0
  68. package/src/numbers.ts +21 -0
  69. package/src/panels.test.ts +225 -0
  70. package/src/panels.ts +187 -0
  71. package/src/paths.test.ts +66 -0
  72. package/src/paths.ts +155 -0
  73. package/src/persistent.test.ts +155 -0
  74. package/src/playerSettings.ts +128 -0
  75. package/src/pluginManager.ts +6 -1
  76. package/src/plugins/animate.ts +34 -9
  77. package/src/plugins/live.ts +18 -5
  78. package/src/plugins/plugins.test.ts +93 -6
  79. package/src/plugins/replaceLabel.ts +7 -3
  80. package/src/preview-host.test.ts +171 -0
  81. package/src/preview-host.ts +190 -0
  82. package/src/preview-protocol.ts +79 -0
  83. package/src/preview.main.ts +34 -0
  84. package/src/preview.test.ts +367 -0
  85. package/src/preview.ts +331 -0
  86. package/src/saveSlots.ts +159 -0
  87. package/src/saves.test.ts +199 -0
  88. package/src/savesDialog.test.ts +290 -0
  89. package/src/savesDialog.ts +499 -0
  90. package/src/scripts.test.ts +130 -0
  91. package/src/settings.test.ts +233 -0
  92. package/src/settingsDialog.ts +160 -0
  93. package/src/skill.test.ts +67 -0
  94. package/src/sound.test.ts +273 -0
  95. package/src/sound.ts +207 -0
  96. package/src/squiffy.page.css +155 -0
  97. package/src/squiffy.runtime.css +1123 -20
  98. package/src/squiffy.runtime.test.ts +2806 -44
  99. package/src/squiffy.runtime.ts +1130 -64
  100. package/src/state.ts +172 -11
  101. package/src/storyLists.test.ts +134 -0
  102. package/src/storyLists.ts +57 -0
  103. package/src/style.test.ts +89 -0
  104. package/src/textProcessor.ts +739 -58
  105. package/src/transitions.test.ts +343 -0
  106. package/src/types.plugins.ts +7 -0
  107. package/src/types.ts +226 -2
  108. package/src/uiLinks.test.ts +156 -0
  109. package/src/updater.ts +26 -8
  110. package/src/utils.test.ts +60 -0
  111. package/src/utils.ts +46 -14
  112. package/vite.config.ts +3 -4
  113. package/vite.preview.config.ts +83 -0
  114. package/dist/infixExpressions.d.ts +0 -2
  115. package/src/infixExpressions.test.ts +0 -187
  116. package/src/infixExpressions.ts +0 -323
  117. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
@@ -1,8 +1,8 @@
1
- import { expect, test, beforeEach, afterEach, beforeAll, vi } from "vitest";
1
+ import { expect, test, describe, beforeEach, afterEach, beforeAll, vi } from "vitest";
2
2
  import fs from "fs/promises";
3
3
  import globalJsdom from "global-jsdom";
4
4
  import { init } from "./squiffy.runtime.js";
5
- import { compile as squiffyCompile } from "squiffy-compiler";
5
+ import { compile as squiffyCompile, convertSetters } from "squiffy-compiler";
6
6
 
7
7
  // Mock crypto.randomUUID() to return a stable value for tests
8
8
  beforeAll(() => {
@@ -26,10 +26,12 @@ const html = `
26
26
  </html>
27
27
  `;
28
28
 
29
- const compile = async (script: string, scriptBaseFilename?: string) => {
29
+ // expressions: compile as a story with a squiffy.json, whose setters take expressions (#373)
30
+ const compile = async (script: string, scriptBaseFilename?: string, expressions = false) => {
30
31
  const compileResult = await squiffyCompile({
31
32
  script: script,
32
33
  scriptBaseFilename: scriptBaseFilename,
34
+ expressions,
33
35
  });
34
36
 
35
37
  if (!compileResult.success) {
@@ -47,14 +49,14 @@ const compile = async (script: string, scriptBaseFilename?: string) => {
47
49
  };
48
50
  };
49
51
 
50
- const initScript = async (script: string) => {
52
+ const initScript = async (script: string, expressions = false) => {
51
53
  const element = document.getElementById("squiffy");
52
54
 
53
55
  if (!element) {
54
56
  throw new Error("Element not found");
55
57
  }
56
58
 
57
- const compileResult = await compile(script);
59
+ const compileResult = await compile(script, undefined, expressions);
58
60
 
59
61
  const squiffyApi = await init({
60
62
  element: element,
@@ -69,6 +71,18 @@ const initScript = async (script: string) => {
69
71
  };
70
72
  };
71
73
 
74
+ // Starts a story whose start section has this text, which the compiler would refuse, as it
75
+ // reports template errors itself, to test how the runtime shows them (in a story built by an
76
+ // older compiler, say)
77
+ const initBrokenText = async (text: string) => {
78
+ const element = document.getElementById("squiffy")!;
79
+ const { story } = await compile("[[start]]:\nPlaceholder.");
80
+ (story.sections as any).start.text = text;
81
+ const squiffyApi = await init({ element, story });
82
+ await squiffyApi.begin();
83
+ return { squiffyApi, element };
84
+ };
85
+
72
86
  const findLink = (element: HTMLElement, linkType: string, linkText: string, onlyEnabled: boolean = false) => {
73
87
  const links = onlyEnabled
74
88
  ? element.querySelectorAll(`.squiffy-output-section:last-child a.squiffy-link.link-${linkType}`)
@@ -145,7 +159,7 @@ Checked.`;
145
159
  });
146
160
 
147
161
  test("Click a section link", async () => {
148
- const script = await fs.readFile("../examples/test/example.squiffy", "utf-8");
162
+ const script = await fs.readFile("../compiler/test/fixtures/test/example.squiffy", "utf-8");
149
163
  const { squiffyApi, element } = await initScript(script);
150
164
  expect(element.innerHTML).toMatchSnapshot();
151
165
 
@@ -179,7 +193,7 @@ test("Click a section link", async () => {
179
193
  });
180
194
 
181
195
  test("Click a section link and go back", async () => {
182
- const script = await fs.readFile("../examples/test/example.squiffy", "utf-8");
196
+ const script = await fs.readFile("../compiler/test/fixtures/test/example.squiffy", "utf-8");
183
197
  const { squiffyApi, element } = await initScript(script);
184
198
 
185
199
  const linkToPassage = findLink(element, "passage", "a link to a passage");
@@ -200,8 +214,50 @@ test("Click a section link and go back", async () => {
200
214
  expect(await squiffyApi.clickLink(linkToPassage)).toBe(true);
201
215
  });
202
216
 
217
+ test("canGoBack says whether there's anything to go back to", async () => {
218
+ const { squiffyApi, element } = await initScript("[[a]]:\nGo to [[b]].\n\n[[b]]:\nThe end.");
219
+ expect(squiffyApi.canGoBack()).toBe(false);
220
+
221
+ await squiffyApi.clickLink(findLink(element, "section", "b"));
222
+ expect(squiffyApi.canGoBack()).toBe(true);
223
+
224
+ squiffyApi.goBack();
225
+ expect(squiffyApi.canGoBack()).toBe(false);
226
+ });
227
+
228
+ test("canGoBack is true for a saved game that has somewhere to go back to", async () => {
229
+ const element = document.getElementById("squiffy")!;
230
+ const compileResult = await compile("[[a]]:\nGo to [[b]].\n\n[[b]]:\nThe end.");
231
+ const first = await init({ element, story: compileResult.story, persist: true });
232
+ await first.begin();
233
+ await first.clickLink(findLink(element, "section", "b"));
234
+
235
+ // A new page loads the saved game, which doesn't fire canGoBackChanged
236
+ element.innerHTML = "";
237
+ const second = await init({ element, story: compileResult.story, persist: true });
238
+ await second.begin();
239
+ expect(second.canGoBack()).toBe(true);
240
+ });
241
+
242
+ test("Going back is saved, so a saved game doesn't bring back what was undone", async () => {
243
+ const element = document.getElementById("squiffy")!;
244
+ const compileResult = await compile("[[a]]:\nGo to [[b]].\n\n[[b]]:\nLook at the [view].\n\n[view]:\nIt's lovely.");
245
+ const first = await init({ element, story: compileResult.story, persist: true });
246
+ await first.begin();
247
+ await first.clickLink(findLink(element, "section", "b"));
248
+ await first.clickLink(findLink(element, "passage", "view"));
249
+ first.goBack();
250
+ expect(element.innerHTML).not.toContain("lovely");
251
+
252
+ element.innerHTML = "";
253
+ const second = await init({ element, story: compileResult.story, persist: true });
254
+ await second.begin();
255
+ expect(element.innerHTML).toContain("Look at the");
256
+ expect(element.innerHTML).not.toContain("lovely");
257
+ });
258
+
203
259
  test("Click a passage link", async () => {
204
- const script = await fs.readFile("../examples/test/example.squiffy", "utf-8");
260
+ const script = await fs.readFile("../compiler/test/fixtures/test/example.squiffy", "utf-8");
205
261
  const { squiffyApi, element } = await initScript(script);
206
262
  expect(element.innerHTML).toMatchSnapshot();
207
263
 
@@ -236,7 +292,7 @@ test("Click a passage link", async () => {
236
292
  });
237
293
 
238
294
  test("Click a passage link and go back", async () => {
239
- const script = await fs.readFile("../examples/test/example.squiffy", "utf-8");
295
+ const script = await fs.readFile("../compiler/test/fixtures/test/example.squiffy", "utf-8");
240
296
  const { squiffyApi, element } = await initScript(script);
241
297
 
242
298
  const linkToPassage = findLink(element, "passage", "a link to a passage");
@@ -293,6 +349,267 @@ Last turn.
293
349
  expectSingleBlock("c", ["You chose c.", "Last turn."]);
294
350
  });
295
351
 
352
+ test("[@after] runs after every passage, before @1 and @last, and with @repeat passages", async () => {
353
+ // https://github.com/textadventures/squiffy/issues/523
354
+ const script = `
355
+ [[start]]:
356
+ Talk to the [guard], or look at the [a] or the [b].
357
+
358
+ [guard]:
359
+ @repeat
360
+ Talk.
361
+
362
+ [a]:
363
+ A.
364
+
365
+ [b]:
366
+ B.
367
+
368
+ [@after]:
369
+ @inc ticks
370
+ Tick {{ticks}}.
371
+
372
+ [@1]:
373
+ One.
374
+
375
+ [@last]:
376
+ Last.
377
+ `;
378
+ const { squiffyApi, element } = await initScript(script);
379
+ const passageTexts = () => Array.from(element.querySelectorAll(".squiffy-output-passage"))
380
+ .map(p => Array.from(p.querySelectorAll(".squiffy-output-block > *")).map(c => c.textContent!.trim()));
381
+
382
+ await squiffyApi.clickLink(findLink(element, "passage", "guard"));
383
+ expect(passageTexts().at(-1)).toEqual(["Talk.", "Tick 1."]);
384
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
385
+ expect(passageTexts().at(-1)).toEqual(["A.", "Tick 2.", "One."]);
386
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
387
+ expect(passageTexts().at(-1)).toEqual(["B.", "Tick 3.", "Last."]);
388
+ expect(squiffyApi.get("ticks")).toBe(3);
389
+ });
390
+
391
+ test("[@after] in the master section runs after every passage in the story, after the section's own", async () => {
392
+ // https://github.com/textadventures/squiffy/issues/523
393
+ const script = `
394
+ [[]]:
395
+
396
+ [@after]:
397
+ Time passes.
398
+
399
+ [[start]]:
400
+ Look at the [a], or go [[on]].
401
+
402
+ [a]:
403
+ A.
404
+
405
+ [@after]:
406
+ In start.
407
+
408
+ [[on]]:
409
+ Look at the [b].
410
+
411
+ [b]:
412
+ B.
413
+ `;
414
+ const { squiffyApi, element } = await initScript(script);
415
+ const lastPassage = () => Array.from(element.querySelectorAll(".squiffy-output-passage")).at(-1)!
416
+ .querySelectorAll(".squiffy-output-block > *");
417
+ const texts = () => Array.from(lastPassage()).map(c => c.textContent!.trim());
418
+
419
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
420
+ expect(texts()).toEqual(["A.", "In start.", "Time passes."]);
421
+ // Going to a section isn't a passage, so it doesn't run
422
+ await squiffyApi.clickLink(findLink(element, "section", "on"));
423
+ expect(element.textContent!.match(/Time passes\./g)).toHaveLength(1);
424
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
425
+ expect(texts()).toEqual(["B.", "Time passes."]);
426
+ });
427
+
428
+ test("A passage with @repeat can be clicked again, and doesn't count towards @1 or @last", async () => {
429
+ // https://github.com/textadventures/squiffy/issues/104
430
+ const script = `
431
+ [[start]]:
432
+ Talk to the [guard], or look at the [a] or the [b].
433
+
434
+ [guard]:
435
+ @repeat
436
+ @inc talks
437
+ Talk {{talks}}.
438
+
439
+ [a]:
440
+ You look at a.
441
+
442
+ [b]:
443
+ You look at b.
444
+
445
+ [@1]:
446
+ Turn one.
447
+
448
+ [@last]:
449
+ Last turn.
450
+ `;
451
+ const { squiffyApi, element } = await initScript(script);
452
+ const passageTexts = () => Array.from(element.querySelectorAll(".squiffy-output-passage"))
453
+ .map(p => p.textContent!.trim());
454
+
455
+ const guard = findLink(element, "passage", "guard");
456
+ expect(await squiffyApi.clickLink(guard)).toBe(true);
457
+ expect(await squiffyApi.clickLink(guard)).toBe(true);
458
+ expect(guard.classList).not.toContain("disabled");
459
+ expect(squiffyApi.get("talks")).toBe(2);
460
+ // Neither click was a turn in the section, so @1 hasn't run
461
+ expect(passageTexts()).toEqual(["Talk 1.", "Talk 2."]);
462
+
463
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
464
+ expect(passageTexts().at(-1)).toBe("You look at a.Turn one.");
465
+
466
+ // @1 doesn't run again after another click on the guard
467
+ await squiffyApi.clickLink(guard);
468
+ expect(passageTexts().at(-1)).toBe("Talk 3.");
469
+
470
+ // @last doesn't wait for the guard, and doesn't run again for it
471
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
472
+ expect(passageTexts().at(-1)).toBe("You look at b.Last turn.");
473
+ await squiffyApi.clickLink(guard);
474
+ expect(passageTexts().at(-1)).toBe("Talk 4.");
475
+ expect(squiffyApi.get("turns")).toBe(6);
476
+ });
477
+
478
+ test("{{deactivate}} with no name stops a passage with @repeat, and going back undoes it", async () => {
479
+ // https://github.com/textadventures/squiffy/issues/13
480
+ const script = `
481
+ [[start]]:
482
+ Talk to the [guard]. Or [[leave]].
483
+
484
+ [guard]:
485
+ @repeat
486
+ @inc talks
487
+ {{#if talks < 2}}Move along.{{else}}The password is swordfish.{{deactivate}}{{/if}}
488
+
489
+ [[leave]]:
490
+ Bye.
491
+ `;
492
+ const { squiffyApi, element } = await initScript(script);
493
+ const guard = findLink(element, "passage", "guard");
494
+
495
+ await squiffyApi.clickLink(guard);
496
+ expect(guard.classList).not.toContain("disabled");
497
+ await squiffyApi.clickLink(guard);
498
+ expect(element.textContent).toContain("The password is swordfish.");
499
+ expect(guard.classList).toContain("disabled");
500
+ expect(await squiffyApi.clickLink(guard)).toBe(false);
501
+
502
+ squiffyApi.goBack();
503
+ expect(guard.classList).not.toContain("disabled");
504
+ expect(guard.hasAttribute("data-deactivated-by")).toBe(false);
505
+ expect(await squiffyApi.clickLink(guard)).toBe(true);
506
+ expect(guard.classList).toContain("disabled");
507
+ });
508
+
509
+ describe("passage links in an {{#each}} (#448)", () => {
510
+ const script = `
511
+ [[start]]:
512
+ @set inventory = ["lamp", "key", "rope"]
513
+ {{#each inventory}}
514
+ - [Examine the {{this}}](examine, item = "{{this}}")
515
+ {{/each}}
516
+
517
+ [examine]:
518
+ It's a {{item}}.
519
+ `;
520
+ const disabled = (element: HTMLElement) =>
521
+ [...element.querySelectorAll("a.link-passage")].map(l => l.classList.contains("disabled"));
522
+
523
+ test("each item's link works on its own", async () => {
524
+ const { squiffyApi, element } = await initScript(script, true);
525
+ await squiffyApi.clickLink(findLink(element, "passage", "Examine the lamp"));
526
+ expect(disabled(element)).toEqual([true, false, false]);
527
+ expect(await squiffyApi.clickLink(findLink(element, "passage", "Examine the key"))).toBe(true);
528
+ expect(element.textContent).toContain("It's a lamp.");
529
+ expect(element.textContent).toContain("It's a key.");
530
+ expect(disabled(element)).toEqual([true, true, false]);
531
+ });
532
+
533
+ test("going back enables only the link that was clicked", async () => {
534
+ const { squiffyApi, element } = await initScript(script, true);
535
+ await squiffyApi.clickLink(findLink(element, "passage", "Examine the lamp"));
536
+ await squiffyApi.clickLink(findLink(element, "passage", "Examine the key"));
537
+ squiffyApi.goBack();
538
+ expect(disabled(element)).toEqual([true, false, false]);
539
+ squiffyApi.goBack();
540
+ expect(disabled(element)).toEqual([false, false, false]);
541
+ expect(element.querySelector("[data-clicked]")).toBeNull();
542
+ });
543
+
544
+ test("updating the story keeps the clicked link disabled, and going back still works", async () => {
545
+ const { squiffyApi, element } = await initScript(script, true);
546
+ await squiffyApi.clickLink(findLink(element, "passage", "Examine the key"));
547
+ const updated = await compile(script.replace("It's a", "It is a"), undefined, true);
548
+ squiffyApi.update(updated.story);
549
+ expect(disabled(element)).toEqual([false, true, false]);
550
+ const changed = await compile(script.replace("- [Examine", "- [Look at"), undefined, true);
551
+ squiffyApi.update(changed.story);
552
+ expect(disabled(element)).toEqual([false, true, false]);
553
+ squiffyApi.goBack();
554
+ expect(disabled(element)).toEqual([false, false, false]);
555
+ });
556
+
557
+ test("a saved game remembers which link was clicked", async () => {
558
+ const first = await initScript(script, true);
559
+ await first.squiffyApi.clickLink(findLink(first.element, "passage", "Examine the rope"));
560
+ first.element.innerHTML = "";
561
+ const { squiffyApi, element } = await initScript(script, true);
562
+ expect(disabled(element)).toEqual([false, false, true]);
563
+ squiffyApi.goBack();
564
+ expect(disabled(element)).toEqual([false, false, false]);
565
+ });
566
+ });
567
+
568
+ test("{{deactivate}} disables links to other passages, and going back only enables the ones it disabled", async () => {
569
+ // https://github.com/textadventures/squiffy/issues/13
570
+ const script = `
571
+ [[start]]:
572
+ You can see [a], [b], [c] and [d].
573
+
574
+ [a]:
575
+ {{deactivate "b" "c"}}A rules out B and C.
576
+
577
+ [b]:
578
+ B.
579
+
580
+ [c]:
581
+ C.
582
+
583
+ [d]:
584
+ D.
585
+ `;
586
+ const { squiffyApi, element } = await initScript(script);
587
+ const link = (name: string) => findLink(element, "passage", name);
588
+
589
+ // C is clicked first, so it's disabled already
590
+ await squiffyApi.clickLink(link("c"));
591
+ await squiffyApi.clickLink(link("a"));
592
+ expect(["a", "b", "c", "d"].map(n => link(n).classList.contains("disabled"))).toEqual([true, true, true, false]);
593
+
594
+ squiffyApi.goBack();
595
+ // A was undone, so B is back, but C stays clicked
596
+ expect(["a", "b", "c", "d"].map(n => link(n).classList.contains("disabled"))).toEqual([false, false, true, false]);
597
+ });
598
+
599
+ test("{{deactivate}} shows an error for a passage that isn't in the section, or with no name in a section", async () => {
600
+ const script = `
601
+ [[start]]:
602
+ {{deactivate}}See [a].
603
+
604
+ [a]:
605
+ {{deactivate "nowhere"}}A.
606
+ `;
607
+ const { squiffyApi, element } = await initScript(script);
608
+ expect(element.textContent).toContain("{{deactivate}} with no passage name only works in a passage");
609
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
610
+ expect(element.textContent).toContain('there is no passage called "nowhere" in this section');
611
+ });
612
+
296
613
  test("Going back to a section re-enables its inputs", async () => {
297
614
  // https://github.com/textadventures/squiffy/issues/123
298
615
  const script = `
@@ -470,6 +787,151 @@ Three.
470
787
  expect(visibleText(element)).toBe("Two. a three");
471
788
  });
472
789
 
790
+ test("Clearing the screen scrolls up to the top of the output", async () => {
791
+ // https://github.com/textadventures/squiffy/issues/54
792
+ const script = `
793
+ [[start]]:
794
+ Start. [[two]]
795
+
796
+ [[two]]:
797
+ Two. [[three]]
798
+
799
+ [[three]]:
800
+ @clear
801
+ Three.
802
+ `;
803
+ const { squiffyApi, element } = await initScript(script);
804
+
805
+ // The reader has scrolled down to 500px, and the output starts 20px from the top of the page
806
+ Object.defineProperty(document.documentElement, "scrollTop", { configurable: true, get: () => 500 });
807
+ (element.firstElementChild as HTMLElement).getBoundingClientRect = () => ({ top: -480 }) as DOMRect;
808
+ const scrollTo = vi.fn();
809
+ window.scrollTo = scrollTo;
810
+
811
+ // No clear, so no scrolling up
812
+ await squiffyApi.clickLink(findLink(element, "section", "two"));
813
+ expect(scrollTo).not.toHaveBeenCalled();
814
+
815
+ await squiffyApi.clickLink(findLink(element, "section", "three"));
816
+ expect(scrollTo).toHaveBeenCalledTimes(1);
817
+ expect(scrollTo).toHaveBeenCalledWith({ top: 20, behavior: "smooth" });
818
+ });
819
+
820
+ describe("{{clear}}", () => {
821
+ // https://github.com/textadventures/squiffy/issues/524
822
+ test("clears the screen only when its {{#if}} says so", async () => {
823
+ const script = `
824
+ [[start]]:
825
+ On the train. [[get off]](platform), [[change]]
826
+
827
+ [[change]]:
828
+ At the other platform. [[back]](platform)
829
+
830
+ [[platform]]:
831
+ {{#if previous_section != "change"}}{{clear}}{{/if}}
832
+ On the platform.
833
+ `;
834
+ const { squiffyApi, element } = await initScript(script);
835
+ await squiffyApi.clickLink(findLink(element, "section", "get off"));
836
+ expect(visibleText(element)).toBe("On the platform.");
837
+
838
+ squiffyApi.goBack();
839
+ expect(visibleText(element)).toBe("On the train. get off, change");
840
+ expect(squiffyApi.get("_section")).toBe("start");
841
+
842
+ await squiffyApi.clickLink(findLink(element, "section", "change", true));
843
+ await squiffyApi.clickLink(findLink(element, "section", "back", true));
844
+ expect(visibleText(element)).toBe("On the train. get off, change At the other platform. back On the platform.");
845
+ });
846
+
847
+ test("takes away the text before it, in the section and in the master section", async () => {
848
+ const script = `
849
+ [[]]:
850
+ Master text.
851
+
852
+ [[start]]:
853
+ Start. [[next]]
854
+
855
+ [[next]]:
856
+ Gone. {{clear}}Kept, *still* in a paragraph.
857
+
858
+ And more. [[last]]
859
+
860
+ [[last]]:
861
+ Last.
862
+ `;
863
+ const { squiffyApi, element } = await initScript(script);
864
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
865
+ expect(visibleText(element)).toBe("Kept, still in a paragraph. And more. last");
866
+ const sections = element.querySelectorAll(".squiffy-output-section");
867
+ expect(sections[sections.length - 1].querySelector("p")!.innerHTML).toBe("Kept, <em>still</em> in a paragraph.");
868
+
869
+ // It's a section like any other
870
+ await squiffyApi.clickLink(findLink(element, "section", "last"));
871
+ expect(visibleText(element)).toBe("Kept, still in a paragraph. And more. last Master text.Last.");
872
+
873
+ squiffyApi.goBack();
874
+ expect(visibleText(element)).toBe("Kept, still in a paragraph. And more. last");
875
+ squiffyApi.goBack();
876
+ expect(visibleText(element)).toBe("Master text.Start. next");
877
+ expect(findLink(element, "section", "next", true)).toBeDefined();
878
+ expect(squiffyApi.get("_section")).toBe("start");
879
+ });
880
+
881
+ test("in a passage, clears the screen, and going back brings it back", async () => {
882
+ const script = `
883
+ [[start]]:
884
+ @set count = 0
885
+ Start. [look], [[on]]
886
+
887
+ [look]:
888
+ @inc count
889
+ {{#if count > 0}}{{clear}}{{/if}}You look.
890
+
891
+ [[on]]:
892
+ On.
893
+ `;
894
+ const { squiffyApi, element } = await initScript(script);
895
+ await squiffyApi.clickLink(findLink(element, "passage", "look"));
896
+ expect(visibleText(element)).toBe("You look.");
897
+ expect(squiffyApi.get("count")).toBe(1);
898
+
899
+ squiffyApi.goBack();
900
+ expect(visibleText(element)).toBe("Start. look, on");
901
+ expect(squiffyApi.get("count")).toBe(0);
902
+ expect(findLink(element, "passage", "look", true)).toBeDefined();
903
+ });
904
+
905
+ test("shows only what comes after it when the text is edited in the editor", async () => {
906
+ const script = `
907
+ [[start]]:
908
+ Start. [[next]]
909
+
910
+ [[next]]:
911
+ Before. {{clear}}After.
912
+ `;
913
+ const { squiffyApi, element } = await initScript(script);
914
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
915
+ expect(visibleText(element)).toBe("After.");
916
+ squiffyApi.update((await compile(script.replace("After.", "Edited."))).story);
917
+ expect(visibleText(element)).toBe("Edited.");
918
+ });
919
+
920
+ test("with no {{#if}} is the same as @clear", async () => {
921
+ const { squiffyApi, element } = await initScript(`
922
+ [[start]]:
923
+ Start. [[next]]
924
+
925
+ [[next]]:
926
+ {{clear}}
927
+ Next.
928
+ `);
929
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
930
+ expect(visibleText(element)).toBe("Next.");
931
+ expect(element.querySelector(".squiffy-clear-stack")!.textContent).toContain("Start.");
932
+ });
933
+ });
934
+
473
935
  test("Run JavaScript functions", async () => {
474
936
  const script = `
475
937
  document.getElementById('test').innerText = 'Initial JavaScript';
@@ -770,6 +1232,159 @@ Text from a passage.
770
1232
  expect(output).toBe("Here is some text from a passage: Text from a passage.");
771
1233
  });
772
1234
 
1235
+ describe("Embed with parameters and wrapped text (#450)", () => {
1236
+ test("Parameters are shown in the embedded text", async () => {
1237
+ const script = `
1238
+ [[section1]]:
1239
+ {{embed "say" who="Ann" mood="happy"}}
1240
+
1241
+ [[say]]:
1242
+ {{who}} looks {{mood}}.
1243
+ `;
1244
+ const { element } = await initScript(script);
1245
+ expect(getSectionContent(element, "section1")).toBe("Ann looks happy.");
1246
+ });
1247
+
1248
+ test("A parameter's value can be an attribute", async () => {
1249
+ const script = `
1250
+ [[section1]]:
1251
+ @set name = Bob
1252
+ {{embed "say" who=name}}
1253
+
1254
+ [[say]]:
1255
+ Hello, {{who}}.
1256
+ `;
1257
+ const { element } = await initScript(script);
1258
+ expect(getSectionContent(element, "section1")).toBe("Hello, Bob.");
1259
+ });
1260
+
1261
+ test("A parameter's value can be an expression", async () => {
1262
+ const script = `
1263
+ [[section1]]:
1264
+ @set gold = 10
1265
+ {{embed "say" left=gold - 3 items=["a", "b"]}}
1266
+
1267
+ [[say]]:
1268
+ {{left}} gold, {{join items " and "}}.
1269
+ `;
1270
+ const { element } = await initScript(script, true);
1271
+ expect(getSectionContent(element, "section1")).toBe("7 gold, a and b.");
1272
+ });
1273
+
1274
+ test("A parameter hides an attribute with the same name, without changing it", async () => {
1275
+ const script = `
1276
+ [[section1]]:
1277
+ @set who = Bob
1278
+ {{embed "say" who="Ann"}} Then {{who}}.
1279
+
1280
+ [[say]]:
1281
+ {{who}}, and {{get "who"}}.
1282
+ `;
1283
+ const { element, squiffyApi } = await initScript(script);
1284
+ expect(getSectionContent(element, "section1")).toBe("Ann, and Ann. Then Bob.");
1285
+ expect(squiffyApi.get("who")).toBe("Bob");
1286
+ });
1287
+
1288
+ test("Setting a parameter changes it for the rest of the embed only", async () => {
1289
+ const script = `
1290
+ [[section1]]:
1291
+ @set who = Bob
1292
+ {{embed "say" who="Ann"}} Then {{who}}, {{mood}}.
1293
+
1294
+ [[say]]:
1295
+ {{set "who" "Cat"}}{{set "mood" "happy"}}{{who}}.
1296
+ `;
1297
+ const { element, squiffyApi } = await initScript(script);
1298
+ expect(getSectionContent(element, "section1")).toBe("Cat. Then Bob, happy.");
1299
+ expect(squiffyApi.get("who")).toBe("Bob");
1300
+ expect(squiffyApi.get("mood")).toBe("happy");
1301
+ });
1302
+
1303
+ test("A parameter works in a condition", async () => {
1304
+ const script = `
1305
+ [[section1]]:
1306
+ {{embed "say" who="Ann"}} {{embed "say" who="Bob"}}
1307
+
1308
+ [[say]]:
1309
+ {{#if who = "Ann"}}Hi Ann.{{else}}Who are you?{{/if}}
1310
+ `;
1311
+ const { element } = await initScript(script, true);
1312
+ expect(getSectionContent(element, "section1")).toBe("Hi Ann. Who are you?");
1313
+ });
1314
+
1315
+ test("An embed inside an embed doesn't see the outer one's parameters", async () => {
1316
+ const script = `
1317
+ [[section1]]:
1318
+ @set who = Bob
1319
+ {{embed "outer" who="Ann"}}
1320
+
1321
+ [[outer]]:
1322
+ {{who}} / {{embed "inner"}}
1323
+
1324
+ [[inner]]:
1325
+ {{who}}
1326
+ `;
1327
+ const { element } = await initScript(script);
1328
+ expect(getSectionContent(element, "section1")).toBe("Ann / Bob");
1329
+ });
1330
+
1331
+ test("Wrapped text is shown by {{content}}, with the caller's attributes", async () => {
1332
+ const script = `
1333
+ [[section1]]:
1334
+ @set name = Bob
1335
+ {{#embed "say" who="Ann" name="not this"}}Hello, {{name}}!{{/embed}}
1336
+
1337
+ [[say]]:
1338
+ {{who}}: "{{content}}"
1339
+ `;
1340
+ const { element } = await initScript(script);
1341
+ expect(getSectionContent(element, "section1")).toBe("Ann: \"Hello, Bob!\"");
1342
+ });
1343
+
1344
+ test("Wrapped text can use the caller's parameters and loop items", async () => {
1345
+ const script = `
1346
+ [[section1]]:
1347
+ {{embed "outer" who="Ann"}}
1348
+
1349
+ [[outer]]:
1350
+ {{#each (array "x" "y")}}{{#embed "box"}}{{who}}-{{this}}{{/embed}}{{/each}}
1351
+
1352
+ [[box]]:
1353
+ ({{content}})
1354
+ `;
1355
+ const { element } = await initScript(script);
1356
+ expect(getSectionContent(element, "section1")).toBe("(Ann-x)(Ann-y)");
1357
+ });
1358
+
1359
+ test("Setting an attribute in wrapped text sets the caller's", async () => {
1360
+ const script = `
1361
+ [[section1]]:
1362
+ {{embed "outer" n=1}}
1363
+
1364
+ [[outer]]:
1365
+ {{#embed "box" n=10}}{{set "n" 2}}{{/embed}}{{n}}
1366
+
1367
+ [[box]]:
1368
+ {{content}}{{n}}
1369
+ `;
1370
+ const { element } = await initScript(script);
1371
+ expect(getSectionContent(element, "section1")).toBe("102");
1372
+ });
1373
+
1374
+ test("{{content}} with nothing wrapped shows a content attribute, if there is one", async () => {
1375
+ const script = `
1376
+ [[section1]]:
1377
+ @set content = stuff
1378
+ {{embed "box"}} {{content}}
1379
+
1380
+ [[box]]:
1381
+ ({{content}})
1382
+ `;
1383
+ const { element } = await initScript(script);
1384
+ expect(getSectionContent(element, "section1")).toBe("(stuff) stuff");
1385
+ });
1386
+ });
1387
+
773
1388
  test("Update section with embedded text", async () => {
774
1389
  const script = `
775
1390
  [[section1]]:
@@ -1741,19 +2356,545 @@ Go to: [[whitespace]]
1741
2356
  expect(section).not.toBeNull();
1742
2357
  });
1743
2358
 
1744
- // State modification helper tests
1745
- test("{{set}} helper sets attribute value", async () => {
2359
+ // Maths helpers and arithmetic in infix expressions
2360
+ test.each([
2361
+ ["{{set \"x\" (add 2 3)}}", 5],
2362
+ ["{{set \"x\" (sub 2 3)}}", -1],
2363
+ ["{{set \"x\" (mul 2 3)}}", 6],
2364
+ ["{{set \"x\" (div 3 2)}}", 1.5],
2365
+ ["{{set \"x\" (mod 7 3)}}", 1],
2366
+ ["{{set \"x\" (add \"2\" 3)}}", 5],
2367
+ ["{{set \"x\" (add \"Bob\" \" the Brave\")}}", "Bob the Brave"],
2368
+ ["{{set \"x\" (add \"Bob\" 2)}}", "Bob2"],
2369
+ ["{{set \"x\" (add unsetattr 2)}}", 2],
2370
+ ["{{set \"x\" (mul unsetattr 2)}}", 0],
2371
+ ])("maths helper: %s", async (text, expected) => {
2372
+ const { squiffyApi } = await initScript(`[[start]]:\n${text}`);
2373
+ expect(squiffyApi.get("x")).toBe(expected);
2374
+ });
2375
+
2376
+ test.each([
2377
+ ["{{= (div 1 0)}}", "division by zero"],
2378
+ ["{{= (mod 1 0)}}", "division by zero"],
2379
+ ["{{= (mul \"a\" 2)}}", "\"mul\" needs numbers, but was given \"a\""],
2380
+ ["{{= (sub 1)}}", "\"sub\" needs two values, but was given 1"],
2381
+ ["{{= (add (array 1) 2)}}", "\"add\" can't add a list"],
2382
+ ])("maths helper error: %s", async (text, message) => {
2383
+ const { element } = await initScript(`[[start]]:\n${text}`);
2384
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain(message);
2385
+ });
2386
+
2387
+ test("arithmetic in {{set}}, {{inc}}, {{dec}} and conditions", async () => {
1746
2388
  const script = `
1747
2389
  [[start]]:
1748
- {{set "score" 100}}
1749
- Score is {{score}}.
2390
+ @set gold = 10
2391
+ @set price = 3
2392
+ @set name = Bob
2393
+ {{set "gold" gold + price * 2}}
2394
+ {{inc "count" price * 2}}
2395
+ {{dec "count" (price - 1) * 2}}
2396
+ {{set "title" name + " the Brave"}}
2397
+ {{#if gold >= price * 5 + 1}}Rich{{else}}Poor{{/if}}. Double: {{= price * 2}}.
1750
2398
  `;
1751
2399
 
1752
- const { squiffyApi } = await initScript(script);
1753
- expect(squiffyApi.get("score")).toBe(100);
2400
+ const { squiffyApi, element } = await initScript(script);
2401
+ expect(squiffyApi.get("gold")).toBe(16);
2402
+ expect(squiffyApi.get("count")).toBe(2);
2403
+ expect(squiffyApi.get("title")).toBe("Bob the Brave");
2404
+ expect(element.textContent).toContain("Rich. Double: 6.");
1754
2405
  });
1755
2406
 
1756
- test("{{set}} helper with string value", async () => {
2407
+ test("Invalid arithmetic shows a template error", async () => {
2408
+ const { element } = await initBrokenText("{{set \"gold\" gold +}}");
2409
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("Invalid expression");
2410
+ });
2411
+
2412
+ test("{{inc}} and {{dec}} use amounts stored as text (#374)", async () => {
2413
+ const script = `
2414
+ [[start]]:
2415
+ @set price = 0
2416
+ {{set "price" "10"}}{{set "a" 0}}{{set "b" 20}}
2417
+ {{inc "a" "10"}}{{inc "a" price}}{{dec "b" price}}
2418
+ `;
2419
+ const { squiffyApi } = await initScript(script);
2420
+ expect(squiffyApi.get("a")).toBe(20);
2421
+ expect(squiffyApi.get("b")).toBe(10);
2422
+ });
2423
+
2424
+ test("{{inc}} and {{dec}} add to values stored as text, rather than joining them (#374)", async () => {
2425
+ const script = `
2426
+ [[start]]:
2427
+ {{set "a" "5"}}{{inc "a"}}{{set "b" "5"}}{{inc "b" 2}}{{set "c" "5"}}{{dec "c"}}
2428
+ `;
2429
+ const { squiffyApi } = await initScript(script);
2430
+ expect(squiffyApi.get("a")).toBe(6);
2431
+ expect(squiffyApi.get("b")).toBe(7);
2432
+ expect(squiffyApi.get("c")).toBe(4);
2433
+ });
2434
+
2435
+ test("{{inc}} on text that isn't a number shows a template error (#374)", async () => {
2436
+ const { element, squiffyApi } = await initScript("[[start]]:\n{{set \"a\" \"abc\"}}{{inc \"a\"}}");
2437
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("\"inc\" needs numbers, but was given \"abc\"");
2438
+ expect(squiffyApi.get("a")).toBe("abc");
2439
+ });
2440
+
2441
+ test("@inc, @dec and += etc. work on values stored as text (#374)", async () => {
2442
+ const script = `
2443
+ [[start]]:
2444
+ {{set "a" "5"}}{{set "b" "5"}}{{set "c" "5"}}{{set "d" "5"}}{{set "price" "3"}}
2445
+ [[next]]
2446
+
2447
+ [[next]]:
2448
+ @inc a
2449
+ @dec b 2
2450
+ @set c += @price
2451
+ @set d *= 2
2452
+ @set e += 4
2453
+ `;
2454
+ const { element, squiffyApi } = await initScript(script);
2455
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
2456
+ expect(squiffyApi.get("a")).toBe(6);
2457
+ expect(squiffyApi.get("b")).toBe(3);
2458
+ expect(squiffyApi.get("c")).toBe(8);
2459
+ expect(squiffyApi.get("d")).toBe(10);
2460
+ expect(squiffyApi.get("e")).toBe(4);
2461
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2462
+ });
2463
+
2464
+ test("+= on text that isn't a number shows an error and leaves the attribute alone (#374)", async () => {
2465
+ const script = `
2466
+ [[start]]:
2467
+ @set name = Bob
2468
+ @set name += 1
2469
+ @set gold += lots
2470
+ Hello.
2471
+ `;
2472
+ const { element, squiffyApi } = await initScript(script);
2473
+ const errors = [...element.querySelectorAll(".squiffy-error")].map(e => e.textContent);
2474
+ expect(errors).toEqual([
2475
+ "Error in \"name += 1\": \"+=\" needs numbers, but was given \"Bob\"",
2476
+ "Error in \"gold += lots\": \"+=\" needs numbers, but was given \"lots\"",
2477
+ ]);
2478
+ expect(squiffyApi.get("name")).toBe("Bob");
2479
+ expect(squiffyApi.get("gold")).toBeNull();
2480
+ expect(element.textContent).toContain("Hello.");
2481
+ });
2482
+
2483
+ test("an error in a link's setters is shown in the next section (#374)", async () => {
2484
+ const script = `
2485
+ [[start]]:
2486
+ @set name = Bob
2487
+ [[Go]](next, name+=1)
2488
+
2489
+ [[next]]:
2490
+ Arrived.
2491
+ `;
2492
+ const { element, squiffyApi } = await initScript(script);
2493
+ await squiffyApi.clickLink(findLink(element, "section", "Go"));
2494
+ expect(getSectionContent(element, "next")).toBe("Error in \"name+=1\": \"+=\" needs numbers, but was given \"Bob\"Arrived.");
2495
+ });
2496
+
2497
+ // ---- Expressions in @set and link setters, for a story with a squiffy.json (#373) ----
2498
+
2499
+ test("@set takes expressions, with the same rules as {{#if}}", async () => {
2500
+ const script = `
2501
+ [[start]]:
2502
+ @set weapon = "sword"
2503
+ @set price = 3
2504
+ @set gold = 10
2505
+ @set gold = gold + price * 2
2506
+ @set rich = gold > 15
2507
+ @set poor = not rich
2508
+ @set best = gold
2509
+ @set title = 'Bob' + " the Brave"
2510
+ @set negative = -price
2511
+ @set empty = ""
2512
+ `;
2513
+ const { squiffyApi } = await initScript(script, true);
2514
+ expect(squiffyApi.get("weapon")).toBe("sword");
2515
+ expect(squiffyApi.get("gold")).toBe(16);
2516
+ expect(squiffyApi.get("rich")).toBe(true);
2517
+ expect(squiffyApi.get("poor")).toBe(false);
2518
+ expect(squiffyApi.get("best")).toBe(16);
2519
+ expect(squiffyApi.get("title")).toBe("Bob the Brave");
2520
+ expect(squiffyApi.get("negative")).toBe(-3);
2521
+ expect(squiffyApi.get("empty")).toBe("");
2522
+ });
2523
+
2524
+ test("+=, -=, *= and /= take expressions", async () => {
2525
+ const script = `
2526
+ [[start]]:
2527
+ @set price = 3
2528
+ @set gold = 10
2529
+ @set gold += price * 2
2530
+ @set gold -= 1
2531
+ @set gold *= (price - 1)
2532
+ @set gold /= 2
2533
+ @inc count
2534
+ @inc count 4
2535
+ @dec count
2536
+ `;
2537
+ const { squiffyApi } = await initScript(script, true);
2538
+ expect(squiffyApi.get("gold")).toBe(15);
2539
+ expect(squiffyApi.get("count")).toBe(4);
2540
+ });
2541
+
2542
+ test("flags and := work as before with expressions", async () => {
2543
+ const script = `
2544
+ [[start]]:
2545
+ @set name = "Bob"
2546
+ @set has_key
2547
+ @set not has_map
2548
+ @set greeting := Hello, {{name}}!
2549
+ `;
2550
+ const { squiffyApi } = await initScript(script, true);
2551
+ expect(squiffyApi.get("has_key")).toBe(true);
2552
+ expect(squiffyApi.get("has_map")).toBe(false);
2553
+ expect(squiffyApi.get("greeting")).toBe("Hello, Bob!");
2554
+ });
2555
+
2556
+ test("helpers can be used in setter expressions", async () => {
2557
+ const script = `
2558
+ [[start]]:
2559
+ @set visited = (seen "start")
2560
+ @set here = (at "start")
2561
+ `;
2562
+ const { squiffyApi } = await initScript(script, true);
2563
+ expect(squiffyApi.get("visited")).toBe(true);
2564
+ expect(squiffyApi.get("here")).toBe(true);
2565
+ });
2566
+
2567
+ describe("objects (#442)", () => {
2568
+ test("@set can set an object, and values inside it", async () => {
2569
+ const script = `
2570
+ [[start]]:
2571
+ @set hero = { hp: 10, name: "Ann", "max hp": 12 }
2572
+ @set hero.hp += 5
2573
+ @set hero.level = 1
2574
+ @set hero.poisoned
2575
+ @set not hero.blessed
2576
+ @set hero.title := {{hero.name}} the Brave
2577
+ @set bag.gold = 3
2578
+ HP: {{hero.hp}}. {{#if hero.hp > 12}}Healthy.{{/if}} {{= hero.hp * 2}}
2579
+ `;
2580
+ const { squiffyApi, element } = await initScript(script, true);
2581
+ expect(squiffyApi.get("hero")).toEqual({ hp: 15, name: "Ann", "max hp": 12, level: 1, poisoned: true, blessed: false, title: "Ann the Brave" });
2582
+ expect(squiffyApi.get("bag")).toEqual({ gold: 3 });
2583
+ expect(element.textContent).toContain("HP: 15. Healthy. 30");
2584
+ });
2585
+
2586
+ test("lists of objects, with an index from another attribute", async () => {
2587
+ const script = `
2588
+ [[start]]:
2589
+ @set inventory = [{ name: "lamp", weight: 2 }, { name: "rope", weight: 1 }]
2590
+ @set i = 1
2591
+ @set inventory[i].weight = 5
2592
+ @set inventory[0].lit = true
2593
+ @set chosen = inventory[i]
2594
+ @set first = inventory[0].name
2595
+ {{#each inventory}}{{this.name}} ({{weight}}) {{/each}}
2596
+ {{#if inventory[i].weight > 4}}Heavy {{= inventory[i].name}}.{{/if}}
2597
+ `;
2598
+ const { squiffyApi, element } = await initScript(script, true);
2599
+ expect(squiffyApi.get("inventory")).toEqual([{ name: "lamp", weight: 2, lit: true }, { name: "rope", weight: 5 }]);
2600
+ expect(squiffyApi.get("chosen")).toEqual({ name: "rope", weight: 5 });
2601
+ expect(squiffyApi.get("first")).toBe("lamp");
2602
+ expect(element.textContent).toContain("lamp (2) rope (5)");
2603
+ expect(element.textContent).toContain("Heavy rope.");
2604
+ });
2605
+
2606
+ test("copying an object copies it, rather than sharing it", async () => {
2607
+ const script = `
2608
+ [[start]]:
2609
+ @set hero = { hp: 10 }
2610
+ @set saved = hero
2611
+ @set hero.hp = 1
2612
+ `;
2613
+ const { squiffyApi } = await initScript(script, true);
2614
+ expect(squiffyApi.get("saved")).toEqual({ hp: 10 });
2615
+ expect(squiffyApi.get("hero.hp")).toBe(1);
2616
+ });
2617
+
2618
+ test("link setters can set values inside objects", async () => {
2619
+ const script = `
2620
+ [[start]]:
2621
+ @set hero = { hp: 10, name: "Ann" }
2622
+ [[Heal]](inn, hero.hp += 5, hero.mood = { happy: true, reason: "rest, at last" })
2623
+
2624
+ [[inn]]:
2625
+ HP {{hero.hp}}.
2626
+ `;
2627
+ const { squiffyApi, element } = await initScript(script, true);
2628
+ await squiffyApi.clickLink(findLink(element, "section", "Heal"));
2629
+ expect(squiffyApi.get("hero")).toEqual({ hp: 15, name: "Ann", mood: { happy: true, reason: "rest, at last" } });
2630
+ expect(element.textContent).toContain("HP 15.");
2631
+ });
2632
+
2633
+ test("a link's setters can use square brackets, which aren't passage links", async () => {
2634
+ const script = `
2635
+ [[start]]:
2636
+ @set party = [{ name: "Ann", hp: 10 }, { name: "Bo", hp: 4 }]
2637
+ @set leader = 0
2638
+ [[Make Bo the leader]](next, leader = 1, party[1].hp += 2, list = ["a", "b"])
2639
+
2640
+ [[next]]:
2641
+ {{= party[leader].name}} has {{= party[leader].hp}} HP.
2642
+ `;
2643
+ const { squiffyApi, element } = await initScript(script, true);
2644
+ await squiffyApi.clickLink(findLink(element, "section", "Make Bo the leader"));
2645
+ expect(element.textContent).toContain("Bo has 6 HP.");
2646
+ expect(squiffyApi.get("list")).toEqual(["a", "b"]);
2647
+ });
2648
+
2649
+ test("going back undoes a change inside an object", async () => {
2650
+ const script = `
2651
+ [[start]]:
2652
+ @set hero = { hp: 10 }
2653
+ [[next]]
2654
+
2655
+ [[next]]:
2656
+ @set hero.hp = 3
2657
+ `;
2658
+ const { squiffyApi, element } = await initScript(script, true);
2659
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
2660
+ expect(squiffyApi.get("hero.hp")).toBe(3);
2661
+ squiffyApi.goBack();
2662
+ expect(squiffyApi.get("hero")).toEqual({ hp: 10 });
2663
+ });
2664
+
2665
+ test("saves keep objects", async () => {
2666
+ const script = `
2667
+ [[start]]:
2668
+ @set hero = { hp: 10, items: ["lamp"] }
2669
+ `;
2670
+ const { squiffyApi } = await initScript(script, true);
2671
+ const save = squiffyApi.getSave();
2672
+ squiffyApi.set("hero.hp", 1);
2673
+ await squiffyApi.loadSave(save);
2674
+ expect(squiffyApi.get("hero")).toEqual({ hp: 10, items: ["lamp"] });
2675
+ });
2676
+
2677
+ test("squiffy.get and set, and {{set}}, {{inc}} and {{append}}, take paths", async () => {
2678
+ const script = `
2679
+ [[start]]:
2680
+ {{set "hero" { hp: 10 }}}{{set "hero.name" "Ann"}}{{inc "hero.hp" 2}}{{append "hero.items" "lamp"}}
2681
+ `;
2682
+ const { squiffyApi } = await initScript(script, true);
2683
+ expect(squiffyApi.get("hero")).toEqual({ hp: 12, name: "Ann", items: ["lamp"] });
2684
+ squiffyApi.set("hero.items.0", "rope");
2685
+ squiffyApi.set("hero[\"max hp\"]", 20);
2686
+ expect(squiffyApi.get("hero.items[0]")).toBe("rope");
2687
+ expect(squiffyApi.get("hero.max hp")).toBe(20);
2688
+ expect(squiffyApi.get("hero.missing.deeper")).toBeNull();
2689
+ expect(squiffyApi.get("nothing.here")).toBeNull();
2690
+ });
2691
+
2692
+ test("setting inside something that isn't an object is an error", async () => {
2693
+ const script = `
2694
+ [[start]]:
2695
+ @set gold = 5
2696
+ @set gold.amount = 1
2697
+
2698
+ [[next]]
2699
+ `;
2700
+ const { squiffyApi, element } = await initScript(script, true);
2701
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
2702
+ expect(squiffyApi.get("gold")).toBe(5);
2703
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("gold isn't an object, so it has no amount");
2704
+ });
2705
+
2706
+ test("an object can't reach the prototype", async () => {
2707
+ const script = `
2708
+ [[start]]:
2709
+ @set hero = {}
2710
+ @set hero.__proto__.polluted = true
2711
+ @set key = "constructor"
2712
+ @set hero[key] = 1
2713
+
2714
+ [[next]]
2715
+ `;
2716
+ const { squiffyApi, element } = await initScript(script, true);
2717
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
2718
+ expect(({} as Record<string, unknown>).polluted).toBeUndefined();
2719
+ expect(squiffyApi.get("hero")).toEqual({});
2720
+ expect(element.querySelectorAll(".squiffy-error").length).toBe(2);
2721
+ });
2722
+ });
2723
+
2724
+ test("link setters take expressions, and can have commas in quotes", async () => {
2725
+ const script = `
2726
+ [[start]]:
2727
+ @set gold = 10
2728
+ @set price = 3
2729
+ [[Buy]](shop, gold -= price, swords += 1, message = "Thanks, come again", weapon = 'sword')
2730
+
2731
+ [[shop]]:
2732
+ {{message}}
2733
+ [[Haggle]](haggle, price = price - 1)
2734
+
2735
+ [[haggle]]:
2736
+ Done.
2737
+ {{section "end" text="End" set="gold = gold + price * 10, done"}}
2738
+
2739
+ [[end]]:
2740
+ The end.
2741
+ `;
2742
+ const { squiffyApi, element } = await initScript(script, true);
2743
+ await squiffyApi.clickLink(findLink(element, "section", "Buy"));
2744
+ expect(squiffyApi.get("gold")).toBe(7);
2745
+ expect(squiffyApi.get("swords")).toBe(1);
2746
+ expect(squiffyApi.get("message")).toBe("Thanks, come again");
2747
+ expect(squiffyApi.get("weapon")).toBe("sword");
2748
+ expect(getSectionContent(element, "shop")).toContain("Thanks, come again");
2749
+ await squiffyApi.clickLink(findLink(element, "section", "Haggle"));
2750
+ expect(squiffyApi.get("price")).toBe(2);
2751
+ await squiffyApi.clickLink(findLink(element, "section", "End"));
2752
+ expect(squiffyApi.get("gold")).toBe(27);
2753
+ expect(squiffyApi.get("done")).toBe(true);
2754
+ });
2755
+
2756
+ test("link setters can have brackets in them", async () => {
2757
+ const script = `
2758
+ [[start]]:
2759
+ @set gold = 10
2760
+ @set price = 3
2761
+ [[Buy]](shop, gold *= (price - 1), title = "Shop (open)")
2762
+
2763
+ [[shop]]:
2764
+ {{title}}
2765
+ [Haggle](deal, gold = (gold + (price * 2)) / 2)
2766
+
2767
+ [deal]:
2768
+ Done.
2769
+ `;
2770
+ const { squiffyApi, element } = await initScript(script, true);
2771
+ await squiffyApi.clickLink(findLink(element, "section", "Buy"));
2772
+ expect(squiffyApi.get("gold")).toBe(20);
2773
+ expect(squiffyApi.get("title")).toBe("Shop (open)");
2774
+ await squiffyApi.clickLink(findLink(element, "passage", "Haggle"));
2775
+ expect(squiffyApi.get("gold")).toBe(13);
2776
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2777
+ });
2778
+
2779
+ test("passage link setters take expressions", async () => {
2780
+ const script = `
2781
+ [[start]]:
2782
+ @set gold = 10
2783
+ [Spend](spend, gold = gold / 2)
2784
+
2785
+ [spend]:
2786
+ Spent.
2787
+ `;
2788
+ const { squiffyApi, element } = await initScript(script, true);
2789
+ await squiffyApi.clickLink(findLink(element, "passage", "Spend"));
2790
+ expect(squiffyApi.get("gold")).toBe(5);
2791
+ });
2792
+
2793
+ test("an invalid setter expression shows an error and leaves the attribute alone", async () => {
2794
+ const script = `
2795
+ [[start]]:
2796
+ @set gold = 10
2797
+ @set gold = gold +
2798
+ @set gold += "lots"
2799
+ @set gold > 5
2800
+ Hello.
2801
+ `;
2802
+ const { squiffyApi, element } = await initScript(script, true);
2803
+ const errors = [...element.querySelectorAll(".squiffy-error")].map(e => e.textContent);
2804
+ expect(errors).toEqual([
2805
+ "Error in \"gold = gold +\": Invalid expression \"gold +\": expected a value after '+'",
2806
+ "Error in \"gold += \"lots\"\": \"+=\" needs numbers, but was given \"lots\"",
2807
+ "Error in \"gold > 5\": expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key",
2808
+ ]);
2809
+ expect(squiffyApi.get("gold")).toBe(10);
2810
+ expect(element.textContent).toContain("Hello.");
2811
+ });
2812
+
2813
+ test("without a squiffy.json, setters keep the Squiffy 6 rules", async () => {
2814
+ const script = `
2815
+ [[start]]:
2816
+ @set weapon = sword
2817
+ @set price = 3
2818
+ @set best = @price
2819
+ @set gold = gold + price
2820
+ [[Go]](next, name = Bob's, message = Hi, there)
2821
+
2822
+ [[next]]:
2823
+ Done.
2824
+ `;
2825
+ const { squiffyApi, element } = await initScript(script);
2826
+ expect(squiffyApi.get("weapon")).toBe("sword");
2827
+ expect(squiffyApi.get("best")).toBe(3);
2828
+ expect(squiffyApi.get("gold")).toBe("gold + price");
2829
+ await squiffyApi.clickLink(findLink(element, "section", "Go"));
2830
+ expect(squiffyApi.get("name")).toBe("Bob's");
2831
+ expect(squiffyApi.get("message")).toBe("Hi");
2832
+ expect(squiffyApi.get("there")).toBe(true);
2833
+ });
2834
+
2835
+ test("a converted story runs the same with expressions as it did without (#373)", async () => {
2836
+ const script = `
2837
+ [[start]]:
2838
+ @set weapon = sword
2839
+ @set greeting = Hello there
2840
+ @set name = Bob's
2841
+ @set quoted = say "hi"
2842
+ @set gold = 10
2843
+ @set price = 3
2844
+ @set half = 0.5
2845
+ @set big = 1e3
2846
+ @set flag = true
2847
+ @set off = false
2848
+ @set best = @gold
2849
+ @set gold += @price
2850
+ @set gold -= 1
2851
+ @set gold *= 2
2852
+ @inc count
2853
+ @inc count 4
2854
+ @dec count
2855
+ @set has_key
2856
+ @set not has_map
2857
+ @set hello := Hi, {{name}}
2858
+ [[Shop]](shop, item = sword and shield, gold -= @price, visited, msg = Hi, there)
2859
+
2860
+ [[shop]]:
2861
+ {{section "end" text="End" set="title = The End, done, final = @gold"}}
2862
+
2863
+ [[end]]:
2864
+ The end.
2865
+ `;
2866
+ const run = async (text: string, expressions: boolean) => {
2867
+ const { squiffyApi, element } = await initScript(text, expressions);
2868
+ await squiffyApi.clickLink(findLink(element, "section", "Shop"));
2869
+ await squiffyApi.clickLink(findLink(element, "section", "End"));
2870
+ const names = ["weapon", "greeting", "name", "quoted", "gold", "price", "half", "big", "flag", "off", "best",
2871
+ "count", "has_key", "has_map", "hello", "item", "visited", "msg", "there", "title", "done", "final"];
2872
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2873
+ return Object.fromEntries(names.map(name => [name, squiffyApi.get(name)]));
2874
+ };
2875
+
2876
+ const before = await run(script, false);
2877
+ const converted = convertSetters(script);
2878
+ expect(converted.problems).toEqual([]);
2879
+ expect(converted.converted).toBeGreaterThan(5);
2880
+ const after = await run(converted.script, true);
2881
+ expect(after).toEqual(before);
2882
+ expect(before).toMatchObject({ weapon: "sword", quoted: "say \"hi\"", gold: 21, best: 10, item: "sword and shield", msg: "Hi", there: true, final: 21 });
2883
+ });
2884
+
2885
+ // State modification helper tests
2886
+ test("{{set}} helper sets attribute value", async () => {
2887
+ const script = `
2888
+ [[start]]:
2889
+ {{set "score" 100}}
2890
+ Score is {{score}}.
2891
+ `;
2892
+
2893
+ const { squiffyApi } = await initScript(script);
2894
+ expect(squiffyApi.get("score")).toBe(100);
2895
+ });
2896
+
2897
+ test("{{set}} helper with string value", async () => {
1757
2898
  const script = `
1758
2899
  [[start]]:
1759
2900
  {{set "name" "Alice"}}
@@ -2415,6 +3556,139 @@ Level: <select data-attribute="level" required>
2415
3556
  expect(getSectionContent(element, "Continue")).toContain("Hero at level 1");
2416
3557
  });
2417
3558
 
3559
+ // Presses Enter in a text box, and waits for the story to go on
3560
+ const pressEnter = async (input: HTMLElement) => {
3561
+ input.dispatchEvent(new window.KeyboardEvent("keypress", { key: "Enter", bubbles: true, cancelable: true }));
3562
+ await new Promise(resolve => setTimeout(resolve, 0));
3563
+ };
3564
+
3565
+ test("A text box with data-section goes to the section when Enter is pressed", async () => {
3566
+ // https://github.com/textadventures/squiffy/issues/454
3567
+ const script = `
3568
+ [[start]]:
3569
+ What's your name? <input type="text" data-attribute="name" data-section="greet">
3570
+
3571
+ [[greet]]:
3572
+ Hello, {{name}}!
3573
+ `;
3574
+ const { squiffyApi, element } = await initScript(script);
3575
+ const input = element.querySelector("input") as HTMLInputElement;
3576
+ input.value = "Ann";
3577
+ await pressEnter(input);
3578
+
3579
+ expect(squiffyApi.get("_section")).toBe("greet");
3580
+ expect(getSectionContent(element, "greet")).toContain("Hello, Ann!");
3581
+ expect(squiffyApi.get("turns")).toBe(1);
3582
+ expect(input.disabled).toBe(true);
3583
+
3584
+ squiffyApi.goBack();
3585
+ expect(squiffyApi.get("_section")).toBe("start");
3586
+ expect(squiffyApi.get("name")).toBe(null);
3587
+ expect(input.disabled).toBe(false);
3588
+ });
3589
+
3590
+ test("A text box with data-passage shows the passage when Enter is pressed, once", async () => {
3591
+ // https://github.com/textadventures/squiffy/issues/454
3592
+ const script = `
3593
+ [[start]]:
3594
+ What's your name? <input type="text" data-attribute="name" data-passage="greet">
3595
+
3596
+ [greet]:
3597
+ Hello, {{name}}!
3598
+ `;
3599
+ const { squiffyApi, element } = await initScript(script);
3600
+ const input = element.querySelector("input") as HTMLInputElement;
3601
+ input.value = "Ann";
3602
+ await pressEnter(input);
3603
+
3604
+ expect(getPassageContent(element, "start", "greet")).toContain("Hello, Ann!");
3605
+ expect(input.disabled).toBe(true);
3606
+ await pressEnter(input);
3607
+ expect(element.querySelectorAll(".squiffy-output-passage").length).toBe(1);
3608
+
3609
+ squiffyApi.goBack();
3610
+ expect(element.querySelectorAll(".squiffy-output-passage").length).toBe(0);
3611
+ expect(input.disabled).toBe(false);
3612
+ expect(squiffyApi.get("name")).toBe(null);
3613
+ });
3614
+
3615
+ test("A text box going to a @repeat passage can be used again", async () => {
3616
+ // https://github.com/textadventures/squiffy/issues/454
3617
+ const script = `
3618
+ [[start]]:
3619
+ Guess: <input type="text" data-attribute="guess" data-passage="check">
3620
+
3621
+ [check]:
3622
+ @repeat
3623
+ You guessed {{guess}}.
3624
+ `;
3625
+ const { element } = await initScript(script);
3626
+ const input = element.querySelector("input") as HTMLInputElement;
3627
+ input.value = "1";
3628
+ await pressEnter(input);
3629
+ input.value = "2";
3630
+ await pressEnter(input);
3631
+
3632
+ expect(input.disabled).toBe(false);
3633
+ expect(element.textContent).toContain("You guessed 1.");
3634
+ expect(element.textContent).toContain("You guessed 2.");
3635
+ });
3636
+
3637
+ test("Enter does nothing until the text boxes are filled in properly", async () => {
3638
+ // https://github.com/textadventures/squiffy/issues/454
3639
+ const script = `
3640
+ [[start]]:
3641
+ <input type="text" data-attribute="name" data-section="greet" required>
3642
+
3643
+ [[greet]]:
3644
+ Hello, {{name}}!
3645
+ `;
3646
+ const { squiffyApi, element } = await initScript(script);
3647
+ const input = element.querySelector("input") as HTMLInputElement;
3648
+ await pressEnter(input);
3649
+ expect(squiffyApi.get("_section")).toBe("start");
3650
+ expect(input.classList.contains("squiffy-invalid")).toBe(true);
3651
+
3652
+ input.value = "Ann";
3653
+ await pressEnter(input);
3654
+ expect(squiffyApi.get("_section")).toBe("greet");
3655
+ });
3656
+
3657
+ test("Enter in a text box without data-section or data-passage does nothing", async () => {
3658
+ const script = `
3659
+ [[start]]:
3660
+ <input type="text" data-attribute="name">
3661
+
3662
+ [[greet]]:
3663
+ Hello.
3664
+ `;
3665
+ const { squiffyApi, element } = await initScript(script);
3666
+ await pressEnter(element.querySelector("input") as HTMLElement);
3667
+ expect(squiffyApi.get("_section")).toBe("start");
3668
+ });
3669
+
3670
+ test("A text box can set a value inside an object", async () => {
3671
+ // https://github.com/textadventures/squiffy/issues/454
3672
+ const script = `
3673
+ [[start]]:
3674
+ @set hero = { name: "", hp: 10 }
3675
+ <input type="text" data-attribute="hero.name" data-section="greet">
3676
+
3677
+ [[greet]]:
3678
+ Hello, {{hero.name}}! You have {{hero.hp}} HP.
3679
+ `;
3680
+ const { squiffyApi, element } = await initScript(script, true);
3681
+ const input = element.querySelector("input") as HTMLInputElement;
3682
+ input.value = "Ann";
3683
+ await pressEnter(input);
3684
+
3685
+ expect(squiffyApi.get("hero")).toEqual({ name: "Ann", hp: 10 });
3686
+ expect(getSectionContent(element, "greet")).toContain("Hello, Ann! You have 10 HP.");
3687
+
3688
+ squiffyApi.goBack();
3689
+ expect(squiffyApi.get("hero")).toEqual({ name: "", hp: 10 });
3690
+ });
3691
+
2418
3692
  // Array management helper tests
2419
3693
 
2420
3694
  test("{{append}} helper adds element to end of array", async () => {
@@ -2580,6 +3854,17 @@ Length is {{length "items"}}.
2580
3854
  expect(element.textContent).toContain("Length is 0.");
2581
3855
  });
2582
3856
 
3857
+ test("{{length}} helper counts the values in an object", async () => {
3858
+ const script = `
3859
+ [[start]]:
3860
+ @set endings = { good: true, bad: true }
3861
+ Found {{length "endings"}}, {{length endings}}{{#if (length "endings") = 2}}, all{{/if}}.
3862
+ `;
3863
+
3864
+ const { element } = await initScript(script, true);
3865
+ expect(element.textContent).toContain("Found 2, 2, all.");
3866
+ });
3867
+
2583
3868
  test("{{length}} helper returns 0 for non-existent variable", async () => {
2584
3869
  const script = `
2585
3870
  [[start]]:
@@ -2600,27 +3885,186 @@ Length is {{length (array "x" "y")}}.
2600
3885
  expect(element.textContent).toContain("Length is 2.");
2601
3886
  });
2602
3887
 
2603
- test("Array helpers work together for game round tracking", async () => {
3888
+ // {{#each}} loops
3889
+
3890
+ test("{{#each}} lists an array, with @index, @first and {{else}}", async () => {
2604
3891
  const script = `
2605
3892
  [[start]]:
2606
- {{set "rounds" (array "Round A" "Round B" "Round C")}}
2607
- {{set "played" (pop "rounds")}}
2608
- Played: {{played}}. Remaining: {{length "rounds"}}.
2609
- {{#if (gt (length "rounds") 0)}}More rounds available.{{else}}No more rounds.{{/if}}
3893
+ @set gold = 3
3894
+ {{set "inventory" (array "sword" "key" "lamp")}}
3895
+ {{set "empty" (array)}}
3896
+ A: {{#each inventory}}{{#unless @first}}, {{/unless}}{{@index}} {{this}}{{/each}}.
3897
+ B: {{#each empty}}{{this}}{{else}}nothing{{/each}}.
2610
3898
  `;
2611
3899
 
2612
- const { squiffyApi, element } = await initScript(script);
2613
- expect(squiffyApi.get("played")).toBe("Round A");
2614
- expect(squiffyApi.get("rounds")).toEqual(["Round B", "Round C"]);
2615
- expect(element.textContent).toContain("Played: Round A.");
2616
- expect(element.textContent).toContain("Remaining: 2.");
2617
- expect(element.textContent).toContain("More rounds available.");
3900
+ const { element } = await initScript(script);
3901
+ expect(element.textContent).toContain("A: 0 sword, 1 key, 2 lamp.");
3902
+ expect(element.textContent).toContain("B: nothing.");
2618
3903
  });
2619
3904
 
2620
- test("{{remove}} helper with value from subexpression", async () => {
3905
+ // {{#join}} as a block (#525)
3906
+
3907
+ test("{{#join}} shows its text for each item, with separators between them", async () => {
2621
3908
  const script = `
2622
3909
  [[start]]:
2623
- {{set "rounds" (array "General Knowledge" "Science" "Mystery")}}
3910
+ @set gold = 3
3911
+ @set bag = ["lamp", "key", "rope"]
3912
+ @set two = ["lamp", "key"]
3913
+ @set one = ["lamp"]
3914
+ @set empty = []
3915
+ A: {{#join bag ", " " and "}}the {{this}}{{/join}}.
3916
+ B: {{#join two ", " " and "}}the {{this}}{{/join}}.
3917
+ C: {{#join one ", " " and "}}the {{this}}{{/join}}.
3918
+ D: {{#join empty ", " " and "}}the {{this}}{{else}}nothing{{/join}}.
3919
+ E: {{#join empty}}the {{this}}{{/join}}.
3920
+ F: {{#join bag}}{{this}}{{/join}}.
3921
+ G: {{#join bag " / "}}{{@index}}{{#if @first}}F{{/if}}{{#if @last}}L{{/if}}{{/join}}.
3922
+ H: {{#join bag "; " as |item i|}}{{i}}={{item}}{{/join}}.
3923
+ I: {{#join two}}{{this}} {{gold}} {{../gold}}{{/join}}.
3924
+ J: {{#join bag " < " " & "}}{{this}}{{/join}}.
3925
+ K: {{join bag ", " " and "}}.
3926
+ `;
3927
+
3928
+ const { element } = await initScript(script, true);
3929
+ const text = element.textContent;
3930
+ expect(text).toContain("A: the lamp, the key and the rope.");
3931
+ expect(text).toContain("B: the lamp and the key.");
3932
+ expect(text).toContain("C: the lamp.");
3933
+ expect(text).toContain("D: nothing.");
3934
+ expect(text).toContain("E: .");
3935
+ expect(text).toContain("F: lamp, key, rope.");
3936
+ expect(text).toContain("G: 0F / 1 / 2L.");
3937
+ expect(text).toContain("H: 0=lamp; 1=key; 2=rope.");
3938
+ expect(text).toContain("I: lamp 3 3, key 3 3.");
3939
+ expect(text).toContain("J: lamp < key & rope.");
3940
+ expect(text).toContain("K: lamp, key and rope.");
3941
+ });
3942
+
3943
+ test("{{#join}} can list links, and items that are objects", async () => {
3944
+ const script = `
3945
+ [[start]]:
3946
+ @set ways = ["north", "south"]
3947
+ @set people = [{"who": "man", "as": "a man"}, {"who": "woman", "as": "a woman"}]
3948
+ I can see {{#join people ", " " and "}}{{passage this.who text=this.as}}{{/join}}.
3949
+
3950
+ Change to {{#join ways ", " " or "}}the [[{{this}}]](change, to = "{{this}}"){{/join}}.
3951
+
3952
+ [man]:
3953
+ He nods.
3954
+
3955
+ [woman]:
3956
+ She waves.
3957
+
3958
+ [[change]]:
3959
+ You go {{to}}.
3960
+ `;
3961
+
3962
+ const { squiffyApi, element } = await initScript(script, true);
3963
+ expect(element.textContent).toContain("I can see a man and a woman.");
3964
+ expect(element.textContent).toContain("Change to the north or the south.");
3965
+ await squiffyApi.clickLink(findLink(element, "passage", "a woman"));
3966
+ expect(element.textContent).toContain("She waves.");
3967
+ await squiffyApi.clickLink(findLink(element, "section", "south"));
3968
+ expect(element.textContent).toContain("You go south.");
3969
+ });
3970
+
3971
+ test("{{#join}} reports a value that isn't a list", async () => {
3972
+ const { element } = await initScript("[[start]]:\n{{#join \"bag\"}}{{this}}{{/join}}");
3973
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("\"join\" needs a list, but was given the text \"bag\"");
3974
+ });
3975
+
3976
+ test("Attributes can be read inside {{#each}}", async () => {
3977
+ const script = `
3978
+ [[start]]:
3979
+ @set gold = 3
3980
+ {{set "inventory" (array "sword" "key")}}
3981
+ A: {{#each inventory}}{{this}} {{gold}}; {{/each}}
3982
+ B: {{#each inventory}}{{../gold}}{{/each}}
3983
+ C: {{#each inventory}}{{#if gold > 2 and this = "key"}}yes{{/if}}{{/each}}
3984
+ D: {{#each inventory}}{{inc "gold"}}{{/each}}{{gold}}
3985
+ `;
3986
+
3987
+ const { element } = await initScript(script, true);
3988
+ expect(element.textContent).toContain("A: sword 3; key 3;");
3989
+ expect(element.textContent).toContain("B: 33");
3990
+ expect(element.textContent).toContain("C: yes");
3991
+ expect(element.textContent).toContain("D: 5");
3992
+ });
3993
+
3994
+ test("Links inside {{#each}} can use the item in their text and setters", async () => {
3995
+ const script = `
3996
+ [[start]]:
3997
+ @set gold = 3
3998
+ {{set "inventory" (array "sword" "key")}}
3999
+ {{#each inventory}}
4000
+ - [[Drop the {{this}}]](drop, item = "{{this}}", gold += 1)
4001
+ - [Look at the {{this}}](look, looking = "{{this}}")
4002
+ {{/each}}
4003
+
4004
+ [look]:
4005
+ You look at the {{looking}}.
4006
+
4007
+ [[drop]]:
4008
+ You dropped the {{item}}, and have {{gold}} gold.
4009
+ `;
4010
+
4011
+ const { squiffyApi, element } = await initScript(script, true);
4012
+ expect(findLink(element, "section", "Drop the sword")).toBeDefined();
4013
+
4014
+ await squiffyApi.clickLink(findLink(element, "passage", "Look at the sword"));
4015
+ expect(element.textContent).toContain("You look at the sword.");
4016
+
4017
+ await squiffyApi.clickLink(findLink(element, "section", "Drop the key"));
4018
+ expect(squiffyApi.get("item")).toBe("key");
4019
+ expect(element.textContent).toContain("You dropped the key, and have 4 gold.");
4020
+ });
4021
+
4022
+ test("A link's text can show an attribute", async () => {
4023
+ const script = `
4024
+ [[start]]:
4025
+ @set gold = 3
4026
+ [[Spend {{gold}} gold]](shop)
4027
+
4028
+ [[shop]]:
4029
+ Spent.
4030
+ `;
4031
+
4032
+ const { element } = await initScript(script, true);
4033
+ expect(findLink(element, "section", "Spend 3 gold")).toBeDefined();
4034
+ });
4035
+
4036
+ test("Names every object has, like valueOf, aren't attributes", async () => {
4037
+ const script = `
4038
+ [[start]]:
4039
+ {{#if constructor}}yes{{else}}no{{/if}}
4040
+ `;
4041
+
4042
+ const { squiffyApi, element } = await initScript(script);
4043
+ expect(element.textContent).toContain("no");
4044
+ expect(squiffyApi.get("valueOf")).toBeNull();
4045
+ });
4046
+
4047
+ test("Array helpers work together for game round tracking", async () => {
4048
+ const script = `
4049
+ [[start]]:
4050
+ {{set "rounds" (array "Round A" "Round B" "Round C")}}
4051
+ {{set "played" (pop "rounds")}}
4052
+ Played: {{played}}. Remaining: {{length "rounds"}}.
4053
+ {{#if (gt (length "rounds") 0)}}More rounds available.{{else}}No more rounds.{{/if}}
4054
+ `;
4055
+
4056
+ const { squiffyApi, element } = await initScript(script);
4057
+ expect(squiffyApi.get("played")).toBe("Round A");
4058
+ expect(squiffyApi.get("rounds")).toEqual(["Round B", "Round C"]);
4059
+ expect(element.textContent).toContain("Played: Round A.");
4060
+ expect(element.textContent).toContain("Remaining: 2.");
4061
+ expect(element.textContent).toContain("More rounds available.");
4062
+ });
4063
+
4064
+ test("{{remove}} helper with value from subexpression", async () => {
4065
+ const script = `
4066
+ [[start]]:
4067
+ {{set "rounds" (array "General Knowledge" "Science" "Mystery")}}
2624
4068
  {{set "current" "Science"}}
2625
4069
  {{remove "rounds" current}}
2626
4070
  Done.
@@ -2633,12 +4077,9 @@ Done.
2633
4077
  // Template error handling tests
2634
4078
 
2635
4079
  test("Template error displays error message instead of failing silently", async () => {
2636
- const script = `
2637
- [[start]]:
2638
- {{invalid * syntax}}
2639
- `;
4080
+ const script = "{{invalid * syntax}}";
2640
4081
 
2641
- const { element } = await initScript(script);
4082
+ const { element } = await initBrokenText(script);
2642
4083
 
2643
4084
  // Should display an error message
2644
4085
  const errorDiv = element.querySelector(".squiffy-error");
@@ -2647,12 +4088,9 @@ test("Template error displays error message instead of failing silently", async
2647
4088
  });
2648
4089
 
2649
4090
  test("Template error preserves monospace styling", async () => {
2650
- const script = `
2651
- [[start]]:
2652
- {{broken (expression}}
2653
- `;
4091
+ const script = "{{broken (expression}}";
2654
4092
 
2655
- const { element } = await initScript(script);
4093
+ const { element } = await initBrokenText(script);
2656
4094
 
2657
4095
  const errorDiv = element.querySelector(".squiffy-error") as HTMLElement;
2658
4096
  expect(errorDiv).not.toBeNull();
@@ -2691,12 +4129,9 @@ test("Infix expressions combine with existing helpers", async () => {
2691
4129
  });
2692
4130
 
2693
4131
  test("Malformed infix expression shows a template error", async () => {
2694
- const script = `
2695
- [[start]]:
2696
- {{#if score >}}Yes{{/if}}
2697
- `;
4132
+ const script = "{{#if score >}}Yes{{/if}}";
2698
4133
 
2699
- const { element } = await initScript(script);
4134
+ const { element } = await initBrokenText(script);
2700
4135
  const errorDiv = element.querySelector(".squiffy-error");
2701
4136
  expect(errorDiv?.textContent).toContain("Invalid condition \"score >\": expected a value after '>'");
2702
4137
  });
@@ -2717,3 +4152,1330 @@ test("Custom helpers can be registered in @ui", async () => {
2717
4152
  expect(section?.querySelector("b")?.textContent).toBe("world");
2718
4153
  expect(section?.querySelector("i")).toBeNull();
2719
4154
  });
4155
+
4156
+ // {{goto}} (#375)
4157
+
4158
+ test("{{goto}} goes to another section after showing this one", async () => {
4159
+ const script = `
4160
+ [[start]]:
4161
+ @set health = 1
4162
+ Start. [[fight]]
4163
+
4164
+ [[fight]]:
4165
+ @set health = 0
4166
+ You fight.
4167
+ {{#if health <= 0}}{{goto "death"}}{{else}}You win. [[win]]{{/if}}
4168
+
4169
+ [[death]]:
4170
+ You died.
4171
+
4172
+ [[win]]:
4173
+ Won.
4174
+ `;
4175
+ const { squiffyApi, element } = await initScript(script, true);
4176
+ await squiffyApi.clickLink(findLink(element, "section", "fight"));
4177
+
4178
+ expect(squiffyApi.get("_section")).toBe("death");
4179
+ expect(visibleText(element)).toBe("Start. fight You fight. You died.");
4180
+ expect(element.innerHTML).not.toContain("You win.");
4181
+ });
4182
+
4183
+ test("{{goto}} isn't followed when its {{#if}} is false", async () => {
4184
+ const script = `
4185
+ [[start]]:
4186
+ @set health = 5
4187
+ {{#if health <= 0}}{{goto "death"}}{{/if}}Alive.
4188
+
4189
+ [[death]]:
4190
+ You died.
4191
+ `;
4192
+ const { squiffyApi, element } = await initScript(script, true);
4193
+ expect(squiffyApi.get("_section")).toBe("start");
4194
+ expect(visibleText(element)).toBe("Alive.");
4195
+ });
4196
+
4197
+ test("{{goto}} in the start section", async () => {
4198
+ const { squiffyApi, element } = await initScript(`Intro.{{goto "next"}}
4199
+
4200
+ [[next]]:
4201
+ Next.`);
4202
+ expect(squiffyApi.get("_section")).toBe("next");
4203
+ expect(visibleText(element)).toBe("Intro. Next.");
4204
+ });
4205
+
4206
+ test("{{goto}} with an expression, e.g. to go somewhere at random", async () => {
4207
+ const script = `
4208
+ {{goto (random (array "a" "b"))}}
4209
+
4210
+ [[a]]:
4211
+ A.
4212
+
4213
+ [[b]]:
4214
+ B.
4215
+ `;
4216
+ const { squiffyApi } = await initScript(script);
4217
+ expect(["a", "b"]).toContain(squiffyApi.get("_section"));
4218
+ });
4219
+
4220
+ test("{{goto}} in a passage", async () => {
4221
+ const script = `
4222
+ [[start]]:
4223
+ Start. [open]
4224
+
4225
+ [open]:
4226
+ @set opened
4227
+ The door opens.{{goto "outside"}}
4228
+
4229
+ [[outside]]:
4230
+ Outside.
4231
+ `;
4232
+ const { squiffyApi, element } = await initScript(script);
4233
+ await squiffyApi.clickLink(findLink(element, "passage", "open"));
4234
+ expect(squiffyApi.get("_section")).toBe("outside");
4235
+ expect(visibleText(element)).toContain("The door opens. Outside.");
4236
+ expect(squiffyApi.get("opened")).toBe(true);
4237
+ });
4238
+
4239
+ test("Only the first {{goto}} counts", async () => {
4240
+ const script = `
4241
+ {{goto "a"}}{{goto "b"}}
4242
+
4243
+ [[a]]:
4244
+ A.
4245
+
4246
+ [[b]]:
4247
+ B.
4248
+ `;
4249
+ const { squiffyApi } = await initScript(script);
4250
+ expect(squiffyApi.get("_section")).toBe("a");
4251
+ });
4252
+
4253
+ test("{{goto}} to a section that doesn't exist shows an error", async () => {
4254
+ const { squiffyApi, element } = await initScript(`@set where = nowhere
4255
+ Start.{{goto where}}`);
4256
+ expect(squiffyApi.get("_section")).toBe("_default");
4257
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("there is no section called \"nowhere\"");
4258
+ });
4259
+
4260
+ test("A {{goto}} loop is stopped and reported", async () => {
4261
+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
4262
+ const script = `
4263
+ [[a]]:
4264
+ A.{{goto "b"}}
4265
+
4266
+ [[b]]:
4267
+ B.{{goto "a"}}
4268
+ `;
4269
+ const { element } = await initScript(script);
4270
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("Is there a loop?");
4271
+ expect(errors).toHaveBeenCalled();
4272
+ errors.mockRestore();
4273
+ });
4274
+
4275
+ test("Going back skips sections and passages that went somewhere else with {{goto}}", async () => {
4276
+ const script = `
4277
+ [[start]]:
4278
+ @set x = 1
4279
+ Start. [[jump]] [open]
4280
+
4281
+ [open]:
4282
+ @set x = 3
4283
+ Open.{{goto "end"}}
4284
+
4285
+ [[jump]]:
4286
+ @set x = 2
4287
+ Jump.{{goto "end"}}
4288
+
4289
+ [[end]]:
4290
+ End.
4291
+ `;
4292
+ const { squiffyApi, element } = await initScript(script);
4293
+ let canGoBack: boolean | undefined;
4294
+ squiffyApi.on("canGoBackChanged", e => canGoBack = e.canGoBack);
4295
+
4296
+ await squiffyApi.clickLink(findLink(element, "section", "jump"));
4297
+ expect(squiffyApi.get("_section")).toBe("end");
4298
+ expect(canGoBack).toBe(true);
4299
+
4300
+ squiffyApi.goBack();
4301
+ expect(squiffyApi.get("_section")).toBe("start");
4302
+ expect(squiffyApi.get("x")).toBe(1);
4303
+ expect(visibleText(element)).toBe("Start. jump open");
4304
+ expect(canGoBack).toBe(false);
4305
+
4306
+ await squiffyApi.clickLink(findLink(element, "passage", "open"));
4307
+ expect(squiffyApi.get("_section")).toBe("end");
4308
+ squiffyApi.goBack();
4309
+ expect(squiffyApi.get("_section")).toBe("start");
4310
+ expect(squiffyApi.get("x")).toBe(1);
4311
+ expect(findLink(element, "passage", "open", true)).toBeDefined();
4312
+ });
4313
+
4314
+ test("Can't go back if the only earlier section went somewhere else with {{goto}}", async () => {
4315
+ const { squiffyApi } = await initScript(`Intro.{{goto "next"}}
4316
+
4317
+ [[next]]:
4318
+ Next.`);
4319
+ let canGoBack = true;
4320
+ squiffyApi.on("canGoBackChanged", e => canGoBack = e.canGoBack);
4321
+ squiffyApi.goBack();
4322
+ expect(squiffyApi.get("_section")).toBe("next");
4323
+ expect(canGoBack).toBe(true); // unchanged: no event
4324
+ });
4325
+
4326
+ test("{{goto ... after=}} waits", async () => {
4327
+ vi.useFakeTimers();
4328
+ try {
4329
+ const script = `
4330
+ [[start]]:
4331
+ The lights go out.{{goto "darkness" after=3000}}
4332
+
4333
+ [[darkness]]:
4334
+ Darkness.
4335
+ `;
4336
+ const { squiffyApi, element } = await initScript(script);
4337
+ expect(squiffyApi.get("_section")).toBe("start");
4338
+ await vi.advanceTimersByTimeAsync(2999);
4339
+ expect(squiffyApi.get("_section")).toBe("start");
4340
+ await vi.advanceTimersByTimeAsync(1);
4341
+ expect(squiffyApi.get("_section")).toBe("darkness");
4342
+ expect(visibleText(element)).toBe("The lights go out. Darkness.");
4343
+ }
4344
+ finally {
4345
+ vi.useRealTimers();
4346
+ }
4347
+ });
4348
+
4349
+ test.each([
4350
+ ["after=(delay * 1000)", 2000],
4351
+ ["after=delay * 1000 + 500", 2500],
4352
+ ['after="1.5s"', 1500],
4353
+ ['after="250ms"', 250],
4354
+ ["after=time", 3000],
4355
+ ])("{{goto ... %s}} waits for a delay worked out as the story runs (#451)", async (after, ms) => {
4356
+ vi.useFakeTimers();
4357
+ try {
4358
+ const script = `
4359
+ [[start]]:
4360
+ @set delay = 2
4361
+ @set time = 3s
4362
+ Waiting.{{goto "later" ${after}}}
4363
+
4364
+ [[later]]:
4365
+ Later.
4366
+ `;
4367
+ const { squiffyApi } = await initScript(script);
4368
+ await vi.advanceTimersByTimeAsync(ms - 1);
4369
+ expect(squiffyApi.get("_section")).toBe("start");
4370
+ await vi.advanceTimersByTimeAsync(1);
4371
+ expect(squiffyApi.get("_section")).toBe("later");
4372
+ }
4373
+ finally {
4374
+ vi.useRealTimers();
4375
+ }
4376
+ });
4377
+
4378
+ test("{{goto ... after=}} with something that isn't a delay is an error", async () => {
4379
+ const { element } = await initScript("{{goto \"later\" after=\"soon\"}}\n\n[[later]]:\nLater.");
4380
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain('after="3s"');
4381
+ });
4382
+
4383
+ test("Following a link cancels a {{goto ... after=}}", async () => {
4384
+ vi.useFakeTimers();
4385
+ try {
4386
+ const script = `
4387
+ [[start]]:
4388
+ Quick! [[run]]{{goto "caught" after=3000}}
4389
+
4390
+ [[run]]:
4391
+ You got away.
4392
+
4393
+ [[caught]]:
4394
+ Caught.
4395
+ `;
4396
+ const { squiffyApi, element } = await initScript(script);
4397
+ await squiffyApi.clickLink(findLink(element, "section", "run"));
4398
+ await vi.advanceTimersByTimeAsync(5000);
4399
+ expect(squiffyApi.get("_section")).toBe("run");
4400
+ }
4401
+ finally {
4402
+ vi.useRealTimers();
4403
+ }
4404
+ });
4405
+
4406
+ test("Going back cancels a {{goto ... after=}}", async () => {
4407
+ vi.useFakeTimers();
4408
+ try {
4409
+ const script = `
4410
+ [[start]]:
4411
+ Start. [[wait]]
4412
+
4413
+ [[wait]]:
4414
+ Waiting.{{goto "later" after=3000}}
4415
+
4416
+ [[later]]:
4417
+ Later.
4418
+ `;
4419
+ const { squiffyApi, element } = await initScript(script);
4420
+ await squiffyApi.clickLink(findLink(element, "section", "wait"));
4421
+ squiffyApi.goBack();
4422
+ expect(squiffyApi.get("_section")).toBe("start");
4423
+ await vi.advanceTimersByTimeAsync(5000);
4424
+ expect(squiffyApi.get("_section")).toBe("start");
4425
+ }
4426
+ finally {
4427
+ vi.useRealTimers();
4428
+ }
4429
+ });
4430
+
4431
+ test("Loading a story saved during a {{goto ... after=}} carries on waiting", async () => {
4432
+ vi.useFakeTimers();
4433
+ try {
4434
+ const script = `
4435
+ [[start]]:
4436
+ Waiting.{{goto "later" after=3000}}
4437
+
4438
+ [[later]]:
4439
+ Later.
4440
+ `;
4441
+ const element = document.getElementById("squiffy")!;
4442
+ const { story } = await compile(script);
4443
+ const first = await init({ element, story });
4444
+ await first.begin();
4445
+ expect(first.get("_section")).toBe("start");
4446
+
4447
+ element.innerHTML = "";
4448
+ const second = await init({ element, story });
4449
+ await second.begin();
4450
+ expect(second.get("_section")).toBe("start");
4451
+ await vi.advanceTimersByTimeAsync(3000);
4452
+ expect(second.get("_section")).toBe("later");
4453
+ }
4454
+ finally {
4455
+ vi.useRealTimers();
4456
+ }
4457
+ });
4458
+
4459
+ test("{{goto}} in the master section, leaving out the section it goes to", async () => {
4460
+ const script = `
4461
+ [[]]:
4462
+ {{#if health <= 0 and not (at "death")}}{{goto "death"}}{{/if}}
4463
+
4464
+ [[start]]:
4465
+ @set health = 1
4466
+ Start. [[Fight]](fight, health -= 1)
4467
+
4468
+ [[fight]]:
4469
+ Ouch.
4470
+
4471
+ [[death]]:
4472
+ You died.
4473
+ `;
4474
+ const { squiffyApi, element } = await initScript(script, true);
4475
+ await squiffyApi.clickLink(findLink(element, "section", "Fight"));
4476
+ expect(squiffyApi.get("_section")).toBe("death");
4477
+ expect(element.querySelector(".squiffy-error")).toBeNull();
4478
+ });
4479
+
4480
+ // Visit counts and the story-wide turn count (#377)
4481
+
4482
+ test("{{visits}} counts visits to sections and passages", async () => {
4483
+ const script = `
4484
+ [[start]]:
4485
+ Start. [look] [[cave]]
4486
+
4487
+ [look]:
4488
+ You look. Looked {{visits "look"}} times.
4489
+
4490
+ [[cave]]:
4491
+ Cave visit {{visits "cave"}}. Start {{visits "start"}}, nowhere {{visits "nowhere"}}. [[start]]
4492
+ `;
4493
+ const { squiffyApi, element } = await initScript(script);
4494
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1 });
4495
+
4496
+ await squiffyApi.clickLink(findLink(element, "passage", "look"));
4497
+ expect(visibleText(element)).toContain("Looked 1 times.");
4498
+
4499
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
4500
+ expect(visibleText(element)).toContain("Cave visit 1. Start 1, nowhere 0.");
4501
+
4502
+ await squiffyApi.clickLink(findLink(element, "section", "start", true));
4503
+ await squiffyApi.clickLink(findLink(element, "passage", "look", true));
4504
+ expect(visibleText(element)).toContain("Looked 2 times.");
4505
+ await squiffyApi.clickLink(findLink(element, "section", "cave", true));
4506
+ expect(visibleText(element)).toContain("Cave visit 2. Start 2, nowhere 0.");
4507
+ });
4508
+
4509
+ test("{{lastvisited}} says how many turns ago a section or passage was visited (#540)", async () => {
4510
+ const script = `
4511
+ [[start]]:
4512
+ Start. [look] [[cave]]
4513
+
4514
+ [look]:
4515
+ You look.
4516
+
4517
+ [[cave]]:
4518
+ Cave {{lastvisited "cave"}}, start {{lastvisited "start"}}, look {{lastvisited "look"}}, lake {{lastvisited "lake"}}. [[lake]]
4519
+
4520
+ [[lake]]:
4521
+ Lake. Cave {{lastvisited "cave"}}. [[start]]
4522
+ `;
4523
+ const { squiffyApi, element } = await initScript(script);
4524
+ await squiffyApi.clickLink(findLink(element, "passage", "look"));
4525
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
4526
+ expect(visibleText(element)).toContain("Cave 0, start 2, look 1, lake -1.");
4527
+ await squiffyApi.clickLink(findLink(element, "section", "lake"));
4528
+ expect(visibleText(element)).toContain("Lake. Cave 1.");
4529
+ });
4530
+
4531
+ for (const expressions of [false, true]) {
4532
+ test(`{{visits}} works in conditions${expressions ? " in a story with a squiffy.json" : ""}`, async () => {
4533
+ const script = `
4534
+ [[start]]:
4535
+ [[cave]]
4536
+
4537
+ [[cave]]:
4538
+ {{#if (visits "cave") > 1}}Back again.{{else}}A new cave.{{/if}} [[start]]
4539
+ `;
4540
+ const { squiffyApi, element } = await initScript(script, expressions);
4541
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
4542
+ expect(visibleText(element)).toContain("A new cave.");
4543
+ await squiffyApi.clickLink(findLink(element, "section", "start", true));
4544
+ await squiffyApi.clickLink(findLink(element, "section", "cave", true));
4545
+ expect(visibleText(element)).toContain("Back again.");
4546
+ });
4547
+ }
4548
+
4549
+ test("squiffy.story.visits() in JS", async () => {
4550
+ // Note: the 4-space indent on the JS lines is the squiffy JS syntax - don't trim it!
4551
+ const script = `Click [a] then [check].
4552
+
4553
+ [a]:
4554
+ Passage a.
4555
+
4556
+ [check]:
4557
+ squiffy.set("visits_a", squiffy.story.visits("a"));
4558
+ squiffy.set("visits_b", squiffy.story.visits("b"));
4559
+ Checked.`;
4560
+ const { squiffyApi, element } = await initScript(script);
4561
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4562
+ await squiffyApi.clickLink(findLink(element, "passage", "check"));
4563
+ expect(squiffyApi.get("visits_a")).toBe(1);
4564
+ expect(squiffyApi.get("visits_b")).toBe(0);
4565
+ });
4566
+
4567
+ test("turns counts every section and passage link clicked, across sections", async () => {
4568
+ const script = `
4569
+ [[start]]:
4570
+ Turn {{turns}}. [a] [b] [[next]]
4571
+
4572
+ [a]:
4573
+ A at turn {{turns}}, section turn {{_turncount}}.
4574
+
4575
+ [b]:
4576
+ B.
4577
+
4578
+ [[next]]:
4579
+ Next at turn {{turns}}. [c]
4580
+
4581
+ [c]:
4582
+ C at turn {{turns}}, section turn {{_turncount}}.
4583
+ `;
4584
+ const { squiffyApi, element } = await initScript(script);
4585
+ expect(visibleText(element)).toContain("Turn 0.");
4586
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4587
+ expect(visibleText(element)).toContain("A at turn 1, section turn 1.");
4588
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
4589
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
4590
+ expect(visibleText(element)).toContain("Next at turn 3.");
4591
+ await squiffyApi.clickLink(findLink(element, "passage", "c"));
4592
+ expect(visibleText(element)).toContain("C at turn 4, section turn 1.");
4593
+ expect(squiffyApi.get("turns")).toBe(4);
4594
+ });
4595
+
4596
+ test("turns works in conditions", async () => {
4597
+ const script = `
4598
+ [[start]]:
4599
+ [a] [b] [c]
4600
+
4601
+ [a]:
4602
+ A.
4603
+
4604
+ [b]:
4605
+ B.
4606
+
4607
+ [c]:
4608
+ {{#if turns > 2}}Late.{{else}}Early.{{/if}}
4609
+ `;
4610
+ const { squiffyApi, element } = await initScript(script, true);
4611
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4612
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
4613
+ await squiffyApi.clickLink(findLink(element, "passage", "c"));
4614
+ expect(visibleText(element)).toContain("Late.");
4615
+ });
4616
+
4617
+ test("{{goto}} counts as a visit but not a turn", async () => {
4618
+ const script = `
4619
+ [[start]]:
4620
+ [[fight]]
4621
+
4622
+ [[fight]]:
4623
+ {{goto "death"}}
4624
+
4625
+ [[death]]:
4626
+ Died at turn {{turns}}, visit {{visits "death"}}.
4627
+ `;
4628
+ const { squiffyApi, element } = await initScript(script);
4629
+ await squiffyApi.clickLink(findLink(element, "section", "fight"));
4630
+ expect(squiffyApi.get("_section")).toBe("death");
4631
+ expect(visibleText(element)).toContain("Died at turn 1, visit 1.");
4632
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, fight: 1, death: 1 });
4633
+ });
4634
+
4635
+ test("Going back undoes visit counts and turns", async () => {
4636
+ const script = `
4637
+ [[start]]:
4638
+ [a] [[next]]
4639
+
4640
+ [a]:
4641
+ A.
4642
+
4643
+ [[next]]:
4644
+ Next.
4645
+ `;
4646
+ const { squiffyApi, element } = await initScript(script);
4647
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4648
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
4649
+ expect(squiffyApi.get("turns")).toBe(2);
4650
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, a: 1, next: 1 });
4651
+
4652
+ squiffyApi.goBack();
4653
+ expect(squiffyApi.get("turns")).toBe(1);
4654
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, a: 1 });
4655
+
4656
+ squiffyApi.goBack();
4657
+ expect(squiffyApi.get("turns")).toBe(0);
4658
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1 });
4659
+
4660
+ await squiffyApi.clickLink(findLink(element, "passage", "a", true));
4661
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, a: 1 });
4662
+ });
4663
+
4664
+ test("A save from before visit counts treats each seen section or passage as visited once", async () => {
4665
+ const script = `
4666
+ [[start]]:
4667
+ Start {{visits "start"}}, cave {{visits "cave"}}, lake {{visits "lake"}}, turns {{turns}}.
4668
+ `;
4669
+ const storyId = "00000000-0000-0000-0000-000000000000";
4670
+ localStorage[`${storyId}-_seen_sections`] = JSON.stringify(["start", "cave"]);
4671
+
4672
+ const element = document.getElementById("squiffy")!;
4673
+ const compileResult = await compile(script, "old-save.squiffy");
4674
+ const squiffyApi = await init({ element, story: compileResult.story, persist: true, storyId });
4675
+ await squiffyApi.begin();
4676
+
4677
+ // Going to start makes it the second visit
4678
+ expect(visibleText(element)).toContain("Start 2, cave 1, lake 0, turns 0.");
4679
+ expect(squiffyApi.get("_visits")).toEqual({ start: 2 });
4680
+
4681
+ localStorage.clear();
4682
+ });
4683
+
4684
+
4685
+ test("previous and previous_section say where the player was before (#56)", async () => {
4686
+ const script = `
4687
+ [[start]]:
4688
+ Start, previous "{{previous}}". [a] [b] [[cave]]
4689
+
4690
+ [a]:
4691
+ A after {{previous}}.
4692
+
4693
+ [b]:
4694
+ B after {{previous}}.
4695
+
4696
+ [[cave]]:
4697
+ Cave after {{previous}}, from section {{previous_section}}. [c]
4698
+
4699
+ [c]:
4700
+ C after {{previous}}, from section {{previous_section}}.
4701
+ `;
4702
+ const { squiffyApi, element } = await initScript(script);
4703
+ expect(visibleText(element)).toContain("Start, previous \"\".");
4704
+ expect(squiffyApi.get("previous")).toBeNull();
4705
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4706
+ expect(visibleText(element)).toContain("A after start.");
4707
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
4708
+ expect(visibleText(element)).toContain("B after a.");
4709
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
4710
+ expect(visibleText(element)).toContain("Cave after b, from section start.");
4711
+ await squiffyApi.clickLink(findLink(element, "passage", "c"));
4712
+ expect(visibleText(element)).toContain("C after cave, from section start.");
4713
+ });
4714
+
4715
+ test("previous works in conditions", async () => {
4716
+ const script = `
4717
+ [[start]]:
4718
+ [[river]] [[forest]]
4719
+
4720
+ [[river]]:
4721
+ [[cave]]
4722
+
4723
+ [[forest]]:
4724
+ [[cave]]
4725
+
4726
+ [[cave]]:
4727
+ {{#if previous_section = "river"}}You squeeze out of the water.{{else}}You step in from the trees.{{/if}}
4728
+ `;
4729
+ const { squiffyApi, element } = await initScript(script, true);
4730
+ await squiffyApi.clickLink(findLink(element, "section", "river"));
4731
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
4732
+ expect(visibleText(element)).toContain("You squeeze out of the water.");
4733
+ });
4734
+
4735
+ test("A section reached with {{goto}} has the section before it as previous", async () => {
4736
+ const script = `
4737
+ [[start]]:
4738
+ [[fight]]
4739
+
4740
+ [[fight]]:
4741
+ {{goto "death"}}
4742
+
4743
+ [[death]]:
4744
+ Died after {{previous}}.
4745
+ `;
4746
+ const { squiffyApi, element } = await initScript(script);
4747
+ await squiffyApi.clickLink(findLink(element, "section", "fight"));
4748
+ expect(visibleText(element)).toContain("Died after fight.");
4749
+ expect(squiffyApi.get("previous_section")).toBe("fight");
4750
+ });
4751
+
4752
+ test("Going back undoes previous and previous_section", async () => {
4753
+ const script = `
4754
+ [[start]]:
4755
+ [a] [[next]]
4756
+
4757
+ [a]:
4758
+ A.
4759
+
4760
+ [[next]]:
4761
+ Next.
4762
+ `;
4763
+ const { squiffyApi, element } = await initScript(script);
4764
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4765
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
4766
+ expect(squiffyApi.get("previous")).toBe("a");
4767
+ expect(squiffyApi.get("previous_section")).toBe("start");
4768
+
4769
+ squiffyApi.goBack();
4770
+ expect(squiffyApi.get("previous")).toBe("start");
4771
+ expect(squiffyApi.get("previous_section")).toBeNull();
4772
+
4773
+ squiffyApi.goBack();
4774
+ expect(squiffyApi.get("previous")).toBeNull();
4775
+ });
4776
+
4777
+ test("squiffy.ui.afterWrite runs once the text and its {{...}} are on the page", async () => {
4778
+ // https://github.com/textadventures/squiffy/issues/106
4779
+ // Note: the 4-space indent on the JS lines is the squiffy JS syntax - don't trim it!
4780
+ const script = `
4781
+ [[start]]:
4782
+ @set n = 5
4783
+ set("order", "before");
4784
+ squiffy.ui.afterWrite(() => {
4785
+ set("shown", document.getElementById("count").textContent);
4786
+ set("order", get("order") + ",after");
4787
+ });
4788
+ set("order", get("order") + ",js");
4789
+ Count: <span id="count">{{n}}</span> [a] [[next]]
4790
+
4791
+ [a]:
4792
+ squiffy.ui.afterWrite(() => set("passage_shown", document.getElementById("passage").textContent));
4793
+ <span id="passage">{{n}} again</span>
4794
+
4795
+ [[next]]:
4796
+ Next.
4797
+ `;
4798
+ const { squiffyApi, element } = await initScript(script);
4799
+ expect(squiffyApi.get("shown")).toBe("5");
4800
+ expect(squiffyApi.get("order")).toBe("before,js,after");
4801
+
4802
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
4803
+ expect(squiffyApi.get("passage_shown")).toBe("5 again");
4804
+
4805
+ // What an afterWrite function changes is part of the turn, so going back undoes it
4806
+ squiffyApi.goBack();
4807
+ expect(squiffyApi.get("passage_shown")).toBeNull();
4808
+ expect(squiffyApi.get("shown")).toBe("5");
4809
+ });
4810
+
4811
+ test("squiffy.story.go() in squiffy.ui.afterWrite goes there once the section has finished", async () => {
4812
+ // https://github.com/textadventures/squiffy/issues/106
4813
+ // Note: the 4-space indent on the JS lines is the squiffy JS syntax - don't trim it!
4814
+ const script = `
4815
+ [[start]]:
4816
+ @set x = 1
4817
+ Start. [[next]]
4818
+
4819
+ [[next]]:
4820
+ @set x = 2
4821
+ squiffy.ui.afterWrite(() => squiffy.story.go("other"));
4822
+ squiffy.ui.afterWrite(() => set("ran", true));
4823
+ Next.
4824
+
4825
+ [[other]]:
4826
+ @set x = 3
4827
+ Other.
4828
+ `;
4829
+ const { squiffyApi, element } = await initScript(script);
4830
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
4831
+ expect(squiffyApi.get("_section")).toBe("other");
4832
+ expect(squiffyApi.get("ran")).toBe(true);
4833
+ expect(visibleText(element)).toBe("Start. next Next. Other.");
4834
+
4835
+ // Going back steps back through both sections, as with {{goto}}
4836
+ squiffyApi.goBack();
4837
+ expect(squiffyApi.get("_section")).toBe("start");
4838
+ expect(squiffyApi.get("x")).toBe(1);
4839
+ expect(visibleText(element)).toBe("Start. next");
4840
+ });
4841
+
4842
+ // Number, text and conditional helpers (#446)
4843
+ test.each([
4844
+ ["{{set \"x\" (round 2.5)}}", 3],
4845
+ ["{{set \"x\" (round -2.5)}}", -2],
4846
+ ["{{set \"x\" (round 1.005 2)}}", 1.01],
4847
+ ["{{set \"x\" (round 1234 -2)}}", 1200],
4848
+ ["{{set \"x\" (round \"2.4\")}}", 2],
4849
+ ["{{set \"x\" (floor 2.7)}}", 2],
4850
+ ["{{set \"x\" (ceil 2.1)}}", 3],
4851
+ ["{{set \"x\" (abs -4)}}", 4],
4852
+ ["{{set \"x\" (min 3 1 2)}}", 1],
4853
+ ["{{set \"x\" (max 3 1 2)}}", 3],
4854
+ ["{{set \"x\" (max (array 4 9 2))}}", 9],
4855
+ ["{{set \"x\" (min 5)}}", 5],
4856
+ ["{{set \"x\" (upper \"Ann\")}}", "ANN"],
4857
+ ["{{set \"x\" (lower \"Ann\")}}", "ann"],
4858
+ ["{{set \"x\" (capitalise \"ann lee\")}}", "Ann lee"],
4859
+ ["{{set \"x\" (capitalize \"ann\")}}", "Ann"],
4860
+ ["{{set \"x\" (upper unsetattr)}}", ""],
4861
+ ["{{set \"x\" (upper 5)}}", "5"],
4862
+ ["{{set \"x\" (cond true \"a\" \"b\")}}", "a"],
4863
+ ["{{set \"x\" (cond 0 \"a\" \"b\")}}", "b"],
4864
+ ])("helper: %s", async (text, expected) => {
4865
+ const { squiffyApi } = await initScript(`[[start]]:\n${text}`);
4866
+ expect(squiffyApi.get("x")).toBe(expected);
4867
+ });
4868
+
4869
+ test.each([
4870
+ ["{{= (round \"a\")}}", "\"round\" needs numbers, but was given \"a\""],
4871
+ ["{{= (round 1 2 3)}}", "\"round\" needs one or two values, but was given 3"],
4872
+ ["{{= (floor 1 2)}}", "\"floor\" needs one value, but was given 2"],
4873
+ ["{{= (max)}}", "\"max\" needs at least one value"],
4874
+ ["{{= (upper (array 1))}}", "\"upper\" needs text, but was given a list"],
4875
+ ["{{= (cond true 1)}}", "\"cond\" needs three values, but was given 2"],
4876
+ ])("helper error: %s", async (text, message) => {
4877
+ const { element } = await initScript(`[[start]]:\n${text}`);
4878
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain(message);
4879
+ });
4880
+
4881
+ // List helpers (#447)
4882
+ test.each([
4883
+ ["{{set \"x\" (join (array \"a\" \"b\" \"c\"))}}", "a, b, c"],
4884
+ ["{{set \"x\" (join (array \"a\" \"b\" \"c\") \" / \")}}", "a / b / c"],
4885
+ ["{{set \"x\" (join (array \"a\" \"b\" \"c\") \", \" \" and \")}}", "a, b and c"],
4886
+ ["{{set \"x\" (join (array \"a\" \"b\") \", \" \" and \")}}", "a and b"],
4887
+ ["{{set \"x\" (join (array \"a\") \", \" \" and \")}}", "a"],
4888
+ ["{{set \"x\" (join unsetattr)}}", ""],
4889
+ ["{{set \"x\" (join (array 1 2) \"\")}}", "12"],
4890
+ ["{{set \"x\" (sort (array \"pear\" \"Apple\" \"item 10\" \"item 2\" 10 2))}}", [2, 10, "Apple", "item 2", "item 10", "pear"]],
4891
+ ["{{set \"x\" (slice (array 1 2 3 4) 1 3)}}", [2, 3]],
4892
+ ["{{set \"x\" (slice (array 1 2 3 4) 1)}}", [2, 3, 4]],
4893
+ ["{{set \"x\" (slice (array 1 2 3 4) -2)}}", [3, 4]],
4894
+ ["{{set \"x\" (slice \"hello\" 1 3)}}", "el"],
4895
+ ["{{set \"x\" (first (array 1 2 3))}}", 1],
4896
+ ["{{set \"x\" (last (array 1 2 3))}}", 3],
4897
+ ["{{set \"x\" (first (array))}}", ""],
4898
+ ["{{set \"x\" (indexof (array \"a\" \"b\") \"b\")}}", 1],
4899
+ ["{{set \"x\" (indexof (array \"a\" \"b\") \"c\")}}", -1],
4900
+ ["{{set \"x\" (indexof \"hello\" \"l\")}}", 2],
4901
+ ["{{set \"x\" (count (array \"a\" \"b\" \"a\") \"a\")}}", 2],
4902
+ ["{{set \"x\" (count \"banana\" \"an\")}}", 2],
4903
+ ["{{set \"x\" (range 1 5)}}", [1, 2, 3, 4, 5]],
4904
+ ["{{set \"x\" (range 3 1)}}", [3, 2, 1]],
4905
+ ["{{set \"x\" (range 0 0)}}", [0]],
4906
+ ])("list helper: %s", async (text, expected) => {
4907
+ const { squiffyApi } = await initScript(`[[start]]:\n${text}`);
4908
+ expect(squiffyApi.get("x")).toEqual(expected);
4909
+ });
4910
+
4911
+ test.each([
4912
+ ["{{= (sort \"bag\")}}", "\"sort\" needs a list, but was given the text \"bag\". To use an attribute's list, leave out the quotes"],
4913
+ ["{{= (sort 5)}}", "\"sort\" needs a list, but was given 5"],
4914
+ ["{{= (slice (array 1))}}", "\"slice\" needs 2 to 3 values, but was given 1"],
4915
+ ["{{= (range 1 100000)}}", "\"range\" can make a list of up to 10,000 numbers, but was asked for 100000"],
4916
+ ["{{= (join (array (array 1)))}}", "\"join\" needs text, but was given a list"],
4917
+ ])("list helper error: %s", async (text, message) => {
4918
+ const { element } = await initScript(`[[start]]:\n${text}`);
4919
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain(message);
4920
+ });
4921
+
4922
+ test("list helpers with attributes, in expressions and loops (#447)", async () => {
4923
+ const script = `
4924
+ [[start]]:
4925
+ @set bag = ["rope", "lamp", "key"]
4926
+ @set i = 1
4927
+ @set n = 3
4928
+ @set bag = (sort bag)
4929
+ @set mixed = (shuffle bag)
4930
+ You have {{join bag ", " " and "}}. First: {{first bag}}. Last: {{last bag}}. Item {{= i}}: {{= bag[i]}}.
4931
+ {{#each (range 1 3)}}n{{this}} {{/each}}
4932
+ {{#if (indexof bag "lamp") = 1}}Lamp second.{{/if}}
4933
+ {{#if (count bag "rope") > 0}}Has rope.{{/if}}
4934
+ Two: {{join (slice bag 0 2)}}.
4935
+ Down: {{#each (range 0 (n - 1))}}n{{this}} {{/each}}. Second last: {{= bag[bag.length - 2]}}.
4936
+ `;
4937
+ const { squiffyApi, element } = await initScript(script, true);
4938
+ expect(squiffyApi.get("bag")).toEqual(["key", "lamp", "rope"]);
4939
+ expect([...squiffyApi.get("mixed")].sort()).toEqual(["key", "lamp", "rope"]);
4940
+ expect(element.textContent).toContain("You have key, lamp and rope. First: key. Last: rope. Item 1: lamp.");
4941
+ expect(element.textContent).toContain("n1 n2 n3");
4942
+ expect(element.textContent).toContain("Lamp second.");
4943
+ expect(element.textContent).toContain("Has rope.");
4944
+ expect(element.textContent).toContain("Two: key, lamp.");
4945
+ expect(element.textContent).toContain("Down: n0 n1 n2 . Second last: lamp.");
4946
+ });
4947
+
4948
+ // An attribute can have a helper's name: {{count}} on its own shows it, rather than calling
4949
+ // the helper with no values (#447)
4950
+ test.each(["count", "first", "min", "round", "upper", "cond"])("an attribute called %s", async (name) => {
4951
+ const { element } = await initScript(`[[start]]:\n@set ${name} = 3\nIt's {{${name}}}, then {{= ${name} + 1}}.`, true);
4952
+ expect(element.textContent).toContain("It's 3, then 4.");
4953
+ });
4954
+
4955
+ test("contains, ? : and the new helpers in expressions (#446)", async () => {
4956
+ const script = `
4957
+ [[start]]:
4958
+ @set name = "Robin"
4959
+ @set hp = 0
4960
+ @set gold = 10
4961
+ @set bag = ["lamp", "key"]
4962
+ @set hero = { hp: 3 }
4963
+ {{set "status" hp > 0 ? "alive" : "dead"}}
4964
+ {{set "share" (round (gold / 3) 2)}}
4965
+ {{set "shout" (upper name) + "!"}}
4966
+ {{#if bag contains "key"}}Key.{{/if}}
4967
+ {{#if not bag contains "rope"}}No rope.{{/if}}
4968
+ {{#if name contains "ob"}}Ob.{{/if}}
4969
+ {{#if hero contains "hp"}}Has hp.{{/if}}
4970
+ {{#if unsetattr contains "x"}}Wrong.{{/if}}
4971
+ {{#if (contains "bag" "lamp")}}Lamp.{{/if}}
4972
+ Letters: {{= name.length}}. Items: {{= bag.length}}. {{= gold > 5 ? "Rich" : "Poor"}}.
4973
+ Lower: {{= (lower name)["length"]}}. Abs: {{= (abs (-gold))}}. Max: {{max gold 3}}.
4974
+ `;
4975
+ const { squiffyApi, element } = await initScript(script, true);
4976
+ expect(squiffyApi.get("status")).toBe("dead");
4977
+ expect(squiffyApi.get("share")).toBe(3.33);
4978
+ expect(squiffyApi.get("shout")).toBe("ROBIN!");
4979
+ expect(element.textContent).toContain("Key.");
4980
+ expect(element.textContent).toContain("No rope.");
4981
+ expect(element.textContent).toContain("Ob.");
4982
+ expect(element.textContent).toContain("Has hp.");
4983
+ expect(element.textContent).not.toContain("Wrong.");
4984
+ expect(element.textContent).toContain("Lamp.");
4985
+ expect(element.textContent).toContain("Letters: 5. Items: 2. Rich.");
4986
+ expect(element.textContent).toContain("Lower: 5. Abs: 10. Max: 10.");
4987
+ });
4988
+
4989
+ // {{#every}} (#451)
4990
+ describe("{{#every}}", () => {
4991
+ beforeEach(() => {
4992
+ vi.useFakeTimers();
4993
+ });
4994
+ afterEach(() => {
4995
+ vi.useRealTimers();
4996
+ });
4997
+
4998
+ const everyText = (element: HTMLElement) =>
4999
+ [...element.querySelectorAll(".squiffy-every")].map(el => el.textContent);
5000
+
5001
+ test("shows its text again every so often, replacing what it showed before", async () => {
5002
+ const { squiffyApi, element } = await initScript("@set n = 0\nTicks: {{#every 1000}}{{inc \"n\"}}{{n}}{{/every}}", true);
5003
+ expect(everyText(element)).toEqual([""]);
5004
+ await vi.advanceTimersByTimeAsync(999);
5005
+ expect(everyText(element)).toEqual([""]);
5006
+ await vi.advanceTimersByTimeAsync(1);
5007
+ expect(everyText(element)).toEqual(["1"]);
5008
+ await vi.advanceTimersByTimeAsync(2000);
5009
+ expect(everyText(element)).toEqual(["3"]);
5010
+ expect(squiffyApi.get("n")).toBe(3);
5011
+ });
5012
+
5013
+ test("scrolls down to the new text once its first tick has filled it in", async () => {
5014
+ // The page is too short, when the section is written, to scroll down to where its text
5015
+ // starts, as the {{#every}} is empty until it ticks. Then it's taller.
5016
+ const { squiffyApi, element } = await initScript("[[start]]:\nStart. [[next]]\n\n[[next]]:\n{{#every 100 times=1}}\n\nA big box.\n\n{{/every}}", true);
5017
+ let pageHeight = 900;
5018
+ Object.defineProperty(window.HTMLElement.prototype, "scrollHeight", { configurable: true, get: () => 1000 });
5019
+ Object.defineProperty(document.documentElement, "scrollHeight", { configurable: true, get: () => pageHeight });
5020
+ Object.defineProperty(document.documentElement, "scrollTop", { configurable: true, get: () => 0 });
5021
+ const scrollTo = vi.fn();
5022
+ window.scrollTo = scrollTo;
5023
+
5024
+ try {
5025
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
5026
+ expect(scrollTo).toHaveBeenLastCalledWith({ top: 900 - window.innerHeight, behavior: "smooth" });
5027
+
5028
+ pageHeight = 2000;
5029
+ await vi.advanceTimersByTimeAsync(100);
5030
+ expect(scrollTo).toHaveBeenLastCalledWith({ top: 1000, behavior: "smooth" });
5031
+ }
5032
+ finally {
5033
+ delete (window.HTMLElement.prototype as any).scrollHeight;
5034
+ }
5035
+ });
5036
+
5037
+ test("append=true adds to what it showed, and times= stops it", async () => {
5038
+ const { element } = await initScript("{{#every 500 append=true times=3}}Drip. {{/every}}", true);
5039
+ await vi.advanceTimersByTimeAsync(5000);
5040
+ expect(everyText(element)).toEqual(["Drip. Drip. Drip. "]);
5041
+ expect(element.querySelector(".squiffy-every")!.hasAttribute("data-every-stopped")).toBe(true);
5042
+ });
5043
+
5044
+ test("{{stop}} and {{goto}} in its text", async () => {
5045
+ const script = `
5046
+ [[start]]:
5047
+ @set fuse = 3
5048
+ {{#every 1000}}{{dec "fuse"}}{{fuse}}...{{#if fuse <= 0}}{{stop}}{{goto "boom"}}{{/if}}{{/every}}
5049
+
5050
+ [[boom]]:
5051
+ BOOM.
5052
+ `;
5053
+ const { squiffyApi, element } = await initScript(script, true);
5054
+ await vi.advanceTimersByTimeAsync(2000);
5055
+ expect(squiffyApi.get("_section")).toBe("start");
5056
+ expect(everyText(element)).toEqual(["1..."]);
5057
+ await vi.advanceTimersByTimeAsync(1000);
5058
+ expect(squiffyApi.get("_section")).toBe("boom");
5059
+ expect(visibleText(element)).toBe("0... BOOM.");
5060
+ await vi.advanceTimersByTimeAsync(5000);
5061
+ expect(squiffyApi.get("fuse")).toBe(0);
5062
+ });
5063
+
5064
+ test.each([
5065
+ ["delay * 100", 1000],
5066
+ ["\"1.5s\"", 1500],
5067
+ ["(delay * 100)", 1000],
5068
+ ])("{{#every %s}} works out its delay as the story runs", async (delay, ms) => {
5069
+ const { element } = await initScript(`@set delay = 10\n{{#every ${delay}}}Tick.{{/every}}`, true);
5070
+ await vi.advanceTimersByTimeAsync(ms - 1);
5071
+ expect(everyText(element)).toEqual([""]);
5072
+ await vi.advanceTimersByTimeAsync(1);
5073
+ expect(everyText(element)).toEqual(["Tick."]);
5074
+ });
5075
+
5076
+ test("text with paragraphs is a block", async () => {
5077
+ const { element } = await initScript("{{#every 1000 times=1}}\n\nOne.\n\nTwo.\n\n{{/every}}", true);
5078
+ await vi.advanceTimersByTimeAsync(1000);
5079
+ const every = element.querySelector(".squiffy-every")!;
5080
+ expect(every.tagName).toBe("DIV");
5081
+ expect(every.querySelectorAll("p").length).toBe(2);
5082
+ });
5083
+
5084
+ test("nested {{#every}}s each keep their own text", async () => {
5085
+ const { element } = await initScript("{{#every 1000 times=1}}Outer {{#every 500 times=2}}inner{{/every}}{{/every}}", true);
5086
+ await vi.advanceTimersByTimeAsync(1000);
5087
+ expect(everyText(element)).toEqual(["Outer ", ""]);
5088
+ await vi.advanceTimersByTimeAsync(500);
5089
+ expect(everyText(element)).toEqual(["Outer inner", "inner"]);
5090
+ });
5091
+
5092
+ test("keeps going when a passage is shown, and stops when the player leaves the section", async () => {
5093
+ const script = `
5094
+ [[start]]:
5095
+ @set n = 0
5096
+ {{#every 1000}}{{inc "n"}}{{/every}} [Look] [[Leave]](away)
5097
+
5098
+ [Look]:
5099
+ You look.
5100
+
5101
+ [[away]]:
5102
+ Away.
5103
+ `;
5104
+ const { squiffyApi, element } = await initScript(script, true);
5105
+ await vi.advanceTimersByTimeAsync(1500);
5106
+ await squiffyApi.clickLink(findLink(element, "passage", "Look"));
5107
+ await vi.advanceTimersByTimeAsync(1500);
5108
+ expect(squiffyApi.get("n")).toBe(3);
5109
+ await squiffyApi.clickLink(findLink(element, "section", "Leave"));
5110
+ await vi.advanceTimersByTimeAsync(5000);
5111
+ expect(squiffyApi.get("n")).toBe(3);
5112
+ });
5113
+
5114
+ test("going back undoes what its text changed", async () => {
5115
+ const script = `
5116
+ [[start]]:
5117
+ @set n = 0
5118
+ [[Next]](next)
5119
+
5120
+ [[next]]:
5121
+ {{#every 1000}}{{inc "n"}}{{n}}{{/every}}
5122
+ `;
5123
+ const { squiffyApi, element } = await initScript(script, true);
5124
+ await squiffyApi.clickLink(findLink(element, "section", "Next"));
5125
+ await vi.advanceTimersByTimeAsync(3000);
5126
+ expect(squiffyApi.get("n")).toBe(3);
5127
+ squiffyApi.goBack();
5128
+ expect(squiffyApi.get("n")).toBe(0);
5129
+ await vi.advanceTimersByTimeAsync(3000);
5130
+ expect(squiffyApi.get("n")).toBe(0);
5131
+ });
5132
+
5133
+ test("going back from a passage undoes the ticks since, and carries on", async () => {
5134
+ const script = `
5135
+ [[start]]:
5136
+ @set n = 0
5137
+ {{#every 1000}}{{inc "n"}}{{/every}} [Look]
5138
+
5139
+ [Look]:
5140
+ You look.
5141
+ `;
5142
+ const { squiffyApi, element } = await initScript(script, true);
5143
+ await vi.advanceTimersByTimeAsync(2000);
5144
+ await squiffyApi.clickLink(findLink(element, "passage", "Look"));
5145
+ await vi.advanceTimersByTimeAsync(3000);
5146
+ expect(squiffyApi.get("n")).toBe(5);
5147
+ squiffyApi.goBack();
5148
+ expect(squiffyApi.get("n")).toBe(2);
5149
+ await vi.advanceTimersByTimeAsync(1000);
5150
+ expect(squiffyApi.get("n")).toBe(3);
5151
+ });
5152
+
5153
+ test("a saved game carries on", async () => {
5154
+ const script = "@set n = 0\n{{#every 1000}}{{inc \"n\"}}{{n}}{{/every}}";
5155
+ const element = document.getElementById("squiffy")!;
5156
+ const { story } = await compile(script, undefined, true);
5157
+ const first = await init({ element, story });
5158
+ await first.begin();
5159
+ await vi.advanceTimersByTimeAsync(2000);
5160
+ first.dispose();
5161
+
5162
+ element.innerHTML = "";
5163
+ const second = await init({ element, story });
5164
+ await second.begin();
5165
+ expect(everyText(element)).toEqual(["2"]);
5166
+ await vi.advanceTimersByTimeAsync(1000);
5167
+ expect(everyText(element)).toEqual(["3"]);
5168
+ expect(element.querySelector(".squiffy-every")!.getAttribute("data-every-count")).toBe("3");
5169
+ });
5170
+
5171
+ test("keeps going after the story is edited, and stops when it's disposed", async () => {
5172
+ const script = "@set n = 0\nTicks: {{#every 1000}}{{inc \"n\"}}{{/every}}";
5173
+ const { squiffyApi } = await initScript(script, true);
5174
+ await vi.advanceTimersByTimeAsync(1000);
5175
+ const updated = await compile(script.replace("Ticks", "Tocks"), undefined, true);
5176
+ squiffyApi.update(updated.story);
5177
+ await vi.advanceTimersByTimeAsync(1000);
5178
+ expect(squiffyApi.get("n")).toBe(2);
5179
+ squiffyApi.dispose();
5180
+ await vi.advanceTimersByTimeAsync(3000);
5181
+ expect(squiffyApi.get("n")).toBe(2);
5182
+ });
5183
+
5184
+ test.each([
5185
+ ["{{#every}}x{{/every}}", "how often"],
5186
+ ["{{#every 0}}x{{/every}}", "how often"],
5187
+ ["{{#every \"soon\"}}x{{/every}}", "not \"soon\""],
5188
+ ["{{#every 1000 times=0}}x{{/every}}", "times="],
5189
+ ])("%s is an error", async (script, message) => {
5190
+ const { element } = await initScript(script, true);
5191
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain(message);
5192
+ });
5193
+ });
5194
+
5195
+ describe('scroll: "element"', () => {
5196
+ // A story in a box 100px tall, whose text is 500px, as jsdom has no layout
5197
+ const boxedStory = (element: HTMLElement) => {
5198
+ element.style.overflowY = "auto";
5199
+ Object.defineProperty(element, "clientHeight", { value: 100 });
5200
+ Object.defineProperty(element, "scrollHeight", { value: 500 });
5201
+ const scrolls: ScrollToOptions[] = [];
5202
+ element.scrollTo = ((options: ScrollToOptions) => { scrolls.push(options); }) as typeof element.scrollTo;
5203
+ return scrolls;
5204
+ };
5205
+
5206
+ test("scrolls the story's own box, and not the page around it", async () => {
5207
+ const element = document.getElementById("squiffy")!;
5208
+ const scrolls = boxedStory(element);
5209
+ const scrollIntoView = vi.fn();
5210
+ window.Element.prototype.scrollIntoView = scrollIntoView;
5211
+ const windowScroll = vi.spyOn(window, "scrollTo").mockImplementation(() => {});
5212
+
5213
+ const { story } = await compile("[[start]]:\n[[Go on]](next)\n\n[[next]]:\nYou go on.\n\n[[Clear]](clear)\n\n[[clear]]:\n@clear\nA fresh page.");
5214
+ const squiffyApi = await init({ element, story, scroll: "element" });
5215
+ await squiffyApi.begin();
5216
+ scrolls.length = 0;
5217
+
5218
+ await squiffyApi.clickLink(findLink(element, "section", "Go on"));
5219
+ expect(scrolls.length).toBeGreaterThan(0);
5220
+
5221
+ scrolls.length = 0;
5222
+ await squiffyApi.clickLink(findLink(element, "section", "Clear"));
5223
+ expect(scrolls.length).toBeGreaterThan(0);
5224
+
5225
+ expect(scrollIntoView).not.toHaveBeenCalled();
5226
+ expect(windowScroll).not.toHaveBeenCalled();
5227
+ });
5228
+ });
5229
+
5230
+ // The CLI's --play carries on from a saved game without beginning the story first, and the
5231
+ // editor's preview begins at the section being edited
5232
+ const helperStory = `
5233
+ @ui
5234
+ window.uiRuns = (window.uiRuns || 0) + 1;
5235
+ squiffy.registerHelper("shout", (text) => text.toUpperCase() + "!");
5236
+ ---
5237
+
5238
+ {{shout "one"}} [[b]]
5239
+
5240
+ [[b]]:
5241
+ {{shout "two"}} [[c]] [more]
5242
+
5243
+ [more]:
5244
+ {{shout "more"}}
5245
+
5246
+ [[c]]:
5247
+ {{shout "three"}}
5248
+ `;
5249
+
5250
+ const initHelperStory = async () => {
5251
+ const compiled = await compile(helperStory);
5252
+ const element = document.getElementById("squiffy")!;
5253
+ element.innerHTML = "";
5254
+ const api = await init({ element, story: compiled.story, scroll: "element" });
5255
+ return { api, element };
5256
+ };
5257
+
5258
+ test("@ui has run when the story begins at another section", async () => {
5259
+ const { api, element } = await initHelperStory();
5260
+ await api.begin({ section: "b", passage: "more" });
5261
+ expect(element.textContent).toContain("TWO!");
5262
+ expect(element.textContent).toContain("MORE!");
5263
+ expect((window as any).uiRuns).toBe(1);
5264
+ });
5265
+
5266
+ test("@ui has run when a saved game is loaded before the story begins, and runs once", async () => {
5267
+ const first = await initHelperStory();
5268
+ await first.api.begin({ section: "b" });
5269
+ const save = JSON.parse(JSON.stringify(first.api.getSave()));
5270
+ expect((window as any).uiRuns).toBe(1);
5271
+
5272
+ const { api, element } = await initHelperStory();
5273
+ expect(await api.loadSave(save)).toEqual({ success: true });
5274
+ expect((window as any).uiRuns).toBe(2);
5275
+ await api.clickLink(element.querySelector<HTMLElement>("a.squiffy-link[data-section='c']")!);
5276
+ expect(element.textContent).toContain("THREE!");
5277
+ expect(element.querySelector(".squiffy-error")).toBeNull();
5278
+
5279
+ // Loading again doesn't run it again, but restarting does, as that resets the attributes
5280
+ await api.loadSave(save);
5281
+ expect((window as any).uiRuns).toBe(2);
5282
+ api.restart();
5283
+ await vi.waitFor(() => expect(element.textContent).toContain("ONE!"));
5284
+ expect((window as any).uiRuns).toBe(3);
5285
+ });
5286
+
5287
+ describe("{{#once}} and {{#firsttime}}", () => {
5288
+ const lastSection = (element: HTMLElement) =>
5289
+ element.querySelector(".squiffy-output-section:last-child")!.textContent!.trim().replace(/\s+/g, " ");
5290
+
5291
+ test("Shows its text the first time, and the {{else}} text after that", async () => {
5292
+ const script = `
5293
+ [[room]]:
5294
+ {{#once}}A bat flies out.{{else}}The cave is quiet.{{/once}} [[again]](room)
5295
+ `;
5296
+ const { squiffyApi, element } = await initScript(script);
5297
+ expect(lastSection(element)).toBe("A bat flies out. again");
5298
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5299
+ expect(lastSection(element)).toBe("The cave is quiet. again");
5300
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5301
+ expect(lastSection(element)).toBe("The cave is quiet. again");
5302
+ });
5303
+
5304
+ test("Shows nothing after the first time when there's no {{else}}", async () => {
5305
+ const script = `
5306
+ [[room]]:
5307
+ Dark.{{#once}} A bat flies out.{{/once}} [[again]](room)
5308
+ `;
5309
+ const { squiffyApi, element } = await initScript(script);
5310
+ expect(lastSection(element)).toBe("Dark. A bat flies out. again");
5311
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5312
+ expect(lastSection(element)).toBe("Dark. again");
5313
+ });
5314
+
5315
+ test("Each one remembers for itself", async () => {
5316
+ const script = `
5317
+ [[room]]:
5318
+ {{#if lit}}{{#once}}Light!{{else}}Lit.{{/once}}{{else}}{{#once}}Dark!{{else}}Unlit.{{/once}}{{/if}} [[again]](room) [[light]](room, lit = true)
5319
+ `;
5320
+ const { squiffyApi, element } = await initScript(script);
5321
+ expect(lastSection(element)).toBe("Dark! again light");
5322
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5323
+ expect(lastSection(element)).toBe("Unlit. again light");
5324
+ await squiffyApi.clickLink(findLink(element, "section", "light", true));
5325
+ expect(lastSection(element)).toBe("Light! again light");
5326
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5327
+ expect(lastSection(element)).toBe("Lit. again light");
5328
+ });
5329
+
5330
+ test("Remembers in embedded text, wherever it's embedded", async () => {
5331
+ const script = `
5332
+ [[one]]:
5333
+ {{embed "bell"}} [[two]]
5334
+
5335
+ [[two]]:
5336
+ {{embed "bell"}} [[one]]
5337
+
5338
+ [[bell]]:
5339
+ A bell rings.{{#once}} You've never heard it before.{{/once}}
5340
+ `;
5341
+ const { squiffyApi, element } = await initScript(script);
5342
+ expect(lastSection(element)).toBe("A bell rings. You've never heard it before. two");
5343
+ await squiffyApi.clickLink(findLink(element, "section", "two", true));
5344
+ expect(lastSection(element)).toBe("A bell rings. one");
5345
+ });
5346
+
5347
+ test("The same text in two passages is remembered separately", async () => {
5348
+ const script = `
5349
+ [[room]]:
5350
+ [a] [b]
5351
+
5352
+ [a]:
5353
+ A: {{#once}}new{{else}}old{{/once}}
5354
+
5355
+ [b]:
5356
+ B: {{#once}}new{{else}}old{{/once}}
5357
+ `;
5358
+ const { squiffyApi, element } = await initScript(script);
5359
+ await squiffyApi.clickLink(findLink(element, "passage", "a", true));
5360
+ await squiffyApi.clickLink(findLink(element, "passage", "b", true));
5361
+ expect(lastSection(element)).toBe("a bA: newB: new");
5362
+ });
5363
+
5364
+ test("Ones with the same name share their memory", async () => {
5365
+ const script = `
5366
+ [[one]]:
5367
+ {{#once "warning"}}Mind the gap.{{/once}} [[two]]
5368
+
5369
+ [[two]]:
5370
+ {{#once "warning"}}Mind the gap.{{else}}You mind it.{{/once}}
5371
+ `;
5372
+ const { squiffyApi, element } = await initScript(script);
5373
+ expect(lastSection(element)).toBe("Mind the gap. two");
5374
+ await squiffyApi.clickLink(findLink(element, "section", "two", true));
5375
+ expect(lastSection(element)).toBe("You mind it.");
5376
+ });
5377
+
5378
+ test("Going back undoes it", async () => {
5379
+ const script = `
5380
+ [[start]]:
5381
+ [[room]]
5382
+
5383
+ [[room]]:
5384
+ {{#once}}A bat flies out.{{else}}The cave is quiet.{{/once}}
5385
+ `;
5386
+ const { squiffyApi, element } = await initScript(script);
5387
+ await squiffyApi.clickLink(findLink(element, "section", "room", true));
5388
+ expect(lastSection(element)).toBe("A bat flies out.");
5389
+ squiffyApi.goBack();
5390
+ await squiffyApi.clickLink(findLink(element, "section", "room", true));
5391
+ expect(lastSection(element)).toBe("A bat flies out.");
5392
+ });
5393
+
5394
+ test("Helpers inside it only run the first time", async () => {
5395
+ const script = `
5396
+ [[room]]:
5397
+ {{#once}}{{inc "bats"}}{{/once}}Bats: {{bats}} [[again]](room)
5398
+ `;
5399
+ const { squiffyApi, element } = await initScript(script);
5400
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5401
+ expect(lastSection(element)).toBe("Bats: 1 again");
5402
+ });
5403
+
5404
+ test("firsttime is another name for it", async () => {
5405
+ const script = `
5406
+ [[room]]:
5407
+ {{#firsttime}}A bat flies out.{{else}}The cave is quiet.{{/firsttime}} [[again]](room)
5408
+ `;
5409
+ const { squiffyApi, element } = await initScript(script);
5410
+ expect(lastSection(element)).toBe("A bat flies out. again");
5411
+ await squiffyApi.clickLink(findLink(element, "section", "again", true));
5412
+ expect(lastSection(element)).toBe("The cave is quiet. again");
5413
+ });
5414
+ });
5415
+
5416
+ test("{{#animate}} around only a {{#label}}", async () => {
5417
+ const { element } = await initScript("{{#animate \"fadeIn\"}}{{#label \"x\"}}Hello{{/label}}{{/animate}}", true);
5418
+ expect(element.querySelector(".squiffy-error")).toBeNull();
5419
+ expect(element.querySelector(".squiffy-label-x")?.textContent).toBe("Hello");
5420
+ });
5421
+
5422
+ test("{{#animate}} inside a {{#replace}} is shown", async () => {
5423
+ const script = `
5424
+ [[start]]:
5425
+ {{#label "x"}}[Go](p){{/label}}
5426
+
5427
+ [p]:
5428
+ {{#replace "x"}}Replaced. {{#animate "fadeIn"}}Animated{{/animate}}{{/replace}}
5429
+ `;
5430
+ const { squiffyApi, element } = await initScript(script, true);
5431
+ await squiffyApi.clickLink(findLink(element, "passage", "Go"));
5432
+ const animate = element.querySelector<HTMLElement>(".squiffy-label-x [data-name]")!;
5433
+ expect(animate.textContent).toBe("Animated");
5434
+ }, 10000);
5435
+
5436
+ test("{{live}} with a section shows it again in the current section, and not in one the player has left", async () => {
5437
+ const script = `
5438
+ [[start]]:
5439
+ {{live "redo" section="shown"}} [Again] [[next]]
5440
+
5441
+ [Again]:
5442
+ {{inc "redo"}}
5443
+
5444
+ [[shown]]:
5445
+ Shown {{inc "count"}}{{count}}.
5446
+
5447
+ [[next]]:
5448
+ Next. [More]
5449
+
5450
+ [More]:
5451
+ {{inc "redo"}}
5452
+ `;
5453
+ const { squiffyApi, element } = await initScript(script, true);
5454
+ const live = () => element.querySelector<HTMLElement>(".squiffy-live")!;
5455
+ expect(live().textContent).toContain("Shown 1.");
5456
+ await squiffyApi.clickLink(findLink(element, "passage", "Again"));
5457
+ await new Promise(resolve => setTimeout(resolve, 2500));
5458
+ expect(live().textContent).toContain("Shown 2.");
5459
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
5460
+ await squiffyApi.clickLink(findLink(element, "passage", "More"));
5461
+ await new Promise(resolve => setTimeout(resolve, 2500));
5462
+ // Left as it was, without running its helpers again
5463
+ expect(live().textContent).toContain("Shown 2.");
5464
+ expect(squiffyApi.get("count")).toBe(2);
5465
+ }, 15000);
5466
+
5467
+ describe("{{#animate}} times", () => {
5468
+ test.each([
5469
+ ["\"1.5s\"", 1500],
5470
+ ["(nothing + \"s\")", undefined],
5471
+ ["\"soon\"", undefined],
5472
+ ])("start=%s", async (start, expected) => {
5473
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
5474
+ const { element } = await initScript(`{{#animate "fadeIn" start=${start}}}Hi{{/animate}}`, true);
5475
+ const animate = element.querySelector<HTMLElement>("[data-name]")!;
5476
+ // One that isn't a time is left out, so the text still appears, at once
5477
+ expect(animate.dataset.start).toBe(expected === undefined ? undefined : String(expected));
5478
+ expect(warn).toHaveBeenCalledTimes(expected === undefined ? 1 : 0);
5479
+ warn.mockRestore();
5480
+ });
5481
+ });