squiffy-runtime 7.0.0-beta.3 → 7.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { expect, test, 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,
@@ -200,6 +202,48 @@ test("Click a section link and go back", async () => {
200
202
  expect(await squiffyApi.clickLink(linkToPassage)).toBe(true);
201
203
  });
202
204
 
205
+ test("canGoBack says whether there's anything to go back to", async () => {
206
+ const { squiffyApi, element } = await initScript("[[a]]:\nGo to [[b]].\n\n[[b]]:\nThe end.");
207
+ expect(squiffyApi.canGoBack()).toBe(false);
208
+
209
+ await squiffyApi.clickLink(findLink(element, "section", "b"));
210
+ expect(squiffyApi.canGoBack()).toBe(true);
211
+
212
+ squiffyApi.goBack();
213
+ expect(squiffyApi.canGoBack()).toBe(false);
214
+ });
215
+
216
+ test("canGoBack is true for a saved game that has somewhere to go back to", async () => {
217
+ const element = document.getElementById("squiffy")!;
218
+ const compileResult = await compile("[[a]]:\nGo to [[b]].\n\n[[b]]:\nThe end.");
219
+ const first = await init({ element, story: compileResult.story, persist: true });
220
+ await first.begin();
221
+ await first.clickLink(findLink(element, "section", "b"));
222
+
223
+ // A new page loads the saved game, which doesn't fire canGoBackChanged
224
+ element.innerHTML = "";
225
+ const second = await init({ element, story: compileResult.story, persist: true });
226
+ await second.begin();
227
+ expect(second.canGoBack()).toBe(true);
228
+ });
229
+
230
+ test("Going back is saved, so a saved game doesn't bring back what was undone", async () => {
231
+ const element = document.getElementById("squiffy")!;
232
+ const compileResult = await compile("[[a]]:\nGo to [[b]].\n\n[[b]]:\nLook at the [view].\n\n[view]:\nIt's lovely.");
233
+ const first = await init({ element, story: compileResult.story, persist: true });
234
+ await first.begin();
235
+ await first.clickLink(findLink(element, "section", "b"));
236
+ await first.clickLink(findLink(element, "passage", "view"));
237
+ first.goBack();
238
+ expect(element.innerHTML).not.toContain("lovely");
239
+
240
+ element.innerHTML = "";
241
+ const second = await init({ element, story: compileResult.story, persist: true });
242
+ await second.begin();
243
+ expect(element.innerHTML).toContain("Look at the");
244
+ expect(element.innerHTML).not.toContain("lovely");
245
+ });
246
+
203
247
  test("Click a passage link", async () => {
204
248
  const script = await fs.readFile("../examples/test/example.squiffy", "utf-8");
205
249
  const { squiffyApi, element } = await initScript(script);
@@ -1771,6 +1815,375 @@ Go to: [[whitespace]]
1771
1815
  expect(section).not.toBeNull();
1772
1816
  });
1773
1817
 
1818
+ // Maths helpers and arithmetic in infix expressions
1819
+ test.each([
1820
+ ["{{set \"x\" (add 2 3)}}", 5],
1821
+ ["{{set \"x\" (sub 2 3)}}", -1],
1822
+ ["{{set \"x\" (mul 2 3)}}", 6],
1823
+ ["{{set \"x\" (div 3 2)}}", 1.5],
1824
+ ["{{set \"x\" (mod 7 3)}}", 1],
1825
+ ["{{set \"x\" (add \"2\" 3)}}", 5],
1826
+ ["{{set \"x\" (add \"Bob\" \" the Brave\")}}", "Bob the Brave"],
1827
+ ["{{set \"x\" (add \"Bob\" 2)}}", "Bob2"],
1828
+ ["{{set \"x\" (add unsetattr 2)}}", 2],
1829
+ ["{{set \"x\" (mul unsetattr 2)}}", 0],
1830
+ ])("maths helper: %s", async (text, expected) => {
1831
+ const { squiffyApi } = await initScript(`[[start]]:\n${text}`);
1832
+ expect(squiffyApi.get("x")).toBe(expected);
1833
+ });
1834
+
1835
+ test.each([
1836
+ ["{{= (div 1 0)}}", "division by zero"],
1837
+ ["{{= (mod 1 0)}}", "division by zero"],
1838
+ ["{{= (mul \"a\" 2)}}", "\"mul\" needs numbers, but was given \"a\""],
1839
+ ["{{= (sub 1)}}", "\"sub\" needs two values, but was given 1"],
1840
+ ["{{= (add (array 1) 2)}}", "\"add\" can't add a list"],
1841
+ ])("maths helper error: %s", async (text, message) => {
1842
+ const { element } = await initScript(`[[start]]:\n${text}`);
1843
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain(message);
1844
+ });
1845
+
1846
+ test("arithmetic in {{set}}, {{inc}}, {{dec}} and conditions", async () => {
1847
+ const script = `
1848
+ [[start]]:
1849
+ @set gold = 10
1850
+ @set price = 3
1851
+ @set name = Bob
1852
+ {{set "gold" gold + price * 2}}
1853
+ {{inc "count" price * 2}}
1854
+ {{dec "count" (price - 1) * 2}}
1855
+ {{set "title" name + " the Brave"}}
1856
+ {{#if gold >= price * 5 + 1}}Rich{{else}}Poor{{/if}}. Double: {{= price * 2}}.
1857
+ `;
1858
+
1859
+ const { squiffyApi, element } = await initScript(script);
1860
+ expect(squiffyApi.get("gold")).toBe(16);
1861
+ expect(squiffyApi.get("count")).toBe(2);
1862
+ expect(squiffyApi.get("title")).toBe("Bob the Brave");
1863
+ expect(element.textContent).toContain("Rich. Double: 6.");
1864
+ });
1865
+
1866
+ test("Invalid arithmetic shows a template error", async () => {
1867
+ const { element } = await initScript("[[start]]:\n{{set \"gold\" gold +}}");
1868
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("Invalid expression");
1869
+ });
1870
+
1871
+ test("{{inc}} and {{dec}} use amounts stored as text (#374)", async () => {
1872
+ const script = `
1873
+ [[start]]:
1874
+ @set price = 0
1875
+ {{set "price" "10"}}{{set "a" 0}}{{set "b" 20}}
1876
+ {{inc "a" "10"}}{{inc "a" price}}{{dec "b" price}}
1877
+ `;
1878
+ const { squiffyApi } = await initScript(script);
1879
+ expect(squiffyApi.get("a")).toBe(20);
1880
+ expect(squiffyApi.get("b")).toBe(10);
1881
+ });
1882
+
1883
+ test("{{inc}} and {{dec}} add to values stored as text, rather than joining them (#374)", async () => {
1884
+ const script = `
1885
+ [[start]]:
1886
+ {{set "a" "5"}}{{inc "a"}}{{set "b" "5"}}{{inc "b" 2}}{{set "c" "5"}}{{dec "c"}}
1887
+ `;
1888
+ const { squiffyApi } = await initScript(script);
1889
+ expect(squiffyApi.get("a")).toBe(6);
1890
+ expect(squiffyApi.get("b")).toBe(7);
1891
+ expect(squiffyApi.get("c")).toBe(4);
1892
+ });
1893
+
1894
+ test("{{inc}} on text that isn't a number shows a template error (#374)", async () => {
1895
+ const { element, squiffyApi } = await initScript("[[start]]:\n{{set \"a\" \"abc\"}}{{inc \"a\"}}");
1896
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("\"inc\" needs numbers, but was given \"abc\"");
1897
+ expect(squiffyApi.get("a")).toBe("abc");
1898
+ });
1899
+
1900
+ test("@inc, @dec and += etc. work on values stored as text (#374)", async () => {
1901
+ const script = `
1902
+ [[start]]:
1903
+ {{set "a" "5"}}{{set "b" "5"}}{{set "c" "5"}}{{set "d" "5"}}{{set "price" "3"}}
1904
+ [[next]]
1905
+
1906
+ [[next]]:
1907
+ @inc a
1908
+ @dec b 2
1909
+ @set c += @price
1910
+ @set d *= 2
1911
+ @set e += 4
1912
+ `;
1913
+ const { element, squiffyApi } = await initScript(script);
1914
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
1915
+ expect(squiffyApi.get("a")).toBe(6);
1916
+ expect(squiffyApi.get("b")).toBe(3);
1917
+ expect(squiffyApi.get("c")).toBe(8);
1918
+ expect(squiffyApi.get("d")).toBe(10);
1919
+ expect(squiffyApi.get("e")).toBe(4);
1920
+ expect(element.querySelector(".squiffy-error")).toBeNull();
1921
+ });
1922
+
1923
+ test("+= on text that isn't a number shows an error and leaves the attribute alone (#374)", async () => {
1924
+ const script = `
1925
+ [[start]]:
1926
+ @set name = Bob
1927
+ @set name += 1
1928
+ @set gold += lots
1929
+ Hello.
1930
+ `;
1931
+ const { element, squiffyApi } = await initScript(script);
1932
+ const errors = [...element.querySelectorAll(".squiffy-error")].map(e => e.textContent);
1933
+ expect(errors).toEqual([
1934
+ "Error in \"name += 1\": \"+=\" needs numbers, but was given \"Bob\"",
1935
+ "Error in \"gold += lots\": \"+=\" needs numbers, but was given \"lots\"",
1936
+ ]);
1937
+ expect(squiffyApi.get("name")).toBe("Bob");
1938
+ expect(squiffyApi.get("gold")).toBeNull();
1939
+ expect(element.textContent).toContain("Hello.");
1940
+ });
1941
+
1942
+ test("an error in a link's setters is shown in the next section (#374)", async () => {
1943
+ const script = `
1944
+ [[start]]:
1945
+ @set name = Bob
1946
+ [[Go]](next, name+=1)
1947
+
1948
+ [[next]]:
1949
+ Arrived.
1950
+ `;
1951
+ const { element, squiffyApi } = await initScript(script);
1952
+ await squiffyApi.clickLink(findLink(element, "section", "Go"));
1953
+ expect(getSectionContent(element, "next")).toBe("Error in \"name+=1\": \"+=\" needs numbers, but was given \"Bob\"Arrived.");
1954
+ });
1955
+
1956
+ // ---- Expressions in @set and link setters, for a story with a squiffy.json (#373) ----
1957
+
1958
+ test("@set takes expressions, with the same rules as {{#if}}", async () => {
1959
+ const script = `
1960
+ [[start]]:
1961
+ @set weapon = "sword"
1962
+ @set price = 3
1963
+ @set gold = 10
1964
+ @set gold = gold + price * 2
1965
+ @set rich = gold > 15
1966
+ @set poor = not rich
1967
+ @set best = gold
1968
+ @set title = 'Bob' + " the Brave"
1969
+ @set negative = -price
1970
+ @set empty = ""
1971
+ `;
1972
+ const { squiffyApi } = await initScript(script, true);
1973
+ expect(squiffyApi.get("weapon")).toBe("sword");
1974
+ expect(squiffyApi.get("gold")).toBe(16);
1975
+ expect(squiffyApi.get("rich")).toBe(true);
1976
+ expect(squiffyApi.get("poor")).toBe(false);
1977
+ expect(squiffyApi.get("best")).toBe(16);
1978
+ expect(squiffyApi.get("title")).toBe("Bob the Brave");
1979
+ expect(squiffyApi.get("negative")).toBe(-3);
1980
+ expect(squiffyApi.get("empty")).toBe("");
1981
+ });
1982
+
1983
+ test("+=, -=, *= and /= take expressions", async () => {
1984
+ const script = `
1985
+ [[start]]:
1986
+ @set price = 3
1987
+ @set gold = 10
1988
+ @set gold += price * 2
1989
+ @set gold -= 1
1990
+ @set gold *= (price - 1)
1991
+ @set gold /= 2
1992
+ @inc count
1993
+ @inc count 4
1994
+ @dec count
1995
+ `;
1996
+ const { squiffyApi } = await initScript(script, true);
1997
+ expect(squiffyApi.get("gold")).toBe(15);
1998
+ expect(squiffyApi.get("count")).toBe(4);
1999
+ });
2000
+
2001
+ test("flags and := work as before with expressions", async () => {
2002
+ const script = `
2003
+ [[start]]:
2004
+ @set name = "Bob"
2005
+ @set has_key
2006
+ @set not has_map
2007
+ @set greeting := Hello, {{name}}!
2008
+ `;
2009
+ const { squiffyApi } = await initScript(script, true);
2010
+ expect(squiffyApi.get("has_key")).toBe(true);
2011
+ expect(squiffyApi.get("has_map")).toBe(false);
2012
+ expect(squiffyApi.get("greeting")).toBe("Hello, Bob!");
2013
+ });
2014
+
2015
+ test("helpers can be used in setter expressions", async () => {
2016
+ const script = `
2017
+ [[start]]:
2018
+ @set visited = (seen "start")
2019
+ @set here = (at "start")
2020
+ `;
2021
+ const { squiffyApi } = await initScript(script, true);
2022
+ expect(squiffyApi.get("visited")).toBe(true);
2023
+ expect(squiffyApi.get("here")).toBe(true);
2024
+ });
2025
+
2026
+ test("link setters take expressions, and can have commas in quotes", async () => {
2027
+ const script = `
2028
+ [[start]]:
2029
+ @set gold = 10
2030
+ @set price = 3
2031
+ [[Buy]](shop, gold -= price, swords += 1, message = "Thanks, come again", weapon = 'sword')
2032
+
2033
+ [[shop]]:
2034
+ {{message}}
2035
+ [[Haggle]](haggle, price = price - 1)
2036
+
2037
+ [[haggle]]:
2038
+ Done.
2039
+ {{section "end" text="End" set="gold = gold + price * 10, done"}}
2040
+
2041
+ [[end]]:
2042
+ The end.
2043
+ `;
2044
+ const { squiffyApi, element } = await initScript(script, true);
2045
+ await squiffyApi.clickLink(findLink(element, "section", "Buy"));
2046
+ expect(squiffyApi.get("gold")).toBe(7);
2047
+ expect(squiffyApi.get("swords")).toBe(1);
2048
+ expect(squiffyApi.get("message")).toBe("Thanks, come again");
2049
+ expect(squiffyApi.get("weapon")).toBe("sword");
2050
+ expect(getSectionContent(element, "shop")).toContain("Thanks, come again");
2051
+ await squiffyApi.clickLink(findLink(element, "section", "Haggle"));
2052
+ expect(squiffyApi.get("price")).toBe(2);
2053
+ await squiffyApi.clickLink(findLink(element, "section", "End"));
2054
+ expect(squiffyApi.get("gold")).toBe(27);
2055
+ expect(squiffyApi.get("done")).toBe(true);
2056
+ });
2057
+
2058
+ test("link setters can have brackets in them", async () => {
2059
+ const script = `
2060
+ [[start]]:
2061
+ @set gold = 10
2062
+ @set price = 3
2063
+ [[Buy]](shop, gold *= (price - 1), title = "Shop (open)")
2064
+
2065
+ [[shop]]:
2066
+ {{title}}
2067
+ [Haggle](deal, gold = (gold + (price * 2)) / 2)
2068
+
2069
+ [deal]:
2070
+ Done.
2071
+ `;
2072
+ const { squiffyApi, element } = await initScript(script, true);
2073
+ await squiffyApi.clickLink(findLink(element, "section", "Buy"));
2074
+ expect(squiffyApi.get("gold")).toBe(20);
2075
+ expect(squiffyApi.get("title")).toBe("Shop (open)");
2076
+ await squiffyApi.clickLink(findLink(element, "passage", "Haggle"));
2077
+ expect(squiffyApi.get("gold")).toBe(13);
2078
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2079
+ });
2080
+
2081
+ test("passage link setters take expressions", async () => {
2082
+ const script = `
2083
+ [[start]]:
2084
+ @set gold = 10
2085
+ [Spend](spend, gold = gold / 2)
2086
+
2087
+ [spend]:
2088
+ Spent.
2089
+ `;
2090
+ const { squiffyApi, element } = await initScript(script, true);
2091
+ await squiffyApi.clickLink(findLink(element, "passage", "Spend"));
2092
+ expect(squiffyApi.get("gold")).toBe(5);
2093
+ });
2094
+
2095
+ test("an invalid setter expression shows an error and leaves the attribute alone", async () => {
2096
+ const script = `
2097
+ [[start]]:
2098
+ @set gold = 10
2099
+ @set gold = gold +
2100
+ @set gold += "lots"
2101
+ @set gold > 5
2102
+ Hello.
2103
+ `;
2104
+ const { squiffyApi, element } = await initScript(script, true);
2105
+ const errors = [...element.querySelectorAll(".squiffy-error")].map(e => e.textContent);
2106
+ expect(errors).toEqual([
2107
+ "Error in \"gold = gold +\": Invalid expression \"gold +\": expected a value after '+'",
2108
+ "Error in \"gold += \"lots\"\": \"+=\" needs numbers, but was given \"lots\"",
2109
+ "Error in \"gold > 5\": expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key",
2110
+ ]);
2111
+ expect(squiffyApi.get("gold")).toBe(10);
2112
+ expect(element.textContent).toContain("Hello.");
2113
+ });
2114
+
2115
+ test("without a squiffy.json, setters keep the Squiffy 6 rules", async () => {
2116
+ const script = `
2117
+ [[start]]:
2118
+ @set weapon = sword
2119
+ @set price = 3
2120
+ @set best = @price
2121
+ @set gold = gold + price
2122
+ [[Go]](next, name = Bob's, message = Hi, there)
2123
+
2124
+ [[next]]:
2125
+ Done.
2126
+ `;
2127
+ const { squiffyApi, element } = await initScript(script);
2128
+ expect(squiffyApi.get("weapon")).toBe("sword");
2129
+ expect(squiffyApi.get("best")).toBe(3);
2130
+ expect(squiffyApi.get("gold")).toBe("gold + price");
2131
+ await squiffyApi.clickLink(findLink(element, "section", "Go"));
2132
+ expect(squiffyApi.get("name")).toBe("Bob's");
2133
+ expect(squiffyApi.get("message")).toBe("Hi");
2134
+ expect(squiffyApi.get("there")).toBe(true);
2135
+ });
2136
+
2137
+ test("a converted story runs the same with expressions as it did without (#373)", async () => {
2138
+ const script = `
2139
+ [[start]]:
2140
+ @set weapon = sword
2141
+ @set greeting = Hello there
2142
+ @set name = Bob's
2143
+ @set quoted = say "hi"
2144
+ @set gold = 10
2145
+ @set price = 3
2146
+ @set half = 0.5
2147
+ @set big = 1e3
2148
+ @set flag = true
2149
+ @set off = false
2150
+ @set best = @gold
2151
+ @set gold += @price
2152
+ @set gold -= 1
2153
+ @set gold *= 2
2154
+ @inc count
2155
+ @inc count 4
2156
+ @dec count
2157
+ @set has_key
2158
+ @set not has_map
2159
+ @set hello := Hi, {{name}}
2160
+ [[Shop]](shop, item = sword and shield, gold -= @price, visited, msg = Hi, there)
2161
+
2162
+ [[shop]]:
2163
+ {{section "end" text="End" set="title = The End, done, final = @gold"}}
2164
+
2165
+ [[end]]:
2166
+ The end.
2167
+ `;
2168
+ const run = async (text: string, expressions: boolean) => {
2169
+ const { squiffyApi, element } = await initScript(text, expressions);
2170
+ await squiffyApi.clickLink(findLink(element, "section", "Shop"));
2171
+ await squiffyApi.clickLink(findLink(element, "section", "End"));
2172
+ const names = ["weapon", "greeting", "name", "quoted", "gold", "price", "half", "big", "flag", "off", "best",
2173
+ "count", "has_key", "has_map", "hello", "item", "visited", "msg", "there", "title", "done", "final"];
2174
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2175
+ return Object.fromEntries(names.map(name => [name, squiffyApi.get(name)]));
2176
+ };
2177
+
2178
+ const before = await run(script, false);
2179
+ const converted = convertSetters(script);
2180
+ expect(converted.problems).toEqual([]);
2181
+ expect(converted.converted).toBeGreaterThan(5);
2182
+ const after = await run(converted.script, true);
2183
+ expect(after).toEqual(before);
2184
+ expect(before).toMatchObject({ weapon: "sword", quoted: "say \"hi\"", gold: 21, best: 10, item: "sword and shield", msg: "Hi", there: true, final: 21 });
2185
+ });
2186
+
1774
2187
  // State modification helper tests
1775
2188
  test("{{set}} helper sets attribute value", async () => {
1776
2189
  const script = `
@@ -2747,3 +3160,476 @@ test("Custom helpers can be registered in @ui", async () => {
2747
3160
  expect(section?.querySelector("b")?.textContent).toBe("world");
2748
3161
  expect(section?.querySelector("i")).toBeNull();
2749
3162
  });
3163
+
3164
+ // {{goto}} (#375)
3165
+
3166
+ test("{{goto}} goes to another section after showing this one", async () => {
3167
+ const script = `
3168
+ [[start]]:
3169
+ @set health = 1
3170
+ Start. [[fight]]
3171
+
3172
+ [[fight]]:
3173
+ @set health = 0
3174
+ You fight.
3175
+ {{#if health <= 0}}{{goto "death"}}{{else}}You win. [[win]]{{/if}}
3176
+
3177
+ [[death]]:
3178
+ You died.
3179
+
3180
+ [[win]]:
3181
+ Won.
3182
+ `;
3183
+ const { squiffyApi, element } = await initScript(script, true);
3184
+ await squiffyApi.clickLink(findLink(element, "section", "fight"));
3185
+
3186
+ expect(squiffyApi.get("_section")).toBe("death");
3187
+ expect(visibleText(element)).toBe("Start. fight You fight. You died.");
3188
+ expect(element.innerHTML).not.toContain("You win.");
3189
+ });
3190
+
3191
+ test("{{goto}} isn't followed when its {{#if}} is false", async () => {
3192
+ const script = `
3193
+ [[start]]:
3194
+ @set health = 5
3195
+ {{#if health <= 0}}{{goto "death"}}{{/if}}Alive.
3196
+
3197
+ [[death]]:
3198
+ You died.
3199
+ `;
3200
+ const { squiffyApi, element } = await initScript(script, true);
3201
+ expect(squiffyApi.get("_section")).toBe("start");
3202
+ expect(visibleText(element)).toBe("Alive.");
3203
+ });
3204
+
3205
+ test("{{goto}} in the start section", async () => {
3206
+ const { squiffyApi, element } = await initScript(`Intro.{{goto "next"}}
3207
+
3208
+ [[next]]:
3209
+ Next.`);
3210
+ expect(squiffyApi.get("_section")).toBe("next");
3211
+ expect(visibleText(element)).toBe("Intro. Next.");
3212
+ });
3213
+
3214
+ test("{{goto}} with an expression, e.g. to go somewhere at random", async () => {
3215
+ const script = `
3216
+ {{goto (random (array "a" "b"))}}
3217
+
3218
+ [[a]]:
3219
+ A.
3220
+
3221
+ [[b]]:
3222
+ B.
3223
+ `;
3224
+ const { squiffyApi } = await initScript(script);
3225
+ expect(["a", "b"]).toContain(squiffyApi.get("_section"));
3226
+ });
3227
+
3228
+ test("{{goto}} in a passage", async () => {
3229
+ const script = `
3230
+ [[start]]:
3231
+ Start. [open]
3232
+
3233
+ [open]:
3234
+ @set opened
3235
+ The door opens.{{goto "outside"}}
3236
+
3237
+ [[outside]]:
3238
+ Outside.
3239
+ `;
3240
+ const { squiffyApi, element } = await initScript(script);
3241
+ await squiffyApi.clickLink(findLink(element, "passage", "open"));
3242
+ expect(squiffyApi.get("_section")).toBe("outside");
3243
+ expect(visibleText(element)).toContain("The door opens. Outside.");
3244
+ expect(squiffyApi.get("opened")).toBe(true);
3245
+ });
3246
+
3247
+ test("Only the first {{goto}} counts", async () => {
3248
+ const script = `
3249
+ {{goto "a"}}{{goto "b"}}
3250
+
3251
+ [[a]]:
3252
+ A.
3253
+
3254
+ [[b]]:
3255
+ B.
3256
+ `;
3257
+ const { squiffyApi } = await initScript(script);
3258
+ expect(squiffyApi.get("_section")).toBe("a");
3259
+ });
3260
+
3261
+ test("{{goto}} to a section that doesn't exist shows an error", async () => {
3262
+ const { squiffyApi, element } = await initScript(`@set where = nowhere
3263
+ Start.{{goto where}}`);
3264
+ expect(squiffyApi.get("_section")).toBe("_default");
3265
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("there is no section called \"nowhere\"");
3266
+ });
3267
+
3268
+ test("A {{goto}} loop is stopped and reported", async () => {
3269
+ const errors = vi.spyOn(console, "error").mockImplementation(() => {});
3270
+ const script = `
3271
+ [[a]]:
3272
+ A.{{goto "b"}}
3273
+
3274
+ [[b]]:
3275
+ B.{{goto "a"}}
3276
+ `;
3277
+ const { element } = await initScript(script);
3278
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("Is there a loop?");
3279
+ expect(errors).toHaveBeenCalled();
3280
+ errors.mockRestore();
3281
+ });
3282
+
3283
+ test("Going back skips sections and passages that went somewhere else with {{goto}}", async () => {
3284
+ const script = `
3285
+ [[start]]:
3286
+ @set x = 1
3287
+ Start. [[jump]] [open]
3288
+
3289
+ [open]:
3290
+ @set x = 3
3291
+ Open.{{goto "end"}}
3292
+
3293
+ [[jump]]:
3294
+ @set x = 2
3295
+ Jump.{{goto "end"}}
3296
+
3297
+ [[end]]:
3298
+ End.
3299
+ `;
3300
+ const { squiffyApi, element } = await initScript(script);
3301
+ let canGoBack: boolean | undefined;
3302
+ squiffyApi.on("canGoBackChanged", e => canGoBack = e.canGoBack);
3303
+
3304
+ await squiffyApi.clickLink(findLink(element, "section", "jump"));
3305
+ expect(squiffyApi.get("_section")).toBe("end");
3306
+ expect(canGoBack).toBe(true);
3307
+
3308
+ squiffyApi.goBack();
3309
+ expect(squiffyApi.get("_section")).toBe("start");
3310
+ expect(squiffyApi.get("x")).toBe(1);
3311
+ expect(visibleText(element)).toBe("Start. jump open");
3312
+ expect(canGoBack).toBe(false);
3313
+
3314
+ await squiffyApi.clickLink(findLink(element, "passage", "open"));
3315
+ expect(squiffyApi.get("_section")).toBe("end");
3316
+ squiffyApi.goBack();
3317
+ expect(squiffyApi.get("_section")).toBe("start");
3318
+ expect(squiffyApi.get("x")).toBe(1);
3319
+ expect(findLink(element, "passage", "open", true)).toBeDefined();
3320
+ });
3321
+
3322
+ test("Can't go back if the only earlier section went somewhere else with {{goto}}", async () => {
3323
+ const { squiffyApi } = await initScript(`Intro.{{goto "next"}}
3324
+
3325
+ [[next]]:
3326
+ Next.`);
3327
+ let canGoBack = true;
3328
+ squiffyApi.on("canGoBackChanged", e => canGoBack = e.canGoBack);
3329
+ squiffyApi.goBack();
3330
+ expect(squiffyApi.get("_section")).toBe("next");
3331
+ expect(canGoBack).toBe(true); // unchanged: no event
3332
+ });
3333
+
3334
+ test("{{goto ... after=}} waits", async () => {
3335
+ vi.useFakeTimers();
3336
+ try {
3337
+ const script = `
3338
+ [[start]]:
3339
+ The lights go out.{{goto "darkness" after=3000}}
3340
+
3341
+ [[darkness]]:
3342
+ Darkness.
3343
+ `;
3344
+ const { squiffyApi, element } = await initScript(script);
3345
+ expect(squiffyApi.get("_section")).toBe("start");
3346
+ await vi.advanceTimersByTimeAsync(2999);
3347
+ expect(squiffyApi.get("_section")).toBe("start");
3348
+ await vi.advanceTimersByTimeAsync(1);
3349
+ expect(squiffyApi.get("_section")).toBe("darkness");
3350
+ expect(visibleText(element)).toBe("The lights go out. Darkness.");
3351
+ }
3352
+ finally {
3353
+ vi.useRealTimers();
3354
+ }
3355
+ });
3356
+
3357
+ test("Following a link cancels a {{goto ... after=}}", async () => {
3358
+ vi.useFakeTimers();
3359
+ try {
3360
+ const script = `
3361
+ [[start]]:
3362
+ Quick! [[run]]{{goto "caught" after=3000}}
3363
+
3364
+ [[run]]:
3365
+ You got away.
3366
+
3367
+ [[caught]]:
3368
+ Caught.
3369
+ `;
3370
+ const { squiffyApi, element } = await initScript(script);
3371
+ await squiffyApi.clickLink(findLink(element, "section", "run"));
3372
+ await vi.advanceTimersByTimeAsync(5000);
3373
+ expect(squiffyApi.get("_section")).toBe("run");
3374
+ }
3375
+ finally {
3376
+ vi.useRealTimers();
3377
+ }
3378
+ });
3379
+
3380
+ test("Going back cancels a {{goto ... after=}}", async () => {
3381
+ vi.useFakeTimers();
3382
+ try {
3383
+ const script = `
3384
+ [[start]]:
3385
+ Start. [[wait]]
3386
+
3387
+ [[wait]]:
3388
+ Waiting.{{goto "later" after=3000}}
3389
+
3390
+ [[later]]:
3391
+ Later.
3392
+ `;
3393
+ const { squiffyApi, element } = await initScript(script);
3394
+ await squiffyApi.clickLink(findLink(element, "section", "wait"));
3395
+ squiffyApi.goBack();
3396
+ expect(squiffyApi.get("_section")).toBe("start");
3397
+ await vi.advanceTimersByTimeAsync(5000);
3398
+ expect(squiffyApi.get("_section")).toBe("start");
3399
+ }
3400
+ finally {
3401
+ vi.useRealTimers();
3402
+ }
3403
+ });
3404
+
3405
+ test("Loading a story saved during a {{goto ... after=}} carries on waiting", async () => {
3406
+ vi.useFakeTimers();
3407
+ try {
3408
+ const script = `
3409
+ [[start]]:
3410
+ Waiting.{{goto "later" after=3000}}
3411
+
3412
+ [[later]]:
3413
+ Later.
3414
+ `;
3415
+ const element = document.getElementById("squiffy")!;
3416
+ const { story } = await compile(script);
3417
+ const first = await init({ element, story });
3418
+ await first.begin();
3419
+ expect(first.get("_section")).toBe("start");
3420
+
3421
+ element.innerHTML = "";
3422
+ const second = await init({ element, story });
3423
+ await second.begin();
3424
+ expect(second.get("_section")).toBe("start");
3425
+ await vi.advanceTimersByTimeAsync(3000);
3426
+ expect(second.get("_section")).toBe("later");
3427
+ }
3428
+ finally {
3429
+ vi.useRealTimers();
3430
+ }
3431
+ });
3432
+
3433
+ test("{{goto}} in the master section, leaving out the section it goes to", async () => {
3434
+ const script = `
3435
+ [[]]:
3436
+ {{#if health <= 0 and not (at "death")}}{{goto "death"}}{{/if}}
3437
+
3438
+ [[start]]:
3439
+ @set health = 1
3440
+ Start. [[Fight]](fight, health -= 1)
3441
+
3442
+ [[fight]]:
3443
+ Ouch.
3444
+
3445
+ [[death]]:
3446
+ You died.
3447
+ `;
3448
+ const { squiffyApi, element } = await initScript(script, true);
3449
+ await squiffyApi.clickLink(findLink(element, "section", "Fight"));
3450
+ expect(squiffyApi.get("_section")).toBe("death");
3451
+ expect(element.querySelector(".squiffy-error")).toBeNull();
3452
+ });
3453
+
3454
+ // Visit counts and the story-wide turn count (#377)
3455
+
3456
+ test("{{visits}} counts visits to sections and passages", async () => {
3457
+ const script = `
3458
+ [[start]]:
3459
+ Start. [look] [[cave]]
3460
+
3461
+ [look]:
3462
+ You look. Looked {{visits "look"}} times.
3463
+
3464
+ [[cave]]:
3465
+ Cave visit {{visits "cave"}}. Start {{visits "start"}}, nowhere {{visits "nowhere"}}. [[start]]
3466
+ `;
3467
+ const { squiffyApi, element } = await initScript(script);
3468
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1 });
3469
+
3470
+ await squiffyApi.clickLink(findLink(element, "passage", "look"));
3471
+ expect(visibleText(element)).toContain("Looked 1 times.");
3472
+
3473
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
3474
+ expect(visibleText(element)).toContain("Cave visit 1. Start 1, nowhere 0.");
3475
+
3476
+ await squiffyApi.clickLink(findLink(element, "section", "start", true));
3477
+ await squiffyApi.clickLink(findLink(element, "passage", "look", true));
3478
+ expect(visibleText(element)).toContain("Looked 2 times.");
3479
+ await squiffyApi.clickLink(findLink(element, "section", "cave", true));
3480
+ expect(visibleText(element)).toContain("Cave visit 2. Start 2, nowhere 0.");
3481
+ });
3482
+
3483
+ for (const expressions of [false, true]) {
3484
+ test(`{{visits}} works in conditions${expressions ? " in a story with a squiffy.json" : ""}`, async () => {
3485
+ const script = `
3486
+ [[start]]:
3487
+ [[cave]]
3488
+
3489
+ [[cave]]:
3490
+ {{#if (visits "cave") > 1}}Back again.{{else}}A new cave.{{/if}} [[start]]
3491
+ `;
3492
+ const { squiffyApi, element } = await initScript(script, expressions);
3493
+ await squiffyApi.clickLink(findLink(element, "section", "cave"));
3494
+ expect(visibleText(element)).toContain("A new cave.");
3495
+ await squiffyApi.clickLink(findLink(element, "section", "start", true));
3496
+ await squiffyApi.clickLink(findLink(element, "section", "cave", true));
3497
+ expect(visibleText(element)).toContain("Back again.");
3498
+ });
3499
+ }
3500
+
3501
+ test("squiffy.story.visits() in JS", async () => {
3502
+ // Note: the 4-space indent on the JS lines is the squiffy JS syntax - don't trim it!
3503
+ const script = `Click [a] then [check].
3504
+
3505
+ [a]:
3506
+ Passage a.
3507
+
3508
+ [check]:
3509
+ squiffy.set("visits_a", squiffy.story.visits("a"));
3510
+ squiffy.set("visits_b", squiffy.story.visits("b"));
3511
+ Checked.`;
3512
+ const { squiffyApi, element } = await initScript(script);
3513
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
3514
+ await squiffyApi.clickLink(findLink(element, "passage", "check"));
3515
+ expect(squiffyApi.get("visits_a")).toBe(1);
3516
+ expect(squiffyApi.get("visits_b")).toBe(0);
3517
+ });
3518
+
3519
+ test("turns counts every section and passage link clicked, across sections", async () => {
3520
+ const script = `
3521
+ [[start]]:
3522
+ Turn {{turns}}. [a] [b] [[next]]
3523
+
3524
+ [a]:
3525
+ A at turn {{turns}}, section turn {{_turncount}}.
3526
+
3527
+ [b]:
3528
+ B.
3529
+
3530
+ [[next]]:
3531
+ Next at turn {{turns}}. [c]
3532
+
3533
+ [c]:
3534
+ C at turn {{turns}}, section turn {{_turncount}}.
3535
+ `;
3536
+ const { squiffyApi, element } = await initScript(script);
3537
+ expect(visibleText(element)).toContain("Turn 0.");
3538
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
3539
+ expect(visibleText(element)).toContain("A at turn 1, section turn 1.");
3540
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
3541
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
3542
+ expect(visibleText(element)).toContain("Next at turn 3.");
3543
+ await squiffyApi.clickLink(findLink(element, "passage", "c"));
3544
+ expect(visibleText(element)).toContain("C at turn 4, section turn 1.");
3545
+ expect(squiffyApi.get("turns")).toBe(4);
3546
+ });
3547
+
3548
+ test("turns works in conditions", async () => {
3549
+ const script = `
3550
+ [[start]]:
3551
+ [a] [b] [c]
3552
+
3553
+ [a]:
3554
+ A.
3555
+
3556
+ [b]:
3557
+ B.
3558
+
3559
+ [c]:
3560
+ {{#if turns > 2}}Late.{{else}}Early.{{/if}}
3561
+ `;
3562
+ const { squiffyApi, element } = await initScript(script, true);
3563
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
3564
+ await squiffyApi.clickLink(findLink(element, "passage", "b"));
3565
+ await squiffyApi.clickLink(findLink(element, "passage", "c"));
3566
+ expect(visibleText(element)).toContain("Late.");
3567
+ });
3568
+
3569
+ test("{{goto}} counts as a visit but not a turn", async () => {
3570
+ const script = `
3571
+ [[start]]:
3572
+ [[fight]]
3573
+
3574
+ [[fight]]:
3575
+ {{goto "death"}}
3576
+
3577
+ [[death]]:
3578
+ Died at turn {{turns}}, visit {{visits "death"}}.
3579
+ `;
3580
+ const { squiffyApi, element } = await initScript(script);
3581
+ await squiffyApi.clickLink(findLink(element, "section", "fight"));
3582
+ expect(squiffyApi.get("_section")).toBe("death");
3583
+ expect(visibleText(element)).toContain("Died at turn 1, visit 1.");
3584
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, fight: 1, death: 1 });
3585
+ });
3586
+
3587
+ test("Going back undoes visit counts and turns", async () => {
3588
+ const script = `
3589
+ [[start]]:
3590
+ [a] [[next]]
3591
+
3592
+ [a]:
3593
+ A.
3594
+
3595
+ [[next]]:
3596
+ Next.
3597
+ `;
3598
+ const { squiffyApi, element } = await initScript(script);
3599
+ await squiffyApi.clickLink(findLink(element, "passage", "a"));
3600
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
3601
+ expect(squiffyApi.get("turns")).toBe(2);
3602
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, a: 1, next: 1 });
3603
+
3604
+ squiffyApi.goBack();
3605
+ expect(squiffyApi.get("turns")).toBe(1);
3606
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, a: 1 });
3607
+
3608
+ squiffyApi.goBack();
3609
+ expect(squiffyApi.get("turns")).toBe(0);
3610
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1 });
3611
+
3612
+ await squiffyApi.clickLink(findLink(element, "passage", "a", true));
3613
+ expect(squiffyApi.get("_visits")).toEqual({ start: 1, a: 1 });
3614
+ });
3615
+
3616
+ test("A save from before visit counts treats each seen section or passage as visited once", async () => {
3617
+ const script = `
3618
+ [[start]]:
3619
+ Start {{visits "start"}}, cave {{visits "cave"}}, lake {{visits "lake"}}, turns {{turns}}.
3620
+ `;
3621
+ const storyId = "00000000-0000-0000-0000-000000000000";
3622
+ localStorage[`${storyId}-_seen_sections`] = JSON.stringify(["start", "cave"]);
3623
+
3624
+ const element = document.getElementById("squiffy")!;
3625
+ const compileResult = await compile(script, "old-save.squiffy");
3626
+ const squiffyApi = await init({ element, story: compileResult.story, persist: true, storyId });
3627
+ await squiffyApi.begin();
3628
+
3629
+ // Going to start makes it the second visit
3630
+ expect(visibleText(element)).toContain("Start 2, cave 1, lake 0, turns 0.");
3631
+ expect(squiffyApi.get("_visits")).toEqual({ start: 2 });
3632
+
3633
+ localStorage.clear();
3634
+ });
3635
+