squiffy-compiler 7.0.0-beta.6 → 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.
@@ -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,11 +312,21 @@ 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
  }
311
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: [] };
312
330
  return this.ctx.story.variable(name, temp);
313
331
  }
314
332
  parse(source) {
@@ -357,6 +375,19 @@ export class SugarCubeExpressions {
357
375
  return { expr: e };
358
376
  }
359
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
+ }
360
391
  class ExpressionParser {
361
392
  constructor(s, tokens) {
362
393
  Object.defineProperty(this, "s", {
@@ -372,35 +403,20 @@ class ExpressionParser {
372
403
  value: tokens
373
404
  });
374
405
  }
406
+ // Including test ? a : b (#446), which is right-associative
375
407
  expression() {
376
- const e = this.or();
377
- if (this.tokens.is("?"))
378
- throw new Unconvertible("the ? : operator");
379
- 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() };
380
414
  }
381
- // Objects are flattened, so $player to { hp: 10 } sets player_hp
382
415
  statement() {
383
416
  const target = this.postfixValue();
384
417
  if (target.v == "expr" && target.e.k == "loop")
385
418
  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
- });
419
+ return [this.singleStatement(target, this.tokens.peek())];
404
420
  }
405
421
  // An object literal, or an ordinary expression
406
422
  postfixOrObject() {
@@ -409,8 +425,9 @@ class ExpressionParser {
409
425
  return { v: "expr", e: this.expression() };
410
426
  }
411
427
  singleStatement(target, t) {
412
- if (target.v == "expr" && target.e.k == "var") {
413
- 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) {
414
431
  if (t?.text == "++" || t?.text == "--") {
415
432
  this.tokens.next();
416
433
  return { kind: t.text == "++" ? "inc" : "dec", name, value: { k: "num", v: 1 } };
@@ -428,7 +445,7 @@ class ExpressionParser {
428
445
  case "/=": return { kind: "set", name, value, op: t.text };
429
446
  }
430
447
  // $x to $x + 1
431
- 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) {
432
449
  if (value.r.k == "array")
433
450
  return this.arrayChange(value.op == "+" ? "append" : "remove", name, value.r);
434
451
  if (value.r.k == "num" || value.op == "-")
@@ -471,11 +488,11 @@ class ExpressionParser {
471
488
  const t = this.tokens.peek()?.text;
472
489
  if (t == "==" || t == "===") {
473
490
  this.tokens.next();
474
- left = { k: "bin", op: "=", l: left, r: this.relational() };
491
+ left = indexOfCheck(left, "=", this.relational());
475
492
  }
476
493
  else if (t == "!=" || t == "!==") {
477
494
  this.tokens.next();
478
- left = { k: "bin", op: "!=", l: left, r: this.relational() };
495
+ left = indexOfCheck(left, "!=", this.relational());
479
496
  }
480
497
  else if (t == "=") {
481
498
  throw new Unconvertible("an assignment (=) in a condition");
@@ -491,7 +508,7 @@ class ExpressionParser {
491
508
  const t = this.tokens.peek()?.text;
492
509
  if (t == ">" || t == "<" || t == ">=" || t == "<=") {
493
510
  this.tokens.next();
494
- left = { k: "bin", op: t, l: left, r: this.additive() };
511
+ left = indexOfCheck(left, t, this.additive());
495
512
  }
496
513
  else {
497
514
  return left;
@@ -545,10 +562,11 @@ class ExpressionParser {
545
562
  if (v.v == "expr")
546
563
  return v.e;
547
564
  if (v.v == "object")
548
- 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)]) };
549
566
  if (v.v == "member") {
567
+ // A list's or text's length (#446)
550
568
  if (v.property == "length")
551
- return { k: "call", fn: "length", args: [this.collection(v.object)] };
569
+ return lengthOf(this.toExpr(v.object));
552
570
  throw new Unconvertible(`properties of variables (.${v.property})`);
553
571
  }
554
572
  throw new Unconvertible(`"${v.name}"`);
@@ -557,7 +575,8 @@ class ExpressionParser {
557
575
  collection(v) {
558
576
  if (v.v == "expr" && v.e.k == "var")
559
577
  return { k: "str", v: v.e.name };
560
- 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")))
561
580
  return v.e;
562
581
  throw new Unconvertible("an array method on something other than a variable");
563
582
  }
@@ -568,9 +587,9 @@ class ExpressionParser {
568
587
  const property = this.tokens.next();
569
588
  if (property.type != "ident")
570
589
  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}` } };
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 }) };
574
593
  continue;
575
594
  }
576
595
  value = this.member(value, property.text);
@@ -579,24 +598,16 @@ class ExpressionParser {
579
598
  this.tokens.next();
580
599
  const index = this.expression();
581
600
  this.tokens.expect("]");
582
- // A widget's arguments, which a call to it puts in args_0, args_1 and so on
583
601
  if (value.v == "expr" && value.e.k == "var" && index.k == "loop" && index.kind == "index" && index.array == value.e.name) {
584
602
  value = { v: "expr", e: { k: "loop", kind: "item", up: index.up } };
585
603
  continue;
586
604
  }
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}` } };
589
- continue;
590
- }
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] } };
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) };
597
608
  continue;
