squiffy-compiler 6.0.1 → 7.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +96 -0
  3. package/dist/analyse.js +951 -0
  4. package/dist/compiler.d.ts +32 -40
  5. package/dist/compiler.js +26 -691
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +71 -0
  9. package/dist/emit.js +192 -0
  10. package/dist/helpers.d.ts +1 -0
  11. package/dist/helpers.js +14 -0
  12. package/dist/ignore.d.ts +8 -0
  13. package/dist/ignore.js +71 -0
  14. package/dist/infix-expressions.d.ts +19 -0
  15. package/dist/infix-expressions.js +713 -0
  16. package/dist/language-service.d.ts +90 -0
  17. package/dist/language-service.js +883 -0
  18. package/dist/node.d.ts +23 -0
  19. package/dist/node.js +122 -0
  20. package/dist/parse.d.ts +22 -0
  21. package/dist/parse.js +316 -0
  22. package/dist/project.d.ts +129 -0
  23. package/dist/project.js +488 -0
  24. package/dist/quest/aslx.d.ts +51 -0
  25. package/dist/quest/aslx.js +184 -0
  26. package/dist/quest/convert.d.ts +20 -0
  27. package/dist/quest/convert.js +552 -0
  28. package/dist/quest/script.d.ts +92 -0
  29. package/dist/quest/script.js +453 -0
  30. package/dist/quest/scripts.d.ts +24 -0
  31. package/dist/quest/scripts.js +506 -0
  32. package/dist/quest/text.d.ts +18 -0
  33. package/dist/quest/text.js +323 -0
  34. package/dist/section-labels.d.ts +4 -0
  35. package/dist/section-labels.js +64 -0
  36. package/dist/setters.d.ts +49 -0
  37. package/dist/setters.js +477 -0
  38. package/dist/story-graph.d.ts +71 -0
  39. package/dist/story-graph.js +445 -0
  40. package/dist/syntax.d.ts +198 -0
  41. package/dist/syntax.js +8 -0
  42. package/dist/templates.d.ts +17 -0
  43. package/dist/templates.js +180 -0
  44. package/dist/text.d.ts +44 -0
  45. package/dist/text.js +348 -0
  46. package/dist/twine/audio.d.ts +21 -0
  47. package/dist/twine/audio.js +80 -0
  48. package/dist/twine/convert.d.ts +131 -0
  49. package/dist/twine/convert.js +1057 -0
  50. package/dist/twine/expression.d.ts +88 -0
  51. package/dist/twine/expression.js +318 -0
  52. package/dist/twine/harlowe.d.ts +27 -0
  53. package/dist/twine/harlowe.js +2341 -0
  54. package/dist/twine/settings.d.ts +9 -0
  55. package/dist/twine/settings.js +322 -0
  56. package/dist/twine/story.d.ts +24 -0
  57. package/dist/twine/story.js +231 -0
  58. package/dist/twine/sugarcube.d.ts +40 -0
  59. package/dist/twine/sugarcube.js +2172 -0
  60. package/dist/v5.js +2 -1
  61. package/package.json +35 -6
  62. package/syntaxes/squiffy.tmLanguage.json +1003 -0
