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
  // 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";
8
- import { dynamicSectionLink, escapeText, isUrl, urlLink, passageLink, sectionLink, setter } from "./convert.js";
7
+ import { delayValue, display, isDynamicTarget, isListCall, lengthOf, member as memberOf, print, quote, randomInteger, skipString, targetName, 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
  const containers = new Set([
10
11
  "if", "for", "switch", "link", "button", "linkreplace", "linkappend", "linkprepend", "nobr", "silently", "capture",
11
12
  "script", "timed", "repeat", "widget", "cycle", "listbox", "append", "prepend", "replace", "type", "done", "do",
@@ -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;
@@ -129,14 +137,11 @@ class Parser {
129
137
  continue;
130
138
  }
131
139
  }
132
- const scriptMatch = /^<(script|style)\b/i.exec(rest);
133
- if (scriptMatch) {
134
- const closeTag = `</${scriptMatch[1].toLowerCase()}>`;
135
- const end = src.toLowerCase().indexOf(closeTag, i);
136
- const stop = end == -1 ? src.length : end + closeTag.length;
140
+ const html = readHtmlBlock(src, i);
141
+ if (html) {
137
142
  flush();
138
- 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.` });
139
- i = stop;
143
+ nodes.push(html.block);
144
+ i = html.end;
140
145
  continue;
141
146
  }
142
147
  const image = /^\[[<>]?img\[(?:([^|\]]*)\|)?([^\]]*)\](?:\[([^\]]*)\])?\]/i.exec(rest);
@@ -304,11 +309,21 @@ export class SugarCubeExpressions {
304
309
  writable: true,
305
310
  value: ctx
306
311
  });
312
+ // Whether a container widget's body is being converted
313
+ Object.defineProperty(this, "inContainerWidget", {
314
+ enumerable: true,
315
+ configurable: true,
316
+ writable: true,
317
+ value: false
318
+ });
307
319
  }
308
320
  attribute(name, temp) {
309
321
  return this.ctx.story.attribute(name, temp);
310
322
  }
311
323
  variable(name, temp) {
324
+ // Inside a container widget, the text its call wraps (#450)
325
+ if (temp && name == "contents" && this.inContainerWidget)
326
+ return { k: "call", fn: "content", args: [] };
312
327
  return this.ctx.story.variable(name, temp);
313
328
  }
314
329
  parse(source) {
@@ -357,6 +372,19 @@ export class SugarCubeExpressions {
357
372
  return { expr: e };
358
373
  }
359
374
  }
375
+ // A comparison, where x.indexOf(y) compared with -1 or 0 to see whether y is there is x contains y
376
+ // (#446). Anything else .indexOf() is for can't be converted: see print().
377
+ function indexOfCheck(left, op, right) {
378
+ if (left.k != "call" || left.fn != "__indexof")
379
+ return { k: "bin", op, l: left, r: right };
380
+ const n = right.k == "num" ? right.v : right.k == "neg" && right.e.k == "num" ? -right.e.v : null;
381
+ const contains = { k: "bin", op: "contains", l: left.args[0], r: left.args[1] };
382
+ if ((n == -1 && (op == "!=" || op == ">")) || (n == 0 && op == ">="))
383
+ return contains;
384
+ if ((n == -1 && (op == "=" || op == "<=")) || (n == 0 && op == "<"))
385
+ return { k: "not", e: contains };
386
+ return { k: "bin", op, l: left, r: right };
387
+ }
360
388
  class ExpressionParser {
361
389
  constructor(s, tokens) {
362
390
  Object.defineProperty(this, "s", {
@@ -372,35 +400,20 @@ class ExpressionParser {
372
400
  value: tokens
373
401
  });
374
402
  }
403
+ // Including test ? a : b (#446), which is right-associative
375
404
  expression() {
376
- const e = this.or();
377
- if (this.tokens.is("?"))
378
- throw new Unconvertible("the ? : operator");
379
- return e;
405
+ const test = this.or();
406
+ if (!this.tokens.accept("?"))
407
+ return test;
408
+ const then = this.expression();
409
+ this.tokens.expect(":");
410
+ return { k: "cond", test, then, otherwise: this.expression() };
380
411
  }
381
- // Objects are flattened, so $player to { hp: 10 } sets player_hp
382
412
  statement() {
383
413
  const target = this.postfixValue();
384
414
  if (target.v == "expr" && target.e.k == "loop")
385
415
  throw new Unconvertible("changing a loop's variable inside the loop");
386
- const t = this.tokens.peek();
387
- if (target.v == "expr" && target.e.k == "var" && t?.text == "=") {
388
- const start = this.tokens.pos;
389
- this.tokens.next();
390
- const value = this.postfixOrObject();
391
- if (value.v == "object")
392
- return this.flatten(target.e.name, value);
393
- this.tokens.pos = start;
394
- }
395
- return [this.singleStatement(target, t)];
396
- }
397
- flatten(name, object) {
398
- return object.entries.flatMap(([key, value]) => {
399
- const attribute = `${name}_${key}`;
400
- if (value.v == "object")
401
- return this.flatten(attribute, value);
402
- return [{ kind: "set", name: attribute, value: this.toExpr(value) }];
403
- });
416
+ return [this.singleStatement(target, this.tokens.peek())];
404
417
  }
405
418
  // An object literal, or an ordinary expression
406
419
  postfixOrObject() {
@@ -409,8 +422,9 @@ class ExpressionParser {
409
422
  return { v: "expr", e: this.expression() };
410
423
  }
411
424
  singleStatement(target, t) {
412
- if (target.v == "expr" && target.e.k == "var") {
413
- const name = target.e.name;
425
+ // An attribute, or a value inside one, such as hero.hp or inventory[i].name (#442)
426
+ const name = target.v == "expr" ? targetName(target.e) : null;
427
+ if (name !== null) {
414
428
  if (t?.text == "++" || t?.text == "--") {
415
429
  this.tokens.next();
416
430
  return { kind: t.text == "++" ? "inc" : "dec", name, value: { k: "num", v: 1 } };
@@ -428,7 +442,7 @@ class ExpressionParser {
428
442
  case "/=": return { kind: "set", name, value, op: t.text };
429
443
  }
430
444
  // $x to $x + 1
431
- if (value.k == "bin" && (value.op == "+" || value.op == "-") && value.l.k == "var" && value.l.name == name) {
445
+ if (value.k == "bin" && (value.op == "+" || value.op == "-") && targetName(value.l) == name) {
432
446
  if (value.r.k == "array")
433
447
  return this.arrayChange(value.op == "+" ? "append" : "remove", name, value.r);
434
448
  if (value.r.k == "num" || value.op == "-")
@@ -471,11 +485,11 @@ class ExpressionParser {
471
485
  const t = this.tokens.peek()?.text;
472
486
  if (t == "==" || t == "===") {
473
487
  this.tokens.next();
474
- left = { k: "bin", op: "=", l: left, r: this.relational() };
488
+ left = indexOfCheck(left, "=", this.relational());
475
489
  }
476
490
  else if (t == "!=" || t == "!==") {
477
491
  this.tokens.next();
478
- left = { k: "bin", op: "!=", l: left, r: this.relational() };
492
+ left = indexOfCheck(left, "!=", this.relational());
479
493
  }
480
494
  else if (t == "=") {
481
495
  throw new Unconvertible("an assignment (=) in a condition");
@@ -491,7 +505,7 @@ class ExpressionParser {
491
505
  const t = this.tokens.peek()?.text;
492
506
  if (t == ">" || t == "<" || t == ">=" || t == "<=") {
493
507
  this.tokens.next();
494
- left = { k: "bin", op: t, l: left, r: this.additive() };
508
+ left = indexOfCheck(left, t, this.additive());
495
509
  }
496
510
  else {
497
511
  return left;
@@ -545,10 +559,11 @@ class ExpressionParser {
545
559
  if (v.v == "expr")
546
560
  return v.e;
547
561
  if (v.v == "object")
548
- throw new Unconvertible("a JavaScript object, other than one set to a variable");
562
+ return { k: "object", entries: v.entries.map(([key, value]) => [key, this.toExpr(value)]) };
549
563
  if (v.v == "member") {
564
+ // A list's or text's length (#446)
550
565
  if (v.property == "length")
551
- return { k: "call", fn: "length", args: [this.collection(v.object)] };
566
+ return lengthOf(this.toExpr(v.object));
552
567
  throw new Unconvertible(`properties of variables (.${v.property})`);
553
568
  }
554
569
  throw new Unconvertible(`"${v.name}"`);
@@ -557,7 +572,8 @@ class ExpressionParser {
557
572
  collection(v) {
558
573
  if (v.v == "expr" && v.e.k == "var")
559
574
  return { k: "str", v: v.e.name };
560
- if (v.v == "expr" && v.e.k == "array")
575
+ // A list inside an object, e.g. $hero.items
576
+ if (v.v == "expr" && (v.e.k == "array" || v.e.k == "member" || (v.e.k == "loop" && v.e.kind == "item")))
561
577
  return v.e;
562
578
  throw new Unconvertible("an array method on something other than a variable");
563
579
  }
@@ -568,9 +584,9 @@ class ExpressionParser {
568
584
  const property = this.tokens.next();
569
585
  if (property.type != "ident")
570
586
  throw new Unconvertible("an expression Squiffy can't read");
571
- // An object's property, which is its own attribute: $player.hp is player_hp
572
- if (value.v == "expr" && value.e.k == "var" && !this.tokens.is("(") && property.text != "length") {
573
- value = { v: "expr", e: { k: "var", name: `${value.e.name}_${property.text}` } };
587
+ // A value inside an object: $player.hp is player.hp (#442)
588
+ if (value.v == "expr" && value.e.k != "array" && value.e.k != "call" && !this.tokens.is("(") && property.text != "length") {
589
+ value = { v: "expr", e: memberOf(value.e, { k: "str", v: property.text }) };
574
590
  continue;
575
591
  }
576
592
  value = this.member(value, property.text);
@@ -579,24 +595,16 @@ class ExpressionParser {
579
595
  this.tokens.next();
580
596
  const index = this.expression();
581
597
  this.tokens.expect("]");
582
- // A widget's arguments, which a call to it puts in args_0, args_1 and so on
583
598
  if (value.v == "expr" && value.e.k == "var" && index.k == "loop" && index.kind == "index" && index.array == value.e.name) {
584
599
  value = { v: "expr", e: { k: "loop", kind: "item", up: index.up } };
585
600
  continue;
586
601
  }
587
- if (value.v == "expr" && value.e.k == "var" && value.e.name == "args" && index.k == "num") {
588
- value = { v: "expr", e: { k: "var", name: `args_${index.v}` } };
602
+ // A value inside an object or list, e.g. $inventory[_i] or $player["hp"] (#442)
603
+ if (value.v == "expr") {
604
+ value = { v: "expr", e: memberOf(value.e, index) };
589
605
  continue;
590
606
  }
591
- if (value.v == "expr" && value.e.k == "var" && index.k == "str" && /^[A-Za-z_]\w*$/.test(index.v)) {
592
- value = { v: "expr", e: { k: "var", name: `${value.e.name}_${index.v}` } };
593
- continue;
594
- }
595
- if (value.v == "expr" && (value.e.k == "var" || value.e.k == "array") && index.k == "num") {
596
- value = { v: "expr", e: { k: "call", fn: "lookup", args: [value.e, index] } };
597
- continue;
598
- }
599
- throw new Unconvertible("array indexes and object properties ([...])");
607
+ throw new Unconvertible("array indexes and object properties ([...]) of something other than a value");
600
608
  }
601
609
  else if (this.tokens.is("(")) {
602
610
  this.tokens.next();
@@ -624,6 +632,9 @@ class ExpressionParser {
624
632
  return { v: "expr", e: { k: "var", name: this.s.attribute(property, false) } };
625
633
  if (object.name == "State.temporary" || object.name == "temporary")
626
634
  return { v: "expr", e: this.s.variable(property, true) };
635
+ // The player's settings (#452), which Squiffy reads the same way
636
+ if (object.name == "settings")
637
+ return { v: "expr", e: memberOf({ k: "var", name: "settings" }, { k: "str", v: property }) };
627
638
  return { v: "global", name: path };
628
639
  }
629
640
  return { v: "member", object, property };
@@ -658,6 +669,19 @@ class ExpressionParser {
658
669
  case "tags":
659
670
  // Only as tags().includes("tag")
660
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 };
661
685
  case "Number":
662
686
  case "String":
663
687
  case "parseInt":
@@ -682,16 +706,63 @@ class ExpressionParser {
682
706
  }
683
707
  if (callee.v == "member") {
684
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
+ };
685
714
  switch (callee.property) {
715
+ // A list or text that has a value in it (#446)
686
716
  case "includes":
687
717
  case "contains":
688
718
  if (args.length != 1)
689
719
  throw new Unconvertible(`.${callee.property}() with more than one value`);
690
- 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()] };
691
739
  case "random":
692
740
  if (callee.object.v == "expr")
693
741
  return { k: "call", fn: "random", args: [callee.object.e] };
694
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]] };
695
766
  case "push":
696
767
  case "pushUnique":
697
768
  case "delete": {
@@ -823,6 +894,13 @@ class Writer {
823
894
  writable: true,
824
895
  value: void 0
825
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
+ });
826
904
  // Element ids targeted by <<replace>> and friends, which become labels
827
905
  Object.defineProperty(this, "targets", {
828
906
  enumerable: true,
@@ -832,6 +910,7 @@ class Writer {
832
910
  });
833
911
  this.expr = new SugarCubeExpressions(ctx);
834
912
  this.widgets = sugarCubeWidgets(ctx.story);
913
+ this.containerWidgets = sugarCubeContainerWidgets(ctx.story);
835
914
  }
836
915
  // A widget passage: each <<widget>> in it, converted to a section
837
916
  widgetSections(nodes) {
@@ -843,25 +922,29 @@ class Writer {
843
922
  const section = name ? this.widgets.get(name) : undefined;
844
923
  if (!section)
845
924
  continue;
846
- if (/\bcontainer\b/.test(n.args))
847
- 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.");
848
925
  // An embedded section's directives don't run, so everything is a helper
849
926
  const state = { leading: false, directives: [], nobr: false };
850
927
  this.open.clear();
851
928
  this.atLineStart = true;
852
- 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
+ }
853
937
  for (const tag of [...this.open].reverse())
854
938
  body += `</${tag}>`;
855
939
  result.push({ section, converted: { directives: [], body } });
856
940
  }
857
941
  return result;
858
942
  }
859
- // A call to a widget: its arguments go in attributes _args_0, _args_1 and so on, then the
860
- // widget's section is embedded
861
- widgetCall(m, section) {
862
- if (m.clauses)
863
- throw new Unconvertible(`the <<${m.name}>> container widget`);
864
- 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 => {
865
948
  let value;
866
949
  try {
867
950
  value = /^[^"'`$_[(\-\d\s][^\s]*$/.test(a) && !["true", "false", "null"].includes(a) ? { k: "str", v: a } : this.expr.parse(a);
@@ -869,9 +952,17 @@ class Writer {
869
952
  catch {
870
953
  value = { k: "str", v: a };
871
954
  }
872
- return `{{set "args_${n}" ${print(value)}}}`;
955
+ return value;
873
956
  });
874
- 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}}}`;
875
966
  }
876
967
  // Finds the ids that <<replace "#id">> and friends change, so they can be labels
877
968
  findTargets(source) {
@@ -888,6 +979,7 @@ class Writer {
888
979
  }
889
980
  passage(nodes, nobr) {
890
981
  const state = { leading: true, directives: [], nobr };
982
+ nodes = topScripts(this.ctx, nodes, state.directives);
891
983
  let body = this.nodes(nodes, state);
892
984
  for (const tag of [...this.open].reverse())
893
985
  body += `</${tag}>`;
@@ -914,6 +1006,8 @@ class Writer {
914
1006
  return node.s;
915
1007
  case "comment":
916
1008
  return this.ctx.unconvertible(node.text, node.reason);
1009
+ case "html":
1010
+ return passageHtmlBlock(this.ctx, node, false).text;
917
1011
  case "var":
918
1012
  state.leading = false;
919
1013
  try {
@@ -986,7 +1080,7 @@ class Writer {
986
1080
  });
987
1081
  }
988
1082
  inlineText(text) {
989
- const nodes = new Parser(text).parse(0).nodes;
1083
+ const nodes = new Parser(text, this.containerWidgets).parse(0).nodes;
990
1084
  return this.nodes(nodes, { leading: false, directives: [], nobr: true }).replace(/\n/g, " ");
991
1085
  }
992
1086
  text(s, state) {
@@ -1097,6 +1191,79 @@ class Writer {
1097
1191
  return null;
1098
1192
  }
1099
1193
  // ---- Macros ----
1194
+ // <<audio "tracks" actions>>
1195
+ audio(m, args) {
1196
+ const tracks = args[0] && /^["']/.test(args[0]) ? unescapeString(args[0]) : null;
1197
+ if (tracks === null)
1198
+ throw new Unconvertible("<<audio>> with tracks that aren't fixed");
1199
+ const action = { play: false, stop: false, loop: false };
1200
+ const num = (i) => {
1201
+ const raw = args[i] && /^["']/.test(args[i]) ? unescapeString(args[i]) : args[i];
1202
+ const n = Number(raw);
1203
+ if (raw === undefined || raw.trim() === "" || isNaN(n))
1204
+ throw new Unconvertible(`<<audio>> with "${args[i - 1]}" and a value that isn't a fixed number`);
1205
+ return n;
1206
+ };
1207
+ for (let i = 1; i < args.length; i++) {
1208
+ const word = args[i].toLowerCase();
1209
+ switch (word) {
1210
+ case "play":
1211
+ case "fadein":
1212
+ action.play = true;
1213
+ break;
1214
+ case "stop":
1215
+ case "fadeout":
1216
+ action.stop = true;
1217
+ break;
1218
+ case "loop":
1219
+ action.loop = true;
1220
+ break;
1221
+ case "unloop":
1222
+ break;
1223
+ case "volume":
1224
+ action.volume = num(++i);
1225
+ break;
1226
+ case "fadeoverto":
1227
+ case "fadeto": {
1228
+ if (word == "fadeoverto")
1229
+ action.fade = num(++i);
1230
+ const level = num(++i);
1231
+ if (level > 0)
1232
+ action.play = true;
1233
+ else
1234
+ action.stop = true;
1235
+ break;
1236
+ }
1237
+ case "pause":
1238
+ throw new Unconvertible("pausing a track");
1239
+ case "mute":
1240
+ case "unmute":
1241
+ throw new Unconvertible("muting a track");
1242
+ case "time":
1243
+ throw new Unconvertible("playing a track from part of the way through");
1244
+ case "goto":
1245
+ throw new Unconvertible("<<audio>> with goto");
1246
+ default:
1247
+ throw new Unconvertible(`<<audio>> with "${args[i]}"`);
1248
+ }
1249
+ }
1250
+ const audio = sugarCubeAudio(this.ctx.story);
1251
+ const ids = tracks.split(/\s+/).filter(t => t);
1252
+ const results = new Set();
1253
+ for (const id of ids) {
1254
+ if (id.startsWith(":")) {
1255
+ // A group: only stopping it can be converted. Looped tracks are music.
1256
+ if (!action.stop || !/^:(all|playing|looped)$/.test(id))
1257
+ throw new Unconvertible("audio groups");
1258
+ if (id != ":looped")
1259
+ results.add("{{stopsounds}}");
1260
+ results.add(`{{stopmusic${action.fade === undefined ? "" : ` fade=${action.fade}`}}}`);
1261
+ continue;
1262
+ }
1263
+ results.add(audioHelper(this.ctx, m.raw, audio, id, action));
1264
+ }
1265
+ return [...results].join("");
1266
+ }
1100
1267
  macro(m, state) {
1101
1268
  try {
1102
1269
  return this.macroOrThrow(m, state);
@@ -1213,20 +1380,29 @@ class Writer {
1213
1380
  return this.nodes(m.clauses[0].nodes, state);
1214
1381
  case "timed": {
1215
1382
  state.leading = false;
1216
- let delay = 0;
1383
+ // Each <<next>> waits after the one before, for its own delay, or, with none, the
1384
+ // delay before it. A delay can be worked out as the story runs (#451).
1385
+ let delay = { k: "num", v: 0 };
1386
+ // The time since the text was shown, while every delay is a number
1387
+ let total = 0;
1217
1388
  let out = "";
1218
- for (const c of m.clauses) {
1389
+ m.clauses.forEach((c, i) => {
1219
1390
  const d = splitMacroArgs(c.args)[0];
1220
- const ms = d ? this.expr.parse(d) : { k: "num", v: 0 };
1221
- if (ms.k != "num")
1222
- throw new Unconvertible("<<timed>> with a delay that isn't fixed");
1223
- delay += ms.v;
1391
+ if (d)
1392
+ delay = this.expr.parse(d);
1393
+ total = total !== null && delay.k == "num" ? total + delay.v : null;
1224
1394
  const goto = this.gotoOnly(c.nodes);
1225
- if (goto)
1226
- out += goto.replace(/\}\}$/, ` after=${delay}}}`);
1227
- else
1228
- out += `{{#animate "fadeIn" start=${delay}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1229
- }
1395
+ if (goto) {
1396
+ // {{goto}} waits from when the text is shown, so it needs the delays added up
1397
+ if (i > 0 && total === null)
1398
+ throw new Unconvertible("<<goto>> in a <<next>> after a delay that isn't fixed");
1399
+ out += goto.replace(/\}\}$/, ` after=${i == 0 ? delayValue(delay) : total}}}`);
1400
+ }
1401
+ else {
1402
+ // Animations play one after another, so each waits after the one before
1403
+ out += `{{#animate "fadeIn" start=${delayValue(delay)}}}${this.nodes(c.nodes, { ...state, leading: false })}{{/animate}}`;
1404
+ }
1405
+ });
1230
1406
  return out;
1231
1407
  }
1232
1408
  case "type": {
@@ -1241,15 +1417,21 @@ class Writer {
1241
1417
  state.leading = false;
1242
1418
  const bound = this.receiver(args[0] ?? "");
1243
1419
  const defaultValue = args[1] ? this.expr.parse(args[1]) : null;
1244
- if (args.slice(2).some(a => a != "autofocus")) {
1245
- this.ctx.approximate(m.raw, "Squiffy's text boxes don't go to a passage when Enter is pressed.");
1420
+ // <<textbox>> and <<numberbox>> can go to a passage when Enter is pressed (#454)
1421
+ const passageArg = m.name == "textarea" ? undefined : args.slice(2).find(a => a != "autofocus");
1422
+ let goes = "";
1423
+ if (passageArg !== undefined) {
1424
+ const target = this.expr.passageName(passageArg);
1425
+ if (!("name" in target))
1426
+ throw new Unconvertible(`<<${m.name}>> going to a passage whose name isn't fixed`);
1427
+ goes = ` data-section="${escapeAttribute(this.sectionName(target.name, m.raw))}"`;
1246
1428
  }
1247
1429
  const value = defaultValue?.k == "str" || defaultValue?.k == "num" ? String(defaultValue.v) : null;
1248
1430
  const set = defaultValue ? `{{set "${bound}" ${print(defaultValue)}}}` : "";
1249
1431
  if (m.name == "textarea")
1250
1432
  return `${set}<textarea data-attribute="${bound}">${escapeText(escapeHtml(value ?? ""))}</textarea>`;
1251
1433
  const type = m.name == "numberbox" ? "number" : "text";
1252
- return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}>`;
1434
+ return `${set}<input type="${type}" data-attribute="${bound}"${value === null ? "" : ` value="${escapeAttribute(value)}"`}${goes}>`;
1253
1435
  }
1254
1436
  case "checkbox": {
1255
1437
  state.leading = false;
@@ -1312,30 +1494,59 @@ class Writer {
1312
1494
  if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1313
1495
  throw new Unconvertible("<<break>> and <<continue>>");
1314
1496
  const loop = this.forLoop(m.args);
1315
- const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state));
1316
- return `{{#each ${print(loop.collection)}}}${body}{{/each}}`;
1497
+ const numbers = loop.numbers || (loop.collection.k == "call" && loop.collection.fn == "range");
1498
+ const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state), numbers);
1499
+ const collection = print(loop.collection);
1500
+ return `{{#each ${loop.collection.k == "cond" ? `(${collection})` : collection}}}${body}{{/each}}`;
1317
1501
  }
1318
1502
  case "widget":
1319
1503
  return "";
1320
1504
  case "back":
1321
1505
  case "return":
1322
- throw new Unconvertible(`<<${m.name}>>. Squiffy has its own Back button`);
1506
+ // Left out on purpose (#445): a screen the player visits and leaves is a panel in Squiffy
1507
+ throw new Unconvertible(`<<${m.name}>>. For a screen like an inventory, use a panel. Squiffy has its own Back button`);
1323
1508
  case "audio":
1509
+ return leadingAudio(this.audio(m, args), state);
1324
1510
  case "cacheaudio":
1325
- case "playlist":
1326
- case "masteraudio":
1327
1511
  case "waitforaudio":
1512
+ // The tracks are found before the story's converted, and Squiffy loads every
1513
+ // sound file when the story starts
1514
+ return "";
1515
+ case "masteraudio":
1516
+ if (args.length == 1 && args[0].toLowerCase() == "stop")
1517
+ return leadingAudio(STOP_ALL_AUDIO, state);
1518
+ throw new Unconvertible("<<masteraudio>>, which changes all the story's sound at once, except to stop it");
1519
+ case "playlist":
1328
1520
  case "createplaylist":
1329
- case "createaudiogroup":
1521
+ case "removeplaylist":
1330
1522
  case "track":
1331
- throw new Unconvertible("audio macros");
1523
+ throw new Unconvertible("playlists");
1524
+ case "createaudiogroup":
1525
+ case "removeaudiogroup":
1526
+ throw new Unconvertible("audio groups");
1332
1527
  case "addclass":
1333
1528
  case "removeclass":
1334
- case "toggleclass":
1335
- throw new Unconvertible("macros that change elements' classes");
1336
- case "repeat":
1337
- throw new Unconvertible("<<repeat>>, which runs again and again");
1529
+ case "toggleclass": {
1530
+ // On the page (#449), which in Squiffy is the story's element. Classes on other
1531
+ // elements can't be converted.
1532
+ if (!/^["'](?:html|body|#story|#passages)["']$/i.test(args[0] ?? "")) {
1533
+ throw new Unconvertible(`<<${m.name}>> on something other than the page ("body")`);
1534
+ }
1535
+ if (args.length != 2)
1536
+ throw new Unconvertible(`<<${m.name}>> without one class to change`);
1537
+ state.leading = false;
1538
+ return `{{${m.name} ${print(this.expr.parse(args[1]))}}}`;
1539
+ }
1540
+ case "repeat": {
1541
+ // <<repeat 1s>>: its text is added again every second, until a <<stop>> (#451)
1542
+ state.leading = false;
1543
+ if (!args[0])
1544
+ throw new Unconvertible("<<repeat>> without a delay");
1545
+ const delay = delayValue(this.expr.parse(args[0]));
1546
+ return `{{#every ${delay} append=true}}${this.body(m, { ...state, leading: false })}{{/every}}`;
1547
+ }
1338
1548
  case "stop":
1549
+ return "{{stop}}";
1339
1550
  case "silent":
1340
1551
  return "";
1341
1552
  case "elseif":
@@ -1348,7 +1559,7 @@ class Writer {
1348
1559
  default:
1349
1560
  if (this.widgets.has(m.name)) {
1350
1561
  state.leading = false;
1351
- return this.widgetCall(m, this.widgets.get(m.name));
1562
+ return this.widgetCall(m, this.widgets.get(m.name), state);
1352
1563
  }
1353
1564
  if (!knownMacros.has(m.name))
1354
1565
  throw new Unconvertible(`the <<${m.name}>> macro, which isn't one of SugarCube's own: it's probably added by the story's JavaScript`);
@@ -1363,8 +1574,20 @@ class Writer {
1363
1574
  if (range) {
1364
1575
  const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1365
1576
  const collection = this.expr.parse(range[3]);
1366
- if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item")) {
1367
- throw new Unconvertible("<<for>> with range over something other than an array");
1577
+ // A number, <<for _i range 5>>, goes through 0 to 4, with the same number as the item
1578
+ // and its position. A calculation must be a number, but an attribute could be a list.
1579
+ if (collection.k == "num" || collection.k == "neg" || (collection.k == "bin" && "+-*/%".includes(collection.op))) {
1580
+ const zero = { k: "num", v: 0 };
1581
+ const last = collection.k == "num" ? { k: "num", v: collection.v - 1 } : { k: "bin", op: "-", l: collection, r: { k: "num", v: 1 } };
1582
+ const numbers = { k: "call", fn: "range", args: [zero, last] };
1583
+ // (range 0 -1) would count down, so there's nothing to go through unless it's above 0
1584
+ const counted = collection.k == "num"
1585
+ ? (collection.v > 0 ? numbers : { k: "array", items: [] })
1586
+ : { k: "cond", test: { k: "bin", op: ">", l: collection, r: zero }, then: numbers, otherwise: { k: "array", items: [] } };
1587
+ return { collection: counted, vars: new Map([...vars.keys()].map(v => [v, "item"])), numbers: true };
1588
+ }
1589
+ if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item") && !isListCall(collection)) {
1590
+ throw new Unconvertible("<<for>> with range over something other than an array or a number");
1368
1591
  }
1369
1592
  // With a position as well, $list[_i] is the item too
1370
1593
  return { collection, vars, array: collection.k == "var" ? collection.name : undefined };
@@ -1374,14 +1597,32 @@ class Writer {
1374
1597
  const array = this.expr.attribute(counted[3], counted[2] == "_");
1375
1598
  return { collection: { k: "var", name: array }, vars: new Map([["_" + counted[1], "index"]]), array };
1376
1599
  }
1377
- throw new Unconvertible("<<for>> loops, except ones that go through an array (with range, or from 0 to its length)");
1600
+ // Counting, <<for _i to 1; _i lte 5; _i++>>, goes through (range 1 5), with _i as the item (#447)
1601
+ 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);
1602
+ if (counting) {
1603
+ const from = this.expr.parse(counting[2]);
1604
+ const bound = this.expr.parse(counting[4]);
1605
+ const up = counting[5].includes("+");
1606
+ const op = { "lt": "<", "lte": "<=", "gt": ">", "gte": ">=" }[counting[3]] ?? counting[3];
1607
+ if (up != op.startsWith("<"))
1608
+ throw new Unconvertible("a <<for>> loop that counts away from where it stops");
1609
+ // < 5 counting up stops at 4, and > 0 counting down at 1
1610
+ const to = op.length == 2 ? bound
1611
+ : bound.k == "num" ? { k: "num", v: bound.v + (up ? -1 : 1) }
1612
+ : { k: "bin", op: up ? "-" : "+", l: bound, r: { k: "num", v: 1 } };
1613
+ return { collection: { k: "call", fn: "range", args: [from, to] }, vars: new Map([["_" + counting[1], "item"]]) };
1614
+ }
1615
+ throw new Unconvertible("<<for>> loops, except ones that go through an array (with range), or count up or down by 1");
1378
1616
  }
1379
- // The attribute a form macro like <<textbox "$name">> sets
1617
+ // The attribute a form macro like <<textbox "$name">> sets, or the value inside an object,
1618
+ // as in <<textbox "$hero.name">> (#454)
1380
1619
  receiver(arg) {
1381
- const match = /^["']([$_])([A-Za-z_]\w*)["']$/.exec(arg);
1382
- if (!match)
1383
- throw new Unconvertible("a form control that doesn't set a plain variable");
1384
- return this.expr.attribute(match[2], match[1] == "_");
1620
+ const match = /^(["'])([$_][\s\S]*)\1$/.exec(arg);
1621
+ const e = match ? this.expr.parse(match[2]) : null;
1622
+ if (e?.k != "var" || isDynamicTarget(e.name)) {
1623
+ throw new Unconvertible("a form control that doesn't set a variable, or a value inside one with a fixed name");
1624
+ }
1625
+ return e.name;
1385
1626
  }
1386
1627
  linkText(arg) {
1387
1628
  if (arg.startsWith("[[")) {
@@ -1419,6 +1660,18 @@ class Writer {
1419
1660
  }
1420
1661
  // <<link>>, <<button>>: the body runs when it's clicked, then the story goes to the passage
1421
1662
  // given, if there is one
1663
+ // "restart", "saves" or "settings", if a link's body is only <<run UI.restart()>>,
1664
+ // UI.saves() or UI.settings(), or the same in <<script>>
1665
+ uiAction(body) {
1666
+ if (body.length != 1 || body[0].t != "macro")
1667
+ return null;
1668
+ const m = body[0];
1669
+ const code = m.name == "run" ? m.args
1670
+ : m.name == "script" ? (m.clauses?.[0]?.nodes ?? []).map(n => n.t == "text" || n.t == "raw" ? n.s : "\0").join("")
1671
+ : null;
1672
+ const match = code === null ? null : /^\s*UI\.(restart|saves|settings)\(\s*\)\s*;?\s*$/.exec(code);
1673
+ return match ? match[1] : null;
1674
+ }
1422
1675
  linkMacro(m, args) {
1423
1676
  let text;
1424
1677
  let passage = null;
@@ -1459,6 +1712,12 @@ class Writer {
1459
1712
  const destination = gotoArg !== null ? this.expr.passageName(gotoArg)
1460
1713
  : passage !== null ? { name: passage }
1461
1714
  : dynamicDestination ? { expr: dynamicDestination } : null;
1715
+ // A link that only runs UI.restart(), UI.saves() or UI.settings(): {{restart}}, {{saves}}
1716
+ // or {{settings}} (#452). Like
1717
+ // SugarCube's, {{restart}} asks the player first.
1718
+ const uiAction = destination ? null : this.uiAction(significant);
1719
+ if (uiAction)
1720
+ return `{{${uiAction} text=${quote(text.plain)}}}`;
1462
1721
  // Only <<set>>s: a link with setters
1463
1722
  const bodySetters = this.bodySetters(significant);
1464
1723
  if (destination && bodySetters) {
@@ -1468,19 +1727,22 @@ class Writer {
1468
1727
  return dynamicSectionLink(text.plain, destination.expr, all);
1469
1728
  }
1470
1729
  const state = { leading: true, directives: [], nobr: false };
1471
- const content = this.nodes(body, state);
1472
- const directives = [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives];
1730
+ // In a loop, the body can use the loop's item, which the link sets an attribute to (#448)
1731
+ const { result: [content, directives], setters: loopSetters } = this.ctx.story.linkBody(() => {
1732
+ const content = this.nodes(body, state);
1733
+ return [content, [...(setterSource === null ? [] : this.setters(setterSource, false).map(s => `@set ${s}`)), ...state.directives]];
1734
+ });
1473
1735
  if (destination) {
1474
1736
  // Run the body in a section of its own, which then goes on to the passage
1475
1737
  const goto = gotoArg !== null ? "" : "\n" + ("name" in destination
1476
1738
  ? `{{goto ${print({ k: "str", v: this.sectionName(destination.name, m.raw) })}}}`
1477
1739
  : `{{goto ${print(destination.expr)}}}`);
1478
- const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives, body: content + goto });
1479
- return sectionLink(text.squiffy, section);
1740
+ const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives: [...directives], body: content + goto });
1741
+ return sectionLink(text.squiffy, section, loopSetters);
1480
1742
  }
1481
1743
  // Stays in this passage: a passage link, whose passage does what the body does
1482
- const name = this.ctx.addPassage(text.plain, { directives, body: content });
1483
- return passageLink(text.squiffy, name);
1744
+ const name = this.ctx.addPassage(text.plain, { directives: [...directives], body: content });
1745
+ return passageLink(text.squiffy, name, loopSetters);
1484
1746
  }
1485
1747
  // The setters for nodes that are only <<set>>s, or null
1486
1748
  bodySetters(nodes) {
@@ -1510,7 +1772,7 @@ class Writer {
1510
1772
  case "inc":
1511
1773
  case "dec": {
1512
1774
  const amount = s.value.k == "num" && Number.isInteger(s.value.v) && s.value.v >= 0 ? s.value.v : null;
1513
- state.directives.push(amount === null
1775
+ state.directives.push(amount === null || isDynamicTarget(s.name)
1514
1776
  ? `@set ${setter(s.name, s.kind == "inc" ? "+=" : "-=", s.value, false)}`
1515
1777
  : `@${s.kind} ${s.name}${amount == 1 ? "" : " " + amount}`);
1516
1778
  continue;
@@ -1521,6 +1783,8 @@ class Writer {
1521
1783
  }
1522
1784
  }
1523
1785
  state.leading = false;
1786
+ if (isDynamicTarget(s.name))
1787
+ throw new Unconvertible("setting a value inside an object or list, by a variable's value, after the start of the passage");
1524
1788
  const name = print({ k: "str", v: s.name });
1525
1789
  switch (s.kind) {
1526
1790
  case "set":
@@ -1552,6 +1816,36 @@ const knownMacros = new Set([
1552
1816
  "createaudiogroup", "createplaylist", "masteraudio", "playlist", "removeaudiogroup", "removeplaylist",
1553
1817
  "waitforaudio", "done", "goto", "repeat", "stop", "timed", "widget", "display", "click", "do", "redo", "track",
1554
1818
  ]);
1819
+ // The story's tracks: the files <<cacheaudio>> gives them, and the ones <<audio>> sets to loop
1820
+ export function sugarCubeAudio(story) {
1821
+ return story.cached("sugarcube-audio", () => {
1822
+ const audio = { files: new Map(), looping: new Set() };
1823
+ const strings = (args) => splitMacroArgs(args).filter(a => /^["']/.test(a)).map(unescapeString);
1824
+ for (const p of story.twine.passages) {
1825
+ for (const m of p.text.matchAll(/<<\s*cacheaudio\s+([\s\S]*?)>>/g)) {
1826
+ const [track, ...sources] = strings(m[1]);
1827
+ // A source can say its format first: "mp3|music/theme.mp3"
1828
+ const file = pickSource(sources.map(s => s.replace(/^\w+\|/, "")));
1829
+ if (track && file && !audio.files.has(track))
1830
+ audio.files.set(track, file);
1831
+ }
1832
+ for (const m of p.text.matchAll(/<<\s*audio\s+([\s\S]*?)>>/g)) {
1833
+ const args = splitMacroArgs(m[1]);
1834
+ if (!args.slice(1).some(a => a.toLowerCase() == "loop") || !/^["']/.test(args[0] ?? ""))
1835
+ continue;
1836
+ for (const track of unescapeString(args[0]).split(/\s+/))
1837
+ if (track)
1838
+ audio.looping.add(track);
1839
+ }
1840
+ }
1841
+ // Tracks added in the story's JavaScript
1842
+ for (const m of story.twine.script.matchAll(/SimpleAudio\.tracks\.add\(\s*(["'])([^"']+)\1\s*,\s*(["'])([^"']+)\3/g)) {
1843
+ if (!audio.files.has(m[2]))
1844
+ audio.files.set(m[2], m[4].replace(/^\w+\|/, ""));
1845
+ }
1846
+ return audio;
1847
+ });
1848
+ }
1555
1849
  // The story's widgets, by name, with the section each is converted to
1556
1850
  export function sugarCubeWidgets(story) {
1557
1851
  return story.cached("sugarcube-widgets", () => {
@@ -1568,9 +1862,39 @@ export function sugarCubeWidgets(story) {
1568
1862
  return result;
1569
1863
  });
1570
1864
  }
1865
+ // The story's widgets that use _args (#450)
1866
+ function sugarCubeWidgetsUsingArgs(story) {
1867
+ return story.cached("sugarcube-widgets-using-args", () => {
1868
+ const result = new Set();
1869
+ for (const p of story.twine.passages) {
1870
+ if (!p.tags.includes("widget"))
1871
+ continue;
1872
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)["']?[^>]*>>([\s\S]*?)<<\/widget>>/g)) {
1873
+ if (/\b_args\b/.test(m[2]))
1874
+ result.add(m[1].toLowerCase());
1875
+ }
1876
+ }
1877
+ return result;
1878
+ });
1879
+ }
1880
+ // The story's container widgets (#450), <<widget "name" container>>, whose calls wrap text
1881
+ function sugarCubeContainerWidgets(story) {
1882
+ return story.cached("sugarcube-container-widgets", () => {
1883
+ const result = new Set();
1884
+ for (const p of story.twine.passages) {
1885
+ if (!p.tags.includes("widget"))
1886
+ continue;
1887
+ for (const m of p.text.matchAll(/<<widget\s+["']?([\w-]+)["']?([^>]*)>>/g)) {
1888
+ if (/\bcontainer\b/.test(m[2]))
1889
+ result.add(m[1].toLowerCase());
1890
+ }
1891
+ }
1892
+ return result;
1893
+ });
1894
+ }
1571
1895
  export function convertSugarCubeWidgets(text, ctx) {
1572
1896
  const writer = new Writer(ctx);
1573
- const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, ""))).parse(0).nodes;
1897
+ const nodes = new Parser(writer.findTargets(text.replace(/\\\r?\n/g, "")), writer.containerWidgets).parse(0).nodes;
1574
1898
  return writer.widgetSections(nodes);
1575
1899
  }
1576
1900
  function cssAttributes(spec) {
@@ -1616,6 +1940,6 @@ export function convertSugarCubePassage(text, ctx) {
1616
1940
  const writer = new Writer(ctx);
1617
1941
  // A backslash at the end of a line joins it to the next
1618
1942
  const source = writer.findTargets(text.replace(/\\\r?\n/g, ""));
1619
- const nodes = new Parser(source).parse(0).nodes;
1943
+ const nodes = new Parser(source, writer.containerWidgets).parse(0).nodes;
1620
1944
  return writer.passage(nodes, ctx.passage.tags.includes("nobr"));
1621
1945
  }