squiffy-runtime 7.0.0-beta.7 → 7.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/dist/confirmDialog.d.ts +8 -0
  2. package/dist/events.d.ts +10 -0
  3. package/dist/every.d.ts +12 -0
  4. package/dist/every.test.d.ts +1 -0
  5. package/dist/playerSettings.d.ts +17 -0
  6. package/dist/preview-html.js +1 -1
  7. package/dist/settings.test.d.ts +1 -0
  8. package/dist/settingsDialog.d.ts +17 -0
  9. package/dist/squiffy.page.css +4 -1
  10. package/dist/squiffy.preview.html +673 -83
  11. package/dist/squiffy.runtime.css +531 -1
  12. package/dist/squiffy.runtime.d.ts +5 -1
  13. package/dist/squiffy.runtime.global.js +106 -85
  14. package/dist/squiffy.runtime.global.js.map +1 -1
  15. package/dist/squiffy.runtime.js +4743 -4157
  16. package/dist/squiffy.runtime.js.map +1 -1
  17. package/dist/state.d.ts +1 -0
  18. package/dist/style.test.d.ts +1 -0
  19. package/dist/textProcessor.d.ts +8 -0
  20. package/dist/transitions.test.d.ts +1 -0
  21. package/dist/types.d.ts +43 -0
  22. package/dist/uiLinks.test.d.ts +1 -0
  23. package/dist/utils.d.ts +1 -0
  24. package/dist/utils.test.d.ts +1 -0
  25. package/package.json +3 -3
  26. package/src/animation.test.ts +44 -0
  27. package/src/animation.ts +7 -3
  28. package/src/confirmDialog.ts +66 -0
  29. package/src/events.ts +17 -0
  30. package/src/every.test.ts +25 -0
  31. package/src/every.ts +94 -0
  32. package/src/panels.test.ts +24 -0
  33. package/src/playerSettings.ts +128 -0
  34. package/src/plugins/animate.ts +9 -0
  35. package/src/plugins/live.ts +3 -1
  36. package/src/plugins/plugins.test.ts +17 -0
  37. package/src/preview.test.ts +53 -3
  38. package/src/preview.ts +60 -1
  39. package/src/settings.test.ts +233 -0
  40. package/src/settingsDialog.ts +160 -0
  41. package/src/squiffy.page.css +4 -1
  42. package/src/squiffy.runtime.css +531 -1
  43. package/src/squiffy.runtime.test.ts +613 -16
  44. package/src/squiffy.runtime.ts +372 -19
  45. package/src/state.ts +16 -1
  46. package/src/style.test.ts +89 -0
  47. package/src/textProcessor.ts +141 -6
  48. package/src/transitions.test.ts +302 -0
  49. package/src/types.ts +56 -0
  50. package/src/uiLinks.test.ts +156 -0
  51. package/src/utils.test.ts +60 -0
  52. package/src/utils.ts +44 -14
  53. package/dist/infixExpressions.d.ts +0 -7
  54. package/src/infixExpressions.test.ts +0 -516
  55. package/src/infixExpressions.ts +0 -672
  56. /package/dist/{infixExpressions.test.d.ts → animation.test.d.ts} +0 -0
package/src/state.ts CHANGED
@@ -1,6 +1,9 @@
1
1
  import { Emitter, SquiffyEventMap } from "./events.js";
2
2
  import { parsePath, valueAt, withValueAt } from "./paths.js";
3
3
 