@@ -0,0 +1,2341 @@
1
+ // Converts a Harlowe passage to Squiffy text.
2
+ //
3
+ // The passage is parsed into a tree (text, macros with the hooks attached to them, links,
4
+ // variables), which is then written out: (if:) chains become {{#if}}, (set:) becomes @set or
5
+ // {{set}}, (link:) and friends become links to generated passages and sections, and Harlowe's
6
+ // markup becomes Markdown and HTML.
7
+ import { conditional, delayValue, display, isBoolean, isDynamicTarget, isListCall, lengthOf, member, print, randomInteger, targetName, skipBalanced, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { audioHelper, leadingAudio, pickSource, STOP_ALL_AUDIO } from "./audio.js";
9
+ import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter, passageHtmlBlock, readHtmlBlock, topScripts } from "./convert.js";
10
+ // Macro names ignore case, - and _
11
+ function normalise(name) {
12
+ return name.toLowerCase().replace(/[-_]/g, "");
13
+ }
14
+ // Macros that change a hook, so may have whitespace between them and it
15
+ const changers = new Set([
16
+ "if", "elseif", "else", "unless", "link", "linkreveal", "linkrepeat", "linkrerun", "linkrevealgoto", "after",
17
+ "live", "textstyle", "textcolour", "textcolor", "colour", "color", "background", "bg", "font", "textsize", "size",
18
+ "align", "css", "transition", "t8n", "transitiontime", "t8ntime", "transitiondepart", "t8ndepart",
19
+ "transitionarrive", "t8narrive", "transitiondelay", "t8ndelay", "transitionskip", "t8nskip", "hidden", "nobr",
20
+ "collapse", "verbatim", "v6m", "replace", "append", "prepend", "click", "clickreplace", "clickappend",
21
+ "clickprepend", "mouseover", "mouseout", "hover", "hoverstyle", "for", "loop", "event", "show", "linkshow",
22
+ "opacity", "textrotate", "textrotatez", "box", "border", "b4r", "bordercolour", "bordercolor", "b4rcolour",
23
+ "cornerradius", "textindent", "float", "hookname", "action", "linkundo", "linkfullscreen", "more",
24
+ "clickgoto", "mouseovergoto", "mouseoverreplace", "mouseoverappend", "mouseoverprepend", "mouseoutreplace",
25
+ "linkstyle", "charstyle", "linestyle", "button", "textshadow", "outline", "hiddenhook", "seqlink", "output", "out",
26
+ ]);
27
+ class Parser {
28
+ constructor(src) {
29
+ Object.defineProperty(this, "src", {
30
+ enumerable: true,
31
+ configurable: true,
32
+ writable: true,
33
+ value: src
34
+ });
35
+ }
36
+ // Parses until the end, or the given closing character at this level
37
+ parse(start, close) {
38
+ const src = this.src;
39
+ const nodes = [];
40
+ let text = "";
41
+ const flush = () => {
42
+ if (text)
43
+ nodes.push({ t: "text", s: text });
44
+ text = "";
45
+ };
46
+ let i = start;
47
+ while (i < src.length) {
48
+ const c = src[i];
49
+ if (c == close) {
50
+ flush();
51
+ return { nodes, end: i };
52
+ }
53
+ const rest = src.substring(i, i + 200);
54
+ if (rest.startsWith("<!--")) {
55
+ const end = src.indexOf("-->", i + 4);
56
+ const stop = end == -1 ? src.length : end + 3;
57
+ flush();
58
+ nodes.push({ t: "raw", s: src.substring(i, stop).replace(/\n/g, " ") });
59
+ i = stop;
60
+ continue;
61
+ }
62
+ const html = readHtmlBlock(src, i);
63
+ if (html) {
64
+ flush();
65
+ nodes.push(html.block);
66
+ i = html.end;
67
+ continue;
68
+ }
69
+ if (c == "`") {
70
+ let n = 0;
71
+ while (src[i + n] == "`")
72
+ n++;
73
+ const fence = "`".repeat(n);
74
+ let end = src.indexOf(fence, i + n);
75
+ while (end != -1 && src[end + n] == "`")
76
+ end = src.indexOf(fence, end + n + 1);
77
+ if (end != -1) {
78
+ flush();
79
+ nodes.push({ t: "raw", s: escapeText(escapeHtml(src.substring(i + n, end))) });
80
+ i = end + n;
81
+ continue;
82
+ }
83
+ }
84
+ if (rest.startsWith("[[") && !rest.startsWith("[[[")) {
85
+ const end = src.indexOf("]]", i + 2);
86
+ const inner = end == -1 ? "" : src.substring(i + 2, end);
87
+ if (end != -1 && !inner.includes("[") && !inner.includes("\n")) {
88
+ flush();
89
+ nodes.push(parseLink(inner, src.substring(i, end + 2)));
90
+ i = end + 2;
91
+ continue;
92
+ }
93
+ }
94
+ const namedHook = /^\|([\w-]+)([>)])\[/.exec(rest);
95
+ if (namedHook) {
96
+ flush();
97
+ const hook = this.hook(i + namedHook[0].length - 1);
98
+ hook.hook.name = namedHook[1];
99
+ hook.hook.hidden = namedHook[2] == ")";
100
+ nodes.push({ t: "hook", hook: hook.hook });
101
+ i = hook.end;
102
+ continue;
103
+ }
104
+ if (c == "[") {
105
+ flush();
106
+ const hook = this.hook(i);
107
+ nodes.push({ t: "hook", hook: hook.hook });
108
+ i = hook.end;
109
+ continue;
110
+ }
111
+ const macroStart = /^\(([A-Za-z][\w-]*):/.exec(rest);
112
+ if (macroStart) {
113
+ const end = skipBalanced(src, i, "(", ")");
114
+ if (end != -1) {
115
+ flush();
116
+ const result = this.macro(i, end);
117
+ nodes.push(result.node);
118
+ i = result.end;
119
+ continue;
120
+ }
121
+ }
122
+ const call = /^\(([$_])(\w+):/.exec(rest);
123
+ if (call) {
124
+ // A call to a custom macro
125
+ const end = skipBalanced(src, i, "(", ")");
126
+ if (end != -1) {
127
+ flush();
128
+ const raw = src.substring(i, end);
129
+ nodes.push({ t: "call", name: call[2], temp: call[1] == "_", args: raw.substring(call[0].length, raw.length - 1), raw });
130
+ i = end;
131
+ continue;
132
+ }
133
+ }
134
+ const tag = c == "<" ? /^<\/?[A-Za-z][^<>]*>/.exec(src.substring(i, i + 2000)) : null;
135
+ if (tag) {
136
+ // An HTML tag is text: target="_blank" isn't a temporary variable
137
+ text += tag[0];
138
+ i += tag[0].length;
139
+ continue;
140
+ }
141
+ const variable = /^([$_])([A-Za-z]\w*)/.exec(rest);
142
+ if (variable && (variable[1] == "$" || !/\w/.test(src[i - 1] ?? ""))) {
143
+ const after = src.substring(i + variable[0].length, i + variable[0].length + 4);
144
+ const property = /^(?:'s\s+(?:[A-Za-z]\w*|\d+(?:st|nd|rd|th)|"[^"\n]*"|'[^'\n]*'))+/.exec(src.substring(i + variable[0].length, i + variable[0].length + 200));
145
+ if (property) {
146
+ // $player's hp: shown as (print:) would show it
147
+ flush();
148
+ const raw = variable[0] + property[0];
149
+ nodes.push({ t: "macro", name: "print", raw, args: raw, changers: [] });
150
+ i += raw.length;
151
+ continue;
152
+ }
153
+ if (after.startsWith("[")) {
154
+ // A changer stored in a variable attached to a hook
155
+ const end = this.hook(i + variable[0].length).end;
156
+ flush();
157
+ nodes.push({ t: "comment", text: src.substring(i, end), reason: "A changer stored in a variable can't be converted." });
158
+ i = end;
159
+ continue;
160
+ }
161
+ flush();
162
+ nodes.push({ t: "var", name: variable[2], temp: variable[1] == "_", raw: variable[0] });
163
+ i += variable[0].length;
164
+ continue;
165
+ }
166
+ if (c == "{") {
167
+ const inner = this.parse(i + 1, "}");
168
+ if (inner.end < src.length) {
169
+ flush();
170
+ nodes.push({ t: "collapse", nodes: inner.nodes });
171
+ i = inner.end + 1;
172
+ continue;
173
+ }
174
+ }
175
+ text += c;
176
+ i++;
177
+ }
178
+ flush();
179
+ return { nodes, end: i };
180
+ }
181
+ // A hook, from its opening [, with any name after its closing ]
182
+ hook(open) {
183
+ const inner = this.parse(open + 1, "]");
184
+ let end = Math.min(inner.end + 1, this.src.length);
185
+ const hook = { nodes: inner.nodes, raw: this.src.substring(open, end) };
186
+ const named = /^([<(])([\w-]+)\|/.exec(this.src.substring(end, end + 100));
187
+ if (named) {
188
+ hook.name = named[2];
189
+ hook.hidden = named[1] == "(";
190
+ end += named[0].length;
191
+ }
192
+ return { hook, end };
193
+ }
194
+ macro(start, end) {
195
+ const src = this.src;
196
+ const raw = src.substring(start, end);
197
+ const colon = raw.indexOf(":");
198
+ const name = normalise(raw.substring(1, colon));
199
+ const node = { t: "macro", name, raw, args: raw.substring(colon + 1, raw.length - 1), changers: [] };
200
+ let i = end;
201
+ // Changers added together: (if: $x)+(text-style: "bold")[...]
202
+ for (;;) {
203
+ const plus = /^\s*\+\s*\(([A-Za-z][\w-]*):/.exec(src.substring(i, i + 100));
204
+ if (!plus)
205
+ break;
206
+ const open = i + plus[0].indexOf("(");
207
+ const close = skipBalanced(src, open, "(", ")");
208
+ if (close == -1)
209
+ break;
210
+ const extra = src.substring(open, close);
211
+ const extraColon = extra.indexOf(":");
212
+ node.changers.push({ t: "macro", name: normalise(extra.substring(1, extraColon)), raw: extra, args: extra.substring(extraColon + 1, extra.length - 1), changers: [] });
213
+ node.raw += src.substring(i, close);
214
+ i = close;
215
+ }
216
+ // Changers can be separated from their hooks by whitespace, even line breaks
217
+ let hookStart = i;
218
+ if (changers.has(name) || name.startsWith("click") || name.startsWith("mouse")) {
219
+ while (/\s/.test(src[hookStart] ?? ""))
220
+ hookStart++;
221
+ if (src[hookStart] != "[" && !src.startsWith("|", hookStart))
222
+ hookStart = i;
223
+ }
224
+ if (src[hookStart] == "[" && !src.startsWith("[[", hookStart) || src.startsWith("[[[", hookStart)) {
225
+ const hook = this.hook(hookStart);
226
+ node.hook = hook.hook;
227
+ return { node, end: hook.end };
228
+ }
229
+ const named = /^\|([\w-]+)([>)])\[/.exec(src.substring(hookStart, hookStart + 100));
230
+ if (named && changers.has(name)) {
231
+ const hook = this.hook(hookStart + named[0].length - 1);
232
+ hook.hook.name = named[1];
233
+ hook.hook.hidden = named[2] == ")";
234
+ node.hook = hook.hook;
235
+ return { node, end: hook.end };
236
+ }
237
+ return { node, end: i };
238
+ }
239
+ }
240
+ function parseLink(inner, raw) {
241
+ let text;
242
+ let target;
243
+ const arrow = inner.lastIndexOf("->");
244
+ const back = inner.indexOf("<-");
245
+ if (arrow != -1) {
246
+ text = inner.substring(0, arrow);
247
+ target = inner.substring(arrow + 2);
248
+ }
249
+ else if (back != -1) {
250
+ target = inner.substring(0, back);
251
+ text = inner.substring(back + 2);
252
+ }
253
+ else if (inner.includes("|")) {
254
+ const bar = inner.lastIndexOf("|");
255
+ text = inner.substring(0, bar);
256
+ target = inner.substring(bar + 1);
257
+ }
258
+ else {
259
+ text = target = inner;
260
+ }
261
+ return { t: "link", raw, text, target: target.trim() };
262
+ }
263
+ function escapeHtml(s) {
264
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
265
+ }
266
+ // Splits macro arguments on the commas between them
267
+ export function splitArgs(args) {
268
+ const result = [];
269
+ let depth = 0;
270
+ let current = "";
271
+ for (let i = 0; i < args.length; i++) {
272
+ const c = args[i];
273
+ const possessive = c == "'" && args[i + 1] == "s" && /\s/.test(args[i + 2] ?? "") && /[\w)]/.test(args[i - 1] ?? "");
274
+ if ((c == "\"" || c == "'") && !possessive) {
275
+ const end = skipString(args, i);
276
+ const stop = end == -1 ? args.length : end;
277
+ current += args.substring(i, stop);
278
+ i = stop - 1;
279
+ continue;
280
+ }
281
+ if (c == "(" || c == "[")
282
+ depth++;
283
+ else if (c == ")" || c == "]")
284
+ depth--;
285
+ if (c == "," && depth == 0) {
286
+ result.push(current);
287
+ current = "";
288
+ }
289
+ else {
290
+ current += c;
291
+ }
292
+ }
293
+ if (current.trim() || result.length)
294
+ result.push(current);
295
+ return result.map(a => a.trim());
296
+ }
297
+ const operators = [">=", "<=", "is not in", "is in", "is not", "does not contain", "'s", "+", "-", "*", "/", "%", ">", "<", "=", "!="];
298
+ function tokenize(s) {
299
+ const tokens = [];
300
+ let i = 0;
301
+ while (i < s.length) {
302
+ const c = s[i];
303
+ if (/\s/.test(c)) {
304
+ i++;
305
+ continue;
306
+ }
307
+ if (s.startsWith("'s", i) && /\s/.test(s[i + 2] ?? "") && i > 0 && /[\w)]/.test(s[i - 1])) {
308
+ tokens.push({ type: "op", text: "'s" });
309
+ i += 2;
310
+ continue;
311
+ }
312
+ // 2nd, or 2ndlast, which is a negative position: from the end
313
+ const ordinal = /^(\d+)(st|nd|rd|th)(last)?\b/.exec(s.substring(i));
314
+ if (ordinal) {
315
+ tokens.push({ type: "word", text: "ordinal", value: parseInt(ordinal[1]) * (ordinal[3] ? -1 : 1) });
316
+ i += ordinal[0].length;
317
+ continue;
318
+ }
319
+ if (c == "\"" || c == "'") {
320
+ const end = skipString(s, i);
321
+ if (end == -1)
322
+ throw new Unconvertible("an expression with a string that isn't closed");
323
+ tokens.push({ type: "str", text: s.substring(i, end), value: unescapeString(s.substring(i, end)) });
324
+ i = end;
325
+ continue;
326
+ }
327
+ const num = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)?(?![\w])/i.exec(s.substring(i));
328
+ if (num) {
329
+ let value = parseFloat(num[1]);
330
+ if (num[2]?.toLowerCase() == "s")
331
+ value *= 1000;
332
+ tokens.push({ type: "num", text: num[0], value });
333
+ i += num[0].length;
334
+ continue;
335
+ }
336
+ const variable = /^([$_?])([A-Za-z]\w*)/.exec(s.substring(i));
337
+ if (variable) {
338
+ tokens.push({ type: variable[1] == "$" ? "var" : variable[1] == "_" ? "temp" : "hook", text: variable[0], value: variable[2] });
339
+ i += variable[0].length;
340
+ continue;
341
+ }
342
+ const macro = /^\(([A-Za-z][\w-]*):/.exec(s.substring(i));
343
+ if (macro) {
344
+ const end = skipBalanced(s, i, "(", ")");
345
+ if (end == -1)
346
+ throw new Unconvertible("an expression with a macro that isn't closed");
347
+ tokens.push({ type: "macro", text: s.substring(i, end), value: normalise(macro[1]) });
348
+ i = end;
349
+ continue;
350
+ }
351
+ if (c == "(" || c == ")" || c == ",") {
352
+ tokens.push({ type: c, text: c });
353
+ i++;
354
+ continue;
355
+ }
356
+ const op = operators.find(o => s.startsWith(o, i) && (!/\w$/.test(o) || !/\w/.test(s[i + o.length] ?? "")));
357
+ if (op) {
358
+ tokens.push({ type: "op", text: op });
359
+ i += op.length;
360
+ continue;
361
+ }
362
+ const word = /^[A-Za-z]\w*/.exec(s.substring(i));
363
+ if (word) {
364
+ tokens.push({ type: "word", text: word[0].toLowerCase(), value: word[0] });
365
+ i += word[0].length;
366
+ continue;
367
+ }
368
+ throw new Unconvertible(`an expression Squiffy can't read ("${s.substring(i, i + 10)}")`);
369
+ }
370
+ return tokens;
371
+ }
372
+ export class HarloweExpressions {
373
+ constructor(ctx) {
374
+ Object.defineProperty(this, "ctx", {
375
+ enumerable: true,
376
+ configurable: true,
377
+ writable: true,
378
+ value: ctx
379
+ });
380
+ }
381
+ // The Squiffy attribute for a Harlowe variable
382
+ attribute(name, temp) {
383
+ return this.ctx.story.attribute(name, temp);
384
+ }
385
+ // A Harlowe variable's value: its attribute, or inside a (for:), the loop's item
386
+ variable(name, temp) {
387
+ return this.ctx.story.variable(name, temp);
388
+ }
389
+ parse(source, it) {
390
+ const tokens = new Tokens(tokenize(source));
391
+ const e = new ExpressionParser(this, tokens, it).expression();
392
+ if (!tokens.done)
393
+ throw new Unconvertible(`an expression Squiffy can't read (at "${tokens.peek().text}")`);
394
+ return e;
395
+ }
396
+ // A Harlowe value used as a passage name, for (goto:), (display:) and links
397
+ passageName(source) {
398
+ const e = this.parse(source);
399
+ if (e.k == "str")
400
+ return { name: e.v };
401
+ return { expr: e };
402
+ }
403
+ // A macro in an expression, e.g. (either: "a", "b")
404
+ macro(name, raw, it) {
405
+ const args = splitArgs(raw.substring(raw.indexOf(":") + 1, raw.length - 1));
406
+ const values = () => args.map(a => this.parse(a, it));
407
+ const one = () => {
408
+ if (args.length != 1)
409
+ throw new Unconvertible(`(${name}:) with ${args.length ? "more than one value" : "no value"}`);
410
+ return values();
411
+ };
412
+ // The values of a macro like (sorted:) as a list: ...$bag is the list itself, and values
413
+ // are a list of them
414
+ const list = (from) => {
415
+ const spread = (v) => /^\s*\.\.\./.test(v) ? this.parse(v.replace(/^\s*\.\.\./, ""), it) : null;
416
+ if (from.length == 1) {
417
+ const e = spread(from[0]);
418
+ if (e)
419
+ return e;
420
+ }
421
+ const items = [];
422
+ for (const v of from) {
423
+ const e = spread(v);
424
+ if (!e)
425
+ items.push(this.parse(v, it));
426
+ else if (e.k == "array")
427
+ items.push(...e.items);
428
+ else
429
+ throw new Unconvertible(`(${name}:) with an array and other values`);
430
+ }
431
+ return { k: "array", items };
432
+ };
433
+ switch (name) {
434
+ case "either":
435
+ return { k: "call", fn: "random", args: [{ k: "array", items: values() }] };
436
+ case "random": {
437
+ const [min, max] = values();
438
+ return randomInteger(min, max);
439
+ }
440
+ case "a":
441
+ case "array":
442
+ return { k: "array", items: values() };
443
+ case "range": {
444
+ // The whole numbers from one to the other
445
+ if (args.length != 2)
446
+ throw new Unconvertible("(range:) without two numbers");
447
+ const [from, to] = values();
448
+ // Squiffy's (range from to) works it out as the story runs (#447). A short one
449
+ // with fixed numbers is written out, as it reads more simply.
450
+ if (from.k != "num" || to.k != "num" || Math.abs(to.v - from.v) > 20)
451
+ return { k: "call", fn: "range", args: [from, to] };
452
+ const step = to.v >= from.v ? 1 : -1;
453
+ const items = [];
454
+ for (let n = Math.round(from.v); n != Math.round(to.v) + step; n += step)
455
+ items.push({ k: "num", v: n });
456
+ return { k: "array", items };
457
+ }
458
+ case "visited": {
459
+ if (args.length == 0)
460
+ return { k: "bin", op: ">", l: this.visits(), r: { k: "num", v: 0 } };
461
+ const target = this.parse(args[0]);
462
+ if (target.k != "str")
463
+ throw new Unconvertible("(visited:) with something other than a passage name");
464
+ return { k: "call", fn: "seen", args: [{ k: "str", v: this.ctx.story.sectionForUnknown(target.v) }] };
465
+ }
466
+ case "str":
467
+ case "string":
468
+ case "text":
469
+ case "num":
470
+ case "number":
471
+ if (args.length != 1)
472
+ throw new Unconvertible(`(${name}:) with more than one value`);
473
+ return this.parse(args[0], it);
474
+ case "history":
475
+ throw new Unconvertible("(history:), except as (history:) contains \"passage\"");
476
+ case "passage":
477
+ throw new Unconvertible("(passage:)");
478
+ case "dm":
479
+ case "datamap": {
480
+ // An object (#442)
481
+ const items = values();
482
+ if (items.length % 2)
483
+ throw new Unconvertible("a datamap with a name that has no value");
484
+ const entries = [];
485
+ for (let n = 0; n < items.length; n += 2) {
486
+ const key = items[n];
487
+ if (key.k != "str" && key.k != "num")
488
+ throw new Unconvertible("a datamap with names that aren't fixed");
489
+ entries.push([String(key.v), items[n + 1]]);
490
+ }
491
+ return { k: "object", entries };
492
+ }
493
+ case "ds":
494
+ case "dataset":
495
+ throw new Unconvertible("Harlowe datasets");
496
+ case "cond":
497
+ return conditional(values(), "(cond:)");
498
+ // Text and numbers (#446)
499
+ case "lowercase":
500
+ case "uppercase":
501
+ case "upperfirst": {
502
+ const [text] = one();
503
+ return { k: "call", fn: name == "lowercase" ? "lower" : name == "uppercase" ? "upper" : "capitalise", args: [text] };
504
+ }
505
+ case "round":
506
+ case "floor":
507
+ case "ceil":
508
+ case "abs":
509
+ return { k: "call", fn: name, args: one() };
510
+ case "min":
511
+ case "max": {
512
+ const items = values();
513
+ if (!items.length)
514
+ throw new Unconvertible(`(${name}:) with no values`);
515
+ return { k: "call", fn: name, args: items };
516
+ }
517
+ // Lists (#447)
518
+ case "joined": {
519
+ if (!args.length)
520
+ throw new Unconvertible("(joined:) with nothing to join");
521
+ const separator = this.parse(args[0], it);
522
+ return { k: "call", fn: "join", args: [list(args.slice(1)), separator] };
523
+ }
524
+ case "sorted":
525
+ case "shuffled":
526
+ if (args.length && /^\s*(via|each)\b/.test(args[0]))
527
+ throw new Unconvertible(`(${name}:) with "${args[0].trim().split(/\s/)[0]}"`);
528
+ return { k: "call", fn: name == "sorted" ? "sort" : "shuffle", args: [list(args)] };
529
+ case "count": {
530
+ if (args.length != 2)
531
+ throw new Unconvertible("(count:) with more than one value to count");
532
+ const [container, value] = values();
533
+ return { k: "call", fn: "count", args: [container, value] };
534
+ }
535
+ default:
536
+ throw new Unconvertible(`the (${name}:) macro`);
537
+ }
538
+ }
539
+ // (visits:), the number of visits to this passage
540
+ visits() {
541
+ return { k: "call", fn: "visits", args: [{ k: "str", v: this.ctx.section }] };
542
+ }
543
+ }
544
+ class ExpressionParser {
545
+ constructor(h, tokens, it) {
546
+ Object.defineProperty(this, "h", {
547
+ enumerable: true,
548
+ configurable: true,
549
+ writable: true,
550
+ value: h
551
+ });
552
+ Object.defineProperty(this, "tokens", {
553
+ enumerable: true,
554
+ configurable: true,
555
+ writable: true,
556
+ value: tokens
557
+ });
558
+ Object.defineProperty(this, "it", {
559
+ enumerable: true,
560
+ configurable: true,
561
+ writable: true,
562
+ value: it
563
+ });
564
+ // The left side of the last comparison, for "$a > 2 and < 5"
565
+ Object.defineProperty(this, "lastComparison", {
566
+ enumerable: true,
567
+ configurable: true,
568
+ writable: true,
569
+ value: void 0
570
+ });
571
+ }
572
+ expression() {
573
+ return this.or();
574
+ }
575
+ or() {
576
+ let left = this.and();
577
+ while (this.tokens.is("or")) {
578
+ this.tokens.next();
579
+ left = { k: "bin", op: "or", l: left, r: this.elided(this.and()) };
580
+ }
581
+ return left;
582
+ }
583
+ and() {
584
+ let left = this.not();
585
+ while (this.tokens.is("and")) {
586
+ this.tokens.next();
587
+ left = { k: "bin", op: "and", l: left, r: this.elided(this.not()) };
588
+ }
589
+ return left;
590
+ }
591
+ // "$a is 1 or 2" means "$a is 1 or $a is 2"
592
+ elided(right) {
593
+ if (this.lastComparison && !isBoolean(right) && right.k != "var" && right.k != "call") {
594
+ return this.compare(this.lastComparison.left, this.lastComparison.op, right);
595
+ }
596
+ return right;
597
+ }
598
+ not() {
599
+ if (this.tokens.is("not")) {
600
+ this.tokens.next();
601
+ return { k: "not", e: this.not() };
602
+ }
603
+ return this.comparison();
604
+ }
605
+ comparisonOp() {
606
+ const t = this.tokens.peek();
607
+ if (!t)
608
+ return null;
609
+ if (t.type == "op") {
610
+ switch (t.text) {
611
+ case ">":
612
+ case "<":
613
+ case ">=":
614
+ case "<=": return t.text;
615
+ case "is not": return "!=";
616
+ case "is in": return "in";
617
+ case "is not in": return "notin";
618
+ case "does not contain": return "notcontains";
619
+ case "=": return "=";
620
+ case "!=": return "!=";
621
+ }
622
+ }
623
+ if (t.type == "word") {
624
+ if (t.text == "is")
625
+ return "=";
626
+ if (t.text == "contains")
627
+ return "contains";
628
+ }
629
+ return null;
630
+ }
631
+ comparison() {
632
+ // "and < 5", with the left side left out
633
+ if (this.comparisonOp() && this.lastComparison) {
634
+ const op = this.comparisonOp();
635
+ this.tokens.next();
636
+ return this.compare(this.lastComparison.left, op, this.additive());
637
+ }
638
+ const left = this.additive();
639
+ const op = this.comparisonOp();
640
+ if (!op)
641
+ return left;
642
+ this.tokens.next();
643
+ const right = this.additive();
644
+ this.lastComparison = { left, op };
645
+ return this.compare(left, op, right);
646
+ }
647
+ compare(left, op, right) {
648
+ switch (op) {
649
+ case "contains": return this.contains(left, right);
650
+ case "notcontains": return { k: "not", e: this.contains(left, right) };
651
+ case "in": return this.contains(right, left);
652
+ case "notin": return { k: "not", e: this.contains(right, left) };
653
+ default: return { k: "bin", op, l: left, r: right };
654
+ }
655
+ }
656
+ // A list, text or datamap that contains a value (#446)
657
+ contains(collection, value) {
658
+ if (collection.k == "call" && collection.fn == "__history") {
659
+ if (value.k != "str")
660
+ throw new Unconvertible("(history:) contains something other than a passage name");
661
+ return { k: "call", fn: "seen", args: [{ k: "str", v: this.h.ctx.story.sectionForUnknown(value.v) }] };
662
+ }
663
+ return { k: "bin", op: "contains", l: collection, r: value };
664
+ }
665
+ additive() {
666
+ let left = this.multiplicative();
667
+ while (this.tokens.is("+") || this.tokens.is("-")) {
668
+ const op = this.tokens.next().text;
669
+ left = { k: "bin", op, l: left, r: this.multiplicative() };
670
+ }
671
+ return left;
672
+ }
673
+ multiplicative() {
674
+ let left = this.unary();
675
+ while (this.tokens.is("*") || this.tokens.is("/") || this.tokens.is("%")) {
676
+ const op = this.tokens.next().text;
677
+ left = { k: "bin", op, l: left, r: this.unary() };
678
+ }
679
+ return left;
680
+ }
681
+ unary() {
682
+ if (this.tokens.is("-")) {
683
+ this.tokens.next();
684
+ const e = this.unary();
685
+ return e.k == "num" ? { k: "num", v: -e.v } : { k: "neg", e };
686
+ }
687
+ return this.postfix();
688
+ }
689
+ postfix() {
690
+ let e = this.primary();
691
+ while (this.tokens.is("'s") || (this.tokens.is("its"))) {
692
+ this.tokens.next();
693
+ const property = this.tokens.next();
694
+ if (property.text == "length") {
695
+ // A list's or text's length (#446)
696
+ e = e.k == "call" && e.fn == "__history" ? { k: "var", name: "turns" } : lengthOf(e);
697
+ }
698
+ else if (property.text == "ordinal" && (e.k == "var" || e.k == "array" || e.k == "member")) {
699
+ // $list's 1st, or $list's 2ndlast, which is bag[bag.length - 2]
700
+ const n = property.value;
701
+ e = n > 0 ? member(e, { k: "num", v: n - 1 }) : member(e, { k: "bin", op: "-", l: lengthOf(e), r: { k: "num", v: -n } });
702
+ }
703
+ else if (property.text == "last" && (e.k == "var" || e.k == "array" || e.k == "member")) {
704
+ // $list's last (#447)
705
+ e = { k: "call", fn: "last", args: [e] };
706
+ }
707
+ else if ((e.k == "var" || e.k == "member") && (property.type == "word" || property.type == "str")) {
708
+ // A value in a datamap: $player's hp is player.hp (#442)
709
+ e = member(e, { k: "str", v: String(property.value ?? property.text) });
710
+ }
711
+ else {
712
+ throw new Unconvertible(`properties of variables ('s ${property.text})`);
713
+ }
714
+ }
715
+ return e;
716
+ }
717
+ primary() {
718
+ const t = this.tokens.next();
719
+ switch (t.type) {
720
+ case "str": return { k: "str", v: t.value };
721
+ case "num": return { k: "num", v: t.value };
722
+ case "var": return this.h.variable(t.value, false);
723
+ case "temp": return this.h.variable(t.value, true);
724
+ case "hook": throw new Unconvertible("a hook name in an expression");
725
+ case "(": {
726
+ const e = this.expression();
727
+ this.tokens.expect(")");
728
+ return e;
729
+ }
730
+ case "macro": {
731
+ if (t.value == "history")
732
+ return { k: "call", fn: "__history", args: [] };
733
+ return this.h.macro(t.value, t.text, this.it);
734
+ }
735
+ case "word":
736
+ switch (t.text) {
737
+ case "true": return { k: "bool", v: true };
738
+ case "false": return { k: "bool", v: false };
739
+ case "it":
740
+ if (!this.it)
741
+ throw new Unconvertible("\"it\" outside (set:)");
742
+ return this.it;
743
+ case "visits":
744
+ case "visit":
745
+ return this.h.visits();
746
+ case "turns":
747
+ case "turn":
748
+ return { k: "var", name: "turns" };
749
+ case "time":
750
+ throw new Unconvertible("\"time\", which Squiffy has no equivalent for");
751
+ }
752
+ throw new Unconvertible(`the word "${t.text}" in an expression`);
753
+ default:
754
+ throw new Unconvertible(`an expression Squiffy can't read (at "${t.text}")`);
755
+ }
756
+ }
757
+ }
758
+ class Writer {
759
+ constructor(ctx) {
760
+ Object.defineProperty(this, "ctx", {
761
+ enumerable: true,
762
+ configurable: true,
763
+ writable: true,
764
+ value: ctx
765
+ });
766
+ Object.defineProperty(this, "expr", {
767
+ enumerable: true,
768
+ configurable: true,
769
+ writable: true,
770
+ value: void 0
771
+ });
772
+ // Named hooks in the passage, by Harlowe name, with the label each becomes
773
+ Object.defineProperty(this, "hooks", {
774
+ enumerable: true,
775
+ configurable: true,
776
+ writable: true,
777
+ value: new Map()
778
+ });
779
+ // Hook names referred to with ?name anywhere in the story
780
+ Object.defineProperty(this, "referenced", {
781
+ enumerable: true,
782
+ configurable: true,
783
+ writable: true,
784
+ value: void 0
785
+ });
786
+ // (click: ?name) and friends, by the hook they make clickable
787
+ Object.defineProperty(this, "clicks", {
788
+ enumerable: true,
789
+ configurable: true,
790
+ writable: true,
791
+ value: new Map()
792
+ });
793
+ // Open emphasis: Harlowe's markup toggles on and off
794
+ Object.defineProperty(this, "open", {
795
+ enumerable: true,
796
+ configurable: true,
797
+ writable: true,
798
+ value: new Set()
799
+ });
800
+ Object.defineProperty(this, "align", {
801
+ enumerable: true,
802
+ configurable: true,
803
+ writable: true,
804
+ value: null
805
+ });
806
+ // Whether the next text starts a line, for markup that only means something there
807
+ Object.defineProperty(this, "atLineStart", {
808
+ enumerable: true,
809
+ configurable: true,
810
+ writable: true,
811
+ value: true
812
+ });
813
+ Object.defineProperty(this, "storyletsShown", {
814
+ enumerable: true,
815
+ configurable: true,
816
+ writable: true,
817
+ value: false
818
+ });
819
+ // Whether this is the body of a custom macro, where (output:) is what it shows
820
+ Object.defineProperty(this, "inMacro", {
821
+ enumerable: true,
822
+ configurable: true,
823
+ writable: true,
824
+ value: false
825
+ });
826
+ this.expr = new HarloweExpressions(ctx);
827
+ this.referenced = referencedHooks(ctx);
828
+ }
829
+ collectHooks(nodes) {
830
+ for (const node of nodes) {
831
+ const hook = node.t == "hook" ? node.hook : node.t == "macro" ? node.hook : undefined;
832
+ if (node.t == "collapse")
833
+ this.collectHooks(node.nodes);
834
+ if (node.t == "macro" && clickMacros.has(node.name)) {
835
+ const target = /^\?([A-Za-z][\w-]*)$/.exec(splitArgs(node.args)[0] ?? "");
836
+ if (target && !this.clicks.has(target[1]))
837
+ this.clicks.set(target[1], node);
838
+ }
839
+ if (!hook)
840
+ continue;
841
+ if (hook.name && !this.hooks.has(hook.name)) {
842
+ this.hooks.set(hook.name, { hook, label: labelName(hook.name) });
843
+ }
844
+ this.collectHooks(hook.nodes);
845
+ }
846
+ }
847
+ passage(nodes) {
848
+ this.collectHooks(nodes);
849
+ const state = { leading: true, directives: [] };
850
+ nodes = this.passageTransition(nodes, state);
851
+ nodes = topScripts(this.ctx, nodes, state.directives);
852
+ let body = this.nodes(nodes, state);
853
+ body += this.closeAll();
854
+ return { directives: state.directives, body };
855
+ }
856
+ // (transition:)[...] around the whole passage becomes @transition (#489), with its
857
+ // (transition-time:), and the passage is the hook's text
858
+ passageTransition(nodes, state) {
859
+ const content = nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
860
+ const m = content[0];
861
+ if (content.length != 1 || m.t != "macro" || !m.hook)
862
+ return nodes;
863
+ let name;
864
+ let time;
865
+ let hook = { nodes: [{ ...m, hook: foldChangers(m), changers: [] }], raw: m.raw };
866
+ // The changers, from outside in, until the passage's text
867
+ for (;;) {
868
+ const inner = hook?.nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
869
+ const changer = inner?.length == 1 && inner[0].t == "macro" && inner[0].hook ? inner[0] : undefined;
870
+ if (!changer)
871
+ break;
872
+ const arg = splitArgs(changer.args)[0]?.trim() ?? "";
873
+ const macro = normalise(changer.name);
874
+ const value = literal(arg);
875
+ if ((macro == "transition" || macro == "t8n") && typeof value == "string")
876
+ name = value;
877
+ // A time such as 2s isn't a string in Harlowe
878
+ else if (macro == "transitiontime" || macro == "t8ntime")
879
+ time = arg;
880
+ else
881
+ break;
882
+ hook = changer.hook;
883
+ }
884
+ // A named hook stays a hook, so that it can still be changed
885
+ if (!name || !hook || hook.name || hook.hidden)
886
+ return nodes;
887
+ const transition = harloweTransitions.get(name.toLowerCase());
888
+ if (!transition) {
889
+ this.ctx.story.note("harlowe-transition", `"${name}"`, "Squiffy has no equivalent for these Harlowe transitions, so they've been left out");
890
+ return hook.nodes;
891
+ }
892
+ const ms = time ? /^(\d+(?:\.\d+)?|\.\d+)(s|ms)$/i.exec(time.trim()) : null;
893
+ state.directives.push(`@transition ${transition}` + (ms ? ` ${ms[1]}${ms[2].toLowerCase()}` : ""));
894
+ return hook.nodes;
895
+ }
896
+ closeAll() {
897
+ let s = "";
898
+ for (const tag of [...this.open].reverse())
899
+ s += `</${tag}>`;
900
+ this.open.clear();
901
+ if (this.align) {
902
+ s += "\n\n</div>";
903
+ this.align = null;
904
+ }
905
+ return s;
906
+ }
907
+ nodes(nodes, state) {
908
+ let out = "";
909
+ // The conditions of the last if chain here, while only text, links and comments have
910
+ // come after it. Harlowe's (else:) goes by the most recent (if:)'s hook, so one can come
911
+ // after other text, which is shown either way: (if: $a)[A] text (else:)[B].
912
+ let previous = null;
913
+ for (let i = 0; i < nodes.length; i++) {
914
+ const node = nodes[i];
915
+ const continues = !!previous && node.t == "macro" && (node.name == "elseif" || node.name == "else");
916
+ if (node.t == "macro" && (node.name == "if" || node.name == "unless" || continues)) {
917
+ // An if chain: (if:)[...](else-if:)[...](else:)[...], with any whitespace or
918
+ // comments between
919
+ const prior = continues ? previous : [];
920
+ const chain = [];
921
+ const comments = [];
922
+ let conditionError = null;
923
+ const condition = (m) => {
924
+ try {
925
+ const e = this.expr.parse(m.args);
926
+ return m.name == "unless" ? { k: "not", e } : e;
927
+ }
928
+ catch (e) {
929
+ if (!(e instanceof Unconvertible))
930
+ throw e;
931
+ conditionError = conditionError ?? e.message;
932
+ return null;
933
+ }
934
+ };
935
+ chain.push({ cond: node.name == "else" ? null : condition(node), hook: foldChangers(node), raw: node.raw });
936
+ let j = i + 1;
937
+ while (node.name != "else") {
938
+ let k = j;
939
+ const between = [];
940
+ while (k < nodes.length && (isBlank(nodes[k]) || isComment(nodes[k]))) {
941
+ if (isComment(nodes[k]))
942
+ between.push(nodes[k].s);
943
+ k++;
944
+ }
945
+ const next = nodes[k];
946
+ if (next?.t != "macro" || (next.name != "elseif" && next.name != "else"))
947
+ break;
948
+ comments.push(...between);
949
+ chain.push({ cond: next.name == "else" ? null : condition(next), hook: foldChangers(next), raw: next.raw });
950
+ j = k + 1;
951
+ if (next.name == "else")
952
+ break;
953
+ }
954
+ i = j - 1;
955
+ state.leading = false;
956
+ out += comments.join("");
957
+ previous = null;
958
+ if (conditionError) {
959
+ out += this.ctx.unconvertible(chain.map(c => c.raw).join(""), `This condition couldn't be converted: ${conditionError}. Its hooks have been left out.`);
960
+ continue;
961
+ }
962
+ // An (else:) is the only branch without a condition, and nothing carries on after it
963
+ const conds = chain.map(c => c.cond);
964
+ if (prior.length) {
965
+ // Carrying on an earlier chain: only if none of its conditions were true
966
+ const none = { k: "not", e: prior.reduce((l, r) => ({ k: "bin", op: "or", l, r })) };
967
+ chain[0].cond = conds[0] ? { k: "bin", op: "and", l: none, r: conds[0] } : none;
968
+ }
969
+ out += chain.map((c, n) => {
970
+ const tag = n == 0 ? `{{#if ${print(c.cond)}}}` : c.cond ? `{{else if ${print(c.cond)}}}` : "{{else}}";
971
+ return tag + (c.hook ? this.hookContent(c.hook, state) : "");
972
+ }).join("") + "{{/if}}";
973
+ if (!conds.includes(null))
974
+ previous = [...prior, ...conds];
975
+ continue;
976
+ }
977
+ if (node.t != "text" && node.t != "raw" && node.t != "link")
978
+ previous = null;
979
+ if (node.t == "macro" && (node.name == "elseif" || node.name == "else")) {
980
+ // (else:) after a hook that isn't an (if:), e.g. after a (link:)
981
+ state.leading = false;
982
+ out += this.ctx.unconvertible(node.raw, "(else:) only converts after (if:) or (unless:).");
983
+ if (node.hook)
984
+ out += this.hookContent(node.hook, state);
985
+ continue;
986
+ }
987
+ if (isPageClick(node)) {
988
+ // (click: ?page)[A] (click: ?page)[B]: each click anywhere shows the next one, so
989
+ // they become a chain of Continue links, each showing its hook and the next link
990
+ const chain = [node];
991
+ let j = i + 1;
992
+ for (;;) {
993
+ let k = j;
994
+ while (k < nodes.length && nodes[k].t == "text" && nodes[k].s.trim() == "")
995
+ k++;
996
+ if (k >= nodes.length || !isPageClick(nodes[k]))
997
+ break;
998
+ chain.push(nodes[k]);
999
+ j = k + 1;
1000
+ }
1001
+ i = j - 1;
1002
+ state.leading = false;
1003
+ this.ctx.story.note("harlowe-page-click", "(click: ?page)", "Clicking anywhere on the page has been converted to Continue links");
1004
+ const links = chain.map(() => {
1005
+ const label = this.ctx.newLabel("continue");
1006
+ const passage = this.ctx.reservePassage("Continue");
1007
+ return { label, passage, link: `{{#label "${label}"}}${passageLink("Continue", passage.name)}{{/label}}` };
1008
+ });
1009
+ chain.forEach((click, n) => {
1010
+ const content = click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : "";
1011
+ const next = links[n + 1] ? "\n\n" + links[n + 1].link : "";
1012
+ links[n].passage.fill(`{{#replace "${links[n].label}"}}{{/replace}}${content}${next}`);
1013
+ });
1014
+ out += links[0].link;
1015
+ this.atLineStart = false;
1016
+ continue;
1017
+ }
1018
+ const written = this.node(node, state);
1019
+ if (node.t != "text" && written)
1020
+ this.atLineStart = false;
1021
+ out += written;
1022
+ }
1023
+ return out;
1024
+ }
1025
+ node(node, state) {
1026
+ switch (node.t) {
1027
+ case "text":
1028
+ if (node.s.trim())
1029
+ state.leading = false;
1030
+ return this.text(node.s);
1031
+ case "raw":
1032
+ return node.s;
1033
+ case "comment":
1034
+ return this.ctx.unconvertible(node.text, node.reason);
1035
+ case "html":
1036
+ return passageHtmlBlock(this.ctx, node, false).text;
1037
+ case "call":
1038
+ state.leading = false;
1039
+ return this.call(node);
1040
+ case "var":
1041
+ state.leading = false;
1042
+ return display(this.expr.variable(node.name, node.temp));
1043
+ case "link":
1044
+ state.leading = false;
1045
+ return this.link(node);
1046
+ case "collapse": {
1047
+ const inner = this.nodes(node.nodes, state);
1048
+ return collapseWhitespace(inner);
1049
+ }
1050
+ case "hook": {
1051
+ const hook = node.hook;
1052
+ if (hook.name && this.clicks.has(hook.name) && !hook.hidden) {
1053
+ state.leading = false;
1054
+ return this.clickable(hook, this.clicks.get(hook.name));
1055
+ }
1056
+ if (hook.hidden) {
1057
+ // Shown later, by (show:)
1058
+ if (!hook.name || !this.referenced.has(hook.name))
1059
+ return "";
1060
+ return `{{#label "${labelName(hook.name)}"}}{{/label}}`;
1061
+ }
1062
+ return this.hookContent(hook, state);
1063
+ }
1064
+ case "macro":
1065
+ return this.macro(node, state);
1066
+ }
1067
+ }
1068
+ // A hook's content, in a {{#label}} if it's named and something refers to it
1069
+ hookContent(hook, state) {
1070
+ const content = this.nodes(hook.nodes, { ...state, leading: false });
1071
+ state.leading = state.leading && content.trim() == "";
1072
+ if (hook.name && !hook.hidden && this.referenced.has(hook.name)) {
1073
+ return `{{#label "${labelName(hook.name)}"}}${content}{{/label}}`;
1074
+ }
1075
+ return content;
1076
+ }
1077
+ // A named hook that (click:) or one of its friends makes into a link
1078
+ clickable(hook, click) {
1079
+ const content = this.nodes(hook.nodes, { leading: false, directives: [] });
1080
+ const text = content.replace(/\s+/g, " ").trim();
1081
+ const label = labelName(hook.name);
1082
+ const args = splitArgs(click.args);
1083
+ let action;
1084
+ switch (click.name) {
1085
+ case "clickgoto":
1086
+ case "mouseovergoto": {
1087
+ if (click.name != "clickgoto")
1088
+ this.ctx.approximate(click.raw, "This has been converted to an ordinary link.");
1089
+ return `{{#label "${label}"}}${this.linkTo(text, args[1] ?? "", click.raw, [])}{{/label}}`;
1090
+ }
1091
+ case "clickreplace":
1092
+ action = `{{#replace "${label}"}}${click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : ""}{{/replace}}`;
1093
+ break;
1094
+ case "clickappend":
1095
+ case "clickprepend": {
1096
+ const extra = click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : "";
1097
+ action = `{{#replace "${label}"}}${click.name == "clickappend" ? content + extra : extra + content}{{/replace}}`;
1098
+ break;
1099
+ }
1100
+ default:
1101
+ if (click.name != "click")
1102
+ this.ctx.approximate(click.raw, "This has been converted to a link.");
1103
+ action = click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : "";
1104
+ // The text stops being a link once it's been clicked, as it does in Harlowe
1105
+ action = `{{#replace "${label}"}}${content}{{/replace}}` + action;
1106
+ }
1107
+ const passage = this.ctx.addPassage(text, action);
1108
+ return `{{#label "${label}"}}${passageLink(text, passage)}{{/label}}`;
1109
+ }
1110
+ link(node) {
1111
+ const text = this.inlineText(node.text);
1112
+ if (isUrl(node.target))
1113
+ return urlLink(text, node.target);
1114
+ const target = this.ctx.story.sectionFor(node.target);
1115
+ if (target === undefined) {
1116
+ this.ctx.approximate(node.raw, `There's no passage called "${node.target}".`);
1117
+ return sectionLink(text, this.ctx.story.sectionForUnknown(node.target));
1118
+ }
1119
+ return sectionLink(text, target);
1120
+ }
1121
+ // Link text, with Harlowe's markup in it
1122
+ inlineText(text) {
1123
+ const nodes = new Parser(text).parse(0).nodes;
1124
+ return this.nodes(nodes, { leading: false, directives: [] }).replace(/\n/g, " ");
1125
+ }
1126
+ // Prose, with Harlowe's markup
1127
+ text(s) {
1128
+ let out = "";
1129
+ for (let i = 0; i < s.length;) {
1130
+ const rest = s.substring(i);
1131
+ if (this.atLineStart) {
1132
+ this.atLineStart = false;
1133
+ const lineEnd = rest.indexOf("\n");
1134
+ const line = lineEnd == -1 ? rest : rest.substring(0, lineEnd);
1135
+ const alignment = /^\s*(==+>|=+><=+|<==+>|<==+)\s*$/.exec(line);
1136
+ if (alignment) {
1137
+ out += this.alignment(alignment[1]);
1138
+ i += line.length;
1139
+ continue;
1140
+ }
1141
+ if (/^\s*\|==+|^\s*=+\|\s*$|^\s*==+\|/.test(line)) {
1142
+ out += this.ctx.unconvertible(line, "Harlowe's columns can't be converted.");
1143
+ i += line.length;
1144
+ continue;
1145
+ }
1146
+ const heading = /^(#{1,6})\s*(?=\S)/.exec(line);
1147
+ if (heading) {
1148
+ out += heading[1] + " ";
1149
+ i += heading[0].length;
1150
+ continue;
1151
+ }
1152
+ const bullet = /^(\*+)\s+/.exec(line);
1153
+ if (bullet) {
1154
+ out += " ".repeat(bullet[1].length - 1) + "* ";
1155
+ i += bullet[0].length;
1156
+ continue;
1157
+ }
1158
+ const numbered = /^(0\.)+\s+/.exec(line);
1159
+ if (numbered) {
1160
+ out += "1. ";
1161
+ i += numbered[0].length;
1162
+ continue;
1163
+ }
1164
+ if (/^\s*-{3,}\s*$/.test(line)) {
1165
+ out += "<hr>";
1166
+ i += line.length;
1167
+ continue;
1168
+ }
1169
+ }
1170
+ const c = s[i];
1171
+ if (c == "\n") {
1172
+ out += "\n";
1173
+ this.atLineStart = true;
1174
+ i++;
1175
+ continue;
1176
+ }
1177
+ const toggle = this.toggle(s, i);
1178
+ if (toggle) {
1179
+ out += toggle.text;
1180
+ i += toggle.length;
1181
+ continue;
1182
+ }
1183
+ if (c == "<") {
1184
+ // HTML passes through as it is
1185
+ const tag = /^<\/?[A-Za-z][^<>]*>/.exec(rest);
1186
+ if (tag) {
1187
+ out += tag[0].replace(/\{\{/g, "&#123;{");
1188
+ i += tag[0].length;
1189
+ continue;
1190
+ }
1191
+ }
1192
+ // {{ would start a helper
1193
+ out += (c == "{" && s[i + 1] == "{") ? "&#123;" : (c == "}" && s[i + 1] == "}") ? "&#125;" : escapeText(c);
1194
+ i++;
1195
+ }
1196
+ return out;
1197
+ }
1198
+ // Emphasis markup, which turns on and off: ''bold'', //italic//, **strong**, *em*,
1199
+ // ~~strike~~, ^^superscript^^
1200
+ toggle(s, i) {
1201
+ const marks = [["''", "b"], ["//", "i"], ["**", "strong"], ["~~", "s"], ["^^", "sup"], ["*", "em"]];
1202
+ for (const [mark, tag] of marks) {
1203
+ if (!s.startsWith(mark, i))
1204
+ continue;
1205
+ if (mark == "//" && s[i - 1] == ":")
1206
+ return null;
1207
+ if (this.open.has(tag)) {
1208
+ this.open.delete(tag);
1209
+ return { text: `</${tag}>`, length: mark.length };
1210
+ }
1211
+ // Only if it's closed later
1212
+ const end = s.indexOf(mark, i + mark.length);
1213
+ if (end == -1 || (mark == "*" && s.substring(i, end).includes("\n")))
1214
+ return null;
1215
+ if (mark == "*" && s[i + 1] == " ")
1216
+ return null;
1217
+ this.open.add(tag);
1218
+ return { text: `<${tag}>`, length: mark.length };
1219
+ }
1220
+ return null;
1221
+ }
1222
+ alignment(marker) {
1223
+ let s = "";
1224
+ if (this.align) {
1225
+ s += "\n\n</div>";
1226
+ this.align = null;
1227
+ }
1228
+ // ==> right, =><= centre, <==> justified, <== left
1229
+ const align = marker.includes("><") ? "center"
1230
+ : marker.startsWith("<") && marker.endsWith(">") ? "justify"
1231
+ : marker.endsWith(">") ? "right" : "left";
1232
+ if (align != "left") {
1233
+ this.align = align;
1234
+ s += `<div style="text-align: ${align}">\n\n`;
1235
+ }
1236
+ return s;
1237
+ }
1238
+ // ---- Macros ----
1239
+ macro(m, state) {
1240
+ try {
1241
+ const result = this.macroOrThrow(m, state);
1242
+ // A hook after a command, rather than a changer, is shown as it is
1243
+ if (m.hook && !changers.has(m.name) && !hookMacros.has(m.name))
1244
+ return result + this.hookContent(m.hook, state);
1245
+ return result;
1246
+ }
1247
+ catch (e) {
1248
+ if (!(e instanceof Unconvertible))
1249
+ throw e;
1250
+ state.leading = false;
1251
+ const reason = `This couldn't be converted: ${e.message}.`;
1252
+ if (m.hook && !["link", "linkreveal", "linkrepeat", "linkrerun", "click", "replace", "append", "prepend", "show", "for", "loop"].includes(m.name)) {
1253
+ // Keep the hook's text, since most changers only change how it looks
1254
+ return this.ctx.unconvertible(m.raw, reason) + this.hookContent(m.hook, state);
1255
+ }
1256
+ return this.ctx.unconvertible(m.raw + (m.hook?.raw ?? ""), reason);
1257
+ }
1258
+ }
1259
+ macroOrThrow(m, state) {
1260
+ const args = splitArgs(m.args);
1261
+ const name = m.name;
1262
+ if (m.changers.length) {
1263
+ return this.macroOrThrow({ ...m, changers: [], hook: foldChangers(m) }, state);
1264
+ }
1265
+ switch (name) {
1266
+ case "set":
1267
+ case "put":
1268
+ return this.set(m, args, state);
1269
+ // What a custom macro shows (#450)
1270
+ case "output":
1271
+ case "out":
1272
+ case "outputdata":
1273
+ case "outdata":
1274
+ if (!this.inMacro)
1275
+ throw new Unconvertible(`(${m.name}:) outside a custom macro`);
1276
+ state.leading = false;
1277
+ if (m.hook && !args.length && (name == "output" || name == "out"))
1278
+ return this.hookContent(m.hook, state);
1279
+ if (args.length != 1)
1280
+ throw new Unconvertible(`(${m.name}:) with more than one value`);
1281
+ return display(this.expr.parse(args[0]));
1282
+ case "print":
1283
+ state.leading = false;
1284
+ if (args.length != 1)
1285
+ throw new Unconvertible("(print:) with more than one value");
1286
+ return display(this.expr.parse(args[0]));
1287
+ case "either":
1288
+ case "random":
1289
+ state.leading = false;
1290
+ return display(this.expr.macro(name, m.raw));
1291
+ case "display": {
1292
+ state.leading = false;
1293
+ const target = this.expr.passageName(args[0] ?? "");
1294
+ if ("name" in target) {
1295
+ const section = this.ctx.story.sectionFor(target.name);
1296
+ if (section === undefined)
1297
+ this.ctx.approximate(m.raw, `There's no passage called "${target.name}".`);
1298
+ return `{{embed "${section ?? this.ctx.story.sectionForUnknown(target.name)}"}}`;
1299
+ }
1300
+ return `{{embed ${print(target.expr)}}}`;
1301
+ }
1302
+ case "goto":
1303
+ case "redirect":
1304
+ state.leading = false;
1305
+ return this.goto(args[0] ?? "", m.raw);
1306
+ case "linkgoto":
1307
+ case "clickgoto":
1308
+ case "mouseovergoto":
1309
+ case "linkrevealgoto": {
1310
+ state.leading = false;
1311
+ if (name == "clickgoto" || name == "mouseovergoto") {
1312
+ // Handled where the hook is
1313
+ const hookName = /^\s*\?([A-Za-z][\w-]*)\s*$/.exec(args[0] ?? "")?.[1];
1314
+ if (hookName && this.hooks.has(hookName))
1315
+ return "";
1316
+ throw new Unconvertible(`(${name}:) on text rather than a named hook in this passage`);
1317
+ }
1318
+ const textExpr = this.expr.parse(args[0] ?? "");
1319
+ if (textExpr.k != "str")
1320
+ throw new Unconvertible("a link whose text isn't fixed");
1321
+ const targetSource = args.length > 1 ? args[1] : args[0];
1322
+ const setters = name == "linkrevealgoto" && m.hook ? this.setters(m.hook) : [];
1323
+ if (setters === null) {
1324
+ // The hook does more than set variables: run it in a section of its own
1325
+ const target = this.expr.passageName(targetSource);
1326
+ const goto = "name" in target ? `{{goto "${this.sectionName(target.name, m.raw)}"}}` : `{{goto ${print(target.expr)}}}`;
1327
+ const content = this.convertedHook(m.hook);
1328
+ const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, { ...content, body: content.body + "\n" + goto });
1329
+ return sectionLink(this.inlineText(textExpr.v), section);
1330
+ }
1331
+ return this.linkTo(this.inlineText(textExpr.v), targetSource, m.raw, setters);
1332
+ }
1333
+ case "link":
1334
+ case "linkreplace":
1335
+ case "linkreveal":
1336
+ case "linkrepeat":
1337
+ case "linkrerun":
1338
+ state.leading = false;
1339
+ return this.linkMacro(m, args);
1340
+ case "linkshow": {
1341
+ state.leading = false;
1342
+ const textExpr = this.expr.parse(args[0] ?? "");
1343
+ if (textExpr.k != "str")
1344
+ throw new Unconvertible("a link whose text isn't fixed");
1345
+ const shows = args.slice(1).map(a => this.show(a, m.raw)).join("");
1346
+ const label = this.ctx.newLabel(textExpr.v);
1347
+ const passage = this.ctx.addPassage(textExpr.v, `{{#replace "${label}"}}${this.inlineText(textExpr.v)}{{/replace}}${shows}`);
1348
+ return `{{#label "${label}"}}${passageLink(this.inlineText(textExpr.v), passage)}{{/label}}`;
1349
+ }
1350
+ case "after": {
1351
+ state.leading = false;
1352
+ // time is how long the passage has been shown, which is no time at all when this
1353
+ // is worked out, so (after: time + 4s) is (after: 4s)
1354
+ const delay = delayValue(this.expr.parse((args[0] ?? "").replace(/^\s*time\s*\+/, "")));
1355
+ if (!m.hook)
1356
+ return "";
1357
+ const goto = this.gotoOnly(m.hook);
1358
+ if (goto)
1359
+ return goto.replace(/\}\}$/, ` after=${delay}}}`);
1360
+ return `{{#animate "fadeIn" start=${delay}}}${this.hookContent(m.hook, state)}{{/animate}}`;
1361
+ }
1362
+ case "live": {
1363
+ state.leading = false;
1364
+ if (!m.hook)
1365
+ throw new Unconvertible("(live:) without a hook");
1366
+ const delay = delayValue(this.expr.parse(args[0] ?? "1s"));
1367
+ // A hook that only goes somewhere else goes there once
1368
+ const goto = this.gotoOnly(m.hook, true);
1369
+ if (goto)
1370
+ return goto.replace(/\}\}$/, ` after=${delay}}}`);
1371
+ // Its hook is shown again every so often, until a (stop:) (#451)
1372
+ return `{{#every ${delay}}}${this.hookContent(m.hook, state)}{{/every}}`;
1373
+ }
1374
+ case "stop":
1375
+ return "{{stop}}";
1376
+ case "inputbox":
1377
+ case "forceinputbox":
1378
+ case "input":
1379
+ case "forceinput":
1380
+ state.leading = false;
1381
+ return this.input(args, m.raw);
1382
+ case "dropdown": {
1383
+ state.leading = false;
1384
+ const bound = this.bound(args[0] ?? "");
1385
+ if (!bound)
1386
+ throw new Unconvertible("(dropdown:) without bind, or bound to something other than a variable or a value inside one");
1387
+ const options = args.slice(1).map(a => this.expr.parse(a));
1388
+ if (options.some(o => o.k != "str" && o.k != "num"))
1389
+ throw new Unconvertible("(dropdown:) with options that aren't fixed");
1390
+ const html = options.map(o => {
1391
+ const v = escapeAttribute(String(o.v));
1392
+ return `<option value="${v}">${v}</option>`;
1393
+ }).join("");
1394
+ return `<select data-attribute="${bound}">${html}</select>`;
1395
+ }
1396
+ case "checkbox": {
1397
+ state.leading = false;
1398
+ const bound = this.bound(args[0] ?? "");
1399
+ const label = args[1] ? this.expr.parse(args[1]) : null;
1400
+ if (!bound || (label && label.k != "str"))
1401
+ throw new Unconvertible("(checkbox:)");
1402
+ this.ctx.approximate(m.raw, "Check how this checkbox works in Squiffy.");
1403
+ return `<label><input type="checkbox" data-attribute="${bound}"> ${label ? escapeText(label.v) : ""}</label>`;
1404
+ }
1405
+ case "cyclinglink":
1406
+ case "seqlink":
1407
+ case "sequencelink": {
1408
+ state.leading = false;
1409
+ let bound = null;
1410
+ let rest = args;
1411
+ if (/^2?bind\s/.test(args[0] ?? "")) {
1412
+ bound = this.bound(args[0]);
1413
+ rest = args.slice(1);
1414
+ }
1415
+ const items = rest.map(a => this.expr.parse(a));
1416
+ const helper = name == "cyclinglink" ? "rotate" : "sequence";
1417
+ const set = bound ? ` set="${bound}"` : "";
1418
+ return `{{${helper} ${print({ k: "array", items })}${set}}}`;
1419
+ }
1420
+ case "textstyle":
1421
+ case "textcolour":
1422
+ case "textcolor":
1423
+ case "colour":
1424
+ case "color":
1425
+ case "background":
1426
+ case "bg":
1427
+ case "font":
1428
+ case "textsize":
1429
+ case "size":
1430
+ case "align":
1431
+ case "css":
1432
+ case "opacity":
1433
+ state.leading = false;
1434
+ return this.style(m, args, state);
1435
+ case "linkstyle":
1436
+ case "box":
1437
+ case "border":
1438
+ case "b4r":
1439
+ case "bordercolour":
1440
+ case "bordercolor":
1441
+ case "b4rcolour":
1442
+ case "b4rcolor":
1443
+ case "bordersize":
1444
+ case "b4rsize":
1445
+ case "cornerradius":
1446
+ case "textindent":
1447
+ case "float":
1448
+ case "textrotate":
1449
+ case "textrotatez":
1450
+ case "textrotatey":
1451
+ case "textrotatex":
1452
+ case "hoverstyle":
1453
+ case "charstyle":
1454
+ case "linestyle":
1455
+ case "button":
1456
+ case "hookname":
1457
+ case "outline":
1458
+ case "textshadow":
1459
+ this.ctx.story.note("harlowe-visual", m.raw.substring(0, m.raw.indexOf(":") + 1) + ")", "These Harlowe changers only change how text looks, so they've been left out, and the text they changed has been kept");
1460
+ return m.hook ? this.hookContent(m.hook, state) : "";
1461
+ case "enchant":
1462
+ case "enchantin": {
1463
+ // Only how links or text look
1464
+ const visual = /\((t8n|transition|text-colou?r|colou?r|text-style|link-style|hover-style|font|background|bg|opacity|css|box|border)[\w-]*:/i;
1465
+ const changer = splitArgs(m.args)[1] ?? "";
1466
+ if (visual.test(changer) && !/\((replace|append|prepend|show|hide|goto|set):/i.test(changer)) {
1467
+ this.ctx.story.note("harlowe-visual", "(enchant:)", "These Harlowe changers only change how text looks, so they've been left out, and the text they changed has been kept");
1468
+ return "";
1469
+ }
1470
+ throw new Unconvertible("(enchant:)");
1471
+ }
1472
+ case "transition":
1473
+ case "t8n":
1474
+ case "transitiontime":
1475
+ case "t8ntime":
1476
+ case "transitiondelay":
1477
+ case "t8ndelay":
1478
+ case "transitionskip":
1479
+ case "t8nskip":
1480
+ // Around the whole passage, this became @transition (#489). Squiffy has none for part of one.
1481
+ this.ctx.story.note("harlowe-transition-hook", m.raw.substring(0, m.raw.indexOf(":") + 1) + ")", "Squiffy's @transition is for a whole passage, so these transitions for part of one have been left out, and the text they changed has been kept");
1482
+ return m.hook ? this.hookContent(m.hook, state) : "";
1483
+ case "transitiondepart":
1484
+ case "t8ndepart":
1485
+ case "transitionarrive":
1486
+ case "t8narrive":
1487
+ this.ctx.story.note("harlowe-transition-link", m.raw.substring(0, m.raw.indexOf(":") + 1) + ")", "Squiffy sets how a passage appears and goes with @transition and @leave in a passage, not on a link, so these have been left out");
1488
+ return m.hook ? this.hookContent(m.hook, state) : "";
1489
+ case "nobr":
1490
+ case "collapse":
1491
+ return m.hook ? collapseWhitespace(this.hookContent(m.hook, state)) : "";
1492
+ case "verbatim":
1493
+ case "v6m":
1494
+ state.leading = false;
1495
+ return m.hook ? escapeText(escapeHtml(m.hook.raw.slice(1, -1))) : "";
1496
+ case "hidden":
1497
+ if (m.hook?.name) {
1498
+ m.hook.hidden = true;
1499
+ return this.node({ t: "hook", hook: m.hook }, state);
1500
+ }
1501
+ return "";
1502
+ case "show":
1503
+ state.leading = false;
1504
+ return args.map(a => this.show(a, m.raw)).join("");
1505
+ case "hide":
1506
+ state.leading = false;
1507
+ return args.map(a => {
1508
+ const label = this.labelFor(a);
1509
+ return `{{#replace "${label}"}}{{/replace}}`;
1510
+ }).join("");
1511
+ case "replace":
1512
+ case "append":
1513
+ case "prepend": {
1514
+ state.leading = false;
1515
+ if (!m.hook)
1516
+ return "";
1517
+ const content = this.hookContent(m.hook, state);
1518
+ return args.map(a => {
1519
+ const target = a.trim();
1520
+ if (!target.startsWith("?"))
1521
+ throw new Unconvertible(`(${name}:) on text rather than a named hook`);
1522
+ const named = this.hooks.get(target.substring(1));
1523
+ // A hook in another passage, e.g. a header: its label has the same name
1524
+ if (!named && name == "replace")
1525
+ return `{{#replace "${labelName(target.substring(1))}"}}${content}{{/replace}}`;
1526
+ if (!named)
1527
+ throw new Unconvertible(`(${name}:) on a hook that isn't in this passage`);
1528
+ if (name == "replace")
1529
+ return `{{#replace "${named.label}"}}${content}{{/replace}}`;
1530
+ this.ctx.approximate(m.raw, `(${name}:) has been converted to {{#replace}}, with the hook's original text. If the hook has changed by then, this will undo that.`);
1531
+ const original = this.nodes(named.hook.nodes, { leading: false, directives: [] });
1532
+ return `{{#replace "${named.label}"}}${name == "append" ? original + content : content + original}{{/replace}}`;
1533
+ }).join("");
1534
+ }
1535
+ case "click":
1536
+ case "clickreplace":
1537
+ case "clickappend":
1538
+ case "clickprepend":
1539
+ case "mouseover":
1540
+ case "mouseout": {
1541
+ const target = (args[0] ?? "").trim();
1542
+ const hookName = /^\?([A-Za-z][\w-]*)$/.exec(target)?.[1];
1543
+ // Handled where the hook is
1544
+ if (hookName && this.hooks.has(hookName))
1545
+ return "";
1546
+ if ((hookName == "page" || hookName == "passage") && m.hook) {
1547
+ state.leading = false;
1548
+ this.ctx.story.note("harlowe-page-click", "(click: ?page)", "Clicking anywhere on the page has been converted to Continue links");
1549
+ const content = this.nodes(m.hook.nodes, { leading: false, directives: [] });
1550
+ const label = this.ctx.newLabel("continue");
1551
+ const passage = this.ctx.addPassage("Continue", `{{#replace "${label}"}}{{/replace}}${content}`);
1552
+ return `{{#label "${label}"}}${passageLink("Continue", passage)}{{/label}}`;
1553
+ }
1554
+ throw new Unconvertible(`(${name}:) on ${hookName ? "a hook that isn't in this passage" : "text rather than a named hook"}`);
1555
+ }
1556
+ case "for":
1557
+ case "loop": {
1558
+ state.leading = false;
1559
+ if (!m.hook)
1560
+ throw new Unconvertible(`(${name}:) without a hook`);
1561
+ // each _item, or _item where ... (which only shows the items it's true for)
1562
+ const lambda = /^\s*(each\s+)?_([A-Za-z_]\w*)(?:\s+where\s+([\s\S]+))?$/i.exec(args[0] ?? "");
1563
+ if (!lambda || (!lambda[1] && !lambda[3]))
1564
+ throw new Unconvertible(`(${name}:) with something other than "each _item" or "_item where ..."`);
1565
+ const collection = this.forCollection(args.slice(1), name);
1566
+ const hook = m.hook;
1567
+ const numbers = collection.k == "call" && collection.fn == "range";
1568
+ return this.ctx.story.inLoop(new Map([["_" + lambda[2], "item"]]), undefined, () => {
1569
+ const body = this.hookContent(hook, state);
1570
+ const shown = lambda[3] ? `{{#if ${print(this.expr.parse(lambda[3]))}}}${body}{{/if}}` : body;
1571
+ return `{{#each ${print(collection)}}}${shown}{{/each}}`;
1572
+ }, numbers);
1573
+ }
1574
+ case "linkstorylet": {
1575
+ state.leading = false;
1576
+ // Every storylet whose condition is true, the first time (link-storylet:) is in a passage
1577
+ if (this.storyletsShown)
1578
+ return "";
1579
+ this.storyletsShown = true;
1580
+ const storylets = harloweStorylets(this.ctx);
1581
+ if (!storylets.length)
1582
+ throw new Unconvertible("(link-storylet:) in a story without storylets");
1583
+ this.ctx.story.note("harlowe-storylets", "(link-storylet:)", "Storylets have been converted to a link to each storylet whose condition is true, in the first place (link-storylet:) is in a passage. (urgency:) and (exclusivity:) have been left out");
1584
+ // All on one line, so the ones that aren't shown don't leave blank lines
1585
+ return storylets.map(st => {
1586
+ const link = sectionLink(escapeText(st.section), st.section) + "<br>";
1587
+ return st.condition ? `{{#if ${print(st.condition)}}}${link}{{/if}}` : link;
1588
+ }).join("");
1589
+ }
1590
+ case "storylet":
1591
+ case "urgency":
1592
+ case "exclusivity":
1593
+ // Converted where the storylets are listed
1594
+ return "";
1595
+ case "mockvisits":
1596
+ case "mockturns":
1597
+ case "debug":
1598
+ case "seed":
1599
+ return "";
1600
+ case "if":
1601
+ case "unless":
1602
+ case "elseif":
1603
+ case "else":
1604
+ // Handled in nodes()
1605
+ return "";
1606
+ case "track":
1607
+ return leadingAudio(this.track(m, args), state);
1608
+ case "newtrack":
1609
+ // Found before the story's converted
1610
+ return "";
1611
+ case "masteraudio":
1612
+ if (args.length == 1 && String(literal(args[0])).toLowerCase() == "stopall")
1613
+ return leadingAudio(STOP_ALL_AUDIO, state);
1614
+ throw new Unconvertible("(masteraudio:), which changes all the story's sound at once, except to stop it");
1615
+ case "playlist":
1616
+ case "newplaylist":
1617
+ throw new Unconvertible("playlists");
1618
+ case "group":
1619
+ case "newgroup":
1620
+ throw new Unconvertible("audio groups");
1621
+ default:
1622
+ if (printedMacros.has(name) && !m.hook) {
1623
+ // A value on its own in the text is printed: (round: $money)
1624
+ state.leading = false;
1625
+ return display(this.expr.macro(name, m.raw));
1626
+ }
1627
+ throw new Unconvertible(`the (${m.raw.substring(1, m.raw.indexOf(":"))}:) macro, which Squiffy has no equivalent for`);
1628
+ }
1629
+ }
1630
+ // (track: "name", "command", ...values), from the Harlowe Audio Library
1631
+ track(m, args) {
1632
+ const track = literal(args[0]);
1633
+ const command = literal(args[1]);
1634
+ if (typeof track != "string")
1635
+ throw new Unconvertible("(track:) with a track that isn't fixed");
1636
+ if (typeof command != "string")
1637
+ throw new Unconvertible("(track:) with a command that isn't fixed");
1638
+ const action = { play: false, stop: false, loop: false };
1639
+ const num = (i) => {
1640
+ const n = literal(args[i]);
1641
+ if (typeof n != "number")
1642
+ throw new Unconvertible(`(track:) "${command}" with a value that isn't a fixed number`);
1643
+ return n;
1644
+ };
1645
+ switch (command.toLowerCase()) {
1646
+ case "play":
1647
+ case "playwhenpossible":
1648
+ action.play = true;
1649
+ break;
1650
+ case "fadein":
1651
+ action.play = true;
1652
+ if (args[2] !== undefined)
1653
+ action.fade = num(2);
1654
+ break;
1655
+ case "stop":
1656
+ action.stop = true;
1657
+ break;
1658
+ case "fadeout":
1659
+ action.stop = true;
1660
+ if (args[2] !== undefined)
1661
+ action.fade = num(2);
1662
+ break;
1663
+ case "fadeto":
1664
+ if (num(2) > 0)
1665
+ action.play = true;
1666
+ else
1667
+ action.stop = true;
1668
+ if (args[3] !== undefined)
1669
+ action.fade = num(3);
1670
+ break;
1671
+ case "loop":
1672
+ // Found before the story's converted
1673
+ return "";
1674
+ case "volume":
1675
+ if (harloweAudio(this.ctx.story).looping.has(track)) {
1676
+ this.ctx.story.note("audio-music-volume", m.raw, "Squiffy plays music at full volume, so the music's volume has been left out");
1677
+ return "";
1678
+ }
1679
+ throw new Unconvertible("(track:) changing the volume of a sound on its own: give {{sound}} a volume= instead");
1680
+ case "pause":
1681
+ throw new Unconvertible("pausing a track");
1682
+ case "mute":
1683
+ case "unmute":
1684
+ throw new Unconvertible("muting a track");
1685
+ case "time":
1686
+ throw new Unconvertible("playing a track from part of the way through");
1687
+ default:
1688
+ throw new Unconvertible(`(track:) with "${command}"`);
1689
+ }
1690
+ return audioHelper(this.ctx, m.raw, harloweAudio(this.ctx.story), track, action);
1691
+ }
1692
+ // What a (for:) goes through: an array spread out (...$list), or values, as {{#each}} takes
1693
+ forCollection(values, name) {
1694
+ const spread = (v) => /^\s*\.\.\./.test(v) ? this.expr.parse(v.replace(/^\s*\.\.\./, "")) : null;
1695
+ if (values.length == 1) {
1696
+ const e = spread(values[0]);
1697
+ if (e && (e.k == "var" || e.k == "array" || (e.k == "loop" && e.kind == "item") || isListCall(e)))
1698
+ return e;
1699
+ }
1700
+ const items = [];
1701
+ for (const v of values) {
1702
+ const e = spread(v);
1703
+ if (!e)
1704
+ items.push(this.expr.parse(v));
1705
+ else if (e.k == "array")
1706
+ items.push(...e.items);
1707
+ else
1708
+ throw new Unconvertible(`(${name}:) with an array and other values`);
1709
+ }
1710
+ if (!items.length)
1711
+ throw new Unconvertible(`(${name}:) with nothing to go through`);
1712
+ return { k: "array", items };
1713
+ }
1714
+ sectionName(passage, raw) {
1715
+ const section = this.ctx.story.sectionFor(passage);
1716
+ if (section === undefined) {
1717
+ this.ctx.approximate(raw, `There's no passage called "${passage}".`);
1718
+ return this.ctx.story.sectionForUnknown(passage);
1719
+ }
1720
+ return section;
1721
+ }
1722
+ goto(arg, raw) {
1723
+ const target = this.expr.passageName(arg);
1724
+ if ("name" in target)
1725
+ return `{{goto "${this.sectionName(target.name, raw)}"}}`;
1726
+ return `{{goto ${print(target.expr)}}}`;
1727
+ }
1728
+ // A link to a passage given as a Harlowe value, with setters
1729
+ linkTo(text, targetSource, raw, setters) {
1730
+ const target = this.expr.passageName(targetSource);
1731
+ if ("name" in target)
1732
+ return sectionLink(text, this.sectionName(target.name, raw), setters);
1733
+ return dynamicSectionLink(text, target.expr, setters);
1734
+ }
1735
+ // (link:) and friends, with a hook that runs when it's clicked
1736
+ linkMacro(m, args) {
1737
+ const textExpr = this.expr.parse(args[0] ?? "");
1738
+ if (textExpr.k != "str")
1739
+ throw new Unconvertible("a link whose text isn't fixed");
1740
+ const text = this.inlineText(textExpr.v);
1741
+ if (!m.hook)
1742
+ throw new Unconvertible("a link with no hook");
1743
+ // A link that only sets variables and goes to another passage is an ordinary link
1744
+ const navigation = this.navigation(m.hook);
1745
+ if (navigation) {
1746
+ if (navigation.setters)
1747
+ return this.linkTo(text, navigation.target, m.raw, navigation.setters);
1748
+ // It does more than set variables, so do that in a section of its own. In a loop, it can
1749
+ // use the loop's item, which the link sets an attribute to (#448).
1750
+ const { result, setters } = this.ctx.story.linkBody(() => navigation.content());
1751
+ const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, result);
1752
+ return sectionLink(text, section, setters);
1753
+ }
1754
+ const hook = m.hook;
1755
+ const { result: content, setters } = this.ctx.story.linkBody(() => this.nodes(hook.nodes, { leading: false, directives: [] }));
1756
+ if (m.name == "linkrepeat" || m.name == "linkrerun") {
1757
+ this.ctx.approximate(m.raw, "In Squiffy, this link can only be clicked once.");
1758
+ const passage = this.ctx.addPassage(textExpr.v, content);
1759
+ return passageLink(text, passage, setters);
1760
+ }
1761
+ const label = this.ctx.newLabel(textExpr.v);
1762
+ const replacement = m.name == "linkreveal" ? text + content : content;
1763
+ const passage = this.ctx.addPassage(textExpr.v, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1764
+ return `{{#label "${label}"}}${passageLink(text, passage, setters)}{{/label}}`;
1765
+ }
1766
+ // If a hook only sets variables and then goes to a passage, the setters and the passage.
1767
+ // If it does other things before going to a passage, content is the Squiffy text for a
1768
+ // section that does those things and then goes there.
1769
+ navigation(hook) {
1770
+ const significant = hook.nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1771
+ const last = significant[significant.length - 1];
1772
+ if (last?.t != "macro" || (last.name != "goto" && last.name != "redirect"))
1773
+ return null;
1774
+ // Only if the (goto:) isn't inside anything
1775
+ const target = splitArgs(last.args)[0] ?? "";
1776
+ const before = significant.slice(0, -1);
1777
+ const setters = this.setters({ nodes: before, raw: "" });
1778
+ return { target, setters, content: () => this.convertedHook(hook) };
1779
+ }
1780
+ // The setters for a hook that only has (set:) and (put:) in it, or null
1781
+ setters(hook) {
1782
+ const setters = [];
1783
+ for (const n of hook.nodes) {
1784
+ if (n.t == "text" && n.s.trim() == "")
1785
+ continue;
1786
+ if (n.t != "macro" || (n.name != "set" && n.name != "put") || n.hook)
1787
+ return null;
1788
+ for (const assignment of splitArgs(n.args)) {
1789
+ try {
1790
+ for (const a of this.assignments(assignment, n.name == "put")) {
1791
+ if (a.kind == "append" || a.kind == "remove")
1792
+ return null;
1793
+ setters.push(a.kind == "inc" ? setter(a.name, "+=", a.value, true)
1794
+ : a.kind == "dec" ? setter(a.name, "-=", a.value, true)
1795
+ : setter(a.name, "=", a.value, true));
1796
+ }
1797
+ }
1798
+ catch (e) {
1799
+ if (e instanceof Unconvertible)
1800
+ return null;
1801
+ throw e;
1802
+ }
1803
+ }
1804
+ }
1805
+ return setters;
1806
+ }
1807
+ // A hook as the text of a section of its own, where (set:)s at the start become @set
1808
+ convertedHook(hook) {
1809
+ const state = { leading: true, directives: [] };
1810
+ const body = this.nodes(hook.nodes, state);
1811
+ return { directives: state.directives, body };
1812
+ }
1813
+ // If a hook only has a (goto:) (and (stop:)), the {{goto}}
1814
+ gotoOnly(hook, allowStop = false) {
1815
+ const significant = hook.nodes.filter(n => !(n.t == "text" && n.s.trim() == "") && !(allowStop && n.t == "macro" && n.name == "stop"));
1816
+ if (significant.length != 1)
1817
+ return null;
1818
+ const n = significant[0];
1819
+ if (n.t != "macro" || (n.name != "goto" && n.name != "redirect"))
1820
+ return null;
1821
+ return this.goto(splitArgs(n.args)[0] ?? "", n.raw);
1822
+ }
1823
+ labelFor(arg) {
1824
+ const target = arg.trim();
1825
+ if (!target.startsWith("?"))
1826
+ throw new Unconvertible("a hook name that isn't ?name");
1827
+ return labelName(target.substring(1));
1828
+ }
1829
+ show(arg, raw) {
1830
+ const label = this.labelFor(arg);
1831
+ const named = this.hooks.get(arg.trim().substring(1));
1832
+ if (!named)
1833
+ throw new Unconvertible(`(show:) of a hook that isn't in this passage (${raw})`);
1834
+ const content = this.nodes(named.hook.nodes, { leading: false, directives: [] });
1835
+ return `{{#replace "${label}"}}${content}{{/replace}}`;
1836
+ }
1837
+ // The attribute for "bind $x", or the value inside an object for "bind $hero's name" (#454),
1838
+ // or null
1839
+ bound(arg) {
1840
+ const match = /^2?bind\s+([$_][\s\S]*)$/.exec(arg.trim());
1841
+ if (!match)
1842
+ return null;
1843
+ const e = this.expr.parse(match[1]);
1844
+ if (e.k != "var" || isDynamicTarget(e.name))
1845
+ return null;
1846
+ return e.name;
1847
+ }
1848
+ input(args, raw) {
1849
+ const bound = this.bound(args[0] ?? "");
1850
+ if (!bound)
1851
+ throw new Unconvertible("an input box without bind, or bound to something other than a variable or a value inside one");
1852
+ let defaultText = null;
1853
+ let rows = 1;
1854
+ for (const a of args.slice(1)) {
1855
+ const e = this.expr.parse(a);
1856
+ if (e.k == "num")
1857
+ rows = e.v;
1858
+ else if (e.k == "str" && /^[=<>]+$/.test(e.v))
1859
+ continue;
1860
+ else if (e.k == "str")
1861
+ defaultText = e.v;
1862
+ }
1863
+ if (raw.toLowerCase().includes("force"))
1864
+ this.ctx.approximate(raw, "This has been converted to an ordinary input box.");
1865
+ const value = defaultText == null ? "" : ` value="${escapeAttribute(defaultText)}"`;
1866
+ const set = defaultText == null ? "" : `{{set "${bound}" ${print({ k: "str", v: defaultText })}}}`;
1867
+ if (rows > 1)
1868
+ return `${set}<textarea data-attribute="${bound}" rows="${rows}">${escapeText(escapeHtml(defaultText ?? ""))}</textarea>`;
1869
+ return `${set}<input type="text" data-attribute="${bound}"${value}>`;
1870
+ }
1871
+ style(m, args, state) {
1872
+ if (!m.hook)
1873
+ throw new Unconvertible(`(${m.name}:) without a hook (as a value, or saved in a variable)`);
1874
+ const content = this.hookContent(m.hook, state);
1875
+ const colourMacros = ["textcolour", "textcolor", "colour", "color", "background", "bg"];
1876
+ const value = colourMacros.includes(m.name) ? { k: "str", v: this.colour(args[0] ?? "") } : this.expr.parse(args[0] ?? "");
1877
+ const str = (e) => {
1878
+ if (e.k == "str")
1879
+ return e.v;
1880
+ if (e.k == "num")
1881
+ return String(e.v);
1882
+ throw new Unconvertible(`(${m.name}:) with a value that isn't fixed`);
1883
+ };
1884
+ switch (m.name) {
1885
+ case "textstyle": {
1886
+ let open = "";
1887
+ let close = "";
1888
+ // The {{#style}} effects (#453) with the same look as Harlowe's
1889
+ const effects = [];
1890
+ for (const a of args) {
1891
+ const style = str(this.expr.parse(a)).toLowerCase().replace(/[\s-]/g, "");
1892
+ const tag = { bold: "b", italic: "i", underline: "u", strike: "s", superscript: "sup", subscript: "sub", mark: "mark" }[style];
1893
+ const effect = {
1894
+ shudder: "shudder", rumble: "rumble", sway: "sway", buoy: "buoy", fidget: "shake",
1895
+ blink: "blink", fadeinout: "fade-in-out", blur: "blur", blurrier: "blurrier",
1896
+ smear: "smear", mirror: "mirror", upsidedown: "upside-down",
1897
+ shadow: "shadow", emboss: "emboss", outline: "outline", condense: "condense",
1898
+ expand: "expand", tall: "tall", flat: "flat", doubleunderline: "double-underline",
1899
+ wavyunderline: "wavy-underline", doublestrike: "double-strike", wavystrike: "wavy-strike",
1900
+ }[style];
1901
+ if (tag) {
1902
+ open += `<${tag}>`;
1903
+ close = `</${tag}>` + close;
1904
+ }
1905
+ else if (effect) {
1906
+ if (!effects.includes(effect))
1907
+ effects.push(effect);
1908
+ }
1909
+ else if (style != "none") {
1910
+ this.ctx.story.note("harlowe-text-style", `"${style}"`, "Squiffy has no equivalent for these Harlowe text styles, so they've been left out");
1911
+ }
1912
+ }
1913
+ if (effects.length) {
1914
+ open = `{{#style "${effects.join(" ")}"}}` + open;
1915
+ close += "{{/style}}";
1916
+ }
1917
+ return open + content + close;
1918
+ }
1919
+ case "align": {
1920
+ const marker = str(value);
1921
+ const align = marker.includes("<") && marker.includes(">") ? (marker.startsWith("<") ? "justify" : "center") : marker.includes(">") ? "right" : "left";
1922
+ return `<div style="text-align: ${align}">${content}</div>`;
1923
+ }
1924
+ case "css":
1925
+ return `<span style="${escapeAttribute(str(value))}">${content}</span>`;
1926
+ default: {
1927
+ const css = {
1928
+ textcolour: "color", textcolor: "color", colour: "color", color: "color",
1929
+ background: "background", bg: "background", font: "font-family", textsize: "font-size", size: "font-size",
1930
+ opacity: "opacity",
1931
+ }[m.name];
1932
+ let v;
1933
+ if (value.k == "num" && (m.name == "textsize" || m.name == "size"))
1934
+ v = `${value.v * 1.5}em`;
1935
+ else if (value.k == "str" || value.k == "num")
1936
+ v = String(value.v);
1937
+ else
1938
+ throw new Unconvertible(`(${m.name}:) with a colour Squiffy can't read`);
1939
+ return `<span style="${css}: ${escapeAttribute(v)}">${content}</span>`;
1940
+ }
1941
+ }
1942
+ }
1943
+ // A Harlowe colour: a colour name or #rrggbb without quotes, a string, or (rgb:) and friends
1944
+ colour(arg) {
1945
+ const a = arg.trim();
1946
+ if (/^#[0-9a-f]{3,8}$/i.test(a) || /^[a-z]+$/i.test(a))
1947
+ return a.toLowerCase();
1948
+ const fn = /^\((rgba?|hsla?):([\s\S]*)\)$/i.exec(a);
1949
+ if (fn) {
1950
+ const values = splitArgs(fn[2]).map(v => this.expr.parse(v));
1951
+ if (values.some(v => v.k != "num"))
1952
+ throw new Unconvertible(`(${fn[1]}:) with values that aren't fixed`);
1953
+ const numbers = values.map(v => v.v);
1954
+ if (fn[1].toLowerCase().startsWith("hsl")) {
1955
+ const [h, sat, l, alpha] = numbers;
1956
+ return `hsl(${h} ${sat * 100}% ${l * 100}%${alpha === undefined ? "" : ` / ${alpha}`})`;
1957
+ }
1958
+ return `rgb(${numbers.slice(0, 3).join(" ")}${numbers[3] === undefined ? "" : ` / ${numbers[3]}`})`;
1959
+ }
1960
+ const e = this.expr.parse(a);
1961
+ if (e.k == "str")
1962
+ return e.v;
1963
+ throw new Unconvertible("a colour that isn't fixed");
1964
+ }
1965
+ // ---- (set:) ----
1966
+ assignments(source, put) {
1967
+ return [this.assignment(source, put)];
1968
+ }
1969
+ assignment(source, put) {
1970
+ let targetSource;
1971
+ let valueSource;
1972
+ const keyword = put ? /\binto\b/ : /\bto\b/;
1973
+ let tokens = splitOutsideStrings(source, keyword);
1974
+ // Not Harlowe, but some stories have (set: $x += 1), which some versions of Harlowe allowed
1975
+ const shorthand = /^\s*([$_][A-Za-z]\w*)\s*([+\-*/]?=)\s*([\s\S]*)$/.exec(source);
1976
+ if (!tokens && !put && shorthand) {
1977
+ const op = shorthand[2];
1978
+ tokens = [shorthand[1], op == "=" ? shorthand[3] : `${shorthand[1]} ${op[0]} (${shorthand[3]})`];
1979
+ }
1980
+ if (!tokens)
1981
+ throw new Unconvertible(put ? "(put:) without \"into\"" : "(set:) without \"to\"");
1982
+ if (put)
1983
+ [valueSource, targetSource] = tokens;
1984
+ else
1985
+ [targetSource, valueSource] = tokens;
1986
+ const target = /^([$_])([A-Za-z]\w*)((?:'s\s+(?:[A-Za-z_]\w*|"[A-Za-z_]\w*"))*)$/.exec(targetSource.trim());
1987
+ if (!target)
1988
+ throw new Unconvertible("setting something other than a variable");
1989
+ // $player's hp is player.hp (#442)
1990
+ const properties = [...target[3].matchAll(/'s\s+"?([A-Za-z_]\w*)"?/g)].map(m => m[1]);
1991
+ const variable = properties.reduce((e, property) => member(e, { k: "str", v: property }), { k: "var", name: this.expr.attribute(target[2], target[1] == "_") });
1992
+ const name = targetName(variable);
1993
+ const value = this.expr.parse(valueSource, variable);
1994
+ // $x to it + 1, and $x to $x - 2
1995
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
1996
+ if (value.r.k == "array") {
1997
+ if (value.r.items.length != 1)
1998
+ throw new Unconvertible("adding or removing more than one item at once");
1999
+ return { kind: value.op == "+" ? "append" : "remove", name, value: value.r.items[0] };
2000
+ }
2001
+ if (value.r.k == "num" || value.op == "-")
2002
+ return { kind: value.op == "+" ? "inc" : "dec", name, value: value.r };
2003
+ }
2004
+ return { kind: "set", name, value };
2005
+ }
2006
+ // A call to a custom macro embeds its section, with its arguments as the parameters (#450)
2007
+ call(node) {
2008
+ const macro = node.temp ? undefined : harloweMacros(this.ctx.story).get(node.name);
2009
+ if (!macro)
2010
+ return this.ctx.unconvertible(node.raw, "Custom macros, made with (macro:), can only be converted when they're kept in a story variable ($), and only show text.");
2011
+ try {
2012
+ const args = splitArgs(node.args);
2013
+ if (args.length > macro.params.length)
2014
+ throw new Unconvertible("more values than the macro has parameters");
2015
+ const params = args.map((a, n) => ` ${macro.params[n]}=${print(this.expr.parse(a))}`).join("");
2016
+ return `{{embed ${print({ k: "str", v: macro.section })}${params}}}`;
2017
+ }
2018
+ catch (e) {
2019
+ if (!(e instanceof Unconvertible))
2020
+ throw e;
2021
+ return this.ctx.unconvertible(node.raw, `This couldn't be converted: ${e.message}.`);
2022
+ }
2023
+ }
2024
+ // A custom macro's body (#450), which becomes a section that calls to it embed. It's a code
2025
+ // hook, so the whitespace between its macros isn't shown.
2026
+ macroBody(source) {
2027
+ const nodes = new Parser(source).parse(0).nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
2028
+ this.collectHooks(nodes);
2029
+ this.inMacro = true;
2030
+ const state = { leading: false, directives: [] };
2031
+ let body = this.nodes(nodes, state);
2032
+ body += this.closeAll();
2033
+ return { directives: [], body };
2034
+ }
2035
+ set(m, args, state) {
2036
+ let out = "";
2037
+ // A custom macro becomes a section when it's defined (#450)
2038
+ args = args.filter(source => {
2039
+ const definition = /^\s*\$(\w+)\s+to\s+\(macro:/i.exec(source);
2040
+ const macro = definition && harloweMacros(this.ctx.story).get(definition[1]);
2041
+ if (!macro || macro.defined)
2042
+ return !macro;
2043
+ macro.defined = true;
2044
+ let converted;
2045
+ try {
2046
+ converted = new Writer(this.ctx).macroBody(macro.body);
2047
+ }
2048
+ catch (e) {
2049
+ if (!(e instanceof Unconvertible))
2050
+ throw e;
2051
+ converted = { directives: [], body: this.ctx.unconvertible(macro.body, `This macro couldn't be converted: ${e.message}.`) };
2052
+ }
2053
+ this.ctx.fillSection(macro.section, converted);
2054
+ return false;
2055
+ });
2056
+ for (const a of args.flatMap(source => this.assignments(source, m.name == "put"))) {
2057
+ const amount = a.value.k == "num" && Number.isInteger(a.value.v) && a.value.v >= 0 ? a.value.v : null;
2058
+ if (state.leading) {
2059
+ switch (a.kind) {
2060
+ case "set":
2061
+ state.directives.push(`@set ${setter(a.name, "=", a.value, false)}`);
2062
+ continue;
2063
+ case "inc":
2064
+ case "dec":
2065
+ if (amount !== null) {
2066
+ state.directives.push(`@${a.kind} ${a.name}${amount == 1 ? "" : " " + amount}`);
2067
+ }
2068
+ else {
2069
+ state.directives.push(`@set ${setter(a.name, a.kind == "inc" ? "+=" : "-=", a.value, false)}`);
2070
+ }
2071
+ continue;
2072
+ }
2073
+ }
2074
+ state.leading = false;
2075
+ const name = print({ k: "str", v: a.name });
2076
+ switch (a.kind) {
2077
+ case "set":
2078
+ out += `{{set ${name} ${print(a.value)}}}`;
2079
+ break;
2080
+ case "inc":
2081
+ case "dec":
2082
+ out += amount === 1 ? `{{${a.kind} ${name}}}` : `{{${a.kind} ${name} ${print(a.value)}}}`;
2083
+ break;
2084
+ case "append":
2085
+ case "remove":
2086
+ out += `{{${a.kind} ${name} ${print(a.value)}}}`;
2087
+ break;
2088
+ }
2089
+ }
2090
+ return out;
2091
+ }
2092
+ }
2093
+ // Harlowe's transitions, as Squiffy's @transition (#489)
2094
+ const harloweTransitions = new Map([
2095
+ ["instant", "none"], ["dissolve", "fade"], ["fade", "fade"], ["rumble", "rumble"], ["shudder", "shudder"],
2096
+ ["pulse", "pulse"], ["zoom", "zoom"], ["flicker", "flicker"], ["blur", "blur"],
2097
+ ["slide-left", "slide-left"], ["slide-right", "slide-right"], ["slide-up", "slide-up"], ["slide-down", "slide-down"],
2098
+ ["fade-left", "slide-left"], ["fade-right", "slide-right"], ["fade-up", "slide-up"], ["fade-down", "slide-down"],
2099
+ ]);
2100
+ // (a:)+(b:)[hook] is (a:) applied to (b:)[hook]: the hook, with the changers after the first
2101
+ // applied to it
2102
+ function foldChangers(m) {
2103
+ if (!m.hook || !m.changers.length)
2104
+ return m.hook;
2105
+ let hook = m.hook;
2106
+ for (let n = m.changers.length - 1; n >= 0; n--) {
2107
+ const changer = { ...m.changers[n], hook, changers: [] };
2108
+ hook = { nodes: [changer], raw: changer.raw + hook.raw };
2109
+ }
2110
+ return hook;
2111
+ }
2112
+ // The story's storylets: passages with (storylet: when ...), with their conditions
2113
+ function harloweStorylets(ctx) {
2114
+ return ctx.story.cached("harlowe-storylets", () => {
2115
+ const result = [];
2116
+ for (const p of ctx.story.twine.passages) {
2117
+ const match = /\(storylet:\s*when\b/i.exec(p.text);
2118
+ if (!match)
2119
+ continue;
2120
+ const end = skipBalanced(p.text, match.index, "(", ")");
2121
+ const section = ctx.story.sectionFor(p.name);
2122
+ if (end == -1 || section === undefined)
2123
+ continue;
2124
+ const source = p.text.substring(match.index + match[0].length, end - 1);
2125
+ // "visits" in a storylet's condition means visits to the storylet
2126
+ const expressions = new HarloweExpressions({ ...ctx, section, passage: p });
2127
+ let condition;
2128
+ try {
2129
+ condition = expressions.parse(source);
2130
+ }
2131
+ catch (e) {
2132
+ if (!(e instanceof Unconvertible))
2133
+ throw e;
2134
+ ctx.story.addProblem({ passage: p.name, text: p.text.substring(match.index, end), reason: `This storylet's condition couldn't be converted: ${e.message}. It's always listed.` });
2135
+ condition = null;
2136
+ }
2137
+ result.push({ section, condition });
2138
+ }
2139
+ return result;
2140
+ });
2141
+ }
2142
+ // (click: ?page) or (click: ?passage), with a hook
2143
+ function isBlank(node) {
2144
+ return node.t == "text" && node.s.trim() == "";
2145
+ }
2146
+ // An HTML comment, <!-- ... -->, which the parser keeps as it is
2147
+ function isComment(node) {
2148
+ return node.t == "raw" && node.s.startsWith("<!--");
2149
+ }
2150
+ function isPageClick(node) {
2151
+ return node?.t == "macro" && node.name == "click" && !!node.hook && /^\s*\?(page|passage)\s*$/i.test(node.args);
2152
+ }
2153
+ // Macros whose hooks are converted with them, as well as the changers
2154
+ // Macros that give a value, which Harlowe prints when one's on its own in the text. Lists and
2155
+ // datamaps aren't here, as Harlowe prints those its own way.
2156
+ const printedMacros = new Set([
2157
+ "str", "string", "text", "num", "number", "cond", "lowercase", "uppercase", "upperfirst", "round", "floor", "ceil",
2158
+ "abs", "min", "max", "joined", "count", "visited",
2159
+ ]);
2160
+ const hookMacros = new Set(["linkreplace", "linkrepeat", "linkrerun", "linkreveal", "linkrevealgoto", "click", "clickreplace", "clickappend", "clickprepend"]);
2161
+ const clickMacros = new Set(["click", "clickreplace", "clickappend", "clickprepend", "clickgoto", "mouseover", "mouseout", "mouseovergoto"]);
2162
+ // The label a named hook becomes, the same in every passage, so (replace:) can change a hook in a
2163
+ // header. The runtime replaces the latest label with the name.
2164
+ function labelName(hook) {
2165
+ return hook.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
2166
+ }
2167
+ // Every hook name referred to with ?name in the story
2168
+ function referencedHooks(ctx) {
2169
+ return ctx.story.cached("harlowe-hooks", () => {
2170
+ const result = new Set();
2171
+ for (const p of ctx.story.twine.passages) {
2172
+ for (const m of p.text.matchAll(/\?([A-Za-z][\w-]*)/g))
2173
+ result.add(m[1]);
2174
+ }
2175
+ return result;
2176
+ });
2177
+ }
2178
+ // Splits "a to b" on the first keyword outside quotes and brackets
2179
+ function splitOutsideStrings(s, keyword) {
2180
+ let depth = 0;
2181
+ for (let i = 0; i < s.length; i++) {
2182
+ const c = s[i];
2183
+ // Harlowe's possessive: $player's hp
2184
+ if (c == "'" && s[i + 1] == "s" && /\s/.test(s[i + 2] ?? "") && /[\w)"]/.test(s[i - 1] ?? ""))
2185
+ continue;
2186
+ if (c == "\"" || c == "'") {
2187
+ const end = skipString(s, i);
2188
+ if (end == -1)
2189
+ return null;
2190
+ i = end - 1;
2191
+ continue;
2192
+ }
2193
+ if (c == "(")
2194
+ depth++;
2195
+ else if (c == ")")
2196
+ depth--;
2197
+ else if (depth == 0 && /\s/.test(c)) {
2198
+ const match = keyword.exec(s.substring(i + 1));
2199
+ if (match && match.index == 0 && /\s/.test(s[i + 1 + match[0].length] ?? "")) {
2200
+ return [s.substring(0, i), s.substring(i + 1 + match[0].length)];
2201
+ }
2202
+ }
2203
+ }
2204
+ return null;
2205
+ }
2206
+ function escapeAttribute(s) {
2207
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{");
2208
+ }
2209
+ // Harlowe's { } markup and (collapse:): runs of whitespace become one space
2210
+ function collapseWhitespace(s) {
2211
+ return s.replace(/\s+/g, " ").trim();
2212
+ }
2213
+ // (click: "text") makes text that's in the passage clickable. Its first appearance becomes a
2214
+ // named hook, so it converts as (click: ?hook) does.
2215
+ function clickableText(source, ctx) {
2216
+ let result = source;
2217
+ let n = 0;
2218
+ for (;;) {
2219
+ const match = /\((click|click-replace|click-append|click-prepend|click-goto|mouseover|mouseover-goto|mouseout)\s*:\s*("[^"\n]+"|'[^'\n]+')/i.exec(result);
2220
+ if (!match)
2221
+ return result;
2222
+ const text = match[2].slice(1, -1);
2223
+ const hook = `click-text-${++n}`;
2224
+ const macroEnd = skipBalanced(result, match.index, "(", ")");
2225
+ const withHookName = result.substring(0, match.index) + `(${match[1]}: ?${hook}` + result.substring(match.index + match[0].length);
2226
+ // The text, outside any macro
2227
+ const macros = [];
2228
+ for (const m of withHookName.matchAll(/\([A-Za-z][\w-]*:/g)) {
2229
+ const end = skipBalanced(withHookName, m.index, "(", ")");
2230
+ if (end != -1)
2231
+ macros.push([m.index, end]);
2232
+ }
2233
+ let at = -1;
2234
+ for (let from = 0;; from = at + 1) {
2235
+ at = withHookName.indexOf(text, from);
2236
+ if (at == -1 || !macros.some(([start, end]) => at >= start && at < end))
2237
+ break;
2238
+ }
2239
+ if (at == -1 || macroEnd == -1) {
2240
+ ctx.approximate(match[0], "The text this makes clickable isn't in the passage.");
2241
+ // Leave it for the macro converter to report
2242
+ return result.substring(0, match.index) + `(${match[1]}-text: ` + result.substring(match.index + match[0].length - match[2].length);
2243
+ }
2244
+ if (withHookName.indexOf(text, at + text.length) != -1) {
2245
+ ctx.approximate(match[0], "Only the first place this text appears has been made clickable.");
2246
+ }
2247
+ result = withHookName.substring(0, at) + `|${hook}>[${text}]` + withHookName.substring(at + text.length);
2248
+ }
2249
+ }
2250
+ // A string, number or boolean written as it is, or undefined for anything else
2251
+ function literal(arg) {
2252
+ if (arg === undefined)
2253
+ return undefined;
2254
+ const a = arg.trim();
2255
+ if (/^["']/.test(a) && skipString(a, 0) == a.length)
2256
+ return unescapeString(a);
2257
+ if (/^-?(\d+\.?\d*|\.\d+)$/.test(a))
2258
+ return Number(a);
2259
+ if (/^(true|false)$/i.test(a))
2260
+ return a.toLowerCase() == "true";
2261
+ return undefined;
2262
+ }
2263
+ // The special passages of the Harlowe Audio Library, which aren't part of the story
2264
+ export const harloweAudioPassages = new Set(["hal.tracks", "hal.config"]);
2265
+ // The story's tracks, from the Harlowe Audio Library's hal.tracks passage ("name: file") and
2266
+ // (newtrack:), and the ones (track:) sets to loop
2267
+ export function harloweAudio(story) {
2268
+ return story.cached("harlowe-audio", () => {
2269
+ const audio = { files: new Map(), looping: new Set() };
2270
+ const definitions = story.twine.passages.find(p => p.name == "hal.tracks")?.text ?? "";
2271
+ for (const line of definitions.split(/\r?\n/)) {
2272
+ // The name ends at the first colon: the files can be web addresses
2273
+ const colon = line.indexOf(":");
2274
+ if (colon == -1)
2275
+ continue;
2276
+ const name = line.substring(0, colon).trim();
2277
+ const file = pickSource(line.substring(colon + 1).split(",").map(f => f.trim()).filter(f => f));
2278
+ if (name && file && !audio.files.has(name))
2279
+ audio.files.set(name, file);
2280
+ }
2281
+ for (const p of story.twine.passages) {
2282
+ for (const m of p.text.matchAll(/\((new-?track|track):/gi)) {
2283
+ const end = skipBalanced(p.text, m.index, "(", ")");
2284
+ if (end == -1)
2285
+ continue;
2286
+ const args = splitArgs(p.text.substring(m.index + m[0].length, end - 1)).map(literal);
2287
+ if (typeof args[0] != "string")
2288
+ continue;
2289
+ if (m[1].toLowerCase() == "track") {
2290
+ if (typeof args[1] == "string" && args[1].toLowerCase() == "loop" && args[2] === true)
2291
+ audio.looping.add(args[0]);
2292
+ }
2293
+ else {
2294
+ const file = pickSource(args.slice(1).filter((a) => typeof a == "string"));
2295
+ if (file && !audio.files.has(args[0]))
2296
+ audio.files.set(args[0], file);
2297
+ }
2298
+ }
2299
+ }
2300
+ return audio;
2301
+ });
2302
+ }
2303
+ // The story's custom macros (#450): (set: $name to (macro: str-type _who, [ ... ])). Each becomes
2304
+ // a section, named before anything's converted so calls know where they go, with its parameters
2305
+ // as the attributes the body's temporary variables become. A macro with a parameter that takes
2306
+ // any number of values (...) isn't one of them, and stays unconverted.
2307
+ export function harloweMacros(story) {
2308
+ return story.cached("harlowe-macros", () => {
2309
+ const result = new Map();
2310
+ for (const p of story.twine.passages) {
2311
+ for (const m of p.text.matchAll(/\$(\w+)\s+to\s+(?=\(macro:)/gi)) {
2312
+ if (result.has(m[1]))
2313
+ continue;
2314
+ const start = m.index + m[0].length;
2315
+ const end = skipBalanced(p.text, start, "(", ")");
2316
+ if (end == -1)
2317
+ continue;
2318
+ const args = splitArgs(p.text.substring(start + "(macro:".length, end - 1));
2319
+ const hook = args.pop()?.trim();
2320
+ if (!hook?.startsWith("[") || !hook.endsWith("]"))
2321
+ continue;
2322
+ const params = args.map(a => /^\s*(?:[\w-]+-type\s+)?_(\w+)\s*$/.exec(a)?.[1]);
2323
+ if (params.some(name => !name))
2324
+ continue;
2325
+ result.set(m[1], {
2326
+ section: story.uniqueSectionName(`macro ${m[1]}`),
2327
+ params: params.map(name => story.attribute(name, true)),
2328
+ body: hook.substring(1, hook.length - 1),
2329
+ defined: false,
2330
+ });
2331
+ }
2332
+ }
2333
+ return result;
2334
+ });
2335
+ }
2336
+ export function convertHarlowePassage(text, ctx) {
2337
+ // A backslash at the end or start of a line joins it to the next or previous line
2338
+ const source = clickableText(text.replace(/\\\n/g, "").replace(/\n\\/g, ""), ctx);
2339
+ const nodes = new Parser(source).parse(0).nodes;
2340
+ return new Writer(ctx).passage(nodes);
2341
+ }