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

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 (47) hide show
  1. package/README.md +10 -2
  2. package/dist/analyse.d.ts +6 -0
  3. package/dist/analyse.js +101 -11
  4. package/dist/compiler.d.ts +9 -2
  5. package/dist/compiler.js +5 -2
  6. package/dist/css-urls.d.ts +4 -0
  7. package/dist/css-urls.js +59 -0
  8. package/dist/emit.d.ts +13 -0
  9. package/dist/emit.js +45 -1
  10. package/dist/language-service.d.ts +1 -0
  11. package/dist/language-service.js +39 -13
  12. package/dist/node.d.ts +7 -1
  13. package/dist/node.js +16 -5
  14. package/dist/parse.d.ts +3 -0
  15. package/dist/parse.js +25 -2
  16. package/dist/project.d.ts +56 -0
  17. package/dist/project.js +148 -15
  18. package/dist/quest/aslx.d.ts +50 -0
  19. package/dist/quest/aslx.js +181 -0
  20. package/dist/quest/convert.d.ts +20 -0
  21. package/dist/quest/convert.js +504 -0
  22. package/dist/quest/script.d.ts +92 -0
  23. package/dist/quest/script.js +453 -0
  24. package/dist/quest/scripts.d.ts +24 -0
  25. package/dist/quest/scripts.js +505 -0
  26. package/dist/quest/text.d.ts +17 -0
  27. package/dist/quest/text.js +305 -0
  28. package/dist/setters.d.ts +4 -0
  29. package/dist/setters.js +10 -5
  30. package/dist/story-graph.d.ts +2 -1
  31. package/dist/story-graph.js +2 -0
  32. package/dist/syntax.d.ts +27 -2
  33. package/dist/text.d.ts +2 -0
  34. package/dist/text.js +24 -15
  35. package/dist/twine/audio.d.ts +21 -0
  36. package/dist/twine/audio.js +80 -0
  37. package/dist/twine/convert.d.ts +15 -1
  38. package/dist/twine/convert.js +217 -21
  39. package/dist/twine/expression.d.ts +26 -1
  40. package/dist/twine/expression.js +111 -6
  41. package/dist/twine/harlowe.d.ts +10 -0
  42. package/dist/twine/harlowe.js +417 -58
  43. package/dist/twine/sugarcube.d.ts +4 -0
  44. package/dist/twine/sugarcube.js +388 -86
  45. package/dist/v5.js +2 -1
  46. package/package.json +3 -2
  47. package/syntaxes/squiffy.tmLanguage.json +9 -4
@@ -4,7 +4,8 @@
4
4
  // such as <<if>>...<</if>>), links and naked variables, which is then written out as Squiffy:
5
5
  // <<if>> becomes {{#if}}, <<set>> becomes @set or {{set}}, links with setters become links with
6
6
  // setters, and <<link>> and friends become links to generated passages and sections.
7
- import { display, print, randomInteger, skipString, Tokens, Unconvertible, unescapeString } from "./expression.js";
7
+ import { display, isDynamicTarget, isListCall, lengthOf, member as memberOf, print, randomInteger, skipString, targetName, Tokens, Unconvertible, unescapeString } from "./expression.js";
8
+ import { audioHelper, leadingAudio, pickSource, STOP_ALL_AUDIO } from "./audio.js";
8
9
  import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
