squiffy-runtime 7.0.0-beta.2 → 7.0.0-beta.4

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,
@@ -470,6 +472,36 @@ Three.
470
472
  expect(visibleText(element)).toBe("Two. a three");
471
473
  });
472
474
 
475
+ test("Clearing the screen scrolls up to the top of the output", async () => {
476
+ // https://github.com/textadventures/squiffy/issues/54
477
+ const script = `
478
+ [[start]]:
479
+ Start. [[two]]
480
+
481
+ [[two]]:
482
+ Two. [[three]]
483
+
484
+ [[three]]:
485
+ @clear
486
+ Three.
487
+ `;
488
+ const { squiffyApi, element } = await initScript(script);
489
+
490
+ // The reader has scrolled down to 500px, and the output starts 20px from the top of the page
491
+ Object.defineProperty(document.documentElement, "scrollTop", { configurable: true, get: () => 500 });
492
+ (element.firstElementChild as HTMLElement).getBoundingClientRect = () => ({ top: -480 }) as DOMRect;
493
+ const scrollTo = vi.fn();
494
+ window.scrollTo = scrollTo;
495
+
496
+ // No clear, so no scrolling up
497
+ await squiffyApi.clickLink(findLink(element, "section", "two"));
498
+ expect(scrollTo).not.toHaveBeenCalled();
499
+
500
+ await squiffyApi.clickLink(findLink(element, "section", "three"));
501
+ expect(scrollTo).toHaveBeenCalledTimes(1);
502
+ expect(scrollTo).toHaveBeenCalledWith({ top: 20, behavior: "smooth" });
503
+ });
504
+
473
505
  test("Run JavaScript functions", async () => {
474
506
  const script = `
475
507
  document.getElementById('test').innerText = 'Initial JavaScript';
@@ -1741,6 +1773,375 @@ Go to: [[whitespace]]
1741
1773
  expect(section).not.toBeNull();
1742
1774
  });
1743
1775
 
1776
+ // Maths helpers and arithmetic in infix expressions
1777
+ test.each([
1778
+ ["{{set \"x\" (add 2 3)}}", 5],
1779
+ ["{{set \"x\" (sub 2 3)}}", -1],
1780
+ ["{{set \"x\" (mul 2 3)}}", 6],
1781
+ ["{{set \"x\" (div 3 2)}}", 1.5],
1782
+ ["{{set \"x\" (mod 7 3)}}", 1],
1783
+ ["{{set \"x\" (add \"2\" 3)}}", 5],
1784
+ ["{{set \"x\" (add \"Bob\" \" the Brave\")}}", "Bob the Brave"],
1785
+ ["{{set \"x\" (add \"Bob\" 2)}}", "Bob2"],
1786
+ ["{{set \"x\" (add unsetattr 2)}}", 2],
1787
+ ["{{set \"x\" (mul unsetattr 2)}}", 0],
1788
+ ])("maths helper: %s", async (text, expected) => {
1789
+ const { squiffyApi } = await initScript(`[[start]]:\n${text}`);
1790
+ expect(squiffyApi.get("x")).toBe(expected);
1791
+ });
1792
+
1793
+ test.each([
1794
+ ["{{= (div 1 0)}}", "division by zero"],
1795
+ ["{{= (mod 1 0)}}", "division by zero"],
1796
+ ["{{= (mul \"a\" 2)}}", "\"mul\" needs numbers, but was given \"a\""],
1797
+ ["{{= (sub 1)}}", "\"sub\" needs two values, but was given 1"],
1798
+ ["{{= (add (array 1) 2)}}", "\"add\" can't add a list"],
1799
+ ])("maths helper error: %s", async (text, message) => {
1800
+ const { element } = await initScript(`[[start]]:\n${text}`);
1801
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain(message);
1802
+ });
1803
+
1804
+ test("arithmetic in {{set}}, {{inc}}, {{dec}} and conditions", async () => {
1805
+ const script = `
1806
+ [[start]]:
1807
+ @set gold = 10
1808
+ @set price = 3
1809
+ @set name = Bob
1810
+ {{set "gold" gold + price * 2}}
1811
+ {{inc "count" price * 2}}
1812
+ {{dec "count" (price - 1) * 2}}
1813
+ {{set "title" name + " the Brave"}}
1814
+ {{#if gold >= price * 5 + 1}}Rich{{else}}Poor{{/if}}. Double: {{= price * 2}}.
1815
+ `;
1816
+
1817
+ const { squiffyApi, element } = await initScript(script);
1818
+ expect(squiffyApi.get("gold")).toBe(16);
1819
+ expect(squiffyApi.get("count")).toBe(2);
1820
+ expect(squiffyApi.get("title")).toBe("Bob the Brave");
1821
+ expect(element.textContent).toContain("Rich. Double: 6.");
1822
+ });
1823
+
1824
+ test("Invalid arithmetic shows a template error", async () => {
1825
+ const { element } = await initScript("[[start]]:\n{{set \"gold\" gold +}}");
1826
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("Invalid expression");
1827
+ });
1828
+
1829
+ test("{{inc}} and {{dec}} use amounts stored as text (#374)", async () => {
1830
+ const script = `
1831
+ [[start]]:
1832
+ @set price = 0
1833
+ {{set "price" "10"}}{{set "a" 0}}{{set "b" 20}}
1834
+ {{inc "a" "10"}}{{inc "a" price}}{{dec "b" price}}
1835
+ `;
1836
+ const { squiffyApi } = await initScript(script);
1837
+ expect(squiffyApi.get("a")).toBe(20);
1838
+ expect(squiffyApi.get("b")).toBe(10);
1839
+ });
1840
+
1841
+ test("{{inc}} and {{dec}} add to values stored as text, rather than joining them (#374)", async () => {
1842
+ const script = `
1843
+ [[start]]:
1844
+ {{set "a" "5"}}{{inc "a"}}{{set "b" "5"}}{{inc "b" 2}}{{set "c" "5"}}{{dec "c"}}
1845
+ `;
1846
+ const { squiffyApi } = await initScript(script);
1847
+ expect(squiffyApi.get("a")).toBe(6);
1848
+ expect(squiffyApi.get("b")).toBe(7);
1849
+ expect(squiffyApi.get("c")).toBe(4);
1850
+ });
1851
+
1852
+ test("{{inc}} on text that isn't a number shows a template error (#374)", async () => {
1853
+ const { element, squiffyApi } = await initScript("[[start]]:\n{{set \"a\" \"abc\"}}{{inc \"a\"}}");
1854
+ expect(element.querySelector(".squiffy-error")?.textContent).toContain("\"inc\" needs numbers, but was given \"abc\"");
1855
+ expect(squiffyApi.get("a")).toBe("abc");
1856
+ });
1857
+
1858
+ test("@inc, @dec and += etc. work on values stored as text (#374)", async () => {
1859
+ const script = `
1860
+ [[start]]:
1861
+ {{set "a" "5"}}{{set "b" "5"}}{{set "c" "5"}}{{set "d" "5"}}{{set "price" "3"}}
1862
+ [[next]]
1863
+
1864
+ [[next]]:
1865
+ @inc a
1866
+ @dec b 2
1867
+ @set c += @price
1868
+ @set d *= 2
1869
+ @set e += 4
1870
+ `;
1871
+ const { element, squiffyApi } = await initScript(script);
1872
+ await squiffyApi.clickLink(findLink(element, "section", "next"));
1873
+ expect(squiffyApi.get("a")).toBe(6);
1874
+ expect(squiffyApi.get("b")).toBe(3);
1875
+ expect(squiffyApi.get("c")).toBe(8);
1876
+ expect(squiffyApi.get("d")).toBe(10);
1877
+ expect(squiffyApi.get("e")).toBe(4);
1878
+ expect(element.querySelector(".squiffy-error")).toBeNull();
1879
+ });
1880
+
1881
+ test("+= on text that isn't a number shows an error and leaves the attribute alone (#374)", async () => {
1882
+ const script = `
1883
+ [[start]]:
1884
+ @set name = Bob
1885
+ @set name += 1
1886
+ @set gold += lots
1887
+ Hello.
1888
+ `;
1889
+ const { element, squiffyApi } = await initScript(script);
1890
+ const errors = [...element.querySelectorAll(".squiffy-error")].map(e => e.textContent);
1891
+ expect(errors).toEqual([
1892
+ "Error in \"name += 1\": \"+=\" needs numbers, but was given \"Bob\"",
1893
+ "Error in \"gold += lots\": \"+=\" needs numbers, but was given \"lots\"",
1894
+ ]);
1895
+ expect(squiffyApi.get("name")).toBe("Bob");
1896
+ expect(squiffyApi.get("gold")).toBeNull();
1897
+ expect(element.textContent).toContain("Hello.");
1898
+ });
1899
+
1900
+ test("an error in a link's setters is shown in the next section (#374)", async () => {
1901
+ const script = `
1902
+ [[start]]:
1903
+ @set name = Bob
1904
+ [[Go]](next, name+=1)
1905
+
1906
+ [[next]]:
1907
+ Arrived.
1908
+ `;
1909
+ const { element, squiffyApi } = await initScript(script);
1910
+ await squiffyApi.clickLink(findLink(element, "section", "Go"));
1911
+ expect(getSectionContent(element, "next")).toBe("Error in \"name+=1\": \"+=\" needs numbers, but was given \"Bob\"Arrived.");
1912
+ });
1913
+
1914
+ // ---- Expressions in @set and link setters, for a story with a squiffy.json (#373) ----
1915
+
1916
+ test("@set takes expressions, with the same rules as {{#if}}", async () => {
1917
+ const script = `
1918
+ [[start]]:
1919
+ @set weapon = "sword"
1920
+ @set price = 3
1921
+ @set gold = 10
1922
+ @set gold = gold + price * 2
1923
+ @set rich = gold > 15
1924
+ @set poor = not rich
1925
+ @set best = gold
1926
+ @set title = 'Bob' + " the Brave"
1927
+ @set negative = -price
1928
+ @set empty = ""
1929
+ `;
1930
+ const { squiffyApi } = await initScript(script, true);
1931
+ expect(squiffyApi.get("weapon")).toBe("sword");
1932
+ expect(squiffyApi.get("gold")).toBe(16);
1933
+ expect(squiffyApi.get("rich")).toBe(true);
1934
+ expect(squiffyApi.get("poor")).toBe(false);
1935
+ expect(squiffyApi.get("best")).toBe(16);
1936
+ expect(squiffyApi.get("title")).toBe("Bob the Brave");
1937
+ expect(squiffyApi.get("negative")).toBe(-3);
1938
+ expect(squiffyApi.get("empty")).toBe("");
1939
+ });
1940
+
1941
+ test("+=, -=, *= and /= take expressions", async () => {
1942
+ const script = `
1943
+ [[start]]:
1944
+ @set price = 3
1945
+ @set gold = 10
1946
+ @set gold += price * 2
1947
+ @set gold -= 1
1948
+ @set gold *= (price - 1)
1949
+ @set gold /= 2
1950
+ @inc count
1951
+ @inc count 4
1952
+ @dec count
1953
+ `;
1954
+ const { squiffyApi } = await initScript(script, true);
1955
+ expect(squiffyApi.get("gold")).toBe(15);
1956
+ expect(squiffyApi.get("count")).toBe(4);
1957
+ });
1958
+
1959
+ test("flags and := work as before with expressions", async () => {
1960
+ const script = `
1961
+ [[start]]:
1962
+ @set name = "Bob"
1963
+ @set has_key
1964
+ @set not has_map
1965
+ @set greeting := Hello, {{name}}!
1966
+ `;
1967
+ const { squiffyApi } = await initScript(script, true);
1968
+ expect(squiffyApi.get("has_key")).toBe(true);
1969
+ expect(squiffyApi.get("has_map")).toBe(false);
1970
+ expect(squiffyApi.get("greeting")).toBe("Hello, Bob!");
1971
+ });
1972
+
1973
+ test("helpers can be used in setter expressions", async () => {
1974
+ const script = `
1975
+ [[start]]:
1976
+ @set visited = (seen "start")
1977
+ @set here = (at "start")
1978
+ `;
1979
+ const { squiffyApi } = await initScript(script, true);
1980
+ expect(squiffyApi.get("visited")).toBe(true);
1981
+ expect(squiffyApi.get("here")).toBe(true);
1982
+ });
1983
+
1984
+ test("link setters take expressions, and can have commas in quotes", async () => {
1985
+ const script = `
1986
+ [[start]]:
1987
+ @set gold = 10
1988
+ @set price = 3
1989
+ [[Buy]](shop, gold -= price, swords += 1, message = "Thanks, come again", weapon = 'sword')
1990
+
1991
+ [[shop]]:
1992
+ {{message}}
1993
+ [[Haggle]](haggle, price = price - 1)
1994
+
1995
+ [[haggle]]:
1996
+ Done.
1997
+ {{section "end" text="End" set="gold = gold + price * 10, done"}}
1998
+
1999
+ [[end]]:
2000
+ The end.
2001
+ `;
2002
+ const { squiffyApi, element } = await initScript(script, true);
2003
+ await squiffyApi.clickLink(findLink(element, "section", "Buy"));
2004
+ expect(squiffyApi.get("gold")).toBe(7);
2005
+ expect(squiffyApi.get("swords")).toBe(1);
2006
+ expect(squiffyApi.get("message")).toBe("Thanks, come again");
2007
+ expect(squiffyApi.get("weapon")).toBe("sword");
2008
+ expect(getSectionContent(element, "shop")).toContain("Thanks, come again");
2009
+ await squiffyApi.clickLink(findLink(element, "section", "Haggle"));
2010
+ expect(squiffyApi.get("price")).toBe(2);
2011
+ await squiffyApi.clickLink(findLink(element, "section", "End"));
2012
+ expect(squiffyApi.get("gold")).toBe(27);
2013
+ expect(squiffyApi.get("done")).toBe(true);
2014
+ });
2015
+
2016
+ test("link setters can have brackets in them", async () => {
2017
+ const script = `
2018
+ [[start]]:
2019
+ @set gold = 10
2020
+ @set price = 3
2021
+ [[Buy]](shop, gold *= (price - 1), title = "Shop (open)")
2022
+
2023
+ [[shop]]:
2024
+ {{title}}
2025
+ [Haggle](deal, gold = (gold + (price * 2)) / 2)
2026
+
2027
+ [deal]:
2028
+ Done.
2029
+ `;
2030
+ const { squiffyApi, element } = await initScript(script, true);
2031
+ await squiffyApi.clickLink(findLink(element, "section", "Buy"));
2032
+ expect(squiffyApi.get("gold")).toBe(20);
2033
+ expect(squiffyApi.get("title")).toBe("Shop (open)");
2034
+ await squiffyApi.clickLink(findLink(element, "passage", "Haggle"));
2035
+ expect(squiffyApi.get("gold")).toBe(13);
2036
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2037
+ });
2038
+
2039
+ test("passage link setters take expressions", async () => {
2040
+ const script = `
2041
+ [[start]]:
2042
+ @set gold = 10
2043
+ [Spend](spend, gold = gold / 2)
2044
+
2045
+ [spend]:
2046
+ Spent.
2047
+ `;
2048
+ const { squiffyApi, element } = await initScript(script, true);
2049
+ await squiffyApi.clickLink(findLink(element, "passage", "Spend"));
2050
+ expect(squiffyApi.get("gold")).toBe(5);
2051
+ });
2052
+
2053
+ test("an invalid setter expression shows an error and leaves the attribute alone", async () => {
2054
+ const script = `
2055
+ [[start]]:
2056
+ @set gold = 10
2057
+ @set gold = gold +
2058
+ @set gold += "lots"
2059
+ @set gold > 5
2060
+ Hello.
2061
+ `;
2062
+ const { squiffyApi, element } = await initScript(script, true);
2063
+ const errors = [...element.querySelectorAll(".squiffy-error")].map(e => e.textContent);
2064
+ expect(errors).toEqual([
2065
+ "Error in \"gold = gold +\": Invalid expression \"gold +\": expected a value after '+'",
2066
+ "Error in \"gold += \"lots\"\": \"+=\" needs numbers, but was given \"lots\"",
2067
+ "Error in \"gold > 5\": expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key",
2068
+ ]);
2069
+ expect(squiffyApi.get("gold")).toBe(10);
2070
+ expect(element.textContent).toContain("Hello.");
2071
+ });
2072
+
2073
+ test("without a squiffy.json, setters keep the Squiffy 6 rules", async () => {
2074
+ const script = `
2075
+ [[start]]:
2076
+ @set weapon = sword
2077
+ @set price = 3
2078
+ @set best = @price
2079
+ @set gold = gold + price
2080
+ [[Go]](next, name = Bob's, message = Hi, there)
2081
+
2082
+ [[next]]:
2083
+ Done.
2084
+ `;
2085
+ const { squiffyApi, element } = await initScript(script);
2086
+ expect(squiffyApi.get("weapon")).toBe("sword");
2087
+ expect(squiffyApi.get("best")).toBe(3);
2088
+ expect(squiffyApi.get("gold")).toBe("gold + price");
2089
+ await squiffyApi.clickLink(findLink(element, "section", "Go"));
2090
+ expect(squiffyApi.get("name")).toBe("Bob's");
2091
+ expect(squiffyApi.get("message")).toBe("Hi");
2092
+ expect(squiffyApi.get("there")).toBe(true);
2093
+ });
2094
+
2095
+ test("a converted story runs the same with expressions as it did without (#373)", async () => {
2096
+ const script = `
2097
+ [[start]]:
2098
+ @set weapon = sword
2099
+ @set greeting = Hello there
2100
+ @set name = Bob's
2101
+ @set quoted = say "hi"
2102
+ @set gold = 10
2103
+ @set price = 3
2104
+ @set half = 0.5
2105
+ @set big = 1e3
2106
+ @set flag = true
2107
+ @set off = false
2108
+ @set best = @gold
2109
+ @set gold += @price
2110
+ @set gold -= 1
2111
+ @set gold *= 2
2112
+ @inc count
2113
+ @inc count 4
2114
+ @dec count
2115
+ @set has_key
2116
+ @set not has_map
2117
+ @set hello := Hi, {{name}}
2118
+ [[Shop]](shop, item = sword and shield, gold -= @price, visited, msg = Hi, there)
2119
+
2120
+ [[shop]]:
2121
+ {{section "end" text="End" set="title = The End, done, final = @gold"}}
2122
+
2123
+ [[end]]:
2124
+ The end.
2125
+ `;
2126
+ const run = async (text: string, expressions: boolean) => {
2127
+ const { squiffyApi, element } = await initScript(text, expressions);
2128
+ await squiffyApi.clickLink(findLink(element, "section", "Shop"));
2129
+ await squiffyApi.clickLink(findLink(element, "section", "End"));
2130
+ const names = ["weapon", "greeting", "name", "quoted", "gold", "price", "half", "big", "flag", "off", "best",
2131
+ "count", "has_key", "has_map", "hello", "item", "visited", "msg", "there", "title", "done", "final"];
2132
+ expect(element.querySelector(".squiffy-error")).toBeNull();
2133
+ return Object.fromEntries(names.map(name => [name, squiffyApi.get(name)]));
2134
+ };
2135
+
2136
+ const before = await run(script, false);
2137
+ const converted = convertSetters(script);
2138
+ expect(converted.problems).toEqual([]);
2139
+ expect(converted.converted).toBeGreaterThan(5);
2140
+ const after = await run(converted.script, true);
2141
+ expect(after).toEqual(before);
2142
+ expect(before).toMatchObject({ weapon: "sword", quoted: "say \"hi\"", gold: 21, best: 10, item: "sword and shield", msg: "Hi", there: true, final: 21 });
2143
+ });
2144
+
1744
2145
  // State modification helper tests
1745
2146
  test("{{set}} helper sets attribute value", async () => {
1746
2147
  const script = `
@@ -1,5 +1,6 @@
1
1
  import { SquiffyApi, SquiffyInitOptions, Story, Section, Passage, StartAt } from "./types.js";
2
- import { TextProcessor } from "./textProcessor.js";
2
+ import { TextProcessor, errorHtml } from "./textProcessor.js";
3
+ import { toNumber } from "./numbers.js";
3
4
  import { Emitter, SquiffyEventMap } from "./events.js";
4
5
  import { State } from "./state.js";
5
6
  import { updateStory } from "./updater.js";
@@ -21,6 +22,11 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
21
22
  let currentPassageElement: HTMLElement | null;
22
23
  let currentBlockOutputElement: HTMLElement | null;
23
24
  let scrollPosition = 0;
25
+ // Set when the screen is cleared, so the next scroll goes up to the top of the new screen (#54)
26
+ let scrollToTop = false;
27
+ // Errors from setting attributes (e.g. @set gold += abc), shown at the start of the next text
28
+ // written. A link's setters run before the next section has anywhere to show them.
29
+ const pendingErrors: string[] = [];
24
30
  const emitter = new Emitter<SquiffyEventMap>();
25
31
  const transitions: (() => Promise<void>)[] = [];
26
32
  let runningTransitions = false;
@@ -122,7 +128,67 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
122
128
  }
123
129
  }
124
130
 
131
+ // Runs a setter from @set or a link, e.g. gold += 5. An error leaves the attribute as it was,
132
+ // and is shown with the next text written.
125
133
  function setAttribute(expr: string) {
134
+ try {
135
+ if (story.expressions) {
136
+ setWithExpression(expr);
137
+ }
138
+ else {
139
+ setWithoutExpression(expr);
140
+ }
141
+ }
142
+ catch (e) {
143
+ const message = e instanceof Error ? e.message : String(e);
144
+ console.error(`Squiffy error in "${expr}":`, message);
145
+ pendingErrors.push(errorHtml(`Error in "${expr}":`, message));
146
+ }
147
+ }
148
+
149
+ // +=, -=, *= and /=, which only work on numbers (#374)
150
+ function operate(lhs: string, op: string, amountValue: unknown) {
151
+ const what = op + "=";
152
+ const amount = toNumber(what, amountValue);
153
+ let value = toNumber(what, get(lhs));
154
+ if (op == "+") value += amount;
155
+ if (op == "-") value -= amount;
156
+ if (op == "*") value *= amount;
157
+ if (op == "/") value /= amount;
158
+ set(lhs, value);
159
+ }
160
+
161
+ // A story with a squiffy.json (#373): the right-hand side is an expression, with the same rules
162
+ // as {{#if}}, e.g. weapon = "sword", gold = gold + price * 2, rich = gold > 100.
163
+ function setWithExpression(expr: string) {
164
+ const textMatch = /^(\w+)\s*:=(.*)$/.exec(expr);
165
+ if (textMatch) {
166
+ // Text with {{...}} processed, as before
167
+ set(textMatch[1], ui.processText(textMatch[2], true));
168
+ return;
169
+ }
170
+ const match = /^(\w+)\s*([+\-*/]?)=(?!=)(.*)$/.exec(expr);
171
+ if (match) {
172
+ const [, lhs, op, rhs] = match;
173
+ const value = textProcessor.evaluate(rhs);
174
+ if (op) {
175
+ operate(lhs, op, value);
176
+ }
177
+ else {
178
+ set(lhs, value);
179
+ }
180
+ return;
181
+ }
182
+ const flagMatch = /^(not\s+)?(\w+)$/.exec(expr.trim());
183
+ if (!flagMatch) {
184
+ throw new Error("expected an attribute name, e.g. gold = 10, gold += 5, has_key or not has_key");
185
+ }
186
+ set(flagMatch[2], !flagMatch[1]);
187
+ }
188
+
189
+ // A story without a squiffy.json, as in Squiffy 6: the right-hand side is a number, true,
190
+ // false, @attribute, or else text
191
+ function setWithoutExpression(expr: string) {
126
192
  expr = expr.replace(/^(\w*\s*):=(.*)$/, (_, name, value) => (name + "=" + ui.processText(value, true)));
127
193
  const setRegex = /^([\w]*)\s*=\s*(.*)$/;
128
194
  const setMatch = setRegex.exec(expr);
@@ -149,24 +215,8 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
149
215
  if (incDecMatch) {
150
216
  const lhs = incDecMatch[1];
151
217
  const op = incDecMatch[2];
152
- let rhs = incDecMatch[3];
153
- if (rhs.startsWith("@")) rhs = get(rhs.substring(1));
154
- const rhsNumeric = parseFloat(rhs);
155
- let value = get(lhs);
156
- if (value === null) value = 0;
157
- if (op == "+") {
158
- value += rhsNumeric;
159
- }
160
- if (op == "-") {
161
- value -= rhsNumeric;
162
- }
163
- if (op == "*") {
164
- value *= rhsNumeric;
165
- }
166
- if (op == "/") {
167
- value /= rhsNumeric;
168
- }
169
- set(lhs, value);
218
+ const rhsText = incDecMatch[3].trim();
219
+ operate(lhs, op, rhsText.startsWith("@") ? get(rhsText.substring(1)) : rhsText);
170
220
  }
171
221
  else {
172
222
  let value = true;
@@ -461,6 +511,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
461
511
 
462
512
  const clearStackItem = document.createElement("div");
463
513
  clearStack.appendChild(clearStackItem);
514
+ scrollToTop = true;
464
515
 
465
516
  // Move everything in the outputElement (except the clearStack itself) into the new clearStackItem
466
517
  for (const child of [...outputElement.children]) {
@@ -493,7 +544,7 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
493
544
  write: (text: string, source: string) => {
494
545
  scrollPosition = outputElement.scrollHeight;
495
546
 
496
- const html = ui.renderHtml(text, false).trim();
547
+ const html = pendingErrors.splice(0).join("") + ui.renderHtml(text, false).trim();
497
548
 
498
549
  // Previously, we skipped the rest of this if "html" came back as an empty string.
499
550
  // But, we _do_ always want the block to be created, in the editor at least - as the
@@ -528,6 +579,21 @@ export const init = async (options: SquiffyInitOptions): Promise<SquiffyApi> =>
528
579
  if (settings.scroll === "none") {
529
580
  // do nothing
530
581
  }
582
+ else if (scrollToTop) {
583
+ // The screen was cleared, so the new text starts at the top of the output, which may be
584
+ // above where the reader has scrolled to.
585
+ scrollToTop = false;
586
+ if (settings.scroll === "element") {
587
+ currentSectionElement.scrollIntoView({ block: "start", inline: "nearest", behavior: "smooth" });
588
+ }
589
+ else {
590
+ const currentScrollTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop);
591
+ const outputTop = outputElement.getBoundingClientRect().top + currentScrollTop;
592
+ if (outputTop < currentScrollTop) {
593
+ window.scrollTo({ top: outputTop, behavior: "smooth" });
594
+ }
595
+ }
596
+ }
531
597
  else if (settings.scroll === "element") {
532
598
  outputElement.lastElementChild?.scrollIntoView({ block: "end", inline: "nearest", behavior: "smooth" });
533
599
  }