squiffy-compiler 7.0.0-beta.4 → 7.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1856 @@
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 { display, isBoolean, print, randomInteger, skipBalanced, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
9
+ // Macro names ignore case, - and _
10
+ function normalise(name) {
11
+ return name.toLowerCase().replace(/[-_]/g, "");
12
+ }
13
+ // Macros that change a hook, so may have whitespace between them and it
14
+ const changers = new Set([
15
+ "if", "elseif", "else", "unless", "link", "linkreveal", "linkrepeat", "linkrerun", "linkrevealgoto", "after",
16
+ "live", "textstyle", "textcolour", "textcolor", "colour", "color", "background", "bg", "font", "textsize", "size",
17
+ "align", "css", "transition", "t8n", "transitiontime", "t8ntime", "transitiondepart", "t8ndepart",
18
+ "transitionarrive", "t8narrive", "transitiondelay", "t8ndelay", "transitionskip", "t8nskip", "hidden", "nobr",
19
+ "collapse", "verbatim", "v6m", "replace", "append", "prepend", "click", "clickreplace", "clickappend",
20
+ "clickprepend", "mouseover", "mouseout", "hover", "hoverstyle", "for", "loop", "event", "show", "linkshow",
21
+ "opacity", "textrotate", "textrotatez", "box", "border", "b4r", "bordercolour", "bordercolor", "b4rcolour",
22
+ "cornerradius", "textindent", "float", "hookname", "action", "linkundo", "linkfullscreen", "more",
23
+ "clickgoto", "mouseovergoto", "mouseoverreplace", "mouseoverappend", "mouseoverprepend", "mouseoutreplace",
24
+ "linkstyle", "charstyle", "linestyle", "button", "textshadow", "outline", "hiddenhook", "seqlink",
25
+ ]);
26
+ class Parser {
27
+ constructor(src) {
28
+ Object.defineProperty(this, "src", {
29
+ enumerable: true,
30
+ configurable: true,
31
+ writable: true,
32
+ value: src
33
+ });
34
+ }
35
+ // Parses until the end, or the given closing character at this level
36
+ parse(start, close) {
37
+ const src = this.src;
38
+ const nodes = [];
39
+ let text = "";
40
+ const flush = () => {
41
+ if (text)
42
+ nodes.push({ t: "text", s: text });
43
+ text = "";
44
+ };
45
+ let i = start;
46
+ while (i < src.length) {
47
+ const c = src[i];
48
+ if (c == close) {
49
+ flush();
50
+ return { nodes, end: i };
51
+ }
52
+ const rest = src.substring(i, i + 200);
53
+ if (rest.startsWith("<!--")) {
54
+ const end = src.indexOf("-->", i + 4);
55
+ const stop = end == -1 ? src.length : end + 3;
56
+ flush();
57
+ nodes.push({ t: "raw", s: src.substring(i, stop).replace(/\n/g, " ") });
58
+ i = stop;
59
+ continue;
60
+ }
61
+ const scriptMatch = /^<(script|style)\b/i.exec(rest);
62
+ if (scriptMatch) {
63
+ const closeTag = `</${scriptMatch[1].toLowerCase()}>`;
64
+ const end = src.toLowerCase().indexOf(closeTag, i);
65
+ const stop = end == -1 ? src.length : end + closeTag.length;
66
+ flush();
67
+ nodes.push({ t: "comment", text: src.substring(i, stop), reason: `A <${scriptMatch[1]}> in a passage isn't run by Squiffy. Move it to the story's JavaScript or CSS file.` });
68
+ i = stop;
69
+ continue;
70
+ }
71
+ if (c == "`") {
72
+ let n = 0;
73
+ while (src[i + n] == "`")
74
+ n++;
75
+ const fence = "`".repeat(n);
76
+ let end = src.indexOf(fence, i + n);
77
+ while (end != -1 && src[end + n] == "`")
78
+ end = src.indexOf(fence, end + n + 1);
79
+ if (end != -1) {
80
+ flush();
81
+ nodes.push({ t: "raw", s: escapeText(escapeHtml(src.substring(i + n, end))) });
82
+ i = end + n;
83
+ continue;
84
+ }
85
+ }
86
+ if (rest.startsWith("[[") && !rest.startsWith("[[[")) {
87
+ const end = src.indexOf("]]", i + 2);
88
+ const inner = end == -1 ? "" : src.substring(i + 2, end);
89
+ if (end != -1 && !inner.includes("[") && !inner.includes("\n")) {
90
+ flush();
91
+ nodes.push(parseLink(inner, src.substring(i, end + 2)));
92
+ i = end + 2;
93
+ continue;
94
+ }
95
+ }
96
+ const namedHook = /^\|([\w-]+)([>)])\[/.exec(rest);
97
+ if (namedHook) {
98
+ flush();
99
+ const hook = this.hook(i + namedHook[0].length - 1);
100
+ hook.hook.name = namedHook[1];
101
+ hook.hook.hidden = namedHook[2] == ")";
102
+ nodes.push({ t: "hook", hook: hook.hook });
103
+ i = hook.end;
104
+ continue;
105
+ }
106
+ if (c == "[") {
107
+ flush();
108
+ const hook = this.hook(i);
109
+ nodes.push({ t: "hook", hook: hook.hook });
110
+ i = hook.end;
111
+ continue;
112
+ }
113
+ const macroStart = /^\(([A-Za-z][\w-]*):/.exec(rest);
114
+ if (macroStart) {
115
+ const end = skipBalanced(src, i, "(", ")");
116
+ if (end != -1) {
117
+ flush();
118
+ const result = this.macro(i, end);
119
+ nodes.push(result.node);
120
+ i = result.end;
121
+ continue;
122
+ }
123
+ }
124
+ if (/^\(\$[\w]+:/.test(rest) || /^\(_[\w]+:/.test(rest)) {
125
+ // A call to a custom macro
126
+ const end = skipBalanced(src, i, "(", ")");
127
+ if (end != -1) {
128
+ flush();
129
+ nodes.push({ t: "comment", text: src.substring(i, end), reason: "Custom macros, made with (macro:), can't be converted." });
130
+ i = end;
131
+ continue;
132
+ }
133
+ }
134
+ const variable = /^([$_])([A-Za-z]\w*)/.exec(rest);
135
+ if (variable && (variable[1] == "$" || !/\w/.test(src[i - 1] ?? ""))) {
136
+ const after = src.substring(i + variable[0].length, i + variable[0].length + 4);
137
+ 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));
138
+ if (property) {
139
+ // $player's hp: shown as (print:) would show it
140
+ flush();
141
+ const raw = variable[0] + property[0];
142
+ nodes.push({ t: "macro", name: "print", raw, args: raw, changers: [] });
143
+ i += raw.length;
144
+ continue;
145
+ }
146
+ if (after.startsWith("[")) {
147
+ // A changer stored in a variable attached to a hook
148
+ const end = this.hook(i + variable[0].length).end;
149
+ flush();
150
+ nodes.push({ t: "comment", text: src.substring(i, end), reason: "A changer stored in a variable can't be converted." });
151
+ i = end;
152
+ continue;
153
+ }
154
+ flush();
155
+ nodes.push({ t: "var", name: variable[2], temp: variable[1] == "_", raw: variable[0] });
156
+ i += variable[0].length;
157
+ continue;
158
+ }
159
+ if (c == "{") {
160
+ const inner = this.parse(i + 1, "}");
161
+ if (inner.end < src.length) {
162
+ flush();
163
+ nodes.push({ t: "collapse", nodes: inner.nodes });
164
+ i = inner.end + 1;
165
+ continue;
166
+ }
167
+ }
168
+ text += c;
169
+ i++;
170
+ }
171
+ flush();
172
+ return { nodes, end: i };
173
+ }
174
+ // A hook, from its opening [, with any name after its closing ]
175
+ hook(open) {
176
+ const inner = this.parse(open + 1, "]");
177
+ let end = Math.min(inner.end + 1, this.src.length);
178
+ const hook = { nodes: inner.nodes, raw: this.src.substring(open, end) };
179
+ const named = /^([<(])([\w-]+)\|/.exec(this.src.substring(end, end + 100));
180
+ if (named) {
181
+ hook.name = named[2];
182
+ hook.hidden = named[1] == "(";
183
+ end += named[0].length;
184
+ }
185
+ return { hook, end };
186
+ }
187
+ macro(start, end) {
188
+ const src = this.src;
189
+ const raw = src.substring(start, end);
190
+ const colon = raw.indexOf(":");
191
+ const name = normalise(raw.substring(1, colon));
192
+ const node = { t: "macro", name, raw, args: raw.substring(colon + 1, raw.length - 1), changers: [] };
193
+ let i = end;
194
+ // Changers added together: (if: $x)+(text-style: "bold")[...]
195
+ for (;;) {
196
+ const plus = /^\s*\+\s*\(([A-Za-z][\w-]*):/.exec(src.substring(i, i + 100));
197
+ if (!plus)
198
+ break;
199
+ const open = i + plus[0].indexOf("(");
200
+ const close = skipBalanced(src, open, "(", ")");
201
+ if (close == -1)
202
+ break;
203
+ const extra = src.substring(open, close);
204
+ const extraColon = extra.indexOf(":");
205
+ node.changers.push({ t: "macro", name: normalise(extra.substring(1, extraColon)), raw: extra, args: extra.substring(extraColon + 1, extra.length - 1), changers: [] });
206
+ node.raw += src.substring(i, close);
207
+ i = close;
208
+ }
209
+ // Changers can be separated from their hooks by whitespace, even line breaks
210
+ let hookStart = i;
211
+ if (changers.has(name) || name.startsWith("click") || name.startsWith("mouse")) {
212
+ while (/\s/.test(src[hookStart] ?? ""))
213
+ hookStart++;
214
+ if (src[hookStart] != "[" && !src.startsWith("|", hookStart))
215
+ hookStart = i;
216
+ }
217
+ if (src[hookStart] == "[" && !src.startsWith("[[", hookStart) || src.startsWith("[[[", hookStart)) {
218
+ const hook = this.hook(hookStart);
219
+ node.hook = hook.hook;
220
+ return { node, end: hook.end };
221
+ }
222
+ const named = /^\|([\w-]+)([>)])\[/.exec(src.substring(hookStart, hookStart + 100));
223
+ if (named && changers.has(name)) {
224
+ const hook = this.hook(hookStart + named[0].length - 1);
225
+ hook.hook.name = named[1];
226
+ hook.hook.hidden = named[2] == ")";
227
+ node.hook = hook.hook;
228
+ return { node, end: hook.end };
229
+ }
230
+ return { node, end: i };
231
+ }
232
+ }
233
+ function parseLink(inner, raw) {
234
+ let text;
235
+ let target;
236
+ const arrow = inner.lastIndexOf("->");
237
+ const back = inner.indexOf("<-");
238
+ if (arrow != -1) {
239
+ text = inner.substring(0, arrow);
240
+ target = inner.substring(arrow + 2);
241
+ }
242
+ else if (back != -1) {
243
+ target = inner.substring(0, back);
244
+ text = inner.substring(back + 2);
245
+ }
246
+ else if (inner.includes("|")) {
247
+ const bar = inner.lastIndexOf("|");
248
+ text = inner.substring(0, bar);
249
+ target = inner.substring(bar + 1);
250
+ }
251
+ else {
252
+ text = target = inner;
253
+ }
254
+ return { t: "link", raw, text, target: target.trim() };
255
+ }
256
+ function escapeHtml(s) {
257
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
258
+ }
259
+ // Splits macro arguments on the commas between them
260
+ export function splitArgs(args) {
261
+ const result = [];
262
+ let depth = 0;
263
+ let current = "";
264
+ for (let i = 0; i < args.length; i++) {
265
+ const c = args[i];
266
+ const possessive = c == "'" && args[i + 1] == "s" && /\s/.test(args[i + 2] ?? "") && /[\w)]/.test(args[i - 1] ?? "");
267
+ if ((c == "\"" || c == "'") && !possessive) {
268
+ const end = skipString(args, i);
269
+ const stop = end == -1 ? args.length : end;
270
+ current += args.substring(i, stop);
271
+ i = stop - 1;
272
+ continue;
273
+ }
274
+ if (c == "(" || c == "[")
275
+ depth++;
276
+ else if (c == ")" || c == "]")
277
+ depth--;
278
+ if (c == "," && depth == 0) {
279
+ result.push(current);
280
+ current = "";
281
+ }
282
+ else {
283
+ current += c;
284
+ }
285
+ }
286
+ if (current.trim() || result.length)
287
+ result.push(current);
288
+ return result.map(a => a.trim());
289
+ }
290
+ const operators = [">=", "<=", "is not in", "is in", "is not", "does not contain", "'s", "+", "-", "*", "/", "%", ">", "<", "=", "!="];
291
+ function tokenize(s) {
292
+ const tokens = [];
293
+ let i = 0;
294
+ while (i < s.length) {
295
+ const c = s[i];
296
+ if (/\s/.test(c)) {
297
+ i++;
298
+ continue;
299
+ }
300
+ if (s.startsWith("'s", i) && /\s/.test(s[i + 2] ?? "") && i > 0 && /[\w)]/.test(s[i - 1])) {
301
+ tokens.push({ type: "op", text: "'s" });
302
+ i += 2;
303
+ continue;
304
+ }
305
+ const ordinal = /^(\d+)(st|nd|rd|th)\b/.exec(s.substring(i));
306
+ if (ordinal) {
307
+ tokens.push({ type: "word", text: "ordinal", value: parseInt(ordinal[1]) });
308
+ i += ordinal[0].length;
309
+ continue;
310
+ }
311
+ if (c == "\"" || c == "'") {
312
+ const end = skipString(s, i);
313
+ if (end == -1)
314
+ throw new Unconvertible("an expression with a string that isn't closed");
315
+ tokens.push({ type: "str", text: s.substring(i, end), value: unescapeString(s.substring(i, end)) });
316
+ i = end;
317
+ continue;
318
+ }
319
+ const num = /^(\d+(?:\.\d+)?|\.\d+)(ms|s)?(?![\w])/i.exec(s.substring(i));
320
+ if (num) {
321
+ let value = parseFloat(num[1]);
322
+ if (num[2]?.toLowerCase() == "s")
323
+ value *= 1000;
324
+ tokens.push({ type: "num", text: num[0], value });
325
+ i += num[0].length;
326
+ continue;
327
+ }
328
+ const variable = /^([$_?])([A-Za-z]\w*)/.exec(s.substring(i));
329
+ if (variable) {
330
+ tokens.push({ type: variable[1] == "$" ? "var" : variable[1] == "_" ? "temp" : "hook", text: variable[0], value: variable[2] });
331
+ i += variable[0].length;
332
+ continue;
333
+ }
334
+ const macro = /^\(([A-Za-z][\w-]*):/.exec(s.substring(i));
335
+ if (macro) {
336
+ const end = skipBalanced(s, i, "(", ")");
337
+ if (end == -1)
338
+ throw new Unconvertible("an expression with a macro that isn't closed");
339
+ tokens.push({ type: "macro", text: s.substring(i, end), value: normalise(macro[1]) });
340
+ i = end;
341
+ continue;
342
+ }
343
+ if (c == "(" || c == ")" || c == ",") {
344
+ tokens.push({ type: c, text: c });
345
+ i++;
346
+ continue;
347
+ }
348
+ const op = operators.find(o => s.startsWith(o, i) && (!/\w$/.test(o) || !/\w/.test(s[i + o.length] ?? "")));
349
+ if (op) {
350
+ tokens.push({ type: "op", text: op });
351
+ i += op.length;
352
+ continue;
353
+ }
354
+ const word = /^[A-Za-z]\w*/.exec(s.substring(i));
355
+ if (word) {
356
+ tokens.push({ type: "word", text: word[0].toLowerCase(), value: word[0] });
357
+ i += word[0].length;
358
+ continue;
359
+ }
360
+ throw new Unconvertible(`an expression Squiffy can't read ("${s.substring(i, i + 10)}")`);
361
+ }
362
+ return tokens;
363
+ }
364
+ export class HarloweExpressions {
365
+ constructor(ctx) {
366
+ Object.defineProperty(this, "ctx", {
367
+ enumerable: true,
368
+ configurable: true,
369
+ writable: true,
370
+ value: ctx
371
+ });
372
+ }
373
+ // The Squiffy attribute for a Harlowe variable
374
+ attribute(name, temp) {
375
+ return this.ctx.story.attribute(name, temp);
376
+ }
377
+ parse(source, it) {
378
+ const tokens = new Tokens(tokenize(source));
379
+ const e = new ExpressionParser(this, tokens, it).expression();
380
+ if (!tokens.done)
381
+ throw new Unconvertible(`an expression Squiffy can't read (at "${tokens.peek().text}")`);
382
+ return e;
383
+ }
384
+ // A Harlowe value used as a passage name, for (goto:), (display:) and links
385
+ passageName(source) {
386
+ const e = this.parse(source);
387
+ if (e.k == "str")
388
+ return { name: e.v };
389
+ return { expr: e };
390
+ }
391
+ // A macro in an expression, e.g. (either: "a", "b")
392
+ macro(name, raw, it) {
393
+ const args = splitArgs(raw.substring(raw.indexOf(":") + 1, raw.length - 1));
394
+ const values = () => args.map(a => this.parse(a, it));
395
+ switch (name) {
396
+ case "either":
397
+ return { k: "call", fn: "random", args: [{ k: "array", items: values() }] };
398
+ case "random": {
399
+ const [min, max] = values();
400
+ return randomInteger(min, max);
401
+ }
402
+ case "a":
403
+ case "array":
404
+ return { k: "array", items: values() };
405
+ case "visited": {
406
+ if (args.length == 0)
407
+ return { k: "bin", op: ">", l: this.visits(), r: { k: "num", v: 0 } };
408
+ const target = this.parse(args[0]);
409
+ if (target.k != "str")
410
+ throw new Unconvertible("(visited:) with something other than a passage name");
411
+ return { k: "call", fn: "seen", args: [{ k: "str", v: this.ctx.story.sectionForUnknown(target.v) }] };
412
+ }
413
+ case "str":
414
+ case "string":
415
+ case "text":
416
+ case "num":
417
+ case "number":
418
+ if (args.length != 1)
419
+ throw new Unconvertible(`(${name}:) with more than one value`);
420
+ return this.parse(args[0], it);
421
+ case "history":
422
+ throw new Unconvertible("(history:), except as (history:) contains \"passage\"");
423
+ case "passage":
424
+ throw new Unconvertible("(passage:)");
425
+ case "dm":
426
+ case "datamap":
427
+ case "ds":
428
+ case "dataset":
429
+ throw new Unconvertible("Harlowe datamaps and datasets");
430
+ case "cond":
431
+ throw new Unconvertible("(cond:), which Squiffy has no equivalent for in an expression");
432
+ default:
433
+ throw new Unconvertible(`the (${name}:) macro`);
434
+ }
435
+ }
436
+ // (visits:), the number of visits to this passage
437
+ visits() {
438
+ return { k: "call", fn: "visits", args: [{ k: "str", v: this.ctx.section }] };
439
+ }
440
+ }
441
+ class ExpressionParser {
442
+ constructor(h, tokens, it) {
443
+ Object.defineProperty(this, "h", {
444
+ enumerable: true,
445
+ configurable: true,
446
+ writable: true,
447
+ value: h
448
+ });
449
+ Object.defineProperty(this, "tokens", {
450
+ enumerable: true,
451
+ configurable: true,
452
+ writable: true,
453
+ value: tokens
454
+ });
455
+ Object.defineProperty(this, "it", {
456
+ enumerable: true,
457
+ configurable: true,
458
+ writable: true,
459
+ value: it
460
+ });
461
+ // The left side of the last comparison, for "$a > 2 and < 5"
462
+ Object.defineProperty(this, "lastComparison", {
463
+ enumerable: true,
464
+ configurable: true,
465
+ writable: true,
466
+ value: void 0
467
+ });
468
+ }
469
+ expression() {
470
+ return this.or();
471
+ }
472
+ or() {
473
+ let left = this.and();
474
+ while (this.tokens.is("or")) {
475
+ this.tokens.next();
476
+ left = { k: "bin", op: "or", l: left, r: this.elided(this.and()) };
477
+ }
478
+ return left;
479
+ }
480
+ and() {
481
+ let left = this.not();
482
+ while (this.tokens.is("and")) {
483
+ this.tokens.next();
484
+ left = { k: "bin", op: "and", l: left, r: this.elided(this.not()) };
485
+ }
486
+ return left;
487
+ }
488
+ // "$a is 1 or 2" means "$a is 1 or $a is 2"
489
+ elided(right) {
490
+ if (this.lastComparison && !isBoolean(right) && right.k != "var" && right.k != "call") {
491
+ return this.compare(this.lastComparison.left, this.lastComparison.op, right);
492
+ }
493
+ return right;
494
+ }
495
+ not() {
496
+ if (this.tokens.is("not")) {
497
+ this.tokens.next();
498
+ return { k: "not", e: this.not() };
499
+ }
500
+ return this.comparison();
501
+ }
502
+ comparisonOp() {
503
+ const t = this.tokens.peek();
504
+ if (!t)
505
+ return null;
506
+ if (t.type == "op") {
507
+ switch (t.text) {
508
+ case ">":
509
+ case "<":
510
+ case ">=":
511
+ case "<=": return t.text;
512
+ case "is not": return "!=";
513
+ case "is in": return "in";
514
+ case "is not in": return "notin";
515
+ case "does not contain": return "notcontains";
516
+ case "=": return "=";
517
+ case "!=": return "!=";
518
+ }
519
+ }
520
+ if (t.type == "word") {
521
+ if (t.text == "is")
522
+ return "=";
523
+ if (t.text == "contains")
524
+ return "contains";
525
+ }
526
+ return null;
527
+ }
528
+ comparison() {
529
+ // "and < 5", with the left side left out
530
+ if (this.comparisonOp() && this.lastComparison) {
531
+ const op = this.comparisonOp();
532
+ this.tokens.next();
533
+ return this.compare(this.lastComparison.left, op, this.additive());
534
+ }
535
+ const left = this.additive();
536
+ const op = this.comparisonOp();
537
+ if (!op)
538
+ return left;
539
+ this.tokens.next();
540
+ const right = this.additive();
541
+ this.lastComparison = { left, op };
542
+ return this.compare(left, op, right);
543
+ }
544
+ compare(left, op, right) {
545
+ switch (op) {
546
+ case "contains": return this.contains(left, right);
547
+ case "notcontains": return { k: "not", e: this.contains(left, right) };
548
+ case "in": return this.contains(right, left);
549
+ case "notin": return { k: "not", e: this.contains(right, left) };
550
+ default: return { k: "bin", op, l: left, r: right };
551
+ }
552
+ }
553
+ contains(collection, value) {
554
+ if (collection.k == "var")
555
+ return { k: "call", fn: "contains", args: [{ k: "str", v: collection.name }, value] };
556
+ if (collection.k == "array")
557
+ return { k: "call", fn: "contains", args: [collection, value] };
558
+ if (collection.k == "call" && collection.fn == "__history") {
559
+ if (value.k != "str")
560
+ throw new Unconvertible("(history:) contains something other than a passage name");
561
+ return { k: "call", fn: "seen", args: [{ k: "str", v: this.h.ctx.story.sectionForUnknown(value.v) }] };
562
+ }
563
+ throw new Unconvertible("\"contains\" with something other than a variable or an array");
564
+ }
565
+ additive() {
566
+ let left = this.multiplicative();
567
+ while (this.tokens.is("+") || this.tokens.is("-")) {
568
+ const op = this.tokens.next().text;
569
+ left = { k: "bin", op, l: left, r: this.multiplicative() };
570
+ }
571
+ return left;
572
+ }
573
+ multiplicative() {
574
+ let left = this.unary();
575
+ while (this.tokens.is("*") || this.tokens.is("/") || this.tokens.is("%")) {
576
+ const op = this.tokens.next().text;
577
+ left = { k: "bin", op, l: left, r: this.unary() };
578
+ }
579
+ return left;
580
+ }
581
+ unary() {
582
+ if (this.tokens.is("-")) {
583
+ this.tokens.next();
584
+ const e = this.unary();
585
+ return e.k == "num" ? { k: "num", v: -e.v } : { k: "neg", e };
586
+ }
587
+ return this.postfix();
588
+ }
589
+ postfix() {
590
+ let e = this.primary();
591
+ while (this.tokens.is("'s") || (this.tokens.is("its"))) {
592
+ this.tokens.next();
593
+ const property = this.tokens.next();
594
+ if (property.text == "length") {
595
+ if (e.k == "var")
596
+ e = { k: "call", fn: "length", args: [{ k: "str", v: e.name }] };
597
+ else if (e.k == "array")
598
+ e = { k: "call", fn: "length", args: [e] };
599
+ else if (e.k == "call" && e.fn == "__history")
600
+ e = { k: "var", name: "turns" };
601
+ else
602
+ throw new Unconvertible("the length of something other than a variable or an array");
603
+ }
604
+ else if (property.text == "ordinal" && (e.k == "var" || e.k == "array")) {
605
+ // $list's 1st
606
+ e = { k: "call", fn: "lookup", args: [e, { k: "num", v: property.value - 1 }] };
607
+ }
608
+ else if (e.k == "var" && (property.type == "word" || property.type == "str") && /^[A-Za-z_]\w*$/.test(String(property.value ?? property.text))) {
609
+ // A datamap's value is its own attribute: $player's hp is player_hp
610
+ e = { k: "var", name: `${e.name}_${property.value ?? property.text}` };
611
+ }
612
+ else {
613
+ throw new Unconvertible(`properties of variables ('s ${property.text})`);
614
+ }
615
+ }
616
+ return e;
617
+ }
618
+ primary() {
619
+ const t = this.tokens.next();
620
+ switch (t.type) {
621
+ case "str": return { k: "str", v: t.value };
622
+ case "num": return { k: "num", v: t.value };
623
+ case "var": return { k: "var", name: this.h.attribute(t.value, false) };
624
+ case "temp": return { k: "var", name: this.h.attribute(t.value, true) };
625
+ case "hook": throw new Unconvertible("a hook name in an expression");
626
+ case "(": {
627
+ const e = this.expression();
628
+ this.tokens.expect(")");
629
+ return e;
630
+ }
631
+ case "macro": {
632
+ if (t.value == "history")
633
+ return { k: "call", fn: "__history", args: [] };
634
+ return this.h.macro(t.value, t.text, this.it);
635
+ }
636
+ case "word":
637
+ switch (t.text) {
638
+ case "true": return { k: "bool", v: true };
639
+ case "false": return { k: "bool", v: false };
640
+ case "it":
641
+ if (!this.it)
642
+ throw new Unconvertible("\"it\" outside (set:)");
643
+ return this.it;
644
+ case "visits":
645
+ case "visit":
646
+ return this.h.visits();
647
+ case "turns":
648
+ case "turn":
649
+ return { k: "var", name: "turns" };
650
+ case "time":
651
+ throw new Unconvertible("\"time\", which Squiffy has no equivalent for");
652
+ }
653
+ throw new Unconvertible(`the word "${t.text}" in an expression`);
654
+ default:
655
+ throw new Unconvertible(`an expression Squiffy can't read (at "${t.text}")`);
656
+ }
657
+ }
658
+ }
659
+ class Writer {
660
+ constructor(ctx) {
661
+ Object.defineProperty(this, "ctx", {
662
+ enumerable: true,
663
+ configurable: true,
664
+ writable: true,
665
+ value: ctx
666
+ });
667
+ Object.defineProperty(this, "expr", {
668
+ enumerable: true,
669
+ configurable: true,
670
+ writable: true,
671
+ value: void 0
672
+ });
673
+ // Named hooks in the passage, by Harlowe name, with the label each becomes
674
+ Object.defineProperty(this, "hooks", {
675
+ enumerable: true,
676
+ configurable: true,
677
+ writable: true,
678
+ value: new Map()
679
+ });
680
+ // Hook names referred to with ?name anywhere in the story
681
+ Object.defineProperty(this, "referenced", {
682
+ enumerable: true,
683
+ configurable: true,
684
+ writable: true,
685
+ value: void 0
686
+ });
687
+ // (click: ?name) and friends, by the hook they make clickable
688
+ Object.defineProperty(this, "clicks", {
689
+ enumerable: true,
690
+ configurable: true,
691
+ writable: true,
692
+ value: new Map()
693
+ });
694
+ // Open emphasis: Harlowe's markup toggles on and off
695
+ Object.defineProperty(this, "open", {
696
+ enumerable: true,
697
+ configurable: true,
698
+ writable: true,
699
+ value: new Set()
700
+ });
701
+ Object.defineProperty(this, "align", {
702
+ enumerable: true,
703
+ configurable: true,
704
+ writable: true,
705
+ value: null
706
+ });
707
+ // Whether the next text starts a line, for markup that only means something there
708
+ Object.defineProperty(this, "atLineStart", {
709
+ enumerable: true,
710
+ configurable: true,
711
+ writable: true,
712
+ value: true
713
+ });
714
+ Object.defineProperty(this, "storyletsShown", {
715
+ enumerable: true,
716
+ configurable: true,
717
+ writable: true,
718
+ value: false
719
+ });
720
+ this.expr = new HarloweExpressions(ctx);
721
+ this.referenced = referencedHooks(ctx);
722
+ }
723
+ collectHooks(nodes) {
724
+ for (const node of nodes) {
725
+ const hook = node.t == "hook" ? node.hook : node.t == "macro" ? node.hook : undefined;
726
+ if (node.t == "collapse")
727
+ this.collectHooks(node.nodes);
728
+ if (node.t == "macro" && clickMacros.has(node.name)) {
729
+ const target = /^\?([A-Za-z][\w-]*)$/.exec(splitArgs(node.args)[0] ?? "");
730
+ if (target && !this.clicks.has(target[1]))
731
+ this.clicks.set(target[1], node);
732
+ }
733
+ if (!hook)
734
+ continue;
735
+ if (hook.name && !this.hooks.has(hook.name)) {
736
+ this.hooks.set(hook.name, { hook, label: labelName(hook.name) });
737
+ }
738
+ this.collectHooks(hook.nodes);
739
+ }
740
+ }
741
+ passage(nodes) {
742
+ this.collectHooks(nodes);
743
+ const state = { leading: true, directives: [] };
744
+ let body = this.nodes(nodes, state);
745
+ body += this.closeAll();
746
+ return { directives: state.directives, body };
747
+ }
748
+ closeAll() {
749
+ let s = "";
750
+ for (const tag of [...this.open].reverse())
751
+ s += `</${tag}>`;
752
+ this.open.clear();
753
+ if (this.align) {
754
+ s += "\n\n</div>";
755
+ this.align = null;
756
+ }
757
+ return s;
758
+ }
759
+ nodes(nodes, state) {
760
+ let out = "";
761
+ for (let i = 0; i < nodes.length; i++) {
762
+ const node = nodes[i];
763
+ if (node.t == "macro" && (node.name == "if" || node.name == "unless")) {
764
+ // An if chain: (if:)[...](else-if:)[...](else:)[...], with any whitespace between
765
+ const chain = [];
766
+ let conditionError = null;
767
+ const condition = (m) => {
768
+ try {
769
+ const e = this.expr.parse(m.args);
770
+ return m.name == "unless" ? { k: "not", e } : e;
771
+ }
772
+ catch (e) {
773
+ if (!(e instanceof Unconvertible))
774
+ throw e;
775
+ conditionError = conditionError ?? e.message;
776
+ return null;
777
+ }
778
+ };
779
+ chain.push({ cond: condition(node), hook: foldChangers(node), raw: node.raw });
780
+ let j = i + 1;
781
+ for (;;) {
782
+ let k = j;
783
+ while (k < nodes.length && nodes[k].t == "text" && nodes[k].s.trim() == "")
784
+ k++;
785
+ const next = nodes[k];
786
+ if (next?.t != "macro" || (next.name != "elseif" && next.name != "else"))
787
+ break;
788
+ chain.push({ cond: next.name == "else" ? null : condition(next), hook: foldChangers(next), raw: next.raw });
789
+ j = k + 1;
790
+ if (next.name == "else")
791
+ break;
792
+ }
793
+ i = j - 1;
794
+ state.leading = false;
795
+ if (conditionError) {
796
+ out += this.ctx.unconvertible(chain.map(c => c.raw).join(""), `This condition couldn't be converted: ${conditionError}. Its hooks have been left out.`);
797
+ continue;
798
+ }
799
+ out += chain.map((c, n) => {
800
+ const tag = n == 0 ? `{{#if ${print(c.cond)}}}` : c.cond ? `{{else if ${print(c.cond)}}}` : "{{else}}";
801
+ return tag + (c.hook ? this.hookContent(c.hook, state) : "");
802
+ }).join("") + "{{/if}}";
803
+ continue;
804
+ }
805
+ if (node.t == "macro" && (node.name == "elseif" || node.name == "else")) {
806
+ // (else:) after a hook that isn't an (if:), e.g. after a (link:)
807
+ state.leading = false;
808
+ out += this.ctx.unconvertible(node.raw, "(else:) only converts after (if:) or (unless:).");
809
+ if (node.hook)
810
+ out += this.hookContent(node.hook, state);
811
+ continue;
812
+ }
813
+ if (isPageClick(node)) {
814
+ // (click: ?page)[A] (click: ?page)[B]: each click anywhere shows the next one, so
815
+ // they become a chain of Continue links, each showing its hook and the next link
816
+ const chain = [node];
817
+ let j = i + 1;
818
+ for (;;) {
819
+ let k = j;
820
+ while (k < nodes.length && nodes[k].t == "text" && nodes[k].s.trim() == "")
821
+ k++;
822
+ if (k >= nodes.length || !isPageClick(nodes[k]))
823
+ break;
824
+ chain.push(nodes[k]);
825
+ j = k + 1;
826
+ }
827
+ i = j - 1;
828
+ state.leading = false;
829
+ this.ctx.story.note("harlowe-page-click", "(click: ?page)", "Clicking anywhere on the page has been converted to Continue links");
830
+ const links = chain.map(() => {
831
+ const label = this.ctx.newLabel("continue");
832
+ const passage = this.ctx.reservePassage("Continue");
833
+ return { label, passage, link: `{{#label "${label}"}}${passageLink("Continue", passage.name)}{{/label}}` };
834
+ });
835
+ chain.forEach((click, n) => {
836
+ const content = click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : "";
837
+ const next = links[n + 1] ? "\n\n" + links[n + 1].link : "";
838
+ links[n].passage.fill(`{{#replace "${links[n].label}"}}{{/replace}}${content}${next}`);
839
+ });
840
+ out += links[0].link;
841
+ this.atLineStart = false;
842
+ continue;
843
+ }
844
+ const written = this.node(node, state);
845
+ if (node.t != "text" && written)
846
+ this.atLineStart = false;
847
+ out += written;
848
+ }
849
+ return out;
850
+ }
851
+ node(node, state) {
852
+ switch (node.t) {
853
+ case "text":
854
+ if (node.s.trim())
855
+ state.leading = false;
856
+ return this.text(node.s);
857
+ case "raw":
858
+ return node.s;
859
+ case "comment":
860
+ return this.ctx.unconvertible(node.text, node.reason);
861
+ case "var":
862
+ state.leading = false;
863
+ return display({ k: "var", name: this.expr.attribute(node.name, node.temp) });
864
+ case "link":
865
+ state.leading = false;
866
+ return this.link(node);
867
+ case "collapse": {
868
+ const inner = this.nodes(node.nodes, state);
869
+ return collapseWhitespace(inner);
870
+ }
871
+ case "hook": {
872
+ const hook = node.hook;
873
+ if (hook.name && this.clicks.has(hook.name) && !hook.hidden) {
874
+ state.leading = false;
875
+ return this.clickable(hook, this.clicks.get(hook.name));
876
+ }
877
+ if (hook.hidden) {
878
+ // Shown later, by (show:)
879
+ if (!hook.name || !this.referenced.has(hook.name))
880
+ return "";
881
+ return `{{#label "${labelName(hook.name)}"}}{{/label}}`;
882
+ }
883
+ return this.hookContent(hook, state);
884
+ }
885
+ case "macro":
886
+ return this.macro(node, state);
887
+ }
888
+ }
889
+ // A hook's content, in a {{#label}} if it's named and something refers to it
890
+ hookContent(hook, state) {
891
+ const content = this.nodes(hook.nodes, { ...state, leading: false });
892
+ state.leading = state.leading && content.trim() == "";
893
+ if (hook.name && !hook.hidden && this.referenced.has(hook.name)) {
894
+ return `{{#label "${labelName(hook.name)}"}}${content}{{/label}}`;
895
+ }
896
+ return content;
897
+ }
898
+ // A named hook that (click:) or one of its friends makes into a link
899
+ clickable(hook, click) {
900
+ const content = this.nodes(hook.nodes, { leading: false, directives: [] });
901
+ const text = content.replace(/\s+/g, " ").trim();
902
+ const label = labelName(hook.name);
903
+ const args = splitArgs(click.args);
904
+ let action;
905
+ switch (click.name) {
906
+ case "clickgoto":
907
+ case "mouseovergoto": {
908
+ if (click.name != "clickgoto")
909
+ this.ctx.approximate(click.raw, "This has been converted to an ordinary link.");
910
+ return `{{#label "${label}"}}${this.linkTo(text, args[1] ?? "", click.raw, [])}{{/label}}`;
911
+ }
912
+ case "clickreplace":
913
+ action = `{{#replace "${label}"}}${click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : ""}{{/replace}}`;
914
+ break;
915
+ case "clickappend":
916
+ case "clickprepend": {
917
+ const extra = click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : "";
918
+ action = `{{#replace "${label}"}}${click.name == "clickappend" ? content + extra : extra + content}{{/replace}}`;
919
+ break;
920
+ }
921
+ default:
922
+ if (click.name != "click")
923
+ this.ctx.approximate(click.raw, "This has been converted to a link.");
924
+ action = click.hook ? this.nodes(click.hook.nodes, { leading: false, directives: [] }) : "";
925
+ // The text stops being a link once it's been clicked, as it does in Harlowe
926
+ action = `{{#replace "${label}"}}${content}{{/replace}}` + action;
927
+ }
928
+ const passage = this.ctx.addPassage(text, action);
929
+ return `{{#label "${label}"}}${passageLink(text, passage)}{{/label}}`;
930
+ }
931
+ link(node) {
932
+ const text = this.inlineText(node.text);
933
+ if (isUrl(node.target))
934
+ return urlLink(text, node.target);
935
+ const target = this.ctx.story.sectionFor(node.target);
936
+ if (target === undefined) {
937
+ this.ctx.approximate(node.raw, `There's no passage called "${node.target}".`);
938
+ return sectionLink(text, this.ctx.story.sectionForUnknown(node.target));
939
+ }
940
+ return sectionLink(text, target);
941
+ }
942
+ // Link text, with Harlowe's markup in it
943
+ inlineText(text) {
944
+ const nodes = new Parser(text).parse(0).nodes;
945
+ return this.nodes(nodes, { leading: false, directives: [] }).replace(/\n/g, " ");
946
+ }
947
+ // Prose, with Harlowe's markup
948
+ text(s) {
949
+ let out = "";
950
+ for (let i = 0; i < s.length;) {
951
+ const rest = s.substring(i);
952
+ if (this.atLineStart) {
953
+ this.atLineStart = false;
954
+ const lineEnd = rest.indexOf("\n");
955
+ const line = lineEnd == -1 ? rest : rest.substring(0, lineEnd);
956
+ const alignment = /^\s*(==+>|=+><=+|<==+>|<==+)\s*$/.exec(line);
957
+ if (alignment) {
958
+ out += this.alignment(alignment[1]);
959
+ i += line.length;
960
+ continue;
961
+ }
962
+ if (/^\s*\|==+|^\s*=+\|\s*$|^\s*==+\|/.test(line)) {
963
+ out += this.ctx.unconvertible(line, "Harlowe's columns can't be converted.");
964
+ i += line.length;
965
+ continue;
966
+ }
967
+ const heading = /^(#{1,6})\s*(?=\S)/.exec(line);
968
+ if (heading) {
969
+ out += heading[1] + " ";
970
+ i += heading[0].length;
971
+ continue;
972
+ }
973
+ const bullet = /^(\*+)\s+/.exec(line);
974
+ if (bullet) {
975
+ out += " ".repeat(bullet[1].length - 1) + "* ";
976
+ i += bullet[0].length;
977
+ continue;
978
+ }
979
+ const numbered = /^(0\.)+\s+/.exec(line);
980
+ if (numbered) {
981
+ out += "1. ";
982
+ i += numbered[0].length;
983
+ continue;
984
+ }
985
+ if (/^\s*-{3,}\s*$/.test(line)) {
986
+ out += "<hr>";
987
+ i += line.length;
988
+ continue;
989
+ }
990
+ }
991
+ const c = s[i];
992
+ if (c == "\n") {
993
+ out += "\n";
994
+ this.atLineStart = true;
995
+ i++;
996
+ continue;
997
+ }
998
+ const toggle = this.toggle(s, i);
999
+ if (toggle) {
1000
+ out += toggle.text;
1001
+ i += toggle.length;
1002
+ continue;
1003
+ }
1004
+ if (c == "<") {
1005
+ // HTML passes through as it is
1006
+ const tag = /^<\/?[A-Za-z][^<>]*>/.exec(rest);
1007
+ if (tag) {
1008
+ out += tag[0].replace(/\{\{/g, "&#123;{");
1009
+ i += tag[0].length;
1010
+ continue;
1011
+ }
1012
+ }
1013
+ // {{ would start a helper
1014
+ out += (c == "{" && s[i + 1] == "{") ? "&#123;" : (c == "}" && s[i + 1] == "}") ? "&#125;" : escapeText(c);
1015
+ i++;
1016
+ }
1017
+ return out;
1018
+ }
1019
+ // Emphasis markup, which turns on and off: ''bold'', //italic//, **strong**, *em*,
1020
+ // ~~strike~~, ^^superscript^^
1021
+ toggle(s, i) {
1022
+ const marks = [["''", "b"], ["//", "i"], ["**", "strong"], ["~~", "s"], ["^^", "sup"], ["*", "em"]];
1023
+ for (const [mark, tag] of marks) {
1024
+ if (!s.startsWith(mark, i))
1025
+ continue;
1026
+ if (mark == "//" && s[i - 1] == ":")
1027
+ return null;
1028
+ if (this.open.has(tag)) {
1029
+ this.open.delete(tag);
1030
+ return { text: `</${tag}>`, length: mark.length };
1031
+ }
1032
+ // Only if it's closed later
1033
+ const end = s.indexOf(mark, i + mark.length);
1034
+ if (end == -1 || (mark == "*" && s.substring(i, end).includes("\n")))
1035
+ return null;
1036
+ if (mark == "*" && s[i + 1] == " ")
1037
+ return null;
1038
+ this.open.add(tag);
1039
+ return { text: `<${tag}>`, length: mark.length };
1040
+ }
1041
+ return null;
1042
+ }
1043
+ alignment(marker) {
1044
+ let s = "";
1045
+ if (this.align) {
1046
+ s += "\n\n</div>";
1047
+ this.align = null;
1048
+ }
1049
+ // ==> right, =><= centre, <==> justified, <== left
1050
+ const align = marker.includes("><") ? "center"
1051
+ : marker.startsWith("<") && marker.endsWith(">") ? "justify"
1052
+ : marker.endsWith(">") ? "right" : "left";
1053
+ if (align != "left") {
1054
+ this.align = align;
1055
+ s += `<div style="text-align: ${align}">\n\n`;
1056
+ }
1057
+ return s;
1058
+ }
1059
+ // ---- Macros ----
1060
+ macro(m, state) {
1061
+ try {
1062
+ const result = this.macroOrThrow(m, state);
1063
+ // A hook after a command, rather than a changer, is shown as it is
1064
+ if (m.hook && !changers.has(m.name) && !hookMacros.has(m.name))
1065
+ return result + this.hookContent(m.hook, state);
1066
+ return result;
1067
+ }
1068
+ catch (e) {
1069
+ if (!(e instanceof Unconvertible))
1070
+ throw e;
1071
+ state.leading = false;
1072
+ const reason = `This couldn't be converted: ${e.message}.`;
1073
+ if (m.hook && !["link", "linkreveal", "linkrepeat", "linkrerun", "click", "replace", "append", "prepend", "show"].includes(m.name)) {
1074
+ // Keep the hook's text, since most changers only change how it looks
1075
+ return this.ctx.unconvertible(m.raw, reason) + this.hookContent(m.hook, state);
1076
+ }
1077
+ return this.ctx.unconvertible(m.raw + (m.hook?.raw ?? ""), reason);
1078
+ }
1079
+ }
1080
+ macroOrThrow(m, state) {
1081
+ const args = splitArgs(m.args);
1082
+ const name = m.name;
1083
+ if (m.changers.length) {
1084
+ return this.macroOrThrow({ ...m, changers: [], hook: foldChangers(m) }, state);
1085
+ }
1086
+ switch (name) {
1087
+ case "set":
1088
+ case "put":
1089
+ return this.set(m, args, state);
1090
+ case "print":
1091
+ state.leading = false;
1092
+ if (args.length != 1)
1093
+ throw new Unconvertible("(print:) with more than one value");
1094
+ return display(this.expr.parse(args[0]));
1095
+ case "either":
1096
+ case "random":
1097
+ state.leading = false;
1098
+ return display(this.expr.macro(name, m.raw));
1099
+ case "display": {
1100
+ state.leading = false;
1101
+ const target = this.expr.passageName(args[0] ?? "");
1102
+ if ("name" in target) {
1103
+ const section = this.ctx.story.sectionFor(target.name);
1104
+ if (section === undefined)
1105
+ this.ctx.approximate(m.raw, `There's no passage called "${target.name}".`);
1106
+ return `{{embed "${section ?? this.ctx.story.sectionForUnknown(target.name)}"}}`;
1107
+ }
1108
+ return `{{embed ${print(target.expr)}}}`;
1109
+ }
1110
+ case "goto":
1111
+ case "redirect":
1112
+ state.leading = false;
1113
+ return this.goto(args[0] ?? "", m.raw);
1114
+ case "linkgoto":
1115
+ case "clickgoto":
1116
+ case "mouseovergoto":
1117
+ case "linkrevealgoto": {
1118
+ state.leading = false;
1119
+ if (name == "clickgoto" || name == "mouseovergoto") {
1120
+ // Handled where the hook is
1121
+ const hookName = /^\s*\?([A-Za-z][\w-]*)\s*$/.exec(args[0] ?? "")?.[1];
1122
+ if (hookName && this.hooks.has(hookName))
1123
+ return "";
1124
+ throw new Unconvertible(`(${name}:) on text rather than a named hook in this passage`);
1125
+ }
1126
+ const textExpr = this.expr.parse(args[0] ?? "");
1127
+ if (textExpr.k != "str")
1128
+ throw new Unconvertible("a link whose text isn't fixed");
1129
+ const targetSource = args.length > 1 ? args[1] : args[0];
1130
+ const setters = name == "linkrevealgoto" && m.hook ? this.setters(m.hook) : [];
1131
+ if (setters === null) {
1132
+ // The hook does more than set variables: run it in a section of its own
1133
+ const target = this.expr.passageName(targetSource);
1134
+ const goto = "name" in target ? `{{goto "${this.sectionName(target.name, m.raw)}"}}` : `{{goto ${print(target.expr)}}}`;
1135
+ const content = this.convertedHook(m.hook);
1136
+ const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, { ...content, body: content.body + "\n" + goto });
1137
+ return sectionLink(this.inlineText(textExpr.v), section);
1138
+ }
1139
+ return this.linkTo(this.inlineText(textExpr.v), targetSource, m.raw, setters);
1140
+ }
1141
+ case "link":
1142
+ case "linkreplace":
1143
+ case "linkreveal":
1144
+ case "linkrepeat":
1145
+ case "linkrerun":
1146
+ state.leading = false;
1147
+ return this.linkMacro(m, args);
1148
+ case "linkshow": {
1149
+ state.leading = false;
1150
+ const textExpr = this.expr.parse(args[0] ?? "");
1151
+ if (textExpr.k != "str")
1152
+ throw new Unconvertible("a link whose text isn't fixed");
1153
+ const shows = args.slice(1).map(a => this.show(a, m.raw)).join("");
1154
+ const label = this.ctx.newLabel(textExpr.v);
1155
+ const passage = this.ctx.addPassage(textExpr.v, `{{#replace "${label}"}}${this.inlineText(textExpr.v)}{{/replace}}${shows}`);
1156
+ return `{{#label "${label}"}}${passageLink(this.inlineText(textExpr.v), passage)}{{/label}}`;
1157
+ }
1158
+ case "after": {
1159
+ state.leading = false;
1160
+ const delay = this.expr.parse(args[0] ?? "");
1161
+ if (delay.k != "num")
1162
+ throw new Unconvertible("(after:) with a delay that isn't fixed");
1163
+ if (!m.hook)
1164
+ return "";
1165
+ const goto = this.gotoOnly(m.hook);
1166
+ if (goto)
1167
+ return goto.replace(/\}\}$/, ` after=${delay.v}}}`);
1168
+ return `{{#animate "fadeIn" start=${delay.v}}}${this.hookContent(m.hook, state)}{{/animate}}`;
1169
+ }
1170
+ case "live": {
1171
+ state.leading = false;
1172
+ const delay = this.expr.parse(args[0] ?? "1s");
1173
+ if (delay.k != "num" || !m.hook)
1174
+ throw new Unconvertible("(live:)");
1175
+ const goto = this.gotoOnly(m.hook, true);
1176
+ if (goto)
1177
+ return goto.replace(/\}\}$/, ` after=${delay.v}}}`);
1178
+ throw new Unconvertible("(live:), which runs its hook again and again");
1179
+ }
1180
+ case "stop":
1181
+ return "";
1182
+ case "inputbox":
1183
+ case "forceinputbox":
1184
+ case "input":
1185
+ case "forceinput":
1186
+ state.leading = false;
1187
+ return this.input(args, m.raw);
1188
+ case "dropdown": {
1189
+ state.leading = false;
1190
+ const bound = this.bound(args[0] ?? "");
1191
+ if (!bound)
1192
+ throw new Unconvertible("(dropdown:) without bind");
1193
+ const options = args.slice(1).map(a => this.expr.parse(a));
1194
+ if (options.some(o => o.k != "str" && o.k != "num"))
1195
+ throw new Unconvertible("(dropdown:) with options that aren't fixed");
1196
+ const html = options.map(o => {
1197
+ const v = escapeAttribute(String(o.v));
1198
+ return `<option value="${v}">${v}</option>`;
1199
+ }).join("");
1200
+ return `<select data-attribute="${bound}">${html}</select>`;
1201
+ }
1202
+ case "checkbox": {
1203
+ state.leading = false;
1204
+ const bound = this.bound(args[0] ?? "");
1205
+ const label = args[1] ? this.expr.parse(args[1]) : null;
1206
+ if (!bound || (label && label.k != "str"))
1207
+ throw new Unconvertible("(checkbox:)");
1208
+ this.ctx.approximate(m.raw, "Check how this checkbox works in Squiffy.");
1209
+ return `<label><input type="checkbox" data-attribute="${bound}"> ${label ? escapeText(label.v) : ""}</label>`;
1210
+ }
1211
+ case "cyclinglink":
1212
+ case "seqlink":
1213
+ case "sequencelink": {
1214
+ state.leading = false;
1215
+ let bound = null;
1216
+ let rest = args;
1217
+ if (/^2?bind\s/.test(args[0] ?? "")) {
1218
+ bound = this.bound(args[0]);
1219
+ rest = args.slice(1);
1220
+ }
1221
+ const items = rest.map(a => this.expr.parse(a));
1222
+ const helper = name == "cyclinglink" ? "rotate" : "sequence";
1223
+ const set = bound ? ` set="${bound}"` : "";
1224
+ return `{{${helper} ${print({ k: "array", items })}${set}}}`;
1225
+ }
1226
+ case "textstyle":
1227
+ case "textcolour":
1228
+ case "textcolor":
1229
+ case "colour":
1230
+ case "color":
1231
+ case "background":
1232
+ case "bg":
1233
+ case "font":
1234
+ case "textsize":
1235
+ case "size":
1236
+ case "align":
1237
+ case "css":
1238
+ case "opacity":
1239
+ state.leading = false;
1240
+ return this.style(m, args, state);
1241
+ case "linkstyle":
1242
+ case "box":
1243
+ case "border":
1244
+ case "b4r":
1245
+ case "bordercolour":
1246
+ case "bordercolor":
1247
+ case "b4rcolour":
1248
+ case "b4rcolor":
1249
+ case "bordersize":
1250
+ case "b4rsize":
1251
+ case "cornerradius":
1252
+ case "textindent":
1253
+ case "float":
1254
+ case "textrotate":
1255
+ case "textrotatez":
1256
+ case "textrotatey":
1257
+ case "textrotatex":
1258
+ case "hoverstyle":
1259
+ case "charstyle":
1260
+ case "linestyle":
1261
+ case "button":
1262
+ case "hookname":
1263
+ case "outline":
1264
+ case "textshadow":
1265
+ 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");
1266
+ return m.hook ? this.hookContent(m.hook, state) : "";
1267
+ case "enchant":
1268
+ case "enchantin": {
1269
+ // Only how links or text look
1270
+ const visual = /\((t8n|transition|text-colou?r|colou?r|text-style|link-style|hover-style|font|background|bg|opacity|css|box|border)[\w-]*:/i;
1271
+ const changer = splitArgs(m.args)[1] ?? "";
1272
+ if (visual.test(changer) && !/\((replace|append|prepend|show|hide|goto|set):/i.test(changer)) {
1273
+ 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");
1274
+ return "";
1275
+ }
1276
+ throw new Unconvertible("(enchant:)");
1277
+ }
1278
+ case "transition":
1279
+ case "t8n":
1280
+ case "transitiontime":
1281
+ case "t8ntime":
1282
+ case "transitiondelay":
1283
+ case "t8ndelay":
1284
+ case "transitionskip":
1285
+ case "t8nskip":
1286
+ case "transitiondepart":
1287
+ case "t8ndepart":
1288
+ case "transitionarrive":
1289
+ case "t8narrive":
1290
+ // Only how the text appears, which Squiffy does its own way
1291
+ return m.hook ? this.hookContent(m.hook, state) : "";
1292
+ case "nobr":
1293
+ case "collapse":
1294
+ return m.hook ? collapseWhitespace(this.hookContent(m.hook, state)) : "";
1295
+ case "verbatim":
1296
+ case "v6m":
1297
+ state.leading = false;
1298
+ return m.hook ? escapeText(escapeHtml(m.hook.raw.slice(1, -1))) : "";
1299
+ case "hidden":
1300
+ if (m.hook?.name) {
1301
+ m.hook.hidden = true;
1302
+ return this.node({ t: "hook", hook: m.hook }, state);
1303
+ }
1304
+ return "";
1305
+ case "show":
1306
+ state.leading = false;
1307
+ return args.map(a => this.show(a, m.raw)).join("");
1308
+ case "hide":
1309
+ state.leading = false;
1310
+ return args.map(a => {
1311
+ const label = this.labelFor(a);
1312
+ return `{{#replace "${label}"}}{{/replace}}`;
1313
+ }).join("");
1314
+ case "replace":
1315
+ case "append":
1316
+ case "prepend": {
1317
+ state.leading = false;
1318
+ if (!m.hook)
1319
+ return "";
1320
+ const content = this.hookContent(m.hook, state);
1321
+ return args.map(a => {
1322
+ const target = a.trim();
1323
+ if (!target.startsWith("?"))
1324
+ throw new Unconvertible(`(${name}:) on text rather than a named hook`);
1325
+ const named = this.hooks.get(target.substring(1));
1326
+ // A hook in another passage, e.g. a header: its label has the same name
1327
+ if (!named && name == "replace")
1328
+ return `{{#replace "${labelName(target.substring(1))}"}}${content}{{/replace}}`;
1329
+ if (!named)
1330
+ throw new Unconvertible(`(${name}:) on a hook that isn't in this passage`);
1331
+ if (name == "replace")
1332
+ return `{{#replace "${named.label}"}}${content}{{/replace}}`;
1333
+ 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.`);
1334
+ const original = this.nodes(named.hook.nodes, { leading: false, directives: [] });
1335
+ return `{{#replace "${named.label}"}}${name == "append" ? original + content : content + original}{{/replace}}`;
1336
+ }).join("");
1337
+ }
1338
+ case "click":
1339
+ case "clickreplace":
1340
+ case "clickappend":
1341
+ case "clickprepend":
1342
+ case "mouseover":
1343
+ case "mouseout": {
1344
+ const target = (args[0] ?? "").trim();
1345
+ const hookName = /^\?([A-Za-z][\w-]*)$/.exec(target)?.[1];
1346
+ // Handled where the hook is
1347
+ if (hookName && this.hooks.has(hookName))
1348
+ return "";
1349
+ if ((hookName == "page" || hookName == "passage") && m.hook) {
1350
+ state.leading = false;
1351
+ this.ctx.story.note("harlowe-page-click", "(click: ?page)", "Clicking anywhere on the page has been converted to Continue links");
1352
+ const content = this.nodes(m.hook.nodes, { leading: false, directives: [] });
1353
+ const label = this.ctx.newLabel("continue");
1354
+ const passage = this.ctx.addPassage("Continue", `{{#replace "${label}"}}{{/replace}}${content}`);
1355
+ return `{{#label "${label}"}}${passageLink("Continue", passage)}{{/label}}`;
1356
+ }
1357
+ throw new Unconvertible(`(${name}:) on ${hookName ? "a hook that isn't in this passage" : "text rather than a named hook"}`);
1358
+ }
1359
+ case "linkstorylet": {
1360
+ state.leading = false;
1361
+ // Every storylet whose condition is true, the first time (link-storylet:) is in a passage
1362
+ if (this.storyletsShown)
1363
+ return "";
1364
+ this.storyletsShown = true;
1365
+ const storylets = harloweStorylets(this.ctx);
1366
+ if (!storylets.length)
1367
+ throw new Unconvertible("(link-storylet:) in a story without storylets");
1368
+ 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");
1369
+ // All on one line, so the ones that aren't shown don't leave blank lines
1370
+ return storylets.map(st => {
1371
+ const link = sectionLink(escapeText(st.section), st.section) + "<br>";
1372
+ return st.condition ? `{{#if ${print(st.condition)}}}${link}{{/if}}` : link;
1373
+ }).join("");
1374
+ }
1375
+ case "storylet":
1376
+ case "urgency":
1377
+ case "exclusivity":
1378
+ // Converted where the storylets are listed
1379
+ return "";
1380
+ case "mockvisits":
1381
+ case "mockturns":
1382
+ case "debug":
1383
+ case "seed":
1384
+ return "";
1385
+ case "if":
1386
+ case "unless":
1387
+ case "elseif":
1388
+ case "else":
1389
+ // Handled in nodes()
1390
+ return "";
1391
+ default:
1392
+ throw new Unconvertible(`the (${m.raw.substring(1, m.raw.indexOf(":"))}:) macro, which Squiffy has no equivalent for`);
1393
+ }
1394
+ }
1395
+ sectionName(passage, raw) {
1396
+ const section = this.ctx.story.sectionFor(passage);
1397
+ if (section === undefined) {
1398
+ this.ctx.approximate(raw, `There's no passage called "${passage}".`);
1399
+ return this.ctx.story.sectionForUnknown(passage);
1400
+ }
1401
+ return section;
1402
+ }
1403
+ goto(arg, raw) {
1404
+ const target = this.expr.passageName(arg);
1405
+ if ("name" in target)
1406
+ return `{{goto "${this.sectionName(target.name, raw)}"}}`;
1407
+ return `{{goto ${print(target.expr)}}}`;
1408
+ }
1409
+ // A link to a passage given as a Harlowe value, with setters
1410
+ linkTo(text, targetSource, raw, setters) {
1411
+ const target = this.expr.passageName(targetSource);
1412
+ if ("name" in target)
1413
+ return sectionLink(text, this.sectionName(target.name, raw), setters);
1414
+ return dynamicSectionLink(text, target.expr, setters);
1415
+ }
1416
+ // (link:) and friends, with a hook that runs when it's clicked
1417
+ linkMacro(m, args) {
1418
+ const textExpr = this.expr.parse(args[0] ?? "");
1419
+ if (textExpr.k != "str")
1420
+ throw new Unconvertible("a link whose text isn't fixed");
1421
+ const text = this.inlineText(textExpr.v);
1422
+ if (!m.hook)
1423
+ throw new Unconvertible("a link with no hook");
1424
+ // A link that only sets variables and goes to another passage is an ordinary link
1425
+ const navigation = this.navigation(m.hook);
1426
+ if (navigation) {
1427
+ if (navigation.setters)
1428
+ return this.linkTo(text, navigation.target, m.raw, navigation.setters);
1429
+ // It does more than set variables, so do that in a section of its own
1430
+ const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, navigation.content());
1431
+ return sectionLink(text, section);
1432
+ }
1433
+ const content = this.nodes(m.hook.nodes, { leading: false, directives: [] });
1434
+ if (m.name == "linkrepeat" || m.name == "linkrerun") {
1435
+ this.ctx.approximate(m.raw, "In Squiffy, this link can only be clicked once.");
1436
+ const passage = this.ctx.addPassage(textExpr.v, content);
1437
+ return passageLink(text, passage);
1438
+ }
1439
+ const label = this.ctx.newLabel(textExpr.v);
1440
+ const replacement = m.name == "linkreveal" ? text + content : content;
1441
+ const passage = this.ctx.addPassage(textExpr.v, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1442
+ return `{{#label "${label}"}}${passageLink(text, passage)}{{/label}}`;
1443
+ }
1444
+ // If a hook only sets variables and then goes to a passage, the setters and the passage.
1445
+ // If it does other things before going to a passage, content is the Squiffy text for a
1446
+ // section that does those things and then goes there.
1447
+ navigation(hook) {
1448
+ const significant = hook.nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1449
+ const last = significant[significant.length - 1];
1450
+ if (last?.t != "macro" || (last.name != "goto" && last.name != "redirect"))
1451
+ return null;
1452
+ // Only if the (goto:) isn't inside anything
1453
+ const target = splitArgs(last.args)[0] ?? "";
1454
+ const before = significant.slice(0, -1);
1455
+ const setters = this.setters({ nodes: before, raw: "" });
1456
+ return { target, setters, content: () => this.convertedHook(hook) };
1457
+ }
1458
+ // The setters for a hook that only has (set:) and (put:) in it, or null
1459
+ setters(hook) {
1460
+ const setters = [];
1461
+ for (const n of hook.nodes) {
1462
+ if (n.t == "text" && n.s.trim() == "")
1463
+ continue;
1464
+ if (n.t != "macro" || (n.name != "set" && n.name != "put") || n.hook)
1465
+ return null;
1466
+ for (const assignment of splitArgs(n.args)) {
1467
+ try {
1468
+ for (const a of this.assignments(assignment, n.name == "put")) {
1469
+ if (a.kind == "append" || a.kind == "remove")
1470
+ return null;
1471
+ setters.push(a.kind == "inc" ? setter(a.name, "+=", a.value, true)
1472
+ : a.kind == "dec" ? setter(a.name, "-=", a.value, true)
1473
+ : setter(a.name, "=", a.value, true));
1474
+ }
1475
+ }
1476
+ catch (e) {
1477
+ if (e instanceof Unconvertible)
1478
+ return null;
1479
+ throw e;
1480
+ }
1481
+ }
1482
+ }
1483
+ return setters;
1484
+ }
1485
+ // A hook as the text of a section of its own, where (set:)s at the start become @set
1486
+ convertedHook(hook) {
1487
+ const state = { leading: true, directives: [] };
1488
+ const body = this.nodes(hook.nodes, state);
1489
+ return { directives: state.directives, body };
1490
+ }
1491
+ // If a hook only has a (goto:) (and (stop:)), the {{goto}}
1492
+ gotoOnly(hook, allowStop = false) {
1493
+ const significant = hook.nodes.filter(n => !(n.t == "text" && n.s.trim() == "") && !(allowStop && n.t == "macro" && n.name == "stop"));
1494
+ if (significant.length != 1)
1495
+ return null;
1496
+ const n = significant[0];
1497
+ if (n.t != "macro" || (n.name != "goto" && n.name != "redirect"))
1498
+ return null;
1499
+ return this.goto(splitArgs(n.args)[0] ?? "", n.raw);
1500
+ }
1501
+ labelFor(arg) {
1502
+ const target = arg.trim();
1503
+ if (!target.startsWith("?"))
1504
+ throw new Unconvertible("a hook name that isn't ?name");
1505
+ return labelName(target.substring(1));
1506
+ }
1507
+ show(arg, raw) {
1508
+ const label = this.labelFor(arg);
1509
+ const named = this.hooks.get(arg.trim().substring(1));
1510
+ if (!named)
1511
+ throw new Unconvertible(`(show:) of a hook that isn't in this passage (${raw})`);
1512
+ const content = this.nodes(named.hook.nodes, { leading: false, directives: [] });
1513
+ return `{{#replace "${label}"}}${content}{{/replace}}`;
1514
+ }
1515
+ // The attribute for "bind $x", or null
1516
+ bound(arg) {
1517
+ const match = /^2?bind\s+([$_])([A-Za-z]\w*)$/.exec(arg.trim());
1518
+ if (!match)
1519
+ return null;
1520
+ return this.expr.attribute(match[2], match[1] == "_");
1521
+ }
1522
+ input(args, raw) {
1523
+ const bound = this.bound(args[0] ?? "");
1524
+ if (!bound)
1525
+ throw new Unconvertible("an input box without bind");
1526
+ let defaultText = null;
1527
+ let rows = 1;
1528
+ for (const a of args.slice(1)) {
1529
+ const e = this.expr.parse(a);
1530
+ if (e.k == "num")
1531
+ rows = e.v;
1532
+ else if (e.k == "str" && /^[=<>]+$/.test(e.v))
1533
+ continue;
1534
+ else if (e.k == "str")
1535
+ defaultText = e.v;
1536
+ }
1537
+ if (raw.toLowerCase().includes("force"))
1538
+ this.ctx.approximate(raw, "This has been converted to an ordinary input box.");
1539
+ const value = defaultText == null ? "" : ` value="${escapeAttribute(defaultText)}"`;
1540
+ const set = defaultText == null ? "" : `{{set "${bound}" ${print({ k: "str", v: defaultText })}}}`;
1541
+ if (rows > 1)
1542
+ return `${set}<textarea data-attribute="${bound}" rows="${rows}">${escapeText(escapeHtml(defaultText ?? ""))}</textarea>`;
1543
+ return `${set}<input type="text" data-attribute="${bound}"${value}>`;
1544
+ }
1545
+ style(m, args, state) {
1546
+ if (!m.hook)
1547
+ throw new Unconvertible(`(${m.name}:) without a hook (as a value, or saved in a variable)`);
1548
+ const content = this.hookContent(m.hook, state);
1549
+ const colourMacros = ["textcolour", "textcolor", "colour", "color", "background", "bg"];
1550
+ const value = colourMacros.includes(m.name) ? { k: "str", v: this.colour(args[0] ?? "") } : this.expr.parse(args[0] ?? "");
1551
+ const str = (e) => {
1552
+ if (e.k == "str")
1553
+ return e.v;
1554
+ if (e.k == "num")
1555
+ return String(e.v);
1556
+ throw new Unconvertible(`(${m.name}:) with a value that isn't fixed`);
1557
+ };
1558
+ switch (m.name) {
1559
+ case "textstyle": {
1560
+ let open = "";
1561
+ let close = "";
1562
+ for (const a of args) {
1563
+ const style = str(this.expr.parse(a)).toLowerCase().replace(/[\s-]/g, "");
1564
+ const tag = { bold: "b", italic: "i", underline: "u", strike: "s", superscript: "sup", subscript: "sub" }[style];
1565
+ if (tag) {
1566
+ open += `<${tag}>`;
1567
+ close = `</${tag}>` + close;
1568
+ }
1569
+ else if (style != "none") {
1570
+ this.ctx.story.note("harlowe-text-style", `"${style}"`, "Squiffy has no equivalent for these Harlowe text styles, so they've been left out");
1571
+ }
1572
+ }
1573
+ return open + content + close;
1574
+ }
1575
+ case "align": {
1576
+ const marker = str(value);
1577
+ const align = marker.includes("<") && marker.includes(">") ? (marker.startsWith("<") ? "justify" : "center") : marker.includes(">") ? "right" : "left";
1578
+ return `<div style="text-align: ${align}">${content}</div>`;
1579
+ }
1580
+ case "css":
1581
+ return `<span style="${escapeAttribute(str(value))}">${content}</span>`;
1582
+ default: {
1583
+ const css = {
1584
+ textcolour: "color", textcolor: "color", colour: "color", color: "color",
1585
+ background: "background", bg: "background", font: "font-family", textsize: "font-size", size: "font-size",
1586
+ opacity: "opacity",
1587
+ }[m.name];
1588
+ let v;
1589
+ if (value.k == "num" && (m.name == "textsize" || m.name == "size"))
1590
+ v = `${value.v * 1.5}em`;
1591
+ else if (value.k == "str" || value.k == "num")
1592
+ v = String(value.v);
1593
+ else
1594
+ throw new Unconvertible(`(${m.name}:) with a colour Squiffy can't read`);
1595
+ return `<span style="${css}: ${escapeAttribute(v)}">${content}</span>`;
1596
+ }
1597
+ }
1598
+ }
1599
+ // A Harlowe colour: a colour name or #rrggbb without quotes, a string, or (rgb:) and friends
1600
+ colour(arg) {
1601
+ const a = arg.trim();
1602
+ if (/^#[0-9a-f]{3,8}$/i.test(a) || /^[a-z]+$/i.test(a))
1603
+ return a.toLowerCase();
1604
+ const fn = /^\((rgba?|hsla?):([\s\S]*)\)$/i.exec(a);
1605
+ if (fn) {
1606
+ const values = splitArgs(fn[2]).map(v => this.expr.parse(v));
1607
+ if (values.some(v => v.k != "num"))
1608
+ throw new Unconvertible(`(${fn[1]}:) with values that aren't fixed`);
1609
+ const numbers = values.map(v => v.v);
1610
+ if (fn[1].toLowerCase().startsWith("hsl")) {
1611
+ const [h, sat, l, alpha] = numbers;
1612
+ return `hsl(${h} ${sat * 100}% ${l * 100}%${alpha === undefined ? "" : ` / ${alpha}`})`;
1613
+ }
1614
+ return `rgb(${numbers.slice(0, 3).join(" ")}${numbers[3] === undefined ? "" : ` / ${numbers[3]}`})`;
1615
+ }
1616
+ const e = this.expr.parse(a);
1617
+ if (e.k == "str")
1618
+ return e.v;
1619
+ throw new Unconvertible("a colour that isn't fixed");
1620
+ }
1621
+ // ---- (set:) ----
1622
+ // An assignment, with a datamap flattened into one for each of its values
1623
+ assignments(source, put) {
1624
+ const datamap = /^\s*([$_])([A-Za-z]\w*)\s+to\s+\((?:dm|datamap):([\s\S]*)\)\s*$/i.exec(source);
1625
+ if (datamap && !put) {
1626
+ const name = this.expr.attribute(datamap[2], datamap[1] == "_");
1627
+ const values = splitArgs(datamap[3]);
1628
+ if (values.length % 2)
1629
+ throw new Unconvertible("a datamap with a name that has no value");
1630
+ const result = [];
1631
+ for (let n = 0; n < values.length; n += 2) {
1632
+ const key = this.expr.parse(values[n]);
1633
+ if (key.k != "str" || !/^[A-Za-z_]\w*$/.test(key.v))
1634
+ throw new Unconvertible("a datamap with names that aren't words");
1635
+ result.push({ kind: "set", name: `${name}_${key.v}`, value: this.expr.parse(values[n + 1]) });
1636
+ }
1637
+ return result;
1638
+ }
1639
+ return [this.assignment(source, put)];
1640
+ }
1641
+ assignment(source, put) {
1642
+ let targetSource;
1643
+ let valueSource;
1644
+ const keyword = put ? /\binto\b/ : /\bto\b/;
1645
+ let tokens = splitOutsideStrings(source, keyword);
1646
+ // Not Harlowe, but some stories have (set: $x += 1), which some versions of Harlowe allowed
1647
+ const shorthand = /^\s*([$_][A-Za-z]\w*)\s*([+\-*/]?=)\s*([\s\S]*)$/.exec(source);
1648
+ if (!tokens && !put && shorthand) {
1649
+ const op = shorthand[2];
1650
+ tokens = [shorthand[1], op == "=" ? shorthand[3] : `${shorthand[1]} ${op[0]} (${shorthand[3]})`];
1651
+ }
1652
+ if (!tokens)
1653
+ throw new Unconvertible(put ? "(put:) without \"into\"" : "(set:) without \"to\"");
1654
+ if (put)
1655
+ [valueSource, targetSource] = tokens;
1656
+ else
1657
+ [targetSource, valueSource] = tokens;
1658
+ const target = /^([$_])([A-Za-z]\w*)((?:'s\s+(?:[A-Za-z_]\w*|"[A-Za-z_]\w*"))*)$/.exec(targetSource.trim());
1659
+ if (!target)
1660
+ throw new Unconvertible("setting something other than a variable");
1661
+ // $player's hp is player_hp
1662
+ const properties = [...target[3].matchAll(/'s\s+"?([A-Za-z_]\w*)"?/g)].map(m => m[1]);
1663
+ const name = [this.expr.attribute(target[2], target[1] == "_"), ...properties].join("_");
1664
+ const variable = { k: "var", name };
1665
+ const value = this.expr.parse(valueSource, variable);
1666
+ // $x to it + 1, and $x to $x - 2
1667
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
1668
+ if (value.r.k == "array") {
1669
+ if (value.r.items.length != 1)
1670
+ throw new Unconvertible("adding or removing more than one item at once");
1671
+ return { kind: value.op == "+" ? "append" : "remove", name, value: value.r.items[0] };
1672
+ }
1673
+ if (value.r.k == "num" || value.op == "-")
1674
+ return { kind: value.op == "+" ? "inc" : "dec", name, value: value.r };
1675
+ }
1676
+ return { kind: "set", name, value };
1677
+ }
1678
+ set(m, args, state) {
1679
+ let out = "";
1680
+ for (const a of args.flatMap(source => this.assignments(source, m.name == "put"))) {
1681
+ const amount = a.value.k == "num" && Number.isInteger(a.value.v) && a.value.v >= 0 ? a.value.v : null;
1682
+ if (state.leading) {
1683
+ switch (a.kind) {
1684
+ case "set":
1685
+ state.directives.push(`@set ${setter(a.name, "=", a.value, false)}`);
1686
+ continue;
1687
+ case "inc":
1688
+ case "dec":
1689
+ if (amount !== null) {
1690
+ state.directives.push(`@${a.kind} ${a.name}${amount == 1 ? "" : " " + amount}`);
1691
+ }
1692
+ else {
1693
+ state.directives.push(`@set ${setter(a.name, a.kind == "inc" ? "+=" : "-=", a.value, false)}`);
1694
+ }
1695
+ continue;
1696
+ }
1697
+ }
1698
+ state.leading = false;
1699
+ const name = print({ k: "str", v: a.name });
1700
+ switch (a.kind) {
1701
+ case "set":
1702
+ out += `{{set ${name} ${print(a.value)}}}`;
1703
+ break;
1704
+ case "inc":
1705
+ case "dec":
1706
+ out += amount === 1 ? `{{${a.kind} ${name}}}` : `{{${a.kind} ${name} ${print(a.value)}}}`;
1707
+ break;
1708
+ case "append":
1709
+ case "remove":
1710
+ out += `{{${a.kind} ${name} ${print(a.value)}}}`;
1711
+ break;
1712
+ }
1713
+ }
1714
+ return out;
1715
+ }
1716
+ }
1717
+ // (a:)+(b:)[hook] is (a:) applied to (b:)[hook]: the hook, with the changers after the first
1718
+ // applied to it
1719
+ function foldChangers(m) {
1720
+ if (!m.hook || !m.changers.length)
1721
+ return m.hook;
1722
+ let hook = m.hook;
1723
+ for (let n = m.changers.length - 1; n >= 0; n--) {
1724
+ const changer = { ...m.changers[n], hook, changers: [] };
1725
+ hook = { nodes: [changer], raw: changer.raw + hook.raw };
1726
+ }
1727
+ return hook;
1728
+ }
1729
+ // The story's storylets: passages with (storylet: when ...), with their conditions
1730
+ function harloweStorylets(ctx) {
1731
+ return ctx.story.cached("harlowe-storylets", () => {
1732
+ const result = [];
1733
+ for (const p of ctx.story.twine.passages) {
1734
+ const match = /\(storylet:\s*when\b/i.exec(p.text);
1735
+ if (!match)
1736
+ continue;
1737
+ const end = skipBalanced(p.text, match.index, "(", ")");
1738
+ const section = ctx.story.sectionFor(p.name);
1739
+ if (end == -1 || section === undefined)
1740
+ continue;
1741
+ const source = p.text.substring(match.index + match[0].length, end - 1);
1742
+ // "visits" in a storylet's condition means visits to the storylet
1743
+ const expressions = new HarloweExpressions({ ...ctx, section, passage: p });
1744
+ let condition;
1745
+ try {
1746
+ condition = expressions.parse(source);
1747
+ }
1748
+ catch (e) {
1749
+ if (!(e instanceof Unconvertible))
1750
+ throw e;
1751
+ 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.` });
1752
+ condition = null;
1753
+ }
1754
+ result.push({ section, condition });
1755
+ }
1756
+ return result;
1757
+ });
1758
+ }
1759
+ // (click: ?page) or (click: ?passage), with a hook
1760
+ function isPageClick(node) {
1761
+ return node?.t == "macro" && node.name == "click" && !!node.hook && /^\s*\?(page|passage)\s*$/i.test(node.args);
1762
+ }
1763
+ // Macros whose hooks are converted with them, as well as the changers
1764
+ const hookMacros = new Set(["linkreplace", "linkrepeat", "linkrerun", "linkreveal", "linkrevealgoto", "click", "clickreplace", "clickappend", "clickprepend"]);
1765
+ const clickMacros = new Set(["click", "clickreplace", "clickappend", "clickprepend", "clickgoto", "mouseover", "mouseout", "mouseovergoto"]);
1766
+ // The label a named hook becomes, the same in every passage, so (replace:) can change a hook in a
1767
+ // header. The runtime replaces the latest label with the name.
1768
+ function labelName(hook) {
1769
+ return hook.toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
1770
+ }
1771
+ // Every hook name referred to with ?name in the story
1772
+ function referencedHooks(ctx) {
1773
+ return ctx.story.cached("harlowe-hooks", () => {
1774
+ const result = new Set();
1775
+ for (const p of ctx.story.twine.passages) {
1776
+ for (const m of p.text.matchAll(/\?([A-Za-z][\w-]*)/g))
1777
+ result.add(m[1]);
1778
+ }
1779
+ return result;
1780
+ });
1781
+ }
1782
+ // Splits "a to b" on the first keyword outside quotes and brackets
1783
+ function splitOutsideStrings(s, keyword) {
1784
+ let depth = 0;
1785
+ for (let i = 0; i < s.length; i++) {
1786
+ const c = s[i];
1787
+ if (c == "\"" || c == "'") {
1788
+ const end = skipString(s, i);
1789
+ if (end == -1)
1790
+ return null;
1791
+ i = end - 1;
1792
+ continue;
1793
+ }
1794
+ if (c == "(")
1795
+ depth++;
1796
+ else if (c == ")")
1797
+ depth--;
1798
+ else if (depth == 0 && /\s/.test(c)) {
1799
+ const match = keyword.exec(s.substring(i + 1));
1800
+ if (match && match.index == 0 && /\s/.test(s[i + 1 + match[0].length] ?? "")) {
1801
+ return [s.substring(0, i), s.substring(i + 1 + match[0].length)];
1802
+ }
1803
+ }
1804
+ }
1805
+ return null;
1806
+ }
1807
+ function escapeAttribute(s) {
1808
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/\[/g, "&#91;").replace(/\]/g, "&#93;").replace(/\{\{/g, "&#123;{");
1809
+ }
1810
+ // Harlowe's { } markup and (collapse:): runs of whitespace become one space
1811
+ function collapseWhitespace(s) {
1812
+ return s.replace(/\s+/g, " ").trim();
1813
+ }
1814
+ // (click: "text") makes text that's in the passage clickable. Its first appearance becomes a
1815
+ // named hook, so it converts as (click: ?hook) does.
1816
+ function clickableText(source, ctx) {
1817
+ let result = source;
1818
+ let n = 0;
1819
+ for (;;) {
1820
+ const match = /\((click|click-replace|click-append|click-prepend|click-goto|mouseover|mouseover-goto|mouseout)\s*:\s*("[^"\n]+"|'[^'\n]+')/i.exec(result);
1821
+ if (!match)
1822
+ return result;
1823
+ const text = match[2].slice(1, -1);
1824
+ const hook = `click-text-${++n}`;
1825
+ const macroEnd = skipBalanced(result, match.index, "(", ")");
1826
+ const withHookName = result.substring(0, match.index) + `(${match[1]}: ?${hook}` + result.substring(match.index + match[0].length);
1827
+ // The text, outside any macro
1828
+ const macros = [];
1829
+ for (const m of withHookName.matchAll(/\([A-Za-z][\w-]*:/g)) {
1830
+ const end = skipBalanced(withHookName, m.index, "(", ")");
1831
+ if (end != -1)
1832
+ macros.push([m.index, end]);
1833
+ }
1834
+ let at = -1;
1835
+ for (let from = 0;; from = at + 1) {
1836
+ at = withHookName.indexOf(text, from);
1837
+ if (at == -1 || !macros.some(([start, end]) => at >= start && at < end))
1838
+ break;
1839
+ }
1840
+ if (at == -1 || macroEnd == -1) {
1841
+ ctx.approximate(match[0], "The text this makes clickable isn't in the passage.");
1842
+ // Leave it for the macro converter to report
1843
+ return result.substring(0, match.index) + `(${match[1]}-text: ` + result.substring(match.index + match[0].length - match[2].length);
1844
+ }
1845
+ if (withHookName.indexOf(text, at + text.length) != -1) {
1846
+ ctx.approximate(match[0], "Only the first place this text appears has been made clickable.");
1847
+ }
1848
+ result = withHookName.substring(0, at) + `|${hook}>[${text}]` + withHookName.substring(at + text.length);
1849
+ }
1850
+ }
1851
+ export function convertHarlowePassage(text, ctx) {
1852
+ // A backslash at the end or start of a line joins it to the next or previous line
1853
+ const source = clickableText(text.replace(/\\\n/g, "").replace(/\n\\/g, ""), ctx);
1854
+ const nodes = new Parser(source).parse(0).nodes;
1855
+ return new Writer(ctx).passage(nodes);
1856
+ }