9
10
  const containers = new Set([
10
11
  "if", "for", "switch", "link", "button", "linkreplace", "linkappend", "linkprepend", "nobr", "silently", "capture",
@@ -20,13 +21,20 @@ const childMacros = {
20
21
  repeat: [],
21
22
  };
22
23
  class Parser {
23
- constructor(src) {
24
+ // The story's container widgets (#450), whose calls wrap text like <<say "Ann">>Hi<</say>>
25
+ constructor(src, containerWidgets = new Set()) {
24
26
  Object.defineProperty(this, "src", {
25
27
  enumerable: true,
26
28
  configurable: true,
27
29
  writable: true,
28
30
  value: src
29
31
  });
32
+ Object.defineProperty(this, "containerWidgets", {
33
+ enumerable: true,
34
+ configurable: true,
35
+ writable: true,
36
+ value: containerWidgets
37
+ });
30
38
  }
31
39
  // Parses until the end, or until the end of the container, or one of its child macros
32
40
  parse(start, container) {
@@ -63,7 +71,7 @@ class Parser {
63
71
  return { nodes, end: macro.end, stop: { name, args, raw: macro.raw, close: false } };
64
72
  }
65
73
  flush();
66
- if (containers.has(name)) {
74
+ if (containers.has(name) || this.containerWidgets.has(name)) {
67
75
  const node = { t: "macro", name, args, raw: macro.raw, clauses: [] };
68
76
  let clause = { name, args, raw: macro.raw, nodes: [] };
69
77
  let j = macro.end;
@@ -304,10 +312,23 @@ export class SugarCubeExpressions {
304
312
  writable: true,
305
313
  value: ctx
306
314
  });
315
+ // Whether a container widget's body is being converted
316
+ Object.defineProperty(this, "inContainerWidget", {
317
+ enumerable: true,
318
+ configurable: true,
319
+ writable: true,
320
+ value: false
321
+ });
307
322
  }
308
323
  attribute(name, temp) {
309
324
  return this.ctx.story.attribute(name, temp);
310
325
  }
326
+ variable(name, temp) {
327
+ // Inside a container widget, the text its call wraps (#450)
328
+ if (temp && name == "contents" && this.inContainerWidget)
329
+ return { k: "call", fn: "content", args: [] };
330
+ return this.ctx.story.variable(name, temp);
331
+ }
311
332
  parse(source) {
312
333
  const tokens = new Tokens(tokenize(source));
313
334
  const e = new ExpressionParser(this, tokens).expression();
@@ -354,6 +375,19 @@ export class SugarCubeExpressions {
354
375
  return { expr: e };
355
376
  }
356
377
  }
378
+ // A comparison, where x.indexOf(y) compared with -1 or 0 to see whether y is there is x contains y
379
+ // (#446). Anything else .indexOf() is for can't be converted: see print().
380
+ function indexOfCheck(left, op, right) {
381
+ if (left.k != "call" || left.fn != "__indexof")
382
+ return { k: "bin", op, l: left, r: right };
383
+ const n = right.k == "num" ? right.v : right.k == "neg" && right.e.k == "num" ? -right.e.v : null;
384
+ const contains = { k: "bin", op: "contains", l: left.args[0], r: left.args[1] };
385
+ if ((n == -1 && (op == "!=" || op == ">")) || (n == 0 && op == ">="))
386
+ return contains;
387
+ if ((n == -1 && (op == "=" || op == "<=")) || (n == 0 && op == "<"))
388
+ return { k: "not", e: contains };
389
+ return { k: "bin", op, l: left, r: right };
390
+ }
357
391
  class ExpressionParser {
358
392
  constructor(s, tokens) {
359
393
  Object.defineProperty(this, "s", {
@@ -369,33 +403,20 @@ class ExpressionParser {
369
403
  value: tokens
370
404
  });
371
405
  }
406
+ // Including test ? a : b (#446), which is right-associative
372
407
  expression() {
373
- const e = this.or();
374
- if (this.tokens.is("?"))
375
- throw new Unconvertible("the ? : operator");
376
- return e;
408
+ const test = this.or();
409
+ if (!this.tokens.accept("?"))
410
+ return test;
411
+ const then = this.expression();
412
+ this.tokens.expect(":");
413
+ return { k: "cond", test, then, otherwise: this.expression() };
377
414
  }
378
- // Objects are flattened, so $player to { hp: 10 } sets player_hp
379
415
  statement() {
380
416
  const target = this.postfixValue();
381
- const t = this.tokens.peek();
382
- if (target.v == "expr" && target.e.k == "var" && t?.text == "=") {
383
- const start = this.tokens.pos;
384
- this.tokens.next();
385
- const value = this.postfixOrObject();
386
- if (value.v == "object")
387
- return this.flatten(target.e.name, value);
388
- this.tokens.pos = start;
389
- }
390
- return [this.singleStatement(target, t)];
391
- }
392
- flatten(name, object) {
393
- return object.entries.flatMap(([key, value]) => {
394
- const attribute = `${name}_${key}`;
395
- if (value.v == "object")
396
- return this.flatten(attribute, value);
397
- return [{ kind: "set", name: attribute, value: this.toExpr(value) }];
398
- });
417
+ if (target.v == "expr" && target.e.k == "loop")
418
+ throw new Unconvertible("changing a loop's variable inside the loop");
419
+ return [this.singleStatement(target, this.tokens.peek())];
399
420
  }
400
421
  // An object literal, or an ordinary expression
401
422
  postfixOrObject() {
@@ -404,8 +425,9 @@ class ExpressionParser {
404
425
  return { v: "expr", e: this.expression() };
405
426
  }
406
427
  singleStatement(target, t) {
407
- if (target.v == "expr" && target.e.k == "var") {
408
- const name = target.e.name;
428
+ // An attribute, or a value inside one, such as hero.hp or inventory[i].name (#442)
429
+ const name = target.v == "expr" ? targetName(target.e) : null;
430
+ if (name !== null) {
409
431
  if (t?.text == "++" || t?.text == "--") {
410
432
  this.tokens.next();
411
433
  return { kind: t.text == "++" ? "inc" : "dec", name, value: { k: "num", v: 1 } };
@@ -423,7 +445,7 @@ class ExpressionParser {
423
445
  case "/=": return { kind: "set", name, value, op: t.text };
424
446
  }
425
447
  // $x to $x + 1
426
- if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
448
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && targetName(value.l) == name) {
427
449
  if (value.r.k == "array")
428
450
  return this.arrayChange(value.op == "+" ? "append" : "remove", name, value.r);
429
451
  if (value.r.k == "num" || value.op == "-")
@@ -466,11 +488,11 @@ class ExpressionParser {
466
488
  const t = this.tokens.peek()?.text;
467
489
  if (t == "==" || t == "===") {
468
490
  this.tokens.next();
469
- left = { k: "bin", op: "=", l: left, r: this.relational() };
491
+ left = indexOfCheck(left, "=", this.relational());
470
492
  }
471
493
  else if (t == "!=" || t == "!==") {
472
494
  this.tokens.next();
473
- left = { k: "bin", op: "!=", l: left, r: this.relational() };
495
+ left = indexOfCheck(left, "!=", this.relational());
474
496
  }
475
497
  else if (t == "=") {
476
498
  throw new Unconvertible("an assignment (=) in a condition");
@@ -486,7 +508,7 @@ class ExpressionParser {
486
508
  const t = this.tokens.peek()?.text;
487
509
  if (t == ">" || t == "<" || t == ">=" || t == "<=") {
488
510
  this.tokens.next();
489
- left = { k: "bin", op: t, l: left, r: this.additive() };
511
+ left = indexOfCheck(left, t, this.additive());
490
512
  }
491
513
  else {
492
514
  return left;
@@ -540,10 +562,11 @@ class ExpressionParser {
540
562
  if (v.v == "expr")
541
563
  return v.e;
542
564
  if (v.v == "object")
543
- throw new Unconvertible("a JavaScript object, other than one set to a variable");
565
+ return { k: "object", entries: v.entries.map(([key, value]) => [key, this.toExpr(value)]) };
544
566
  if (v.v == "member") {
567
+ // A list's or text's length (#446)
545
568
  if (v.property == "length")
546
- return { k: "call", fn: "length", args: [this.collection(v.object)] };
569
+ return lengthOf(this.toExpr(v.object));
547
570
  throw new Unconvertible(`properties of variables (.${v.property})`);
548
571
  }
549
572
  throw new Unconvertible(`"${v.name}"`);
@@ -552,7 +575,8 @@ class ExpressionParser {
552
575
  collection(v) {
553
576
  if (v.v == "expr" && v.e.k == "var")
554
577
  return { k: "str", v: v.e.name };
555
- if (v.v == "expr" && v.e.k == "array")
578
+ // A list inside an object, e.g. $hero.items
579
+ if (v.v == "expr" && (v.e.k == "array" || v.e.k == "member" || (v.e.k == "loop" && v.e.kind == "item")))
556
580
  return v.e;
557
581
  throw new Unconvertible("an array method on something other than a variable");
558
582
  }
@@ -563,9 +587,9 @@ class ExpressionParser {
563
587
  const property = this.tokens.next();
564
588
  if (property.type != "ident")
565
589
  throw new Unconvertible("an expression Squiffy can't read");
566
- // An object's property, which is its own attribute: $player.hp is player_hp
567
- if (value.v == "expr" && value.e.k == "var" && !this.tokens.is("(") && property.text != "length") {
568
- value = { v: "expr", e: { k: "var", name: `${value.e.name}_${property.text}` } };
590
+ // A value inside an object: $player.hp is player.hp (#442)
591
+ if (value.v == "expr" && value.e.k != "array" && value.e.k != "call" && !this.tokens.is("(") && property.text != "length") {
592
+ value = { v: "expr", e: memberOf(value.e, { k: "str", v: property.text }) };
569
593
  continue;
570
594
  }
571
595
  value = this.member(value, property.text);
@@ -574,20 +598,16 @@ class ExpressionParser {
574
598
  this.tokens.next();
575
599
  const index = this.expression();
576
600
  this.tokens.expect("]");
577
- // A widget's arguments, which a call to it puts in args_0, args_1 and so on
578
- if (value.v == "expr" && value.e.k == "var" && value.e.name == "args" && index.k == "num") {
579
- value = { v: "expr", e: { k: "var", name: `args_${index.v}` } };
580
- continue;
581
- }
582
- if (value.v == "expr" && value.e.k == "var" && index.k == "str" && /^[A-Za-z_]\w*$/.test(index.v)) {
583
- value = { v: "expr", e: { k: "var", name: `${value.e.name}_${index.v}` } };
601
+ if (value.v == "expr" && value.e.k == "var" && index.k == "loop" && index.kind == "index" && index.array == value.e.name) {
602
+ value = { v: "expr", e: { k: "loop", kind: "item", up: index.up } };
584
603
  continue;
585
604
  }
586
- if (value.v == "expr" && (value.e.k == "var" || value.e.k == "array") && index.k == "num") {
587
- value = { v: "expr", e: { k: "call", fn: "lookup", args: [value.e, index] } };
605
+ // A value inside an object or list, e.g. $inventory[_i] or $player["hp"] (#442)
606
+ if (value.v == "expr") {
607
+ value = { v: "expr", e: memberOf(value.e, index) };
588
608
  continue;
589
609
  }
590
- throw new Unconvertible("array indexes and object properties ([...])");
610
+ throw new Unconvertible("array indexes and object properties ([...]) of something other than a value");
591
611
  }
592
612
  else if (this.tokens.is("(")) {
593
613
  this.tokens.next();
@@ -614,7 +634,7 @@ class ExpressionParser {
614
634
  if (object.name == "State.variables" || object.name == "variables")
615
635
  return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
616
636
  if (object.name == "State.temporary" || object.name == "temporary")
617
- return { v: "expr", e: { k: "var", name: this.s.attribute(property, true) } };
637
+ return { v: "expr", e: this.s.variable(property, true) };
618
638
  return { v: "global", name: path };
619
639
  }
620
640
  return { v: "member", object, property };
@@ -649,6 +669,19 @@ class ExpressionParser {
649
669
  case "tags":
650
670
  // Only as tags().includes("tag")
651
671
  return { k: "call", fn: "__tags", args: [] };
672
+ // Numbers (#446)
673
+ case "Math.round":
674
+ case "Math.floor":
675
+ case "Math.ceil":
676
+ case "Math.abs":
677
+ if (args.length != 1)
678
+ throw new Unconvertible(`${callee.name}() with ${args.length ? "more than one value" : "no value"}`);
679
+ return { k: "call", fn: callee.name.substring(5), args };
680
+ case "Math.min":
681
+ case "Math.max":
682
+ if (!args.length)
683
+ throw new Unconvertible(`${callee.name}() with no values`);
684
+ return { k: "call", fn: callee.name.substring(5), args };
652
685
  case "Number":
653
686
  case "String":
654
687
  case "parseInt":
@@ -673,16 +706,63 @@ class ExpressionParser {
673
706
  }
674
707
  if (callee.v == "member") {
675
708
  const collection = () => this.collection(callee.object);
709
+ const value = () => this.toExpr(callee.object);
710
+ const noArguments = () => {
711
+ if (args.length)
712
+ throw new Unconvertible(`.${callee.property}() with a value`);
713
+ };
676
714
  switch (callee.property) {
715
+ // A list or text that has a value in it (#446)
677
716
  case "includes":
678
717
  case "contains":
679
718
  if (args.length != 1)
680
719
  throw new Unconvertible(`.${callee.property}() with more than one value`);
681
- return { k: "call", fn: "contains", args: [collection(), args[0]] };
720
+ return { k: "bin", op: "contains", l: value(), r: args[0] };
721
+ // Only to check whether something is there, e.g. .indexOf(x) != -1: see indexOfCheck
722
+ case "indexOf":
723
+ if (args.length != 1)
724
+ throw new Unconvertible(`.${callee.property}() with more than one value`);
725
+ return { k: "call", fn: "__indexof", args: [value(), args[0]] };
726
+ // Text (#446)
727
+ case "toLowerCase":
728
+ case "toLocaleLowerCase":
729
+ noArguments();
730
+ return { k: "call", fn: "lower", args: [value()] };
731
+ case "toUpperCase":
732
+ case "toLocaleUpperCase":
733
+ noArguments();
734
+ return { k: "call", fn: "upper", args: [value()] };
735
+ case "toUpperFirst":
736
+ case "toLocaleUpperFirst":
737
+ noArguments();
738
+ return { k: "call", fn: "capitalise", args: [value()] };
682
739
  case "random":
683
740
  if (callee.object.v == "expr")
684
741
  return { k: "call", fn: "random", args: [callee.object.e] };
685
742
  break;
743
+ // Lists (#447). JavaScript's .join() puts a comma with no space between the items.
744
+ case "join":
745
+ if (args.length > 1)
746
+ throw new Unconvertible(".join() with more than one value");
747
+ return { k: "call", fn: "join", args: [value(), args[0] ?? { k: "str", v: "," }] };
748
+ case "sort":
749
+ case "shuffle":
750
+ // Squiffy's give back a new list, and leave the attribute as it was
751
+ if (args.length)
752
+ throw new Unconvertible(`.${callee.property}() with a function to compare the items`);
753
+ return { k: "call", fn: callee.property, args: [value()] };
754
+ case "slice":
755
+ if (args.length > 2)
756
+ throw new Unconvertible(".slice() with more than two values");
757
+ return { k: "call", fn: "slice", args: [value(), args[0] ?? { k: "num", v: 0 }, ...args.slice(1)] };
758
+ case "first":
759
+ case "last":
760
+ noArguments();
761
+ return { k: "call", fn: callee.property, args: [value()] };
762
+ case "count":
763
+ if (args.length != 1)
764
+ throw new Unconvertible(".count() with a position to start from");
765
+ return { k: "call", fn: "count", args: [value(), args[0]] };
686
766
  case "push":
687
767
  case "pushUnique":
688
768
  case "delete": {
@@ -701,8 +781,8 @@ class ExpressionParser {
701
781
  switch (t.type) {
702
782
  case "str": return { v: "expr", e: { k: "str", v: t.value } };
703
783
  case "num": return { v: "expr", e: { k: "num", v: t.value } };
704
- case "var": return { v: "expr", e: { k: "var", name: this.s.attribute(t.value, false) } };
705
- case "temp": return { v: "expr", e: { k: "var", name: this.s.attribute(t.value, true) } };
784
+ case "var": return { v: "expr", e: this.s.variable(t.value, false) };
785
+ case "temp": return { v: "expr", e: this.s.variable(t.value, true) };
706
786
  case "ident":
707
787
  switch (t.text) {
708
788
  case "true": return { v: "expr", e: { k: "bool", v: true } };
@@ -814,6 +894,13 @@ class Writer {
814
894
  writable: true,
815
895
  value: void 0
816
896
  });
897
+ // The widgets whose calls wrap text (#450)
898
+ Object.defineProperty(this, "containerWidgets", {
899
+ enumerable: true,
900
+ configurable: true,
901
+ writable: true,
902
+ value: void 0
903
+ });
817
904
  // Element ids targeted by <<replace>> and friends, which become labels
818
905
  Object.defineProperty(this, "targets", {
819
906
  enumerable: true,
@@ -823,6 +910,7 @@ class Writer {
823
910
  });
824
911
  this.expr = new SugarCubeExpressions(ctx);
825
912
  this.widgets = sugarCubeWidgets(ctx.story);
913
+ this.containerWidgets = sugarCubeContainerWidgets(ctx.story);
826
914
  }
827
915
  // A widget passage: each <<widget>> in it, converted to a section
828
916
  widgetSections(nodes) {
@@ -834,25 +922,29 @@ class Writer {
834
922
  const section = name ? this.widgets.get(name) : undefined;
835
923
  if (!section)
836
924
  continue;
837
- if (/\bcontainer\b/.test(n.args))
838
- this.ctx.approximate(n.raw, "Container widgets (whose calls have text in them) can't be converted. Wherever the story uses one, it's been left as a comment.");
839
925
  // An embedded section's directives don't run, so everything is a helper
840
926
  const state = { leading: false, directives: [], nobr: false };
841
927
  this.open.clear();
842
928
  this.atLineStart = true;
843
- let body = this.nodes(n.clauses?.[0]?.nodes ?? [], state);
929
+ this.expr.inContainerWidget = this.containerWidgets.has(name);
930
+ let body;
931
+ try {
932
+ body = this.nodes(n.clauses?.[0]?.nodes ?? [], state);
933
+ }
934
+ finally {
935
+ this.expr.inContainerWidget = false;
936
+ }
844
937
  for (const tag of [...this.open].reverse())
845
938
  body += `</${tag}>`;
846
939
  result.push({ section, converted: { directives: [], body } });
847
940
  }
848
941
  return result;
849
942
  }
850
- // A call to a widget: its arguments go in attributes _args_0, _args_1 and so on, then the
851
- // widget's section is embedded
852
- widgetCall(m, section) {
853
- if (m.clauses)
854
- throw new Unconvertible(`the <<${m.name}>> container widget`);
855
- const sets = splitMacroArgs(m.args).map((a, n) => {
943
+ // A call to a widget embeds the widget's section, with its arguments as the parameter args, a
944
+ // list, as _args is in SugarCube. A container widget's call wraps text, which the widget shows
945
+ // as _contents (#450).
946
+ widgetCall(m, section, state) {
947
+ const items = splitMacroArgs(m.args).map(a => {
856
948
  let value;
857
949
  try {
858
950
  value = /^[^"'`$_[(\-\d\s][^\s]*$/.test(a) && !["true", "false", "null"].includes(a) ? { k: "str", v: a } : this.expr.parse(a);
@@ -860,9 +952,17 @@ class Writer {
860
952
  catch {
861
953
  value = { k: "str", v: a };
862
954
  }
863
- return `{{set "args_${n}" ${print(value)}}}`;
955
+ return value;
864
956
  });
865
- return sets.join("") + `{{embed ${print({ k: "str", v: section })}}}`;
957
+ // With no arguments, an empty list, so that a widget that changes _args doesn't change
958
+ // the story's attribute
959
+ const params = items.length || sugarCubeWidgetsUsingArgs(this.ctx.story).has(m.name)
960
+ ? ` ${this.expr.attribute("args", true)}=${print({ k: "array", items })}`
961
+ : "";
962
+ const name = print({ k: "str", v: section });
963
+ if (m.clauses)
964
+ return `{{#embed ${name}${params}}}${this.body(m, state)}{{/embed}}`;
965
+ return `{{embed ${name}${params}}}`;
866
966
  }
867
967
  // Finds the ids that <<replace "#id">> and friends change, so they can be labels
868
968
  findTargets(source) {
@@ -977,7 +1077,7 @@ class Writer {
977
1077
  });
978
1078
  }
979
1079
  inlineText(text) {
980
- const nodes = new Parser(text).parse(0).nodes;
1080
+ const nodes = new Parser(text, this.containerWidgets).parse(0).nodes;
981
1081
  return this.nodes(nodes, { leading: false, directives: [], nobr: true }).replace(/\n/g, " ");
982
1082
  }
983
1083
  text(s, state) {
@@ -1088,6 +1188,79 @@ class Writer {
1088
1188
  return null;
1089
1189
  }
1090
1190
  // ---- Macros ----
1191
+ // <<audio "tracks" actions>>
1192
+ audio(m, args) {
1193
+ const tracks = args[0] && /^["']/.test(args[0]) ? unescapeString(args[0]) : null;
1194
+ if (tracks === null)
1195
+ throw new Unconvertible("<<audio>> with tracks that aren't fixed");
1196
+ const action = { play: false, stop: false, loop: false };
1197
+ const num = (i) => {
1198
+ const raw = args[i] && /^["']/.test(args[i]) ? unescapeString(args[i]) : args[i];
1199
+ const n = Number(raw);
1200
+ if (raw === undefined || raw.trim() === "" || isNaN(n))
1201
+ throw new Unconvertible(`<<audio>> with "${args[i - 1]}" and a value that isn't a fixed number`);
1202
+ return n;
1203
+ };
1204
+ for (let i = 1; i < args.length; i++) {
1205
+ const word = args[i].toLowerCase();
1206
+ switch (word) {
1207
+ case "play":
1208
+ case "fadein":
1209
+ action.play = true;
1210
+ break;
1211
+ case "stop":
1212
+ case "fadeout":
1213
+ action.stop = true;
1214
+ break;
1215
+ case "loop":
1216
+ action.loop = true;
1217
+ break;
1218
+ case "unloop":
1219
+ break;
1220
+ case "volume":
1221
+ action.volume = num(++i);
1222
+ break;
1223
+ case "fadeoverto":
1224
+ case "fadeto": {
1225
+ if (word == "fadeoverto")
1226
+ action.fade = num(++i);
1227
+ const level = num(++i);
1228
+ if (level > 0)
1229
+ action.play = true;
1230
+ else
1231
+ action.stop = true;
1232
+ break;
1233
+ }
1234
+ case "pause":
1235
+ throw new Unconvertible("pausing a track");
1236
+ case "mute":
1237
+ case "unmute":
1238
+ throw new Unconvertible("muting a track");
1239
+ case "time":
1240
+ throw new Unconvertible("playing a track from part of the way through");
1241
+ case "goto":
1242
+ throw new Unconvertible("<<audio>> with goto");
1243
+ default:
1244
+ throw new Unconvertible(`<<audio>> with "${args[i]}"`);
1245
+ }
1246
+ }
1247
+ const audio = sugarCubeAudio(this.ctx.story);
1248
+ const ids = tracks.split(/\s+/).filter(t => t);
1249
+ const results = new Set();
1250
+ for (const id of ids) {
1251
+ if (id.startsWith(":")) {
1252
+ // A group: only stopping it can be converted. Looped tracks are music.
1253
+ if (!action.stop || !/^:(all|playing|looped)$/.test(id))
1254
+ throw new Unconvertible("audio groups");
1255
+ if (id != ":looped")
1256
+ results.add("{{stopsounds}}");
1257
+ results.add(`{{stopmusic${action.fade === undefined ? "" : ` fade=${action.fade}`}}}`);
1258
+ continue;
1259
+ }
1260
+ results.add(audioHelper(this.ctx, m.raw, audio, id, action));
1261
+ }
1262
+ return [...results].join("");
1263
+ }
1091
1264
  macro(m, state) {
1092
1265
  try {
1093
1266
  return this.macroOrThrow(m, state);
@@ -1298,26 +1471,53 @@ class Writer {
1298
1471
  }
1299
1472
  case "script":
1300
1473
  throw new Unconvertible("<<script>>, which runs SugarCube JavaScript");
1301
- case "for":
1302
- throw new Unconvertible("<<for>> loops");
1474
+ case "for": {
1475
+ state.leading = false;
1476
+ if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1477
+ throw new Unconvertible("<<break>> and <<continue>>");
1478
+ const loop = this.forLoop(m.args);
1479
+ const numbers = loop.collection.k == "call" && loop.collection.fn == "range";
1480
+ const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state), numbers);
1481
+ return `{{#each ${print(loop.collection)}}}${body}{{/each}}`;
1482
+ }
1303
1483
  case "widget":
1304
1484
  return "";
1305
1485
  case "back":
1306
1486
  case "return":
1307
- throw new Unconvertible(`<<${m.name}>>. Squiffy has its own Back button`);
1487
+ // Left out on purpose (#445): a screen the player visits and leaves is a panel in Squiffy
1488
+ throw new Unconvertible(`<<${m.name}>>. For a screen like an inventory, use a panel. Squiffy has its own Back button`);
1308
1489
  case "audio":
1490
+ return leadingAudio(this.audio(m, args), state);
1309
1491
  case "cacheaudio":
1310
- case "playlist":
1311
- case "masteraudio":
1312
1492
  case "waitforaudio":
1493
+ // The tracks are found before the story's converted, and Squiffy loads every
1494
+ // sound file when the story starts
1495
+ return "";
1496
+ case "masteraudio":
1497
+ if (args.length == 1 && args[0].toLowerCase() == "stop")
1498
+ return leadingAudio(STOP_ALL_AUDIO, state);
1499
+ throw new Unconvertible("<<masteraudio>>, which changes all the story's sound at once, except to stop it");
1500
+ case "playlist":
1313
1501
  case "createplaylist":
1314
- case "createaudiogroup":
1502
+ case "removeplaylist":
1315
1503
  case "track":
1316
- throw new Unconvertible("audio macros");
1504
+ throw new Unconvertible("playlists");
1505
+ case "createaudiogroup":
1506
+ case "removeaudiogroup":
1507
+ throw new Unconvertible("audio groups");
1317
1508
  case "addclass":
1318
1509
  case "removeclass":
1319
- case "toggleclass":
1320
- throw new Unconvertible("macros that change elements' classes");
1510
+ case "toggleclass": {
1511
+ // On the page (#449), which in Squiffy is the story's element. Classes on other
1512
+ // elements can't be converted.
1513
+ if (!/^["'](?:html|body|#story|#passages)["']$/i.test(args[0] ?? "")) {
1514
+ throw new Unconvertible(`<<${m.name}>> on something other than the page ("body")`);
1515
+ }
1516
+ if (args.length != 2)
1517
+ throw new Unconvertible(`<<${m.name}>> without one class to change`);
1518
+ state.leading = false;
1519
+ return `{{${m.name} ${print(this.expr.parse(args[1]))}}}`;
1520
+ }
1321
1521
  case "repeat":
1322
1522
  throw new Unconvertible("<<repeat>>, which runs again and again");
1323
1523
  case "stop":
@@ -1333,13 +1533,49 @@ class Writer {
1333
1533
  default:
1334
1534
  if (this.widgets.has(m.name)) {
1335
1535
  state.leading = false;
1336
- return this.widgetCall(m, this.widgets.get(m.name));
1536
+ return this.widgetCall(m, this.widgets.get(m.name), state);
1337
1537
  }
1338
1538
  if (!knownMacros.has(m.name))
1339
1539
  throw new Unconvertible(`the <<${m.name}>> macro, which isn't one of SugarCube's own: it's probably added by the story's JavaScript`);
1340
1540
  throw new Unconvertible(`the <<${m.name}>> macro, which Squiffy has no equivalent for`);
1341
1541
  }
1342
1542
  }
1543
+ // What a <<for>> goes through, as {{#each}} does, and the variables (with their $ or _) that
1544
+ // stand for its item and position. It can go through an array with range, or by position:
1545
+ // <<for _i to 0; _i lt $list.length; _i++>>. Either way, $list[_i] is the item.
1546
+ forLoop(args) {
1547
+ const range = /^\s*([$_][A-Za-z_]\w*)\s*(?:,\s*([$_][A-Za-z_]\w*)\s*)?\brange\b([\s\S]+)$/.exec(args);
1548
+ if (range) {
1549
+ const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1550
+ const collection = this.expr.parse(range[3]);
1551
+ if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item") && !isListCall(collection)) {
1552
+ throw new Unconvertible("<<for>> with range over something other than an array");
1553
+ }
1554
+ // With a position as well, $list[_i] is the item too
1555
+ return { collection, vars, array: collection.k == "var" ? collection.name : undefined };
1556
+ }
1557
+ const counted = /^\s*_([A-Za-z_]\w*)\s*(?:to|=)\s*0\s*;\s*_\1\s*(?:lt|<)\s*([$_])([A-Za-z_]\w*)\.length\s*;\s*(?:_\1\s*\+\+|\+\+\s*_\1|_\1\s*\+=\s*1)\s*$/.exec(args);
1558
+ if (counted) {
1559
+ const array = this.expr.attribute(counted[3], counted[2] == "_");
1560
+ return { collection: { k: "var", name: array }, vars: new Map([["_" + counted[1], "index"]]), array };
1561
+ }
1562
+ // Counting, <<for _i to 1; _i lte 5; _i++>>, goes through (range 1 5), with _i as the item (#447)
1563
+ const counting = /^\s*_([A-Za-z_]\w*)\s*(?:to|=)\s*([^;]+);\s*_\1\s*(lte|lt|gte|gt|<=|>=|<|>)\s*([^;]+);\s*(_\1\s*\+\+|\+\+\s*_\1|_\1\s*\+=\s*1|_\1\s*--|--\s*_\1|_\1\s*-=\s*1)\s*$/.exec(args);
1564
+ if (counting) {
1565
+ const from = this.expr.parse(counting[2]);
1566
+ const bound = this.expr.parse(counting[4]);
1567
+ const up = counting[5].includes("+");
1568
+ const op = { "lt": "<", "lte": "<=", "gt": ">", "gte": ">=" }[counting[3]] ?? counting[3];
1569
+ if (up != op.startsWith("<"))
1570
+ throw new Unconvertible("a <<for>> loop that counts away from where it stops");
1571
+ // < 5 counting up stops at 4, and > 0 counting down at 1
1572
+ const to = op.length == 2 ? bound
1573
+ : bound.k == "num" ? { k: "num", v: bound.v + (up ? -1 : 1) }
1574
+ : { k: "bin", op: up ? "-" : "+", l: bound, r: { k: "num", v: 1 } };
1575
+ return { collection: { k: "call", fn: "range", args: [from, to] }, vars: new Map([["_" + counting[1], "item"]]) };
1576
+ }
1577
+ throw new Unconvertible("<<for>> loops, except ones that go through an array (with range), or count up or down by 1");
1578
+ }
1343
1579
  // The attribute a form macro like <<textbox "$name">> sets
1344
1580
  receiver(arg) {
1345
1581
  const match = /^["']([$_])([A-Za-z_]\w*)["']$/.exec(arg);
@@ -1353,9 +1589,10 @@ class Writer {
1353
1589
  return { plain: node.text, squiffy: this.inlineText(node.text) };
1354
1590
  }
1355
1591
  const e = this.expr.parse(arg);
1356
- if (e.k != "str")
1357
- throw new Unconvertible("a link whose text isn't fixed");
1358
- return { plain: e.v, squiffy: this.inlineText(e.v) };
1592
+ if (e.k == "str")
1593
+ return { plain: e.v, squiffy: this.inlineText(e.v) };
1594
+ // Text worked out as the story runs, e.g. a loop's item: named after the expression
1595
+ return { plain: arg.replace(/[^\w\s]+/g, " ").trim() || "link", squiffy: display(e) };
1359
1596
  }
1360
1597
  sectionName(passage, raw) {
1361
1598
  const section = this.ctx.story.sectionFor(passage);
@@ -1431,19 +1668,22 @@ class Writer {
1431
1668
  return dynamicSectionLink(text.plain, destination.expr, all);
1432
1669
  }
1433
1670
  const state = { leading: true, directives: [], nobr: false };
1434
- const content = this.nodes(body, state);
1435
- const directives = [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives];
1671
+ // In a loop, the body can use the loop's item, which the link sets an attribute to (#448)
1672
+ const { result: [content, directives], setters: loopSetters } = this.ctx.story.linkBody(() => {
1673
+ const content = this.nodes(body, state);
1674
+ return [content, [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives]];
1675
+ });
1436
1676
  if (destination) {
1437
1677
  // Run the body in a section of its own, which then goes on to the passage
1438
1678
  const goto = gotoArg !== null ? "" : "\n" + ("name" in destination
1439
1679
  ? `{{goto ${print({ k: "str", v: this.sectionName(destination.name, m.raw) })}}}`
1440
1680
  : `{{goto ${print(destination.expr)}}}`);
1441
- const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives, body: content + goto });
1442
- return sectionLink(text.squiffy, section);
1681
+ const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives: [...directives], body: content + goto });
1682
+ return sectionLink(text.squiffy, section, loopSetters);
1443
1683
  }
1444
1684
  // Stays in this passage: a passage link, whose passage does what the body does
1445
- const name = this.ctx.addPassage(text.plain, { directives, body: content });
1446
- return passageLink(text.squiffy, name);
1685
+ const name = this.ctx.addPassage(text.plain, { directives: [...directives], body: content });
1686
+ return passageLink(text.squiffy, name, loopSetters);
1447
1687
  }
1448
1688
  // The setters for nodes that are only <<set>>s, or null
1449
1689
  bodySetters(nodes) {
@@ -1473,7 +1713,7 @@ class Writer {
1473
1713
  case "inc":
1474
1714
  case "dec": {
1475
1715
  const amount = s.value.k == "num" && Number.isInteger(s.value.v) && s.value.v >= 0 ? s.value.v : null;
1476
- state.directives.push(amount === null
1716
+ state.directives.push(amount === null || isDynamicTarget(s.name)
1477
1717
  ? `@set ${setter(s.name, s.kind == "inc" ? "+=" : "-=", s.value, false)}`
1478
1718
  : `@${s.kind} ${s.name}${amount == 1 ? "" : " " + amount}`);
1479
1719
  continue;
@@ -1484,6 +1724,8 @@ class Writer {
1484
1724
  }
1485
1725
  }
1486
1726
  state.leading = false;
1727
+ if (isDynamicTarget(s.name))
1728
+ throw new Unconvertible("setting a value inside an object or list, by a variable's value, after the start of the passage");
1487
1729
  const name = print({ k: "str", v: s.name });
1488
1730
  switch (s.kind) {
1489
1731
  case "set":
@@ -1515,6 +1757,36 @@ const knownMacros = new Set([
1515
1757
  "createaudiogroup", "createplaylist", "masteraudio", "playlist", "removeaudiogroup", "removeplaylist",
1516
1758
  "waitforaudio", "done", "goto", "repeat", "stop", "timed", "widget", "display", "click", "do", "redo", "track",
1517
1759
  ]);
1760
+ // The story's tracks: the files <<cacheaudio>> gives them, and the ones <<audio>> sets to loop
1761
+ export function sugarCubeAudio(story) {
1762
+ return story.cached("sugarcube-audio", () => {
1763
+ const audio = { files: new Map(), looping: new Set() };
1764
+ const strings = (args) => splitMacroArgs(args).filter(a => /^["']/.test(a)).map(unescapeString);
1765
+ for (const p of story.twine.passages) {
1766
+ for (const m of p.text.matchAll(/<<\s*cacheaudio\s+([\s\S]*?)>>/g)) {
1767
+ const [track, ...sources] = strings(m[1]);
1768
+ // A source can say its format first: "mp3|music/theme.mp3"
1769
+ const file = pickSource(sources.map(s => s.replace(/^\w+\|/, "")));
1770
+ if (track && file && !audio.files.has(track))
1771
+ audio.files.set(track, file);
1772
+ }
1773
+ for (const m of p.text.matchAll(/<<\s*audio\s+([\s\S]*?)>>/g)) {
1774
+ const args = splitMacroArgs(m[1]);
1775
+ if (!args.slice(1).some(a => a.toLowerCase() == "loop") || !/^["']/.test(args[0] ?? ""))
1776
+ continue;
1777
+ for (const track of unescapeString(args[0]).split(/\s+/))
1778
+ if (track)
1779
+ audio.looping.add(track);
1780
+ }
1781
+ }
1782
+ // Tracks added in the story's JavaScript
1783
+ for (const m of story.twine.script.matchAll(/SimpleAudio\.tracks\.add\(\s*(["'])([^"']+)\1\s*,\s*(["'])([^"']+)\3/g)) {
1784
+ if (!audio.files.has(m[2]))
1785
+ audio.files.set(m[2], m[4].replace(/^\w+\|/, ""));
1786
+ }
1787
+ return audio;
1788
+ });
1789
+ }
1518
1790
  // The story's widgets, by name, with the section each is converted to
1519
1791
  export function sugarCubeWidgets(story) {
1520
1792
  return story.cached("sugarcube-widgets", () => {
@@ -1531,9 +1803,39 @@ export function sugarCubeWidgets(story) {
1531
1803
  return result;
1532
1804
  });
1533
1805
  }
1806
+ // The story's widgets that use _args (#450)
1807
+ function sugarCubeWidgetsUsingArgs(story) {
1808
+ return story.cached("sugarcube-widgets-using-args", () => {
1809
+ const result = new Set();
1810
+ for (const p of story.twine.passages) {
1811
+ if (!p.tags.includes("widget"))
1812
+ continue;
1813
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)["']?[^>]*>>([\s\S]*?)<<\/widget>>/g)) {
1814
+ if (/\b_args\b/.test(m[2]))
1815
+ result.add(m[1].toLowerCase());
1816
+ }
1817
+ }
1818
+ return result;
1819
+ });
1820
+ }
1821
+ // The story's container widgets (#450), <<widget "name" container>>, whose calls wrap text
1822
+ function sugarCubeContainerWidgets(story) {
1823
+ return story.cached("sugarcube-container-widgets", () => {
1824
+ const result = new Set();
1825
+ for (const p of story.twine.passages) {
1826
+ if (!p.tags.includes("widget"))
1827
+ continue;
1828
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)["']?([^>]*)>>/g)) {
1829
+ if (/\bcontainer\b/.test(m[2]))
1830
+ result.add(m[1].toLowerCase());
1831
+ }
1832
+ }
1833
+ return result;
1834
+ });
1835
+ }
1534
1836
  export function convertSugarCubeWidgets(text, ctx) {
1535
1837
  const writer = new Writer(ctx);
1536
- const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, ""))).parse(0).nodes;
1838
+ const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, "")), writer.containerWidgets).parse(0).nodes;
1537
1839
  return writer.widgetSections(nodes);
1538
1840
  }
1539
1841
  function cssAttributes(spec) {
@@ -1579,6 +1881,6 @@ export function convertSugarCubePassage(text, ctx) {
1579
1881
  const writer = new Writer(ctx);
1580
1882
  // A backslash at the end of a line joins it to the next
1581
1883
  const source = writer.findTargets(text.replace(/\\\r?\n/g, ""));
1582
- const nodes = new Parser(source).parse(0).nodes;
1884
+ const nodes = new Parser(source, writer.containerWidgets).parse(0).nodes;
1583
1885
  return writer.passage(nodes, ctx.passage.tags.includes("nobr"));
1584
1886
  }