4
+ // The attribute the story reads the player's settings from
5
+ const SETTINGS = "settings";
6
+
4
7
  export class State {
5
8
  persist: boolean;
6
9
  storyId: string;
@@ -25,6 +28,10 @@ export class State {
25
28
  return this.persist && window.localStorage && this.storyId;
26
29
  }
27
30
 
31
+ // The player's settings (#452), which the story reads as the attribute "settings", e.g.
32
+ // settings.textSize, or null if the story has none, when "settings" is an attribute like any other
33
+ playerSettings: () => Record<string, unknown> | null = () => null;
34
+
28
35
  // While this is true, set() does nothing: e.g. while a panel is rendered, so its {{set}}s
29
36
  // don't change the story
30
37
  readOnly = false;
@@ -40,6 +47,11 @@ export class State {
40
47
  setAt(segments: string[], value: any) {
41
48
  if (this.readOnly) return;
42
49
  const [attribute, ...inside] = segments;
50
+ // Only the player changes their settings, in the Settings dialog
51
+ if (attribute == SETTINGS && this.playerSettings()) {
52
+ console.warn("Squiffy: the story can't change the player's settings.");
53
+ return;
54
+ }
43
55
  if (!inside.length) {
44
56
  this.setInternal(attribute, value, true);
45
57
  return;
@@ -71,6 +83,7 @@ export class State {
71
83
 
72
84
  // Only the store's own properties are attributes, not ones it inherits, such as valueOf
73
85
  has(attribute: string) {
86
+ if (attribute == SETTINGS && this.playerSettings()) return true;
74
87
  return Object.prototype.hasOwnProperty.call(this.store, attribute);
75
88
  }
76
89
 
@@ -82,6 +95,8 @@ export class State {
82
95
  getAt(segments: string[]): any {
83
96
  const [attribute, ...inside] = segments;
84
97
  if (!this.has(attribute)) return null;
98
+ const settings = attribute == SETTINGS ? this.playerSettings() : null;
99
+ if (settings) return inside.length ? structuredClone(valueAt(settings, inside)) : { ...settings };
85
100
  const value = inside.length ? valueAt(this.store[attribute], inside) : this.store[attribute];
86
101
  return structuredClone(value);
87
102
  }
@@ -97,7 +112,7 @@ export class State {
97
112
  ? this.getAt([prop])
98
113
  : Reflect.get(target, prop),
99
114
  has: (_, prop) => this.has(String(prop)),
100
- ownKeys: () => Object.keys(this.store),
115
+ ownKeys: () => [...new Set([...Object.keys(this.store), ...(this.playerSettings() ? [SETTINGS] : [])])],
101
116
  getOwnPropertyDescriptor: (_, prop) => {
102
117
  const key = String(prop);
103
118
  if (this.has(key)) {
@@ -0,0 +1,89 @@
1
+ // {{#style}} (#453): gives some text a class, for the story's CSS or the built-in effects
2
+ import { expect, test, beforeEach, afterEach } from "vitest";
3
+ import globalJsdom from "global-jsdom";
4
+ import { init } from "./squiffy.runtime.js";
5
+ import { compile as squiffyCompile } from "squiffy-compiler";
6
+
7
+ let cleanup: () => void;
8
+
9
+ beforeEach(() => {
10
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
11
+ });
12
+
13
+ afterEach(() => {
14
+ localStorage.clear();
15
+ cleanup();
16
+ });
17
+
18
+ const start = async (script: string) => {
19
+ const result = await squiffyCompile({ script });
20
+ if (!result.success) throw new Error("Compile failed");
21
+ const story = {
22
+ ...result.output.story,
23
+ js: result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n"))) as any,
24
+ };
25
+ const element = document.getElementById("squiffy")!;
26
+ const api = await init({ element, story, persist: false, storyId: "test", scroll: "none" });
27
+ await api.begin();
28
+ return element;
29
+ };
30
+
31
+ test("{{#style}} wraps inline text in a span with the class", async () => {
32
+ const element = await start("A {{#style \"warning\"}}**loud** noise{{/style}} here.");
33
+ const span = element.querySelector(".squiffy-style")!;
34
+ expect(span.tagName).toBe("SPAN");
35
+ expect([...span.classList]).toEqual(["squiffy-style", "warning"]);
36
+ expect(span.innerHTML).toBe("<strong>loud</strong> noise");
37
+ expect(span.closest("p")?.textContent).toBe("A loud noise here.");
38
+ });
39
+
40
+ test("{{#style}} takes several classes, from strings or attributes", async () => {
41
+ const element = await start(`@set mood = gloomy
42
+ {{#style "big shudder" mood}}Text{{/style}}`);
43
+ expect([...element.querySelector(".squiffy-style")!.classList]).toEqual(["squiffy-style", "big", "shudder", "gloomy"]);
44
+ });
45
+
46
+ test("{{#style}} puts each effect after the first on an element of its own, so they all apply", async () => {
47
+ const element = await start("{{#style \"big shudder fade-in-out mirror\"}}**Text**{{/style}}");
48
+ const p = element.querySelector(".squiffy-output-block p")!;
49
+ expect(p.innerHTML).toBe("<span class=\"squiffy-style big shudder\"><span class=\"squiffy-style fade-in-out\">"
50
+ + "<span class=\"squiffy-style mirror\"><strong>Text</strong></span></span></span>");
51
+ });
52
+
53
+ test("{{#style}} nests divs for several effects around paragraphs", async () => {
54
+ const element = await start("{{#style \"letter sway blur\"}}\nDear *you*,\n\nGoodbye.\n{{/style}}");
55
+ const outer = element.querySelector(".squiffy-style")!;
56
+ expect(outer.tagName).toBe("DIV");
57
+ expect([...outer.classList]).toEqual(["squiffy-style", "letter", "sway"]);
58
+ const inner = outer.querySelector(":scope > .squiffy-style")!;
59
+ expect(inner.tagName).toBe("DIV");
60
+ expect([...inner.classList]).toEqual(["squiffy-style", "blur"]);
61
+ expect([...inner.querySelectorAll("p")].map(p => p.innerHTML)).toEqual(["Dear <em>you</em>,", "Goodbye."]);
62
+ });
63
+
64
+ test("{{#style}} around paragraphs makes a div, with Markdown rendered inside", async () => {
65
+ const element = await start(`{{#style "letter"}}
66
+ Dear *you*,
67
+
68
+ Goodbye.
69
+ {{/style}}`);
70
+ const div = element.querySelector(".squiffy-style")!;
71
+ expect(div.tagName).toBe("DIV");
72
+ expect(div.classList.contains("letter")).toBe(true);
73
+ expect([...div.querySelectorAll("p")].map(p => p.innerHTML)).toEqual(["Dear <em>you</em>,", "Goodbye."]);
74
+ });
75
+
76
+ test("{{#style}} escapes the class names, and shows helpers inside it", async () => {
77
+ const element = await start(`@set name = Ann
78
+ {{#style "a\\"b"}}Hi {{name}}{{/style}}`);
79
+ const span = element.querySelector(".squiffy-style")!;
80
+ expect(span.getAttribute("class")).toBe("squiffy-style a\"b");
81
+ expect(span.textContent).toBe("Hi Ann");
82
+ });
83
+
84
+ test("{{#style}} can wrap an {{#every}}", async () => {
85
+ const element = await start("The wheel: {{#style \"wheel\"}}{{#every 100 times=2}}spin{{/every}}{{/style}}");
86
+ expect(element.querySelector(".squiffy-error")).toBeNull();
87
+ const span = element.querySelector(".squiffy-style.wheel")!;
88
+ expect(span.querySelector(".squiffy-every")).not.toBeNull();
89
+ });
@@ -2,9 +2,17 @@ import * as marked from "marked";
2
2
  import Handlebars from "handlebars";
3
3
  import { Section, Story } from "./types.js";
4
4
  import { State } from "./state.js";
5
- import { rewriteInfixExpressions, rewriteValueExpression, splitSetters } from "./infixExpressions.js";
5
+ import { rewriteInfixExpressions, rewriteValueExpression, splitSetters } from "squiffy-compiler/infix-expressions";
6
6
  import { isNumeric, isBlank, toNumber } from "./numbers.js";
7
7
  import { checkSegment, parsePath, valueAt, withValueAt } from "./paths.js";
8
+ import { parseDelay } from "./utils.js";
9
+ import { captureEveryBodies } from "./every.js";
10
+
11
+ // The built-in effects for {{#style}} (#453), in squiffy.runtime.css
12
+ const styleEffects = new Set([
13
+ "shake", "shudder", "rumble", "sway", "buoy", "pulse", "fade-in-out", "blink", "flicker",
14
+ "blur", "blurrier", "smear", "mirror", "upside-down",
15
+ ]);
8
16
 
9
17
  // An embed being shown (#450): its parameters, and the text it wraps, if any
10
18
  interface EmbedScope {
@@ -103,16 +111,52 @@ export class TextProcessor {
103
111
  }
104
112
  let after = 0;
105
113
  if (options.hash.after !== undefined) {
106
- after = Number(unwrapValue(options.hash.after));
107
- if (!Number.isFinite(after) || after < 0) {
114
+ // A number of milliseconds, or a time like "3s" (#451)
115
+ const delay = parseDelay(unwrapValue(options.hash.after));
116
+ if (delay === null) {
108
117
  return new Handlebars.SafeString(errorHtml("Error in {{goto}}:",
109
- `after= should be a number of milliseconds, e.g. after=3000, not "${options.hash.after}"`));
118
+ `after= should be a number of milliseconds or a time, e.g. after=3000 or after="3s", not "${options.hash.after}"`));
110
119
  }
120
+ after = delay;
111
121
  }
112
122
  this.goto ??= { section, after };
113
123
  return "";
114
124
  });
115
125
 
126
+ // {{#every 1000}}...{{/every}} (#451): text that's shown again and again while the player
127
+ // is in the section. This only writes the element: the runtime's timers show the text
128
+ // (see every.ts), first after one delay, as in Twine.
129
+ this.handlebars.registerHelper("every", (...args: any[]) => {
130
+ const options = args.pop();
131
+ const error = (message: string) => new Handlebars.SafeString(errorHtml("Error in {{#every}}:", message));
132
+ const delay = args.length ? parseDelay(unwrapValue(args[0])) : null;
133
+ if (delay === null || delay <= 0) {
134
+ return error(`expected how often to show the text, as a number of milliseconds or a time, e.g. {{#every 1000}} or {{#every "1s"}}${args.length ? `, not "${args[0]}"` : ""}`);
135
+ }
136
+ const body = options.hash.__body;
137
+ if (typeof options.fn != "function" || typeof body != "string") {
138
+ return error("it needs some text to show, e.g. {{#every 1000}}Tick.{{/every}}");
139
+ }
140
+ let attrs = ` data-every="${body}" data-every-delay="${delay}" data-every-count="0"`;
141
+ if (options.hash.times !== undefined) {
142
+ const times = Number(unwrapValue(options.hash.times));
143
+ if (!Number.isInteger(times) || times < 1) {
144
+ return error(`times= should be a whole number of times, e.g. times=10, not "${options.hash.times}"`);
145
+ }
146
+ attrs += ` data-every-times="${times}"`;
147
+ }
148
+ if (options.hash.append) attrs += " data-every-append=\"\"";
149
+ // Text with paragraphs in it is a block, like {{#animate}}'s
150
+ const tag = decodeURIComponent(body).includes("\n\n") ? "div" : "span";
151
+ return new Handlebars.SafeString(`<${tag} class="squiffy-every"${attrs}></${tag}>`);
152
+ });
153
+
154
+ // {{stop}} (#451): the {{#every}} whose text this is stops after this time
155
+ this.handlebars.registerHelper("stop", () => {
156
+ this.stopEvery = true;
157
+ return "";
158
+ });
159
+
116
160
  // {{deactivate "name"}} (#13): the runtime disables the links to that passage on the screen
117
161
  // once the section or passage being shown has been written. With no name, it's the passage
118
162
  // being shown, e.g. one with @repeat that the player is done with (#104).
@@ -282,6 +326,30 @@ export class TextProcessor {
282
326
  textHelper("capitalise", capitalise);
283
327
  textHelper("capitalize", capitalise);
284
328
 
329
+ // {{#once}}...{{else}}...{{/once}} shows its text the first time it's shown, and the
330
+ // {{else}} text (or nothing) after that. Each one remembers for itself, wherever it is:
331
+ // in a section or passage shown again, or in text embedded in several places. Which ones
332
+ // have been shown is in _once, an attribute, so going back undoes it. One with a name,
333
+ // {{#once "warning"}}, shares its memory with the others of that name. firsttime, as
334
+ // Quest has it, is another name for once.
335
+ const once = function (this: unknown, ...args: any[]) {
336
+ const options = args.pop();
337
+ if (typeof options?.fn != "function") {
338
+ throw new Error("once wraps the text to show the first time: {{#once}}...{{/once}}");
339
+ }
340
+ const name = args.length ? unwrapValue(args[0]) : undefined;
341
+ if (args.length && (typeof name != "string" || !name)) {
342
+ throw new Error("the name of a {{#once}} is text, such as {{#once \"warning\"}}");
343
+ }
344
+ const key = name ?? processor.positionKey(options.loc);
345
+ const shown: string[] = processor.state.get("_once") || [];
346
+ if (shown.includes(key)) return options.inverse(this);
347
+ processor.state.set("_once", [...shown, key]);
348
+ return options.fn(this);
349
+ };
350
+ this.handlebars.registerHelper("once", once);
351
+ this.handlebars.registerHelper("firsttime", once);
352
+
285
353
  // (cond test a b) is a if test is true, otherwise b (#446). It's what a ? b : c in an
286
354
  // expression is rewritten to. Handlebars works out both a and b before calling it, so a
287
355
  // helper with side effects, such as (pop "list"), runs whichever is chosen.
@@ -316,7 +384,7 @@ export class TextProcessor {
316
384
  });
317
385
 
318
386
  // An object literal in an expression, e.g. { hp: 10, name: "Ann" } (#442), which
319
- // infixExpressions.ts rewrites to (__object "hp" 10 "name" "Ann")
387
+ // compiler/src/infix-expressions.ts rewrites to (__object "hp" 10 "name" "Ann")
320
388
  this.handlebars.registerHelper("__object", (...args) => {
321
389
  args.pop();
322
390
  const result: Record<string, unknown> = {};
@@ -541,8 +609,56 @@ export class TextProcessor {
541
609
  const text = fillIn(options.hash.text as string || passage, this, options, true);
542
610
  return new Handlebars.SafeString(`<a class="squiffy-link link-passage" data-passage="${escapeAttr(passage)}"${addAdditionalParameters(this, options)} role="link" tabindex="0">${text}</a>`);
543
611
  });
612
+
613
+ // {{restart}} and {{saves}} (#452): links that restart the story, asking first unless
614
+ // confirm=false, and open the Saved games dialog, like the page's own buttons
615
+ this.handlebars.registerHelper("restart", function (this: unknown, options) {
616
+ const text = fillIn(options.hash.text as string || processor.strings.restart, this, options, true);
617
+ const confirm = options.hash.confirm === false || options.hash.confirm === "false" ? " data-confirm=\"false\"" : "";
618
+ return new Handlebars.SafeString(`<a class="squiffy-link link-restart" data-handler="restart"${confirm} role="link" tabindex="0">${text}</a>`);
619
+ });
620
+
621
+ this.handlebars.registerHelper("saves", function (this: unknown, options) {
622
+ const text = fillIn(options.hash.text as string || processor.strings.saves, this, options, true);
623
+ return new Handlebars.SafeString(`<a class="squiffy-link link-saves" data-handler="saves" role="link" tabindex="0">${text}</a>`);
624
+ });
625
+
626
+ // {{settings}} (#452): a link that opens the Settings dialog, where the player changes the
627
+ // story's settings (squiffy.json's "settings")
628
+ this.handlebars.registerHelper("settings", function (this: unknown, options) {
629
+ const text = fillIn(options.hash.text as string || processor.strings.settings, this, options, true);
630
+ return new Handlebars.SafeString(`<a class="squiffy-link link-settings" data-handler="settings" role="link" tabindex="0">${text}</a>`);
631
+ });
632
+
633
+ // {{#style "warning"}}...{{/style}} (#453) gives the text it wraps one or more classes, for
634
+ // the story's own CSS or the built-in effects (shudder, blur, ...: .squiffy-style.shudder
635
+ // in squiffy.runtime.css). Text with blank lines in it is a block, so it gets a div.
636
+ this.handlebars.registerHelper("style", function (this: unknown, ...args: any[]) {
637
+ const options = args.pop();
638
+ // String(): text that's only one helper, such as an {{#every}}, comes back as the helper's
639
+ // SafeString
640
+ const content = typeof options?.fn == "function" ? String(options.fn(this)) : "";
641
+ const classes = args.flatMap(a => String(unwrapValue(a) ?? "").split(/\s+/)).filter(c => c.length > 0);
642
+ // An element has one animation and one transform, so a second effect would replace the
643
+ // first. Each effect after the first goes on an element of its own inside it, where
644
+ // they add up.
645
+ const extraEffects = classes.filter(c => styleEffects.has(c)).slice(1);
646
+ const outer = classes.filter(c => !extraEffects.includes(c));
647
+ const isBlock = content.includes("\n\n");
648
+ const tag = isBlock ? "div" : "span";
649
+ // The blank lines around a block's content let Markdown in it be rendered inside the div
650
+ let html = isBlock ? `\n\n${content.trim()}\n\n` : content;
651
+ for (const c of [...extraEffects].reverse()) {
652
+ html = `<${tag} class="squiffy-style ${escapeAttr(c)}">${html}</${tag}>`;
653
+ }
654
+ return new Handlebars.SafeString(`<${tag} class="${escapeAttr(["squiffy-style", ...outer].join(" "))}">${html}</${tag}>`);
655
+ });
544
656
  }
545
657
 
658
+ // The default text of {{restart}}, {{saves}} and {{settings}} links, which the runtime sets
659
+ // from the page's strings
660
+ strings = { restart: "Restart", saves: "Saved games", settings: "Settings" };
661
+
546
662
  // Evaluates an expression, such as gold + price * 2, with the same rules and helpers as
547
663
  // {{#if}} and {{set}}. Throws if it isn't valid, or a helper fails.
548
664
  evaluate(expression: string): unknown {
@@ -562,6 +678,9 @@ export class TextProcessor {
562
678
  // The passages whose links a {{deactivate}} asked to disable. Like goto, the runtime clears it
563
679
  // before showing a section or passage, and acts on it afterwards.
564
680
  deactivate = new Set<string>();
681
+ // Set by a {{stop}} in an {{#every}}'s text (#451). The runtime clears it before showing the
682
+ // text, and checks it afterwards.
683
+ stopEvery = false;
565
684
 
566
685
  // The embeds being shown, innermost last (#450). Each embed's text sees its own parameters
567
686
  // and the story's attributes, but not the parameters of the embed it's inside.
@@ -633,14 +752,28 @@ export class TextProcessor {
633
752
  });
634
753
  }
635
754
 
755
+ // The texts being processed, innermost last: a section's or passage's, and any it embeds
756
+ private processing: string[] = [];
757
+
758
+ // Identifies a place in the text being processed, for a {{#once}} to remember itself by: a
759
+ // hash of the text, and where in it the block starts. A name that starts with a space can't
760
+ // be the name an author gave one.
761
+ private positionKey(loc?: { start: { line: number; column: number } }): string {
762
+ const text = this.processing[this.processing.length - 1] ?? "";
763
+ let hash = 5381;
764
+ for (let i = 0; i < text.length; i++) hash = ((hash * 33) ^ text.charCodeAt(i)) >>> 0;
765
+ return ` ${hash.toString(36)}:${loc?.start.line ?? 0}:${loc?.start.column ?? 0}`;
766
+ }
767
+
636
768
  private expressionCache = new Map<string, HandlebarsTemplateDelegate>();
637
769
  // Where the __value helper puts the value of the expression being evaluated
638
770
  private evaluated: unknown;
639
771
 
640
772
  process(text: string, inline: boolean) {
773
+ this.processing.push(text);
641
774
  try {
642
775
  // compat: inside an {{#each}}, a name that isn't one of the item's looks for an attribute
643
- const template = this.handlebars.compile(rewriteInfixExpressions(text), { compat: true });
776
+ const template = this.handlebars.compile(rewriteInfixExpressions(captureEveryBodies(text)), { compat: true });
644
777
  text = template(this.context());
645
778
 
646
779
  if (inline) {
@@ -653,6 +786,8 @@ export class TextProcessor {
653
786
  const errorMessage = e instanceof Error ? e.message : String(e);
654
787
  console.error("Squiffy template error:", errorMessage);
655
788
  return errorHtml("Template error:", errorMessage);
789
+ } finally {
790
+ this.processing.pop();
656
791
  }
657
792
  }
658
793
  }
@@ -0,0 +1,302 @@
1
+ // @transition (#489): how a section or passage appears
2
+ import { expect, test, beforeEach, afterEach, vi } from "vitest";
3
+ import globalJsdom from "global-jsdom";
4
+ import { init } from "./squiffy.runtime.js";
5
+ import { compile as squiffyCompile } from "squiffy-compiler";
6
+
7
+ let cleanup: () => void;
8
+
9
+ beforeEach(() => {
10
+ cleanup = globalJsdom("<!DOCTYPE html><html><body><div id=\"squiffy\"></div></body></html>");
11
+ vi.useFakeTimers();
12
+ });
13
+
14
+ afterEach(() => {
15
+ vi.useRealTimers();
16
+ localStorage.clear();
17
+ cleanup();
18
+ });
19
+
20
+ const start = async (script: string, options: { persist?: boolean } = {}) => {
21
+ const result = await squiffyCompile({ script });
22
+ if (!result.success) throw new Error("Compile failed");
23
+ const story = {
24
+ ...result.output.story,
25
+ js: result.output.js.map(lines => new Function("squiffy", "get", "set", lines.join("\n"))) as any,
26
+ };
27
+ const element = document.getElementById("squiffy")!;
28
+ const api = await init({ element, story, persist: options.persist ?? false, storyId: "test", scroll: "none" });
29
+ await api.begin();
30
+ return { api, element };
31
+ };
32
+
33
+ const click = async (element: HTMLElement, text: string) => {
34
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
35
+ .find(l => l.textContent == text && !l.classList.contains("disabled"));
36
+ if (!link) throw new Error(`No link "${text}"`);
37
+ link.click();
38
+ await vi.runAllTimersAsync();
39
+ };
40
+
41
+ const sectionElement = (element: HTMLElement, name: string) =>
42
+ element.querySelector<HTMLElement>(`.squiffy-output-section[data-section="${name}"]`)!;
43
+
44
+ const passageElement = (element: HTMLElement, name: string) =>
45
+ element.querySelector<HTMLElement>(`.squiffy-output-passage[data-passage="${name}"]`)!;
46
+
47
+ // What a transition puts on an element while it plays
48
+ const transition = (el: HTMLElement) => el.classList.contains("squiffy-transition")
49
+ ? { name: el.getAttribute("data-transition"), time: el.style.getPropertyValue("--squiffy-transition-time") }
50
+ : null;
51
+
52
+ const story = `
53
+ [[forest]]:
54
+ @transition fade
55
+ The forest. [[Go to the cave]](cave), [look up], [listen]
56
+
57
+ [look up]:
58
+ @transition zoom 300ms
59
+ The stars are out.
60
+
61
+ [listen]:
62
+ Owls.
63
+
64
+ [[cave]]:
65
+ @transition slide-up 1.5s
66
+ @clear
67
+ The cave. [[Leave]](outside)
68
+
69
+ [[outside]]:
70
+ Outside.
71
+ `;
72
+
73
+ test("A section's transition plays as it appears, with its time", async () => {
74
+ const { element } = await start(story);
75
+ expect(transition(sectionElement(element, "forest"))).toEqual({ name: "fade", time: "" });
76
+ expect(sectionElement(element, "forest").classList).toContain("fade");
77
+
78
+ await click(element, "Go to the cave");
79
+ expect(transition(sectionElement(element, "cave"))).toEqual({ name: "slide-up", time: "1500ms" });
80
+
81
+ await click(element, "Leave");
82
+ expect(transition(sectionElement(element, "outside"))).toBeNull();
83
+ });
84
+
85
+ test("A passage has its own transition, or else its section's", async () => {
86
+ const { element } = await start(story);
87
+ await click(element, "look up");
88
+ expect(transition(passageElement(element, "look up"))).toEqual({ name: "zoom", time: "300ms" });
89
+
90
+ await click(element, "listen");
91
+ expect(transition(passageElement(element, "listen"))).toEqual({ name: "fade", time: "" });
92
+ });
93
+
94
+ test("The master section's transition is for every section, unless one has @transition none", async () => {
95
+ const { element } = await start(`
96
+ [[]]:
97
+ @transition blur 1s
98
+
99
+ [[a]]:
100
+ A. [[b]] [p]
101
+
102
+ [p]:
103
+ P.
104
+
105
+ [[b]]:
106
+ @transition none
107
+ B.
108
+ `);
109
+ expect(transition(sectionElement(element, "a"))).toEqual({ name: "blur", time: "1000ms" });
110
+ await click(element, "p");
111
+ expect(transition(passageElement(element, "p"))).toEqual({ name: "blur", time: "1000ms" });
112
+ await click(element, "b");
113
+ expect(transition(sectionElement(element, "b"))).toBeNull();
114
+ });
115
+
116
+ test("The transition's class comes off when it ends", async () => {
117
+ const { element } = await start(story);
118
+ const forest = sectionElement(element, "forest");
119
+ // An animation in the text doesn't end the section's transition
120
+ forest.querySelector("p, div")!.dispatchEvent(new window.Event("animationend", { bubbles: true }));
121
+ expect(transition(forest)).not.toBeNull();
122
+
123
+ forest.dispatchEvent(new window.Event("animationend", { bubbles: true }));
124
+ expect(transition(forest)).toBeNull();
125
+ expect(forest.classList).not.toContain("fade");
126
+ expect(forest.hasAttribute("style")).toBe(false);
127
+ });
128
+
129
+ test("Going back past @clear doesn't play the transition again", async () => {
130
+ const { api, element } = await start(story);
131
+ await click(element, "Go to the cave");
132
+ api.goBack();
133
+ await vi.runAllTimersAsync();
134
+ expect(transition(sectionElement(element, "forest"))).toBeNull();
135
+ });
136
+
137
+ test("A saved game doesn't play the transitions again when it's loaded", async () => {
138
+ const first = await start(story, { persist: true });
139
+ await click(first.element, "Go to the cave");
140
+ expect(transition(sectionElement(first.element, "cave"))).not.toBeNull();
141
+ first.api.dispose();
142
+ first.element.innerHTML = "";
143
+
144
+ const second = await start(story, { persist: true });
145
+ expect(sectionElement(second.element, "cave")).not.toBeNull();
146
+ expect(second.element.querySelector(".squiffy-transition")).toBeNull();
147
+ });
148
+
149
+ // @leave: how the old text goes when the screen is cleared
150
+
151
+ // So the leave transitions have an animation, which jsdom doesn't play: it's ended by hand
152
+ const animateLeaving = () => {
153
+ const style = document.createElement("style");
154
+ style.textContent = ".squiffy-leave { animation-name: leaving; animation-duration: 1s; }";
155
+ document.head.appendChild(style);
156
+ };
157
+
158
+ const clickWithoutWaiting = async (element: HTMLElement, text: string) => {
159
+ const link = [...element.querySelectorAll<HTMLElement>("a.squiffy-link")]
160
+ .find(l => l.textContent == text && !l.classList.contains("disabled"));
161
+ if (!link) throw new Error(`No link "${text}"`);
162
+ link.click();
163
+ await vi.advanceTimersByTimeAsync(0);
164
+ };
165
+
166
+ const leaving = (el: HTMLElement) => el.classList.contains("squiffy-leave")
167
+ ? { name: el.getAttribute("data-transition"), time: el.style.getPropertyValue("--squiffy-transition-time") }
168
+ : null;
169
+
170
+ const leaveStory = `
171
+ [[forest]]:
172
+ The forest. [[Go to the cave]](cave), [look up]
173
+
174
+ [look up]:
175
+ The stars are out.
176
+
177
+ [[cave]]:
178
+ @clear
179
+ @leave blur 2s
180
+ The cave. [listen]
181
+
182
+ [listen]:
183
+ @clear
184
+ Water dripping. [[Leave]](outside)
185
+
186
+ [[outside]]:
187
+ @clear
188
+ @leave none
189
+ Outside.
190
+ `;
191
+
192
+ test("The old text plays the leave transition before the screen is cleared", async () => {
193
+ animateLeaving();
194
+ const { api, element } = await start(leaveStory);
195
+ await click(element, "look up");
196
+ await clickWithoutWaiting(element, "Go to the cave");
197
+
198
+ // Everything on the screen is leaving, and the cave isn't there yet
199
+ const forest = sectionElement(element, "forest");
200
+ expect(leaving(forest)).toEqual({ name: "blur", time: "2000ms" });
201
+ expect(forest.classList).toContain("squiffy-transition");
202
+ expect(sectionElement(element, "cave")).toBeNull();
203
+ // Back waits for it
204
+ api.goBack();
205
+ await vi.advanceTimersByTimeAsync(0);
206
+ expect(leaving(forest)).not.toBeNull();
207
+ expect(passageElement(element, "look up")).not.toBeNull();
208
+
209
+ forest.dispatchEvent(new window.Event("animationend", { bubbles: true }));
210
+ await vi.runAllTimersAsync();
211
+ expect(sectionElement(element, "cave")).not.toBeNull();
212
+ // The old text is put away as it was, for going back
213
+ const putAway = element.querySelector<HTMLElement>(".squiffy-clear-stack .squiffy-output-section")!;
214
+ expect(putAway.getAttribute("data-section")).toBe("forest");
215
+ expect(putAway.classList).not.toContain("squiffy-leave");
216
+ expect(putAway.hasAttribute("style")).toBe(false);
217
+ });
218
+
219
+ test("A passage that clears the screen uses its section's leave transition, and @leave none plays none", async () => {
220
+ animateLeaving();
221
+ const { element } = await start(leaveStory);
222
+ await click(element, "Go to the cave");
223
+
224
+ await clickWithoutWaiting(element, "listen");
225
+ expect(leaving(sectionElement(element, "cave"))).toEqual({ name: "blur", time: "2000ms" });
226
+ await vi.runAllTimersAsync();
227
+ expect(passageElement(element, "listen")).not.toBeNull();
228
+
229
+ await clickWithoutWaiting(element, "Leave");
230
+ expect(sectionElement(element, "outside")).not.toBeNull();
231
+ });
232
+
233
+ test("The story goes on if the leave transition never ends", async () => {
234
+ animateLeaving();
235
+ const { element } = await start(leaveStory);
236
+ await clickWithoutWaiting(element, "Go to the cave");
237
+ await vi.advanceTimersByTimeAsync(1500);
238
+ expect(sectionElement(element, "cave")).toBeNull();
239
+ // Its 1s animation, and a second more
240
+ await vi.advanceTimersByTimeAsync(600);
241
+ expect(sectionElement(element, "cave")).not.toBeNull();
242
+ });
243
+
244
+ test("Without an animation for it, the leave transition doesn't hold the story up", async () => {
245
+ const { element } = await start(leaveStory);
246
+ await clickWithoutWaiting(element, "Go to the cave");
247
+ expect(sectionElement(element, "cave")).not.toBeNull();
248
+ });
249
+
250
+ test("Going back brings the old text back as it was", async () => {
251
+ animateLeaving();
252
+ const { api, element } = await start(leaveStory);
253
+ await click(element, "Go to the cave");
254
+ api.goBack();
255
+ await vi.runAllTimersAsync();
256
+ const forest = sectionElement(element, "forest");
257
+ expect(leaving(forest)).toBeNull();
258
+ expect(transition(forest)).toBeNull();
259
+ expect(sectionElement(element, "cave")).toBeNull();
260
+ });
261
+
262
+ test("The master section's leave transition is for every section that clears the screen", async () => {
263
+ animateLeaving();
264
+ const { element } = await start(`
265
+ [[]]:
266
+ @leave fade
267
+
268
+ [[a]]:
269
+ A. [[b]]
270
+
271
+ [[b]]:
272
+ @clear
273
+ B.
274
+ `);
275
+ await clickWithoutWaiting(element, "b");
276
+ expect(leaving(sectionElement(element, "a"))).toEqual({ name: "fade", time: "" });
277
+ });
278
+
279
+ test("A slide moves the way it's named, arriving or leaving", async () => {
280
+ const { readFileSync } = await import("fs");
281
+ const style = document.createElement("style");
282
+ style.textContent = readFileSync(new URL("./squiffy.runtime.css", import.meta.url), "utf8");
283
+ document.head.appendChild(style);
284
+
285
+ const animation = (classes: string) => {
286
+ const el = document.createElement("div");
287
+ el.className = classes;
288
+ document.body.appendChild(el);
289
+ const computed = getComputedStyle(el);
290
+ const result = `${computed.animationName} ${computed.animationDirection || "normal"}`;
291
+ el.remove();
292
+ return result;
293
+ };
294
+ // Arriving, slide-left comes in from the right, and leaving, goes off to the left, by playing
295
+ // the animation from the left backwards
296
+ expect(animation("squiffy-transition slide-left")).toBe("squiffy-transition-from-right normal");
297
+ expect(animation("squiffy-transition squiffy-leave slide-left")).toBe("squiffy-transition-from-left reverse");
298
+ expect(animation("squiffy-transition slide-up")).toBe("squiffy-transition-from-below normal");
299
+ expect(animation("squiffy-transition squiffy-leave slide-up")).toBe("squiffy-transition-from-above reverse");
300
+ // Others play backwards to leave
301
+ expect(animation("squiffy-transition squiffy-leave zoom")).toBe("squiffy-transition-zoom reverse");
302
+ });