squiffy-compiler 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.
@@ -0,0 +1,322 @@
1
+ // SugarCube's player settings (#452), from the story's JavaScript: Setting.addToggle(),
2
+ // Setting.addList() and Setting.addRange() become squiffy.json's "settings". The story reads them
3
+ // as settings.name, as in SugarCube. Their onInit and onChange functions can't come with them, as
4
+ // they're JavaScript written for SugarCube, but each setting puts classes on the story's element,
5
+ // which the stylesheet can use instead.
6
+ //
7
+ // Only literal values are read: text, numbers, true and false, lists of those, and a list held in a
8
+ // variable the script sets to one, as in `var settingFontSize = ["100%", "125%"]`.
9
+ const isCode = (v) => !!v && typeof v == "object" && !Array.isArray(v) && "code" in v && Object.keys(v).length == 1;
10
+ const isName = (v) => !!v && typeof v == "object" && !Array.isArray(v) && "name" in v && Object.keys(v).length == 1;
11
+ export function sugarCubeSettings(script) {
12
+ const settings = [];
13
+ const problems = [];
14
+ const calls = /\bSetting\s*\.\s*add(Toggle|List|Range|Header|Value)\s*\(/g;
15
+ for (const match of script.matchAll(calls)) {
16
+ const kind = match[1];
17
+ const start = match.index + match[0].length;
18
+ let args;
19
+ try {
20
+ args = new LiteralParser(script, start).arguments();
21
+ }
22
+ catch {
23
+ problems.push({ text: `Setting.add${kind}()`, reason: "This setting couldn't be read, so it isn't in Squiffy's Settings dialog." });
24
+ continue;
25
+ }
26
+ // How the import report names it
27
+ const callText = typeof args[0] == "string" ? `Setting.add${kind}(${JSON.stringify(args[0])})` : `Setting.add${kind}()`;
28
+ if (kind == "Header" || kind == "Value") {
29
+ if (kind == "Header")
30
+ problems.push({ text: callText, reason: "Squiffy's Settings dialog has no headings, so this has been left out." });
31
+ continue;
32
+ }
33
+ const [name, options] = args;
34
+ if (typeof name != "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
35
+ problems.push({ text: callText, reason: "A setting's name in Squiffy is letters, digits and underscores, so this has been left out." });
36
+ continue;
37
+ }
38
+ if (settings.some(s => s.name == name))
39
+ continue;
40
+ const o = options && typeof options == "object" && !Array.isArray(options) && !isCode(options) && !isName(options)
41
+ ? options : {};
42
+ const label = typeof o.label == "string" && o.label.trim() ? stripHtml(o.label) : name;
43
+ const description = typeof o.desc == "string" && o.desc.trim() ? stripHtml(o.desc) : undefined;
44
+ const base = { name, label, ...(description ? { description } : {}) };
45
+ if (kind == "Toggle") {
46
+ settings.push({ ...base, type: "toggle", ...(typeof o.default == "boolean" ? { default: o.default } : {}) });
47
+ }
48
+ else if (kind == "List") {
49
+ const list = isName(o.list) ? arrayNamed(script, o.list.name) : o.list;
50
+ const options = Array.isArray(list) ? list.map(optionOf) : null;
51
+ if (!options?.length || options.some(option => !option)) {
52
+ problems.push({ text: callText, reason: "This setting's list of options couldn't be read, so it isn't in Squiffy's Settings dialog." });
53
+ continue;
54
+ }
55
+ const unique = options.filter((option, i, all) => all.findIndex(o => o.value == option.value) == i);
56
+ const defaultValue = o.default === undefined || o.default === null ? undefined : String(o.default);
57
+ settings.push({
58
+ ...base, type: "list", options: unique,
59
+ ...(defaultValue !== undefined && unique.some(option => option.value == defaultValue) ? { default: defaultValue } : {}),
60
+ });
61
+ }
62
+ else {
63
+ const { min, max, step } = o;
64
+ if (typeof min != "number" || typeof max != "number" || min > max) {
65
+ problems.push({ text: callText, reason: "This setting's min and max couldn't be read, so it isn't in Squiffy's Settings dialog." });
66
+ continue;
67
+ }
68
+ settings.push({
69
+ ...base, type: "range", min, max,
70
+ ...(typeof step == "number" && step > 0 ? { step } : {}),
71
+ ...(typeof o.default == "number" && o.default >= min && o.default <= max ? { default: o.default } : {}),
72
+ });
73
+ }
74
+ if (o.onInit !== undefined || o.onChange !== undefined) {
75
+ const setting = settings[settings.length - 1];
76
+ const example = setting.type == "toggle" ? `setting-${name}`
77
+ : setting.type == "list" ? `setting-${name}-${setting.options[0].value.replace(/[^A-Za-z0-9_-]+/g, "-")}`
78
+ : `setting-${name}-${setting.default ?? setting.min}`;
79
+ problems.push({
80
+ text: callText,
81
+ reason: `This setting's onInit and onChange are SugarCube JavaScript, which Squiffy doesn't run. The setting puts a class on the story's element instead, such as ${example}, which the stylesheet can use.`,
82
+ });
83
+ }
84
+ }
85
+ return { settings, problems };
86
+ }
87
+ function optionOf(item) {
88
+ if (typeof item == "string" && item.trim())
89
+ return { value: item, label: item };
90
+ if (typeof item == "number" || typeof item == "boolean")
91
+ return { value: String(item), label: String(item) };
92
+ return null;
93
+ }
94
+ const stripHtml = (text) => text.replace(/<[^>]*>/g, "").replace(/\s+/g, " ").trim();
95
+ // The list a variable is set to in the script, e.g. var sizes = ["Small", "Large"], or
96
+ // setup.sizes = [...]
97
+ function arrayNamed(script, name) {
98
+ const escaped = name.replace(/[.$]/g, m => "\\" + m);
99
+ const declaration = new RegExp(`(?:\\b(?:var|let|const)\\s+|(?<![\\w.$]))${escaped}\\s*=\\s*(?=\\[)`, "g");
100
+ const match = declaration.exec(script);
101
+ if (!match)
102
+ return undefined;
103
+ try {
104
+ return new LiteralParser(script, match.index + match[0].length).value(false);
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ }
110
+ // Reads JavaScript literals from a script. Anything else, such as a function, is skipped over and
111
+ // kept as code, so the arguments around it can still be read.
112
+ class LiteralParser {
113
+ constructor(s, i) {
114
+ Object.defineProperty(this, "s", {
115
+ enumerable: true,
116
+ configurable: true,
117
+ writable: true,
118
+ value: s
119
+ });
120
+ Object.defineProperty(this, "i", {
121
+ enumerable: true,
122
+ configurable: true,
123
+ writable: true,
124
+ value: i
125
+ });
126
+ }
127
+ // A call's arguments, up to its closing bracket
128
+ arguments() {
129
+ const args = [];
130
+ this.space();
131
+ if (this.accept(")"))
132
+ return args;
133
+ do {
134
+ this.space();
135
+ if (this.peek() == ")")
136
+ break;
137
+ args.push(this.value());
138
+ this.space();
139
+ } while (this.accept(","));
140
+ this.expect(")");
141
+ return args;
142
+ }
143
+ // A value, which is code if there's more to it, e.g. a sum. In a statement (not wholeExpression),
144
+ // what comes after it isn't looked at.
145
+ value(wholeExpression = true) {
146
+ this.space();
147
+ const c = this.peek();
148
+ const start = this.i;
149
+ let v;
150
+ if (c == "\"" || c == "'" || c == "`")
151
+ v = this.string();
152
+ else if (c == "[")
153
+ v = this.array();
154
+ else if (c == "{")
155
+ v = this.object();
156
+ else if (/[-+\d.]/.test(c) && /^[-+]?(\d|\.\d)/.test(this.s.substring(this.i, this.i + 3)))
157
+ v = this.number();
158
+ else {
159
+ const word = /^[A-Za-z_$][\w$]*(?:\s*\.\s*[A-Za-z_$][\w$]*)*/.exec(this.s.substring(this.i));
160
+ if (word && !["function", "async", "new"].includes(word[0])) {
161
+ this.i += word[0].length;
162
+ const name = word[0].replace(/\s+/g, "");
163
+ v = name == "true" ? true : name == "false" ? false : name == "null" || name == "undefined" ? null : { name };
164
+ }
165
+ else
166
+ v = { code: "" };
167
+ }
168
+ // Anything more, e.g. an arrow function's body or a sum, makes it code
169
+ if (!wholeExpression && !isCode(v))
170
+ return v;
171
+ this.space();
172
+ if (!this.atEnd()) {
173
+ this.skipExpression();
174
+ return { code: this.s.substring(start, this.i) };
175
+ }
176
+ return v;
177
+ }
178
+ atEnd() {
179
+ const c = this.peek();
180
+ return c == "," || c == ")" || c == "]" || c == "}" || c == "";
181
+ }
182
+ // Skips to the end of the expression: the next comma or closing bracket outside any brackets
183
+ skipExpression() {
184
+ let depth = 0;
185
+ while (this.i < this.s.length) {
186
+ const c = this.peek();
187
+ if (c == "\"" || c == "'" || c == "`") {
188
+ this.string();
189
+ continue;
190
+ }
191
+ if (c == "/" && (this.s[this.i + 1] == "/" || this.s[this.i + 1] == "*")) {
192
+ this.space();
193
+ continue;
194
+ }
195
+ if (c == "(" || c == "[" || c == "{")
196
+ depth++;
197
+ else if (c == ")" || c == "]" || c == "}") {
198
+ if (depth == 0)
199
+ return;
200
+ depth--;
201
+ }
202
+ else if (c == "," && depth == 0)
203
+ return;
204
+ this.i++;
205
+ }
206
+ throw new Error("Unfinished expression");
207
+ }
208
+ string() {
209
+ const quote = this.s[this.i++];
210
+ let out = "";
211
+ let template = false;
212
+ while (this.i < this.s.length) {
213
+ const c = this.s[this.i++];
214
+ if (c == quote)
215
+ return template ? { code: out } : out;
216
+ if (c == "\\") {
217
+ const e = this.s[this.i++];
218
+ out += e == "n" ? "\n" : e == "t" ? "\t" : e;
219
+ }
220
+ else {
221
+ if (quote == "`" && c == "$" && this.s[this.i] == "{")
222
+ template = true;
223
+ out += c;
224
+ }
225
+ }
226
+ throw new Error("Unfinished string");
227
+ }
228
+ number() {
229
+ const match = /^[-+]?(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?/i.exec(this.s.substring(this.i));
230
+ this.i += match[0].length;
231
+ return Number(match[0]);
232
+ }
233
+ array() {
234
+ this.expect("[");
235
+ const items = [];
236
+ this.space();
237
+ while (!this.accept("]")) {
238
+ items.push(this.value());
239
+ this.space();
240
+ if (!this.accept(",")) {
241
+ this.expect("]");
242
+ break;
243
+ }
244
+ this.space();
245
+ }
246
+ return items;
247
+ }
248
+ object() {
249
+ this.expect("{");
250
+ const result = {};
251
+ this.space();
252
+ while (!this.accept("}")) {
253
+ const c = this.peek();
254
+ let key;
255
+ if (c == "\"" || c == "'") {
256
+ const k = this.string();
257
+ if (typeof k != "string")
258
+ throw new Error("Bad key");
259
+ key = k;
260
+ }
261
+ else {
262
+ const word = /^[A-Za-z_$][\w$]*/.exec(this.s.substring(this.i));
263
+ if (!word)
264
+ throw new Error("Bad key");
265
+ key = word[0];
266
+ this.i += key.length;
267
+ }
268
+ this.space();
269
+ if (this.accept(":")) {
270
+ result[key] = this.value();
271
+ }
272
+ else if (this.peek() == "(") {
273
+ // A method, e.g. onChange() { ... }
274
+ const start = this.i;
275
+ this.skipExpression();
276
+ result[key] = { code: this.s.substring(start, this.i) };
277
+ }
278
+ else {
279
+ // Shorthand, e.g. { list }
280
+ result[key] = { name: key };
281
+ }
282
+ this.space();
283
+ if (!this.accept(",")) {
284
+ this.expect("}");
285
+ break;
286
+ }
287
+ this.space();
288
+ }
289
+ return result;
290
+ }
291
+ // Skips spaces and comments
292
+ space() {
293
+ for (;;) {
294
+ const rest = this.s.substring(this.i, this.i + 2);
295
+ if (/^\s/.test(rest))
296
+ this.i++;
297
+ else if (rest == "//") {
298
+ const end = this.s.indexOf("\n", this.i);
299
+ this.i = end < 0 ? this.s.length : end;
300
+ }
301
+ else if (rest == "/*") {
302
+ const end = this.s.indexOf("*/", this.i + 2);
303
+ this.i = end < 0 ? this.s.length : end + 2;
304
+ }
305
+ else
306
+ return;
307
+ }
308
+ }
309
+ peek() {
310
+ return this.s[this.i] ?? "";
311
+ }
312
+ accept(c) {
313
+ if (this.s[this.i] != c)
314
+ return false;
315
+ this.i++;
316
+ return true;
317
+ }
318
+ expect(c) {
319
+ if (!this.accept(c))
320
+ throw new Error(`Expected ${c}`);
321
+ }
322
+ }
@@ -4,9 +4,9 @@
4
4
  // such as <<if>>...<</if>>), links and naked variables, which is then written out as Squiffy:
5
5
  // <<if>> becomes {{#if}}, <<set>> becomes @set or {{set}}, links with setters become links with
6
6
  // setters, and <<link>> and friends become links to generated passages and sections.
7
- import { display, isDynamicTarget, isListCall, lengthOf, member as memberOf, print, randomInteger, skipString, targetName, Tokens, Unconvertible, unescapeString } from "./expression.js";
7
+ import { delayValue, display, isDynamicTarget, isListCall, lengthOf, member as memberOf, print, quote, randomInteger, skipString, targetName, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
8
  import { audioHelper, leadingAudio, pickSource, STOP_ALL_AUDIO } from "./audio.js";
9
- import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
9
+ import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter, passageHtmlBlock, readHtmlBlock, topScripts } from "./convert.js";
10
10
  const containers = new Set([
11
11
  "if", "for", "switch", "link", "button", "linkreplace", "linkappend", "linkprepend", "nobr", "silently", "capture",
12
12
  "script", "timed", "repeat", "widget", "cycle", "listbox", "append", "prepend", "replace", "type", "done", "do",
@@ -137,14 +137,11 @@ class Parser {
137
137
  continue;
138
138
  }
139
139
  }
140
- const scriptMatch = /^<(script|style)\b/i.exec(rest);
141
- if (scriptMatch) {
142
- const closeTag = `</${scriptMatch[1].toLowerCase()}>`;
143
- const end = src.toLowerCase().indexOf(closeTag, i);
144
- const stop = end == -1 ? src.length : end + closeTag.length;
140
+ const html = readHtmlBlock(src, i);
141
+ if (html) {
145
142
  flush();
146
- nodes.push({ t: "comment", text: src.substring(i, stop), reason: `A <${scriptMatch[1]}> in a passage isn't run by Squiffy. Move it to the story's JavaScript or CSS file.` });
147
- i = stop;
143
+ nodes.push(html.block);
144
+ i = html.end;
148
145
  continue;
149
146
  }
150
147
  const image = /^\[[<>]?img\[(?:([^|\]]*)\|)?([^\]]*)\](?:\[([^\]]*)\])?\]/i.exec(rest);
@@ -635,6 +632,9 @@ class ExpressionParser {
635
632
  return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
636
633
  if (object.name == "State.temporary" || object.name == "temporary")
637
634
  return { v: "expr", e: this.s.variable(property, true) };
635
+ // The player's settings (#452), which Squiffy reads the same way
636
+ if (object.name == "settings")
637
+ return { v: "expr", e: memberOf({ k: "var", name: "settings" }, { k: "str", v: property }) };
638
638
  return { v: "global", name: path };
639
639
  }
640
640
  return { v: "member", object, property };
@@ -979,6 +979,7 @@ class Writer {
979
979
  }
980
980
  passage(nodes, nobr) {
981
981
  const state = { leading: true, directives: [], nobr };
982
+ nodes = topScripts(this.ctx, nodes, state.directives);
982
983
  let body = this.nodes(nodes, state);
983
984
  for (const tag of [...this.open].reverse())
984
985
  body += `</${tag}>`;
@@ -1005,6 +1006,8 @@ class Writer {
1005
1006
  return node.s;
1006
1007
  case "comment":
1007
1008
  return this.ctx.unconvertible(node.text, node.reason);
1009
+ case "html":
1010
+ return passageHtmlBlock(this.ctx, node, false).text;
1008
1011
  case "var":
1009
1012
  state.leading = false;
1010
1013
  try {
@@ -1377,20 +1380,29 @@ class Writer {
1377
1380
  return this.nodes(m.clauses[0].nodes, state);
1378
1381
  case "timed": {
1379
1382
  state.leading = false;
1380
- let delay = 0;
1383
+ // Each <<next>> waits after the one before, for its own delay, or, with none, the
1384
+ // delay before it. A delay can be worked out as the story runs (#451).
1385
+ let delay = { k: "num", v: 0 };
1386
+ // The time since the text was shown, while every delay is a number
1387
+ let total = 0;
1381
1388
  let out = "";
1382
- for (const c of m.clauses) {
1389
+ m.clauses.forEach((c, i) => {
1383
1390
  const d = splitMacroArgs(c.args)[0];
1384
- const ms = d ? this.expr.parse(d) : { k: "num", v: 0 };
1385
- if (ms.k != "num")
1386
- throw new Unconvertible("<<timed>> with a delay that isn't fixed");
1387
- delay += ms.v;
1391
+ if (d)
1392
+ delay = this.expr.parse(d);
1393
+ total = total !== null && delay.k == "num" ? total + delay.v : null;
1388
1394
  const goto = this.gotoOnly(c.nodes);
1389
- if (goto)
1390
- out += goto.replace(/\}\}$/, ` after=${delay}}}`);
1391
- else
1392
- out += `{{#animate "fadeIn" start=${delay}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1393
- }
1395
+ if (goto) {
1396
+ // {{goto}} waits from when the text is shown, so it needs the delays added up
1397
+ if (i > 0 && total === null)
1398
+ throw new Unconvertible("<<goto>> in a <<next>> after a delay that isn't fixed");
1399
+ out += goto.replace(/\}\}$/, ` after=${i == 0 ? delayValue(delay) : total}}}`);
1400
+ }
1401
+ else {
1402
+ // Animations play one after another, so each waits after the one before
1403
+ out += `{{#animate "fadeIn" start=${delayValue(delay)}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1404
+ }
1405
+ });
1394
1406
  return out;
1395
1407
  }
1396
1408
  case "type": {
@@ -1405,15 +1417,21 @@ class Writer {
1405
1417
  state.leading = false;
1406
1418
  const bound = this.receiver(args[0] ?? "");
1407
1419
  const defaultValue = args[1] ? this.expr.parse(args[1]) : null;
1408
- if (args.slice(2).some(a => a != "autofocus")) {
1409
- this.ctx.approximate(m.raw, "Squiffy's text boxes don't go to a passage when Enter is pressed.");
1420
+ // <<textbox>> and <<numberbox>> can go to a passage when Enter is pressed (#454)
1421
+ const passageArg = m.name == "textarea" ? undefined : args.slice(2).find(a => a != "autofocus");
1422
+ let goes = "";
1423
+ if (passageArg !== undefined) {
1424
+ const target = this.expr.passageName(passageArg);
1425
+ if (!("name" in target))
1426
+ throw new Unconvertible(`<<${m.name}>> going to a passage whose name isn't fixed`);
1427
+ goes = ` data-section="${escapeAttribute(this.sectionName(target.name, m.raw))}"`;
1410
1428
  }
1411
1429
  const value = defaultValue?.k == "str" || defaultValue?.k == "num" ? String(defaultValue.v) : null;
1412
1430
  const set = defaultValue ? `{{set "${bound}" ${print(defaultValue)}}}` : "";
1413
1431
  if (m.name == "textarea")
1414
1432
  return `${set}<textarea data-attribute="${bound}">${escapeText(escapeHtml(value ?? ""))}</textarea>`;
1415
1433
  const type = m.name == "numberbox" ? "number" : "text";
1416
- return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}>`;
1434
+ return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}${goes}>`;
1417
1435
  }
1418
1436
  case "checkbox": {
1419
1437
  state.leading = false;
@@ -1476,9 +1494,10 @@ class Writer {
1476
1494
  if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1477
1495
  throw new Unconvertible("<<break>> and <<continue>>");
1478
1496
  const loop = this.forLoop(m.args);
1479
- const numbers = loop.collection.k == "call" && loop.collection.fn == "range";
1497
+ const numbers = loop.numbers || (loop.collection.k == "call" && loop.collection.fn == "range");
1480
1498
  const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state), numbers);
1481
- return `{{#each ${print(loop.collection)}}}${body}{{/each}}`;
1499
+ const collection = print(loop.collection);
1500
+ return `{{#each ${loop.collection.k == "cond" ? `(${collection})` : collection}}}${body}{{/each}}`;
1482
1501
  }
1483
1502
  case "widget":
1484
1503
  return "";
@@ -1518,9 +1537,16 @@ class Writer {
1518
1537
  state.leading = false;
1519
1538
  return `{{${m.name} ${print(this.expr.parse(args[1]))}}}`;
1520
1539
  }
1521
- case "repeat":
1522
- throw new Unconvertible("<<repeat>>, which runs again and again");
1540
+ case "repeat": {
1541
+ // <<repeat 1s>>: its text is added again every second, until a <<stop>> (#451)
1542
+ state.leading = false;
1543
+ if (!args[0])
1544
+ throw new Unconvertible("<<repeat>> without a delay");
1545
+ const delay = delayValue(this.expr.parse(args[0]));
1546
+ return `{{#every ${delay} append=true}}${this.body(m, { ...state, leading: false })}{{/every}}`;
1547
+ }
1523
1548
  case "stop":
1549
+ return "{{stop}}";
1524
1550
  case "silent":
1525
1551
  return "";
1526
1552
  case "elseif":
@@ -1548,8 +1574,20 @@ class Writer {
1548
1574
  if (range) {
1549
1575
  const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1550
1576
  const collection = this.expr.parse(range[3]);
1577
+ // A number, <<for _i range 5>>, goes through 0 to 4, with the same number as the item
1578
+ // and its position. A calculation must be a number, but an attribute could be a list.
1579
+ if (collection.k == "num" || collection.k == "neg" || (collection.k == "bin" && "+-*/%".includes(collection.op))) {
1580
+ const zero = { k: "num", v: 0 };
1581
+ const last = collection.k == "num" ? { k: "num", v: collection.v - 1 } : { k: "bin", op: "-", l: collection, r: { k: "num", v: 1 } };
1582
+ const numbers = { k: "call", fn: "range", args: [zero, last] };
1583
+ // (range 0 -1) would count down, so there's nothing to go through unless it's above 0
1584
+ const counted = collection.k == "num"
1585
+ ? (collection.v > 0 ? numbers : { k: "array", items: [] })
1586
+ : { k: "cond", test: { k: "bin", op: ">", l: collection, r: zero }, then: numbers, otherwise: { k: "array", items: [] } };
1587
+ return { collection: counted, vars: new Map([...vars.keys()].map(v => [v, "item"])), numbers: true };
1588
+ }
1551
1589
  if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item") && !isListCall(collection)) {
1552
- throw new Unconvertible("<<for>> with range over something other than an array");
1590
+ throw new Unconvertible("<<for>> with range over something other than an array or a number");
1553
1591
  }
1554
1592
  // With a position as well, $list[_i] is the item too
1555
1593
  return { collection, vars, array: collection.k == "var" ? collection.name : undefined };
@@ -1576,12 +1614,15 @@ class Writer {
1576
1614
  }
1577
1615
  throw new Unconvertible("<<for>> loops, except ones that go through an array (with range), or count up or down by 1");
1578
1616
  }
1579
- // The attribute a form macro like <<textbox "$name">> sets
1617
+ // The attribute a form macro like <<textbox "$name">> sets, or the value inside an object,
1618
+ // as in <<textbox "$hero.name">> (#454)
1580
1619
  receiver(arg) {
1581
- const match = /^["']([$_])([A-Za-z_]\w*)["']$/.exec(arg);
1582
- if (!match)
1583
- throw new Unconvertible("a form control that doesn't set a plain variable");
1584
- return this.expr.attribute(match[2], match[1] == "_");
1620
+ const match = /^(["'])([$_][\s\S]*)\1$/.exec(arg);
1621
+ const e = match ? this.expr.parse(match[2]) : null;
1622
+ if (e?.k != "var" || isDynamicTarget(e.name)) {
1623
+ throw new Unconvertible("a form control that doesn't set a variable, or a value inside one with a fixed name");
1624
+ }
1625
+ return e.name;
1585
1626
  }
1586
1627
  linkText(arg) {
1587
1628
  if (arg.startsWith("[[")) {
@@ -1619,6 +1660,18 @@ class Writer {
1619
1660
  }
1620
1661
  // <<link>>, <<button>>: the body runs when it's clicked, then the story goes to the passage
1621
1662
  // given, if there is one
1663
+ // "restart", "saves" or "settings", if a link's body is only <<run UI.restart()>>,
1664
+ // UI.saves() or UI.settings(), or the same in <<script>>
1665
+ uiAction(body) {
1666
+ if (body.length != 1 || body[0].t != "macro")
1667
+ return null;
1668
+ const m = body[0];
1669
+ const code = m.name == "run" ? m.args
1670
+ : m.name == "script" ? (m.clauses?.[0]?.nodes ?? []).map(n => n.t == "text" || n.t == "raw" ? n.s : "\0").join("")
1671
+ : null;
1672
+ const match = code === null ? null : /^\s*UI\.(restart|saves|settings)\(\s*\)\s*;?\s*$/.exec(code);
1673
+ return match ? match[1] : null;
1674
+ }
1622
1675
  linkMacro(m, args) {
1623
1676
  let text;
1624
1677
  let passage = null;
@@ -1659,6 +1712,12 @@ class Writer {
1659
1712
  const destination = gotoArg !== null ? this.expr.passageName(gotoArg)
1660
1713
  : passage !== null ? { name: passage }
1661
1714
  : dynamicDestination ? { expr: dynamicDestination } : null;
1715
+ // A link that only runs UI.restart(), UI.saves() or UI.settings(): {{restart}}, {{saves}}
1716
+ // or {{settings}} (#452). Like
1717
+ // SugarCube's, {{restart}} asks the player first.
1718
+ const uiAction = destination ? null : this.uiAction(significant);
1719
+ if (uiAction)
1720
+ return `{{${uiAction} text=${quote(text.plain)}}}`;
1662
1721
  // Only <<set>>s: a link with setters
1663
1722
  const bodySetters = this.bodySetters(significant);
1664
1723
  if (destination && bodySetters) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "squiffy-compiler",
3
- "version": "7.0.0-beta.7",
3
+ "version": "7.0.0-beta.8",
4
4
  "description": "A tool for creating multiple-choice interactive stories",
5
5
  "author": "Alex Warren",
6
6
  "contributors": [
@@ -15,6 +15,9 @@
15
15
  },
16
16
  "license": "MIT",
17
17
  "preferGlobal": true,
18
+ "dependencies": {
19
+ "handlebars": "^4.7.10"
20
+ },
18
21
  "devDependencies": {
19
22
  "@types/node": "^26.6.6",
20
23
  "glob": "^14.0.6",
@@ -39,6 +42,10 @@
39
42
  "types": "./dist/language-service.d.ts",
40
43
  "default": "./dist/language-service.js"
41
44
  },
45
+ "./infix-expressions": {
46
+ "types": "./dist/infix-expressions.d.ts",
47
+ "default": "./dist/infix-expressions.js"
48
+ },
42
49
  "./node": {
43
50
  "types": "./dist/node.d.ts",
44
51
  "default": "./dist/node.js"
@@ -51,5 +58,5 @@
51
58
  "syntaxes/squiffy.tmLanguage.json"
52
59
  ],
53
60
  "type": "module",
54
- "gitHead": "ce089d0f0d0901c10e5a148e38cb1fdbb5d5a2d2"
61
+ "gitHead": "385947977612d33f310c92ef6ed9e1a423d8cb19"
55
62
  }
@@ -285,7 +285,7 @@
285
285
  }
286
286
  },
287
287
  {
288
- "match": "^\\s*(@)(title|start|import|ui|music|sound|class)\\s+(.*?)\\s*$",
288
+ "match": "^\\s*(@)(title|start|import|ui|music|sound|class|transition|leave)\\s+(.*?)\\s*$",
289
289
  "captures": {
290
290
  "0": {
291
291
  "name": "meta.directive.squiffy"