598
609
  }
599
- throw new Unconvertible("array indexes and object properties ([...])");
610
+ throw new Unconvertible("array indexes and object properties ([...]) of something other than a value");
600
611
  }
601
612
  else if (this.tokens.is("(")) {
602
613
  this.tokens.next();
@@ -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) {
@@ -986,7 +1077,7 @@ class Writer {
986
1077
  });
987
1078
  }
988
1079
  inlineText(text) {
989
- const nodes = new Parser(text).parse(0).nodes;
1080
+ const nodes = new Parser(text, this.containerWidgets).parse(0).nodes;
990
1081
  return this.nodes(nodes, { leading: false, directives: [], nobr: true }).replace(/\n/g, " ");
991
1082
  }
992
1083
  text(s, state) {
@@ -1097,6 +1188,79 @@ class Writer {
1097
1188
  return null;
1098
1189
  }
1099
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
+ }
1100
1264
  macro(m, state) {
1101
1265
  try {
1102
1266
  return this.macroOrThrow(m, state);
@@ -1312,27 +1476,48 @@ class Writer {
1312
1476
  if (/<<\s*(?:break|continue)\s*>>/.test(m.raw))
1313
1477
  throw new Unconvertible("<<break>> and <<continue>>");
1314
1478
  const loop = this.forLoop(m.args);
1315
- const body = this.ctx.story.inLoop(loop.vars, loop.array, () => this.body(m, state));
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);
1316
1481
  return `{{#each ${print(loop.collection)}}}${body}{{/each}}`;
1317
1482
  }
1318
1483
  case "widget":
1319
1484
  return "";
1320
1485
  case "back":
1321
1486
  case "return":
1322
- 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`);
1323
1489
  case "audio":
1490
+ return leadingAudio(this.audio(m, args), state);
1324
1491
  case "cacheaudio":
1325
- case "playlist":
1326
- case "masteraudio":
1327
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":
1328
1501
  case "createplaylist":
1329
- case "createaudiogroup":
1502
+ case "removeplaylist":
1330
1503
  case "track":
1331
- throw new Unconvertible("audio macros");
1504
+ throw new Unconvertible("playlists");
1505
+ case "createaudiogroup":
1506
+ case "removeaudiogroup":
1507
+ throw new Unconvertible("audio groups");
1332
1508
  case "addclass":
1333
1509
  case "removeclass":
1334
- case "toggleclass":
1335
- 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
+ }
1336
1521
  case "repeat":
1337
1522
  throw new Unconvertible("<<repeat>>, which runs again and again");
1338
1523
  case "stop":
@@ -1348,7 +1533,7 @@ class Writer {
1348
1533
  default:
1349
1534
  if (this.widgets.has(m.name)) {
1350
1535
  state.leading = false;
1351
- return this.widgetCall(m, this.widgets.get(m.name));
1536
+ return this.widgetCall(m, this.widgets.get(m.name), state);
1352
1537
  }
1353
1538
  if (!knownMacros.has(m.name))
1354
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`);
@@ -1363,7 +1548,7 @@ class Writer {
1363
1548
  if (range) {
1364
1549
  const vars = new Map(range[2] ? [[range[1], "index"], [range[2], "item"]] : [[range[1], "item"]]);
1365
1550
  const collection = this.expr.parse(range[3]);
1366
- if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item")) {
1551
+ if (collection.k != "var" && collection.k != "array" && !(collection.k == "loop" && collection.kind == "item") && !isListCall(collection)) {
1367
1552
  throw new Unconvertible("<<for>> with range over something other than an array");
1368
1553
  }
1369
1554
  // With a position as well, $list[_i] is the item too
@@ -1374,7 +1559,22 @@ class Writer {
1374
1559
  const array = this.expr.attribute(counted[3], counted[2] == "_");
1375
1560
  return { collection: { k: "var", name: array }, vars: new Map([["_" + counted[1], "index"]]), array };
1376
1561
  }
1377
- throw new Unconvertible("<<for>> loops, except ones that go through an array (with range, or from 0 to its length)");
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");
1378
1578
  }
1379
1579
  // The attribute a form macro like <<textbox "$name">> sets
1380
1580
  receiver(arg) {
@@ -1468,19 +1668,22 @@ class Writer {
1468
1668
  return dynamicSectionLink(text.plain, destination.expr, all);
1469
1669
  }
1470
1670
  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];
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
+ });
1473
1676
  if (destination) {
1474
1677
  // Run the body in a section of its own, which then goes on to the passage
1475
1678
  const goto = gotoArg !== null ? "" : "\n" + ("name" in destination
1476
1679
  ? `{{goto ${print({ k: "str", v: this.sectionName(destination.name, m.raw) })}}}`
1477
1680
  : `{{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);
1681
+ const section = this.ctx.addSection(`${this.ctx.section}: ${text.plain}`, { directives: [...directives], body: content + goto });
1682
+ return sectionLink(text.squiffy, section, loopSetters);
1480
1683
  }
1481
1684
  // 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);
1685
+ const name = this.ctx.addPassage(text.plain, { directives: [...directives], body: content });
1686
+ return passageLink(text.squiffy, name, loopSetters);
1484
1687
  }
1485
1688
  // The setters for nodes that are only <<set>>s, or null
1486
1689
  bodySetters(nodes) {
@@ -1510,7 +1713,7 @@ class Writer {
1510
1713
  case "inc":
1511
1714
  case "dec": {
1512
1715
  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
1716
+ state.directives.push(amount === null || isDynamicTarget(s.name)
1514
1717
  ? `@set ${setter(s.name, s.kind == "inc" ? "+=" : "-=", s.value, false)}`
1515
1718
  : `@${s.kind} ${s.name}${amount == 1 ? "" : " " + amount}`);
1516
1719
  continue;
@@ -1521,6 +1724,8 @@ class Writer {
1521
1724
  }
1522
1725
  }
1523
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");
1524
1729
  const name = print({ k: "str", v: s.name });
1525
1730
  switch (s.kind) {
1526
1731
  case "set":
@@ -1552,6 +1757,36 @@ const knownMacros = new Set([
1552
1757
  "createaudiogroup", "createplaylist", "masteraudio", "playlist", "removeaudiogroup", "removeplaylist",
1553
1758
  "waitforaudio", "done", "goto", "repeat", "stop", "timed", "widget", "display", "click", "do", "redo", "track",
1554
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
+ }
1555
1790
  // The story's widgets, by name, with the section each is converted to
1556
1791
  export function sugarCubeWidgets(story) {
1557
1792
  return story.cached("sugarcube-widgets", () => {
@@ -1568,9 +1803,39 @@ export function sugarCubeWidgets(story) {
1568
1803
  return result;
1569
1804
  });
1570
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
+ }
1571
1836
  export function convertSugarCubeWidgets(text, ctx) {
1572
1837
  const writer = new Writer(ctx);
1573
- 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;
1574
1839
  return writer.widgetSections(nodes);
1575
1840
  }
1576
1841
  function cssAttributes(spec) {
@@ -1616,6 +1881,6 @@ export function convertSugarCubePassage(text, ctx) {
1616
1881
  const writer = new Writer(ctx);
1617
1882
  // A backslash at the end of a line joins it to the next
1618
1883
  const source = writer.findTargets(text.replace(/\\\r?\n/g, ""));
1619
- const nodes = new Parser(source).parse(0).nodes;
1884
+ const nodes = new Parser(source, writer.containerWidgets).parse(0).nodes;
1620
1885
  return writer.passage(nodes, ctx.passage.tags.includes("nobr"));
1621
1886
  }