squiffy-compiler 7.0.0-beta.6 → 7.0.0-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/dist/analyse.d.ts +12 -1
  2. package/dist/analyse.js +156 -9
  3. package/dist/compiler.d.ts +5 -3
  4. package/dist/compiler.js +3 -2
  5. package/dist/css-urls.d.ts +4 -0
  6. package/dist/css-urls.js +59 -0
  7. package/dist/emit.d.ts +18 -1
  8. package/dist/emit.js +46 -0
  9. package/dist/infix-expressions.d.ts +19 -0
  10. package/dist/infix-expressions.js +713 -0
  11. package/dist/language-service.d.ts +1 -0
  12. package/dist/language-service.js +34 -15
  13. package/dist/node.d.ts +2 -1
  14. package/dist/node.js +1 -0
  15. package/dist/parse.d.ts +4 -0
  16. package/dist/parse.js +29 -0
  17. package/dist/project.d.ts +31 -0
  18. package/dist/project.js +98 -0
  19. package/dist/quest/convert.js +67 -11
  20. package/dist/quest/scripts.js +13 -9
  21. package/dist/quest/text.js +17 -8
  22. package/dist/section-labels.d.ts +4 -0
  23. package/dist/section-labels.js +64 -0
  24. package/dist/setters.d.ts +4 -0
  25. package/dist/setters.js +11 -9
  26. package/dist/story-graph.d.ts +2 -0
  27. package/dist/story-graph.js +61 -16
  28. package/dist/syntax.d.ts +24 -3
  29. package/dist/templates.d.ts +6 -0
  30. package/dist/templates.js +128 -0
  31. package/dist/text.d.ts +3 -1
  32. package/dist/text.js +45 -11
  33. package/dist/twine/audio.d.ts +21 -0
  34. package/dist/twine/audio.js +80 -0
  35. package/dist/twine/convert.d.ts +45 -3
  36. package/dist/twine/convert.js +305 -37
  37. package/dist/twine/expression.d.ts +21 -1
  38. package/dist/twine/expression.js +105 -8
  39. package/dist/twine/harlowe.d.ts +9 -0
  40. package/dist/twine/harlowe.js +461 -86
  41. package/dist/twine/settings.d.ts +9 -0
  42. package/dist/twine/settings.js +322 -0
  43. package/dist/twine/sugarcube.d.ts +3 -0
  44. package/dist/twine/sugarcube.js +438 -114
  45. package/package.json +9 -2
  46. package/syntaxes/squiffy.tmLanguage.json +8 -3
@@ -4,8 +4,9 @@
4
4
  // variables), which is then written out: (if:) chains become {{#if}}, (set:) becomes @set or
5
5
  // {{set}}, (link:) and friends become links to generated passages and sections, and Harlowe's
6
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";
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";
9
10
  // Macro names ignore case, - and _
10
11
  function normalise(name) {
11
12
  return name.toLowerCase().replace(/[-_]/g, "");
@@ -21,7 +22,7 @@ const changers = new Set([
21
22
  "opacity", "textrotate", "textrotatez", "box", "border", "b4r", "bordercolour", "bordercolor", "b4rcolour",
22
23
  "cornerradius", "textindent", "float", "hookname", "action", "linkundo", "linkfullscreen", "more",
23
24
  "clickgoto", "mouseovergoto", "mouseoverreplace", "mouseoverappend", "mouseoverprepend", "mouseoutreplace",
24
- "linkstyle", "charstyle", "linestyle", "button", "textshadow", "outline", "hiddenhook", "seqlink",
25
+ "linkstyle", "charstyle", "linestyle", "button", "textshadow", "outline", "hiddenhook", "seqlink", "output", "out",
25
26
  ]);
26
27
  class Parser {
27
28
  constructor(src) {
@@ -58,14 +59,11 @@ class Parser {
58
59
  i = stop;
59
60
  continue;
60
61
  }
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;
62
+ const html = readHtmlBlock(src, i);
63
+ if (html) {
66
64
  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;
65
+ nodes.push(html.block);
66
+ i = html.end;
69
67
  continue;
70
68
  }
71
69
  if (c == "`") {
@@ -121,12 +119,14 @@ class Parser {
121
119
  continue;
122
120
  }
123
121
  }
124
- if (/^\(\$[\w]+:/.test(rest) || /^\(_[\w]+:/.test(rest)) {
122
+ const call = /^\(([$_])(\w+):/.exec(rest);
123
+ if (call) {
125
124
  // A call to a custom macro
126
125
  const end = skipBalanced(src, i, "(", ")");
127
126
  if (end != -1) {
128
127
  flush();
129
- nodes.push({ t: "comment", text: src.substring(i, end), reason: "Custom macros, made with (macro:), can't be converted." });
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
130
  i = end;
131
131
  continue;
132
132
  }
@@ -302,9 +302,10 @@ function tokenize(s) {
302
302
  i += 2;
303
303
  continue;
304
304
  }
305
- const ordinal = /^(\d+)(st|nd|rd|th)\b/.exec(s.substring(i));
305
+ // 2nd, or 2ndlast, which is a negative position: from the end
306
+ const ordinal = /^(\d+)(st|nd|rd|th)(last)?\b/.exec(s.substring(i));
306
307
  if (ordinal) {
307
- tokens.push({ type: "word", text: "ordinal", value: parseInt(ordinal[1]) });
308
+ tokens.push({ type: "word", text: "ordinal", value: parseInt(ordinal[1]) * (ordinal[3] ? -1 : 1) });
308
309
  i += ordinal[0].length;
309
310
  continue;
310
311
  }
@@ -396,6 +397,32 @@ export class HarloweExpressions {
396
397
  macro(name, raw, it) {
397
398
  const args = splitArgs(raw.substring(raw.indexOf(":") + 1, raw.length - 1));
398
399
  const values = () => args.map(a => this.parse(a, it));
400
+ const one = () => {
401
+ if (args.length != 1)
402
+ throw new Unconvertible(`(${name}:) with ${args.length ? "more than one value" : "no value"}`);
403
+ return values();
404
+ };
405
+ // The values of a macro like (sorted:) as a list: ...$bag is the list itself, and values
406
+ // are a list of them
407
+ const list = (from) => {
408
+ const spread = (v) => /^\s*\.\.\./.test(v) ? this.parse(v.replace(/^\s*\.\.\./, ""), it) : null;
409
+ if (from.length == 1) {
410
+ const e = spread(from[0]);
411
+ if (e)
412
+ return e;
413
+ }
414
+ const items = [];
415
+ for (const v of from) {
416
+ const e = spread(v);
417
+ if (!e)
418
+ items.push(this.parse(v, it));
419
+ else if (e.k == "array")
420
+ items.push(...e.items);
421
+ else
422
+ throw new Unconvertible(`(${name}:) with an array and other values`);
423
+ }
424
+ return { k: "array", items };
425
+ };
399
426
  switch (name) {
400
427
  case "either":
401
428
  return { k: "call", fn: "random", args: [{ k: "array", items: values() }] };
@@ -408,12 +435,14 @@ export class HarloweExpressions {
408
435
  return { k: "array", items: values() };
409
436
  case "range": {
410
437
  // The whole numbers from one to the other
438
+ if (args.length != 2)
439
+ throw new Unconvertible("(range:) without two numbers");
411
440
  const [from, to] = values();
412
- if (from?.k != "num" || to?.k != "num")
413
- throw new Unconvertible("(range:) with numbers that aren't fixed");
441
+ // Squiffy's (range from to) works it out as the story runs (#447). A short one
442
+ // with fixed numbers is written out, as it reads more simply.
443
+ if (from.k != "num" || to.k != "num" || Math.abs(to.v - from.v) > 20)
444
+ return { k: "call", fn: "range", args: [from, to] };
414
445
  const step = to.v >= from.v ? 1 : -1;
415
- if (Math.abs(to.v - from.v) > 100)
416
- throw new Unconvertible("(range:) of more than 100 numbers");
417
446
  const items = [];
418
447
  for (let n = Math.round(from.v); n != Math.round(to.v) + step; n += step)
419
448
  items.push({ k: "num", v: n });
@@ -440,12 +469,62 @@ export class HarloweExpressions {
440
469
  case "passage":
441
470
  throw new Unconvertible("(passage:)");
442
471
  case "dm":
443
- case "datamap":
472
+ case "datamap": {
473
+ // An object (#442)
474
+ const items = values();
475
+ if (items.length % 2)
476
+ throw new Unconvertible("a datamap with a name that has no value");
477
+ const entries = [];
478
+ for (let n = 0; n < items.length; n += 2) {
479
+ const key = items[n];
480
+ if (key.k != "str" && key.k != "num")
481
+ throw new Unconvertible("a datamap with names that aren't fixed");
482
+ entries.push([String(key.v), items[n + 1]]);
483
+ }
484
+ return { k: "object", entries };
485
+ }
444
486
  case "ds":
445
487
  case "dataset":
446
- throw new Unconvertible("Harlowe datamaps and datasets");
488
+ throw new Unconvertible("Harlowe datasets");
447
489
  case "cond":
448
- throw new Unconvertible("(cond:), which Squiffy has no equivalent for in an expression");
490
+ return conditional(values(), "(cond:)");
491
+ // Text and numbers (#446)
492
+ case "lowercase":
493
+ case "uppercase":
494
+ case "upperfirst": {
495
+ const [text] = one();
496
+ return { k: "call", fn: name == "lowercase" ? "lower" : name == "uppercase" ? "upper" : "capitalise", args: [text] };
497
+ }
498
+ case "round":
499
+ case "floor":
500
+ case "ceil":
501
+ case "abs":
502
+ return { k: "call", fn: name, args: one() };
503
+ case "min":
504
+ case "max": {
505
+ const items = values();
506
+ if (!items.length)
507
+ throw new Unconvertible(`(${name}:) with no values`);
508
+ return { k: "call", fn: name, args: items };
509
+ }
510
+ // Lists (#447)
511
+ case "joined": {
512
+ if (!args.length)
513
+ throw new Unconvertible("(joined:) with nothing to join");
514
+ const separator = this.parse(args[0], it);
515
+ return { k: "call", fn: "join", args: [list(args.slice(1)), separator] };
516
+ }
517
+ case "sorted":
518
+ case "shuffled":
519
+ if (args.length && /^\s*(via|each)\b/.test(args[0]))
520
+ throw new Unconvertible(`(${name}:) with "${args[0].trim().split(/\s/)[0]}"`);
521
+ return { k: "call", fn: name == "sorted" ? "sort" : "shuffle", args: [list(args)] };
522
+ case "count": {
523
+ if (args.length != 2)
524
+ throw new Unconvertible("(count:) with more than one value to count");
525
+ const [container, value] = values();
526
+ return { k: "call", fn: "count", args: [container, value] };
527
+ }
449
528
  default:
450
529
  throw new Unconvertible(`the (${name}:) macro`);
451
530
  }
@@ -567,17 +646,14 @@ class ExpressionParser {
567
646
  default: return { k: "bin", op, l: left, r: right };
568
647
  }
569
648
  }
649
+ // A list, text or datamap that contains a value (#446)
570
650
  contains(collection, value) {
571
- if (collection.k == "var")
572
- return { k: "call", fn: "contains", args: [{ k: "str", v: collection.name }, value] };
573
- if (collection.k == "array")
574
- return { k: "call", fn: "contains", args: [collection, value] };
575
651
  if (collection.k == "call" && collection.fn == "__history") {
576
652
  if (value.k != "str")
577
653
  throw new Unconvertible("(history:) contains something other than a passage name");
578
654
  return { k: "call", fn: "seen", args: [{ k: "str", v: this.h.ctx.story.sectionForUnknown(value.v) }] };
579
655
  }
580
- throw new Unconvertible("\"contains\" with something other than a variable or an array");
656
+ return { k: "bin", op: "contains", l: collection, r: value };
581
657
  }
582
658
  additive() {
583
659
  let left = this.multiplicative();
@@ -609,22 +685,21 @@ class ExpressionParser {
609
685
  this.tokens.next();
610
686
  const property = this.tokens.next();
611
687
  if (property.text == "length") {
612
- if (e.k == "var")
613
- e = { k: "call", fn: "length", args: [{ k: "str", v: e.name }] };
614
- else if (e.k == "array")
615
- e = { k: "call", fn: "length", args: [e] };
616
- else if (e.k == "call" && e.fn == "__history")
617
- e = { k: "var", name: "turns" };
618
- else
619
- throw new Unconvertible("the length of something other than a variable or an array");
688
+ // A list's or text's length (#446)
689
+ e = e.k == "call" && e.fn == "__history" ? { k: "var", name: "turns" } : lengthOf(e);
690
+ }
691
+ else if (property.text == "ordinal" && (e.k == "var" || e.k == "array" || e.k == "member")) {
692
+ // $list's 1st, or $list's 2ndlast, which is bag[bag.length - 2]
693
+ const n = property.value;
694
+ e = n > 0 ? member(e, { k: "num", v: n - 1 }) : member(e, { k: "bin", op: "-", l: lengthOf(e), r: { k: "num", v: -n } });
620
695
  }
621
- else if (property.text == "ordinal" && (e.k == "var" || e.k == "array")) {
622
- // $list's 1st
623
- e = { k: "call", fn: "lookup", args: [e, { k: "num", v: property.value - 1 }] };
696
+ else if (property.text == "last" && (e.k == "var" || e.k == "array" || e.k == "member")) {
697
+ // $list's last (#447)
698
+ e = { k: "call", fn: "last", args: [e] };
624
699
  }
625
- else if (e.k == "var" && (property.type == "word" || property.type == "str") && /^[A-Za-z_]\w*$/.test(String(property.value ?? property.text))) {
626
- // A datamap's value is its own attribute: $player's hp is player_hp
627
- e = { k: "var", name: `${e.name}_${property.value ?? property.text}` };
700
+ else if ((e.k == "var" || e.k == "member") && (property.type == "word" || property.type == "str")) {
701
+ // A value in a datamap: $player's hp is player.hp (#442)
702
+ e = member(e, { k: "str", v: String(property.value ?? property.text) });
628
703
  }
629
704
  else {
630
705
  throw new Unconvertible(`properties of variables ('s ${property.text})`);
@@ -734,6 +809,13 @@ class Writer {
734
809
  writable: true,
735
810
  value: false
736
811
  });
812
+ // Whether this is the body of a custom macro, where (output:) is what it shows
813
+ Object.defineProperty(this, "inMacro", {
814
+ enumerable: true,
815
+ configurable: true,
816
+ writable: true,
817
+ value: false
818
+ });
737
819
  this.expr = new HarloweExpressions(ctx);
738
820
  this.referenced = referencedHooks(ctx);
739
821
  }
@@ -758,10 +840,52 @@ class Writer {
758
840
  passage(nodes) {
759
841
  this.collectHooks(nodes);
760
842
  const state = { leading: true, directives: [] };
843
+ nodes = this.passageTransition(nodes, state);
844
+ nodes = topScripts(this.ctx, nodes, state.directives);
761
845
  let body = this.nodes(nodes, state);
762
846
  body += this.closeAll();
763
847
  return { directives: state.directives, body };
764
848
  }
849
+ // (transition:)[...] around the whole passage becomes @transition (#489), with its
850
+ // (transition-time:), and the passage is the hook's text
851
+ passageTransition(nodes, state) {
852
+ const content = nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
853
+ const m = content[0];
854
+ if (content.length != 1 || m.t != "macro" || !m.hook)
855
+ return nodes;
856
+ let name;
857
+ let time;
858
+ let hook = { nodes: [{ ...m, hook: foldChangers(m), changers: [] }], raw: m.raw };
859
+ // The changers, from outside in, until the passage's text
860
+ for (;;) {
861
+ const inner = hook?.nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
862
+ const changer = inner?.length == 1 && inner[0].t == "macro" && inner[0].hook ? inner[0] : undefined;
863
+ if (!changer)
864
+ break;
865
+ const arg = splitArgs(changer.args)[0]?.trim() ?? "";
866
+ const macro = normalise(changer.name);
867
+ const value = literal(arg);
868
+ if ((macro == "transition" || macro == "t8n") && typeof value == "string")
869
+ name = value;
870
+ // A time such as 2s isn't a string in Harlowe
871
+ else if (macro == "transitiontime" || macro == "t8ntime")
872
+ time = arg;
873
+ else
874
+ break;
875
+ hook = changer.hook;
876
+ }
877
+ // A named hook stays a hook, so that it can still be changed
878
+ if (!name || !hook || hook.name || hook.hidden)
879
+ return nodes;
880
+ const transition = harloweTransitions.get(name.toLowerCase());
881
+ if (!transition) {
882
+ this.ctx.story.note("harlowe-transition", `"${name}"`, "Squiffy has no equivalent for these Harlowe transitions, so they've been left out");
883
+ return hook.nodes;
884
+ }
885
+ const ms = time ? /^(\d+(?:\.\d+)?|\.\d+)(s|ms)$/i.exec(time.trim()) : null;
886
+ state.directives.push(`@transition ${transition}` + (ms ? ` ${ms[1]}${ms[2].toLowerCase()}` : ""));
887
+ return hook.nodes;
888
+ }
765
889
  closeAll() {
766
890
  let s = "";
767
891
  for (const tag of [...this.open].reverse())
@@ -875,6 +999,11 @@ class Writer {
875
999
  return node.s;
876
1000
  case "comment":
877
1001
  return this.ctx.unconvertible(node.text, node.reason);
1002
+ case "html":
1003
+ return passageHtmlBlock(this.ctx, node, false).text;
1004
+ case "call":
1005
+ state.leading = false;
1006
+ return this.call(node);
878
1007
  case "var":
879
1008
  state.leading = false;
880
1009
  return display(this.expr.variable(node.name, node.temp));
@@ -1104,6 +1233,19 @@ class Writer {
1104
1233
  case "set":
1105
1234
  case "put":
1106
1235
  return this.set(m, args, state);
1236
+ // What a custom macro shows (#450)
1237
+ case "output":
1238
+ case "out":
1239
+ case "outputdata":
1240
+ case "outdata":
1241
+ if (!this.inMacro)
1242
+ throw new Unconvertible(`(${m.name}:) outside a custom macro`);
1243
+ state.leading = false;
1244
+ if (m.hook && !args.length && (name == "output" || name == "out"))
1245
+ return this.hookContent(m.hook, state);
1246
+ if (args.length != 1)
1247
+ throw new Unconvertible(`(${m.name}:) with more than one value`);
1248
+ return display(this.expr.parse(args[0]));
1107
1249
  case "print":
1108
1250
  state.leading = false;
1109
1251
  if (args.length != 1)
@@ -1174,28 +1316,30 @@ class Writer {
1174
1316
  }
1175
1317
  case "after": {
1176
1318
  state.leading = false;
1177
- const delay = this.expr.parse(args[0] ?? "");
1178
- if (delay.k != "num")
1179
- throw new Unconvertible("(after:) with a delay that isn't fixed");
1319
+ // time is how long the passage has been shown, which is no time at all when this
1320
+ // is worked out, so (after: time + 4s) is (after: 4s)
1321
+ const delay = delayValue(this.expr.parse((args[0] ?? "").replace(/^\s*time\s*\+/, "")));
1180
1322
  if (!m.hook)
1181
1323
  return "";
1182
1324
  const goto = this.gotoOnly(m.hook);
1183
1325
  if (goto)
1184
- return goto.replace(/\}\}$/, ` after=${delay.v}}}`);
1185
- return `{{#animate "fadeIn" start=${delay.v}}}${this.hookContent(m.hook, state)}{{/animate}}`;
1326
+ return goto.replace(/\}\}$/, ` after=${delay}}}`);
1327
+ return `{{#animate "fadeIn" start=${delay}}}${this.hookContent(m.hook, state)}{{/animate}}`;
1186
1328
  }
1187
1329
  case "live": {
1188
1330
  state.leading = false;
1189
- const delay = this.expr.parse(args[0] ?? "1s");
1190
- if (delay.k != "num" || !m.hook)
1191
- throw new Unconvertible("(live:)");
1331
+ if (!m.hook)
1332
+ throw new Unconvertible("(live:) without a hook");
1333
+ const delay = delayValue(this.expr.parse(args[0] ?? "1s"));
1334
+ // A hook that only goes somewhere else goes there once
1192
1335
  const goto = this.gotoOnly(m.hook, true);
1193
1336
  if (goto)
1194
- return goto.replace(/\}\}$/, ` after=${delay.v}}}`);
1195
- throw new Unconvertible("(live:), which runs its hook again and again");
1337
+ return goto.replace(/\}\}$/, ` after=${delay}}}`);
1338
+ // Its hook is shown again every so often, until a (stop:) (#451)
1339
+ return `{{#every ${delay}}}${this.hookContent(m.hook, state)}{{/every}}`;
1196
1340
  }
1197
1341
  case "stop":
1198
- return "";
1342
+ return "{{stop}}";
1199
1343
  case "inputbox":
1200
1344
  case "forceinputbox":
1201
1345
  case "input":
@@ -1206,7 +1350,7 @@ class Writer {
1206
1350
  state.leading = false;
1207
1351
  const bound = this.bound(args[0] ?? "");
1208
1352
  if (!bound)
1209
- throw new Unconvertible("(dropdown:) without bind");
1353
+ throw new Unconvertible("(dropdown:) without bind, or bound to something other than a variable or a value inside one");
1210
1354
  const options = args.slice(1).map(a => this.expr.parse(a));
1211
1355
  if (options.some(o => o.k != "str" && o.k != "num"))
1212
1356
  throw new Unconvertible("(dropdown:) with options that aren't fixed");
@@ -1300,11 +1444,14 @@ class Writer {
1300
1444
  case "t8ndelay":
1301
1445
  case "transitionskip":
1302
1446
  case "t8nskip":
1447
+ // Around the whole passage, this became @transition (#489). Squiffy has none for part of one.
1448
+ 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");
1449
+ return m.hook ? this.hookContent(m.hook, state) : "";
1303
1450
  case "transitiondepart":
1304
1451
  case "t8ndepart":
1305
1452
  case "transitionarrive":
1306
1453
  case "t8narrive":
1307
- // Only how the text appears, which Squiffy does its own way
1454
+ 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");
1308
1455
  return m.hook ? this.hookContent(m.hook, state) : "";
1309
1456
  case "nobr":
1310
1457
  case "collapse":
@@ -1384,11 +1531,12 @@ class Writer {
1384
1531
  throw new Unconvertible(`(${name}:) with something other than "each _item" or "_item where ..."`);
1385
1532
  const collection = this.forCollection(args.slice(1), name);
1386
1533
  const hook = m.hook;
1534
+ const numbers = collection.k == "call" && collection.fn == "range";
1387
1535
  return this.ctx.story.inLoop(new Map([["_" + lambda[2], "item"]]), undefined, () => {
1388
1536
  const body = this.hookContent(hook, state);
1389
1537
  const shown = lambda[3] ? `{{#if ${print(this.expr.parse(lambda[3]))}}}${body}{{/if}}` : body;
1390
1538
  return `{{#each ${print(collection)}}}${shown}{{/each}}`;
1391
- });
1539
+ }, numbers);
1392
1540
  }
1393
1541
  case "linkstorylet": {
1394
1542
  state.leading = false;
@@ -1422,16 +1570,93 @@ class Writer {
1422
1570
  case "else":
1423
1571
  // Handled in nodes()
1424
1572
  return "";
1573
+ case "track":
1574
+ return leadingAudio(this.track(m, args), state);
1575
+ case "newtrack":
1576
+ // Found before the story's converted
1577
+ return "";
1578
+ case "masteraudio":
1579
+ if (args.length == 1 && String(literal(args[0])).toLowerCase() == "stopall")
1580
+ return leadingAudio(STOP_ALL_AUDIO, state);
1581
+ throw new Unconvertible("(masteraudio:), which changes all the story's sound at once, except to stop it");
1582
+ case "playlist":
1583
+ case "newplaylist":
1584
+ throw new Unconvertible("playlists");
1585
+ case "group":
1586
+ case "newgroup":
1587
+ throw new Unconvertible("audio groups");
1425
1588
  default:
1426
1589
  throw new Unconvertible(`the (${m.raw.substring(1, m.raw.indexOf(":"))}:) macro, which Squiffy has no equivalent for`);
1427
1590
  }
1428
1591
  }
1592
+ // (track: "name", "command", ...values), from the Harlowe Audio Library
1593
+ track(m, args) {
1594
+ const track = literal(args[0]);
1595
+ const command = literal(args[1]);
1596
+ if (typeof track != "string")
1597
+ throw new Unconvertible("(track:) with a track that isn't fixed");
1598
+ if (typeof command != "string")
1599
+ throw new Unconvertible("(track:) with a command that isn't fixed");
1600
+ const action = { play: false, stop: false, loop: false };
1601
+ const num = (i) => {
1602
+ const n = literal(args[i]);
1603
+ if (typeof n != "number")
1604
+ throw new Unconvertible(`(track:) "${command}" with a value that isn't a fixed number`);
1605
+ return n;
1606
+ };
1607
+ switch (command.toLowerCase()) {
1608
+ case "play":
1609
+ case "playwhenpossible":
1610
+ action.play = true;
1611
+ break;
1612
+ case "fadein":
1613
+ action.play = true;
1614
+ if (args[2] !== undefined)
1615
+ action.fade = num(2);
1616
+ break;
1617
+ case "stop":
1618
+ action.stop = true;
1619
+ break;
1620
+ case "fadeout":
1621
+ action.stop = true;
1622
+ if (args[2] !== undefined)
1623
+ action.fade = num(2);
1624
+ break;
1625
+ case "fadeto":
1626
+ if (num(2) > 0)
1627
+ action.play = true;
1628
+ else
1629
+ action.stop = true;
1630
+ if (args[3] !== undefined)
1631
+ action.fade = num(3);
1632
+ break;
1633
+ case "loop":
1634
+ // Found before the story's converted
1635
+ return "";
1636
+ case "volume":
1637
+ if (harloweAudio(this.ctx.story).looping.has(track)) {
1638
+ this.ctx.story.note("audio-music-volume", m.raw, "Squiffy plays music at full volume, so the music's volume has been left out");
1639
+ return "";
1640
+ }
1641
+ throw new Unconvertible("(track:) changing the volume of a sound on its own: give {{sound}} a volume= instead");
1642
+ case "pause":
1643
+ throw new Unconvertible("pausing a track");
1644
+ case "mute":
1645
+ case "unmute":
1646
+ throw new Unconvertible("muting a track");
1647
+ case "time":
1648
+ throw new Unconvertible("playing a track from part of the way through");
1649
+ default:
1650
+ throw new Unconvertible(`(track:) with "${command}"`);
1651
+ }
1652
+ return audioHelper(this.ctx, m.raw, harloweAudio(this.ctx.story), track, action);
1653
+ }
1429
1654
  // What a (for:) goes through: an array spread out (...$list), or values, as {{#each}} takes
1430
1655
  forCollection(values, name) {
1431
1656
  const spread = (v) => /^\s*\.\.\./.test(v) ? this.expr.parse(v.replace(/^\s*\.\.\./, "")) : null;
1432
1657
  if (values.length == 1) {
1433
1658
  const e = spread(values[0]);
1434
- if (e && (e.k == "var" || e.k == "array" || (e.k == "loop" && e.kind == "item")))
1659
+ if (e && (e.k == "var" || e.k == "array" || (e.k == "loop" && e.kind == "item") || isListCall(e)))
1435
1660
  return e;
1436
1661
  }
1437
1662
  const items = [];
@@ -1482,20 +1707,23 @@ class Writer {
1482
1707
  if (navigation) {
1483
1708
  if (navigation.setters)
1484
1709
  return this.linkTo(text, navigation.target, m.raw, navigation.setters);
1485
- // It does more than set variables, so do that in a section of its own
1486
- const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, navigation.content());
1487
- return sectionLink(text, section);
1488
- }
1489
- const content = this.nodes(m.hook.nodes, { leading: false, directives: [] });
1710
+ // It does more than set variables, so do that in a section of its own. In a loop, it can
1711
+ // use the loop's item, which the link sets an attribute to (#448).
1712
+ const { result, setters } = this.ctx.story.linkBody(() => navigation.content());
1713
+ const section = this.ctx.addSection(`${this.ctx.section}: ${textExpr.v}`, result);
1714
+ return sectionLink(text, section, setters);
1715
+ }
1716
+ const hook = m.hook;
1717
+ const { result: content, setters } = this.ctx.story.linkBody(() => this.nodes(hook.nodes, { leading: false, directives: [] }));
1490
1718
  if (m.name == "linkrepeat" || m.name == "linkrerun") {
1491
1719
  this.ctx.approximate(m.raw, "In Squiffy, this link can only be clicked once.");
1492
1720
  const passage = this.ctx.addPassage(textExpr.v, content);
1493
- return passageLink(text, passage);
1721
+ return passageLink(text, passage, setters);
1494
1722
  }
1495
1723
  const label = this.ctx.newLabel(textExpr.v);
1496
1724
  const replacement = m.name == "linkreveal" ? text + content : content;
1497
1725
  const passage = this.ctx.addPassage(textExpr.v, `{{#replace "${label}"}}${replacement}{{/replace}}`);
1498
- return `{{#label "${label}"}}${passageLink(text, passage)}{{/label}}`;
1726
+ return `{{#label "${label}"}}${passageLink(text, passage, setters)}{{/label}}`;
1499
1727
  }
1500
1728
  // If a hook only sets variables and then goes to a passage, the setters and the passage.
1501
1729
  // If it does other things before going to a passage, content is the Squiffy text for a
@@ -1568,17 +1796,21 @@ class Writer {
1568
1796
  const content = this.nodes(named.hook.nodes, { leading: false, directives: [] });
1569
1797
  return `{{#replace "${label}"}}${content}{{/replace}}`;
1570
1798
  }
1571
- // The attribute for "bind $x", or null
1799
+ // The attribute for "bind $x", or the value inside an object for "bind $hero's name" (#454),
1800
+ // or null
1572
1801
  bound(arg) {
1573
- const match = /^2?bind\s+([$_])([A-Za-z]\w*)$/.exec(arg.trim());
1802
+ const match = /^2?bind\s+([$_][\s\S]*)$/.exec(arg.trim());
1574
1803
  if (!match)
1575
1804
  return null;
1576
- return this.expr.attribute(match[2], match[1] == "_");
1805
+ const e = this.expr.parse(match[1]);
1806
+ if (e.k != "var" || isDynamicTarget(e.name))
1807
+ return null;
1808
+ return e.name;
1577
1809
  }
1578
1810
  input(args, raw) {
1579
1811
  const bound = this.bound(args[0] ?? "");
1580
1812
  if (!bound)
1581
- throw new Unconvertible("an input box without bind");
1813
+ throw new Unconvertible("an input box without bind, or bound to something other than a variable or a value inside one");
1582
1814
  let defaultText = null;
1583
1815
  let rows = 1;
1584
1816
  for (const a of args.slice(1)) {
@@ -1615,17 +1847,32 @@ class Writer {
1615
1847
  case "textstyle": {
1616
1848
  let open = "";
1617
1849
  let close = "";
1850
+ // The {{#style}} effects (#453) with the same look as Harlowe's
1851
+ const effects = [];
1618
1852
  for (const a of args) {
1619
1853
  const style = str(this.expr.parse(a)).toLowerCase().replace(/[\s-]/g, "");
1620
- const tag = { bold: "b", italic: "i", underline: "u", strike: "s", superscript: "sup", subscript: "sub" }[style];
1854
+ const tag = { bold: "b", italic: "i", underline: "u", strike: "s", superscript: "sup", subscript: "sub", mark: "mark" }[style];
1855
+ const effect = {
1856
+ shudder: "shudder", rumble: "rumble", sway: "sway", buoy: "buoy", fidget: "shake",
1857
+ blink: "blink", fadeinout: "fade-in-out", blur: "blur", blurrier: "blurrier",
1858
+ smear: "smear", mirror: "mirror", upsidedown: "upside-down",
1859
+ }[style];
1621
1860
  if (tag) {
1622
1861
  open += `<${tag}>`;
1623
1862
  close = `</${tag}>` + close;
1624
1863
  }
1864
+ else if (effect) {
1865
+ if (!effects.includes(effect))
1866
+ effects.push(effect);
1867
+ }
1625
1868
  else if (style != "none") {
1626
1869
  this.ctx.story.note("harlowe-text-style", `"${style}"`, "Squiffy has no equivalent for these Harlowe text styles, so they've been left out");
1627
1870
  }
1628
1871
  }
1872
+ if (effects.length) {
1873
+ open = `{{#style "${effects.join(" ")}"}}` + open;
1874
+ close += "{{/style}}";
1875
+ }
1629
1876
  return open + content + close;
1630
1877
  }
1631
1878
  case "align": {
@@ -1675,23 +1922,7 @@ class Writer {
1675
1922
  throw new Unconvertible("a colour that isn't fixed");
1676
1923
  }
1677
1924
  // ---- (set:) ----
1678
- // An assignment, with a datamap flattened into one for each of its values
1679
1925
  assignments(source, put) {
1680
- const datamap = /^\s*([$_])([A-Za-z]\w*)\s+to\s+\((?:dm|datamap):([\s\S]*)\)\s*$/i.exec(source);
1681
- if (datamap && !put) {
1682
- const name = this.expr.attribute(datamap[2], datamap[1] == "_");
1683
- const values = splitArgs(datamap[3]);
1684
- if (values.length % 2)
1685
- throw new Unconvertible("a datamap with a name that has no value");
1686
- const result = [];
1687
- for (let n = 0; n < values.length; n += 2) {
1688
- const key = this.expr.parse(values[n]);
1689
- if (key.k != "str" || !/^[A-Za-z_]\w*$/.test(key.v))
1690
- throw new Unconvertible("a datamap with names that aren't words");
1691
- result.push({ kind: "set", name: `${name}_${key.v}`, value: this.expr.parse(values[n + 1]) });
1692
- }
1693
- return result;
1694
- }
1695
1926
  return [this.assignment(source, put)];
1696
1927
  }
1697
1928
  assignment(source, put) {
@@ -1714,10 +1945,10 @@ class Writer {
1714
1945
  const target = /^([$_])([A-Za-z]\w*)((?:'s\s+(?:[A-Za-z_]\w*|"[A-Za-z_]\w*"))*)$/.exec(targetSource.trim());
1715
1946
  if (!target)
1716
1947
  throw new Unconvertible("setting something other than a variable");
1717
- // $player's hp is player_hp
1948
+ // $player's hp is player.hp (#442)
1718
1949
  const properties = [...target[3].matchAll(/'s\s+"?([A-Za-z_]\w*)"?/g)].map(m => m[1]);
1719
- const name = [this.expr.attribute(target[2], target[1] == "_"), ...properties].join("_");
1720
- const variable = { k: "var", name };
1950
+ const variable = properties.reduce((e, property) => member(e, { k: "str", v: property }), { k: "var", name: this.expr.attribute(target[2], target[1] == "_") });
1951
+ const name = targetName(variable);
1721
1952
  const value = this.expr.parse(valueSource, variable);
1722
1953
  // $x to it + 1, and $x to $x - 2
1723
1954
  if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
@@ -1731,8 +1962,56 @@ class Writer {
1731
1962
  }
1732
1963
  return { kind: "set", name, value };
1733
1964
  }
1965
+ // A call to a custom macro embeds its section, with its arguments as the parameters (#450)
1966
+ call(node) {
1967
+ const macro = node.temp ? undefined : harloweMacros(this.ctx.story).get(node.name);
1968
+ if (!macro)
1969
+ 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.");
1970
+ try {
1971
+ const args = splitArgs(node.args);
1972
+ if (args.length > macro.params.length)
1973
+ throw new Unconvertible("more values than the macro has parameters");
1974
+ const params = args.map((a, n) => ` ${macro.params[n]}=${print(this.expr.parse(a))}`).join("");
1975
+ return `{{embed ${print({ k: "str", v: macro.section })}${params}}}`;
1976
+ }
1977
+ catch (e) {
1978
+ if (!(e instanceof Unconvertible))
1979
+ throw e;
1980
+ return this.ctx.unconvertible(node.raw, `This couldn't be converted: ${e.message}.`);
1981
+ }
1982
+ }
1983
+ // A custom macro's body (#450), which becomes a section that calls to it embed. It's a code
1984
+ // hook, so the whitespace between its macros isn't shown.
1985
+ macroBody(source) {
1986
+ const nodes = new Parser(source).parse(0).nodes.filter(n => !(n.t == "text" && n.s.trim() == ""));
1987
+ this.collectHooks(nodes);
1988
+ this.inMacro = true;
1989
+ const state = { leading: false, directives: [] };
1990
+ let body = this.nodes(nodes, state);
1991
+ body += this.closeAll();
1992
+ return { directives: [], body };
1993
+ }
1734
1994
  set(m, args, state) {
1735
1995
  let out = "";
1996
+ // A custom macro becomes a section when it's defined (#450)
1997
+ args = args.filter(source => {
1998
+ const definition = /^\s*\$(\w+)\s+to\s+\(macro:/i.exec(source);
1999
+ const macro = definition && harloweMacros(this.ctx.story).get(definition[1]);
2000
+ if (!macro || macro.defined)
2001
+ return !macro;
2002
+ macro.defined = true;
2003
+ let converted;
2004
+ try {
2005
+ converted = new Writer(this.ctx).macroBody(macro.body);
2006
+ }
2007
+ catch (e) {
2008
+ if (!(e instanceof Unconvertible))
2009
+ throw e;
2010
+ converted = { directives: [], body: this.ctx.unconvertible(macro.body, `This macro couldn't be converted: ${e.message}.`) };
2011
+ }
2012
+ this.ctx.fillSection(macro.section, converted);
2013
+ return false;
2014
+ });
1736
2015
  for (const a of args.flatMap(source => this.assignments(source, m.name == "put"))) {
1737
2016
  const amount = a.value.k == "num" && Number.isInteger(a.value.v) && a.value.v >= 0 ? a.value.v : null;
1738
2017
  if (state.leading) {
@@ -1770,6 +2049,13 @@ class Writer {
1770
2049
  return out;
1771
2050
  }
1772
2051
  }
2052
+ // Harlowe's transitions, as Squiffy's @transition (#489)
2053
+ const harloweTransitions = new Map([
2054
+ ["instant", "none"], ["dissolve", "fade"], ["fade", "fade"], ["rumble", "rumble"], ["shudder", "shudder"],
2055
+ ["pulse", "pulse"], ["zoom", "zoom"], ["flicker", "flicker"], ["blur", "blur"],
2056
+ ["slide-left", "slide-left"], ["slide-right", "slide-right"], ["slide-up", "slide-up"], ["slide-down", "slide-down"],
2057
+ ["fade-left", "slide-left"], ["fade-right", "slide-right"], ["fade-up", "slide-up"], ["fade-down", "slide-down"],
2058
+ ]);
1773
2059
  // (a:)+(b:)[hook] is (a:) applied to (b:)[hook]: the hook, with the changers after the first
1774
2060
  // applied to it
1775
2061
  function foldChangers(m) {
@@ -1840,6 +2126,9 @@ function splitOutsideStrings(s, keyword) {
1840
2126
  let depth = 0;
1841
2127
  for (let i = 0; i < s.length; i++) {
1842
2128
  const c = s[i];
2129
+ // Harlowe's possessive: $player's hp
2130
+ if (c == "'" && s[i + 1] == "s" && /\s/.test(s[i + 2] ?? "") && /[\w)"]/.test(s[i - 1] ?? ""))
2131
+ continue;
1843
2132
  if (c == "\"" || c == "'") {
1844
2133
  const end = skipString(s, i);
1845
2134
  if (end == -1)
@@ -1904,6 +2193,92 @@ function clickableText(source, ctx) {
1904
2193
  result = withHookName.substring(0, at) + `|${hook}>[${text}]` + withHookName.substring(at + text.length);
1905
2194
  }
1906
2195
  }
2196
+ // A string, number or boolean written as it is, or undefined for anything else
2197
+ function literal(arg) {
2198
+ if (arg === undefined)
2199
+ return undefined;
2200
+ const a = arg.trim();
2201
+ if (/^["']/.test(a) && skipString(a, 0) == a.length)
2202
+ return unescapeString(a);
2203
+ if (/^-?(\d+\.?\d*|\.\d+)$/.test(a))
2204
+ return Number(a);
2205
+ if (/^(true|false)$/i.test(a))
2206
+ return a.toLowerCase() == "true";
2207
+ return undefined;
2208
+ }
2209
+ // The special passages of the Harlowe Audio Library, which aren't part of the story
2210
+ export const harloweAudioPassages = new Set(["hal.tracks", "hal.config"]);
2211
+ // The story's tracks, from the Harlowe Audio Library's hal.tracks passage ("name: file") and
2212
+ // (newtrack:), and the ones (track:) sets to loop
2213
+ export function harloweAudio(story) {
2214
+ return story.cached("harlowe-audio", () => {
2215
+ const audio = { files: new Map(), looping: new Set() };
2216
+ const definitions = story.twine.passages.find(p => p.name == "hal.tracks")?.text ?? "";
2217
+ for (const line of definitions.split(/\r?\n/)) {
2218
+ // The name ends at the first colon: the files can be web addresses
2219
+ const colon = line.indexOf(":");
2220
+ if (colon == -1)
2221
+ continue;
2222
+ const name = line.substring(0, colon).trim();
2223
+ const file = pickSource(line.substring(colon + 1).split(",").map(f => f.trim()).filter(f => f));
2224
+ if (name && file && !audio.files.has(name))
2225
+ audio.files.set(name, file);
2226
+ }
2227
+ for (const p of story.twine.passages) {
2228
+ for (const m of p.text.matchAll(/\((new-?track|track):/gi)) {
2229
+ const end = skipBalanced(p.text, m.index, "(", ")");
2230
+ if (end == -1)
2231
+ continue;
2232
+ const args = splitArgs(p.text.substring(m.index + m[0].length, end - 1)).map(literal);
2233
+ if (typeof args[0] != "string")
2234
+ continue;
2235
+ if (m[1].toLowerCase() == "track") {
2236
+ if (typeof args[1] == "string" && args[1].toLowerCase() == "loop" && args[2] === true)
2237
+ audio.looping.add(args[0]);
2238
+ }
2239
+ else {
2240
+ const file = pickSource(args.slice(1).filter((a) => typeof a == "string"));
2241
+ if (file && !audio.files.has(args[0]))
2242
+ audio.files.set(args[0], file);
2243
+ }
2244
+ }
2245
+ }
2246
+ return audio;
2247
+ });
2248
+ }
2249
+ // The story's custom macros (#450): (set: $name to (macro: str-type _who, [ ... ])). Each becomes
2250
+ // a section, named before anything's converted so calls know where they go, with its parameters
2251
+ // as the attributes the body's temporary variables become. A macro with a parameter that takes
2252
+ // any number of values (...) isn't one of them, and stays unconverted.
2253
+ export function harloweMacros(story) {
2254
+ return story.cached("harlowe-macros", () => {
2255
+ const result = new Map();
2256
+ for (const p of story.twine.passages) {
2257
+ for (const m of p.text.matchAll(/\$(\w+)\s+to\s+(?=\(macro:)/gi)) {
2258
+ if (result.has(m[1]))
2259
+ continue;
2260
+ const start = m.index + m[0].length;
2261
+ const end = skipBalanced(p.text, start, "(", ")");
2262
+ if (end == -1)
2263
+ continue;
2264
+ const args = splitArgs(p.text.substring(start + "(macro:".length, end - 1));
2265
+ const hook = args.pop()?.trim();
2266
+ if (!hook?.startsWith("[") || !hook.endsWith("]"))
2267
+ continue;
2268
+ const params = args.map(a => /^\s*(?:[\w-]+-type\s+)?_(\w+)\s*$/.exec(a)?.[1]);
2269
+ if (params.some(name => !name))
2270
+ continue;
2271
+ result.set(m[1], {
2272
+ section: story.uniqueSectionName(`macro ${m[1]}`),
2273
+ params: params.map(name => story.attribute(name, true)),
2274
+ body: hook.substring(1, hook.length - 1),
2275
+ defined: false,
2276
+ });
2277
+ }
2278
+ }
2279
+ return result;
2280
+ });
2281
+ }
1907
2282
  export function convertHarlowePassage(text, ctx) {
1908
2283
  // A backslash at the end or start of a line joins it to the next or previous line
1909
2284
  const source = clickableText(text.replace(/\\\n/g, "").replace(/\n\\/g, ""), ctx);