@rohal12/spindle 0.59.28 → 0.59.30

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 (55) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +718 -300
  4. package/dist/pkg/macro-registry.js +19 -0
  5. package/dist/pkg/macro-registry.json +19 -0
  6. package/dist/pkg/story-variables.js +731 -234
  7. package/package.json +1 -1
  8. package/src/action-registry.ts +59 -5
  9. package/src/automation/load-yaml.ts +111 -20
  10. package/src/automation/runner.ts +15 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +187 -24
  14. package/src/components/macros/Checkbox.tsx +5 -2
  15. package/src/components/macros/Cycle.tsx +1 -0
  16. package/src/components/macros/For.tsx +1 -7
  17. package/src/components/macros/Listbox.tsx +1 -0
  18. package/src/components/macros/MenubarButtons.tsx +6 -1
  19. package/src/components/macros/Nobr.tsx +1 -0
  20. package/src/components/macros/PassageDisplay.tsx +42 -0
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/SaveManager.tsx +19 -4
  23. package/src/components/macros/SettingsControls.tsx +19 -4
  24. package/src/components/macros/Span.tsx +1 -0
  25. package/src/components/macros/StoryTitle.tsx +1 -0
  26. package/src/components/macros/VarDisplay.tsx +2 -3
  27. package/src/components/macros/Widget.tsx +2 -0
  28. package/src/components/macros/WidgetInvocation.tsx +5 -6
  29. package/src/components/macros/arg-utils.ts +58 -21
  30. package/src/components/macros/input-macro.ts +1 -0
  31. package/src/components/macros/locals-scope.tsx +19 -8
  32. package/src/components/macros/macro-args.ts +11 -3
  33. package/src/expression.ts +34 -18
  34. package/src/hooks/use-merged-locals.ts +17 -2
  35. package/src/hooks/use-modal-focus.ts +190 -129
  36. package/src/index.tsx +23 -13
  37. package/src/js-bindings.ts +332 -0
  38. package/src/js-lexer.ts +12 -3
  39. package/src/macro-discovery.ts +25 -22
  40. package/src/static-literal.ts +87 -16
  41. package/src/store.ts +31 -2
  42. package/src/story-api.ts +15 -5
  43. package/src/story-variables.ts +91 -28
  44. package/src/structural.ts +19 -15
  45. package/src/tooling.ts +36 -10
  46. package/src/transform.ts +22 -7
  47. package/src/utils/namespace.ts +4 -0
  48. package/src/utils/object-path.ts +2 -2
  49. package/src/utils/stable-key.ts +17 -6
  50. package/src/utils/value-kinds.ts +38 -1
  51. package/src/widgets/register-widget-def.ts +7 -8
  52. package/src/widgets/widget-def.ts +41 -4
  53. package/src/widgets/widget-registry.ts +14 -0
  54. package/types/index.d.ts +12 -5
  55. package/types/tooling.d.ts +12 -2
@@ -9601,7 +9601,7 @@ function walkTokens(src, from, handlers, nesting, goal, oneTemplate) {
9601
9601
  if (t === types$1.name) {
9602
9602
  const sigil = sigilAt(src, tok.start, tok.value);
9603
9603
  const property = prev === types$1.dot || prev === types$1.questionDot || (sigil === "$" || sigil === "_") && keyPosition(src, tok.end, prev);
9604
- if (sigil && !property) handlers.variable?.(sigil, src.slice(tok.start + 1, tok.end), tok.start, nesting);
9604
+ if (sigil && !property) handlers.variable?.(sigil, tok.value.slice(1), tok.start, nesting, tok.end);
9605
9605
  else code(tok.start, tok.end);
9606
9606
  } else if (t === types$1.string || t === types$1.regexp || t === types$1.template || t === types$1.invalidTemplate) literal(tok.start, tok.end);
9607
9607
  else if (t === types$1.backQuote) {
@@ -10053,6 +10053,8 @@ function checkVariableName(name, label = name) {
10053
10053
  const error = variableNameError(name, label);
10054
10054
  if (error) throw new TypeError(`spindle: ${error}`);
10055
10055
  }
10056
+ /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
10057
+ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
10056
10058
  /** Whether `obj` holds `key` as an own property. */
10057
10059
  var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10058
10060
  /** `ns[key]` if `ns` holds it as an own property, else undefined. */
@@ -10128,18 +10130,29 @@ var widgets = new NameMap();
10128
10130
  * that no namespace can hold (`@__proto__`) throws a TypeError and the
10129
10131
  * widget is not registered.
10130
10132
  */
10131
- function registerWidget(name, bodyAST, params, isBlock = false) {
10133
+ function registerWidget(name, bodyAST, params, isBlock = false, holds = {}) {
10132
10134
  const filteredParams = params.filter((p) => p !== "@children");
10133
10135
  for (const param of filteredParams) if (param.startsWith("@")) checkVariableName(param.slice(1), param);
10134
10136
  widgets.set(name, {
10135
10137
  body: bodyAST,
10136
10138
  params: filteredParams,
10139
+ holds,
10137
10140
  isBlock
10138
10141
  });
10139
10142
  }
10140
10143
  function getWidget(name) {
10141
10144
  return widgets.get(name);
10142
10145
  }
10146
+ /** The widgets as `parameterLookup` reads them (see MacroParameters). */
10147
+ function widgetMacros() {
10148
+ return [...widgets].map(([name, { params, holds }]) => ({
10149
+ name,
10150
+ widget: {
10151
+ params,
10152
+ holds
10153
+ }
10154
+ }));
10155
+ }
10143
10156
  //#endregion
10144
10157
  //#region src/utils/parse-delay.ts
10145
10158
  /**
@@ -10336,19 +10349,19 @@ function topLevelIndices(src, isSeparator) {
10336
10349
  return indices;
10337
10350
  }
10338
10351
  /**
10339
- * Split `src` at every depth-0 separator (see `topLevelIndices`). Segments
10340
- * are returned as written, untrimmed, and empty segments are kept, so
10352
+ * The segments of `src` between its depth-0 separators (see
10353
+ * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
10341
10354
  * `n` separators always give `n + 1` segments.
10342
10355
  */
10343
- function splitTopLevel(src, isSeparator) {
10344
- const segments = [];
10356
+ function topLevelSpans(src, isSeparator) {
10357
+ const spans = [];
10345
10358
  let from = 0;
10346
10359
  for (const i of topLevelIndices(src, isSeparator)) {
10347
- segments.push(src.slice(from, i));
10360
+ spans.push([from, i]);
10348
10361
  from = i + 1;
10349
10362
  }
10350
- segments.push(src.slice(from));
10351
- return segments;
10363
+ spans.push([from, src.length]);
10364
+ return spans;
10352
10365
  }
10353
10366
  /**
10354
10367
  * Check whether a whitespace-delimited token looks like a standalone value
@@ -10373,29 +10386,44 @@ function startsLikeValue(token) {
10373
10386
  * Try to split a raw string on whitespace at depth 0 (respecting strings,
10374
10387
  * template literals, parentheses, brackets, and braces). Each resulting token
10375
10388
  * must pass `isStandaloneValue()` or the split is rejected and `null` is
10376
- * returned.
10389
+ * returned. The spans are those of the tokens in `raw`.
10377
10390
  */
10378
10391
  function trySplitOnWhitespace(raw) {
10379
- const args = splitTopLevel(raw, isWhitespace).filter(Boolean);
10392
+ const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
10380
10393
  if (args.length < 2) return null;
10381
- for (const arg of args) if (!isStandaloneValue(arg)) return null;
10394
+ for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
10382
10395
  return args;
10383
10396
  }
10397
+ /** `span` less the whitespace at its ends. */
10398
+ function trimmed$1(src, [start, end]) {
10399
+ const text = src.slice(start, end);
10400
+ const lead = text.length - text.trimStart().length;
10401
+ return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
10402
+ }
10384
10403
  /**
10385
- * Split rawArgs by commas, respecting parentheses, brackets, braces, and
10386
- * strings. When no top-level commas are present, also supports adjacent quoted
10387
- * string literals separated by whitespace (e.g. `"Label" "target"`).
10404
+ * Where the arguments in `raw` are written (see `splitArgs`), as spans of
10405
+ * `raw`.
10388
10406
  */
10389
- function splitArgs(raw) {
10390
- const args = splitTopLevel(raw, (ch) => ch === ",").map((a) => a.trim());
10407
+ function splitArgSpans(raw) {
10408
+ const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
10391
10409
  const hasComma = args.length > 1;
10392
- if (args[args.length - 1] === "") args.pop();
10410
+ const last = args[args.length - 1];
10411
+ if (last[0] === last[1]) args.pop();
10393
10412
  if (!hasComma && args.length === 1) {
10394
- const split = trySplitOnWhitespace(args[0]);
10395
- if (split) return split;
10413
+ const [start, end] = args[0];
10414
+ const split = trySplitOnWhitespace(raw.slice(start, end));
10415
+ if (split) return split.map(([a, b]) => [start + a, start + b]);
10396
10416
  }
10397
10417
  return args;
10398
10418
  }
10419
+ /**
10420
+ * Split rawArgs by commas, respecting parentheses, brackets, braces, and
10421
+ * strings. When no top-level commas are present, also supports adjacent quoted
10422
+ * string literals separated by whitespace (e.g. `"Label" "target"`).
10423
+ */
10424
+ function splitArgs(raw) {
10425
+ return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
10426
+ }
10399
10427
  //#endregion
10400
10428
  //#region src/components/macros/macro-args.ts
10401
10429
  /**
@@ -10516,10 +10544,12 @@ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
10516
10544
  * Where the rest of `src` is without the flag `word` as its last or first
10517
10545
  * term, or `null` if it has no such flag. Next to a binary operator the
10518
10546
  * word is an operand (`"a" + inline`), not a flag; the closing `/` of a
10519
- * regex literal is not one.
10547
+ * regex literal is not one. A word with nothing else beside it is the flag
10548
+ * only when `alone` says no argument is waiting for it (#499).
10520
10549
  */
10521
- function takeFlag(src, word) {
10550
+ function takeFlag(src, word, alone) {
10522
10551
  const spans = terms(src);
10552
+ if (spans.length === 1) return alone && slice(src, spans[0]) === word ? [src.length, src.length] : null;
10523
10553
  if (spans.length < 2) return null;
10524
10554
  if (slice(src, spans[spans.length - 1]) === word) {
10525
10555
  const rest = [0, spans[spans.length - 2][1]];
@@ -10566,8 +10596,9 @@ function trimmed(src, at) {
10566
10596
  */
10567
10597
  function readGroup(params, src, args, { at: srcAt, spans }) {
10568
10598
  let [text, at] = trimmed(src ?? "", srcAt);
10599
+ const alone = !params.some((p) => p.type !== "flag" && p.required);
10569
10600
  for (const flag of params.filter((p) => p.type === "flag")) {
10570
- const rest = src === null ? null : takeFlag(text, flag.name);
10601
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
10571
10602
  args[flag.name] = rest !== null;
10572
10603
  if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
10573
10604
  }
@@ -10764,6 +10795,18 @@ var CONDITION_MACROS = /* @__PURE__ */ new Set([
10764
10795
  /** Block macros whose body is the name of a passage. */
10765
10796
  var PASSAGE_BODIES = /* @__PURE__ */ new Set(["dialog"]);
10766
10797
  /**
10798
+ * The parameters of a widget given its `@` parameters and what they declare
10799
+ * to hold, or none when it declares nothing (a call is then not read by
10800
+ * parameter).
10801
+ */
10802
+ function widgetParameters(params, holds = {}) {
10803
+ if (!params.some((param) => hasOwn(holds, param))) return void 0;
10804
+ return params.map((name) => ({
10805
+ name,
10806
+ ...hasOwn(holds, name) ? { holds: holds[name] } : {}
10807
+ }));
10808
+ }
10809
+ /**
10767
10810
  * `params` with each `string` and `text` parameter (options too) saying
10768
10811
  * what it holds: what it declares, else `holds`.
10769
10812
  */
@@ -10785,11 +10828,17 @@ function withHolds(params, holds) {
10785
10828
  * collection and tooling read arguments by. Each `string` and `text`
10786
10829
  * parameter says what it holds: what it declares, else `markup` for a macro
10787
10830
  * with `interpolate` (which can resolve markup) and `text` for any other.
10831
+ * A widget among `macros` says what its parameters hold (see ParametersOf).
10788
10832
  */
10789
10833
  function parameterLookup(macros) {
10790
10834
  const parameters = new NameMap();
10791
- for (const { name, parameters: params, interpolate } of macros) if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
10792
- return (name) => {
10835
+ const widgets = new NameMap();
10836
+ for (const { name, parameters: params, interpolate, widget } of macros) {
10837
+ if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
10838
+ const declared = widget && widgetParameters(widget.params, widget.holds);
10839
+ if (declared) widgets.set(name, declared);
10840
+ }
10841
+ const lookup = (name) => {
10793
10842
  let params = parameters.get(name);
10794
10843
  if (!params) {
10795
10844
  const sub = subMacroParameters(name);
@@ -10797,6 +10846,8 @@ function parameterLookup(macros) {
10797
10846
  }
10798
10847
  return params;
10799
10848
  };
10849
+ if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
10850
+ return lookup;
10800
10851
  }
10801
10852
  /** What a `string` or `text` argument holds when its parameter doesn't say. */
10802
10853
  var holdsByDefault = (interpolate) => interpolate ? "markup" : "text";
@@ -10899,6 +10950,8 @@ function* codeAndText(src, tokens, parametersOf) {
10899
10950
  }
10900
10951
  const params = parametersOf(name);
10901
10952
  if (params) yield* argPieces(args, argsAt, params, token.name, label);
10953
+ const widget = parametersOf.widget?.(name);
10954
+ if (widget) yield* widgetPieces(args, argsAt, widget, token.name, label);
10902
10955
  }
10903
10956
  }
10904
10957
  }
@@ -10966,31 +11019,56 @@ function nestedPiece(piece, toRoot, where) {
10966
11019
  ...nested
10967
11020
  };
10968
11021
  }
11022
+ /** An escape sequence of a JavaScript string literal (with its backslash). */
11023
+ var JS_ESCAPE_RE = /\\(?:u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-3][0-7]{0,2}|[4-7][0-7]?|\r\n|[^])/y;
11024
+ /**
11025
+ * The escape written at `raw[i]` (a backslash): how long it is as written and
11026
+ * what it stands for, or none when it is not one under these `escapes`.
11027
+ */
11028
+ function escapeAt(raw, i, escapes) {
11029
+ if (escapes === "quotes") {
11030
+ const next = raw.charAt(i + 1);
11031
+ return /["'\\]/.test(next) ? {
11032
+ length: 2,
11033
+ text: next
11034
+ } : void 0;
11035
+ }
11036
+ JS_ESCAPE_RE.lastIndex = i;
11037
+ const written = JS_ESCAPE_RE.exec(raw)?.[0];
11038
+ const text = written && stringLiteralValue(`"${written}"`);
11039
+ return typeof text === "string" ? {
11040
+ length: written.length,
11041
+ text
11042
+ } : void 0;
11043
+ }
10969
11044
  /**
10970
11045
  * Where each character of `value`, the unescaped text of a quoted string
10971
- * written as `raw` from `at` on (a backslash before a quote or a backslash
10972
- * is dropped), is
10973
- * in the source, and where the text ends. None when the text is where its
10974
- * length says, or is not that string.
11046
+ * written as `raw` from `at` on (its escapes are those of `escapes`), is in
11047
+ * the source, and where the text ends. A character that an escape stands for
11048
+ * is where the escape begins. None when the text is where its length says, or
11049
+ * is not that string.
10975
11050
  */
10976
- function escapeOffsets(raw, at, value) {
11051
+ function escapeOffsets(raw, at, value, escapes) {
10977
11052
  const offsets = [];
10978
11053
  let escaped = false;
10979
11054
  let i = 0;
10980
11055
  while (offsets.length < value.length) {
10981
11056
  if (i >= raw.length) return void 0;
10982
- offsets.push(at + i);
10983
- if (raw[i] === "\\" && /["'\\]/.test(raw.charAt(i + 1))) {
10984
- escaped = true;
10985
- i += 2;
10986
- } else i++;
11057
+ const escape = raw[i] === "\\" ? escapeAt(raw, i, escapes) : void 0;
11058
+ if (!escape) {
11059
+ offsets.push(at + i++);
11060
+ continue;
11061
+ }
11062
+ if (!value.startsWith(escape.text, offsets.length)) return void 0;
11063
+ for (let k = 0; k < escape.text.length; k++) offsets.push(at + i);
11064
+ escaped = true;
11065
+ i += escape.length;
10987
11066
  }
10988
11067
  offsets.push(at + i);
10989
11068
  return escaped ? offsets : void 0;
10990
11069
  }
10991
11070
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
10992
11071
  function* argPieces(args, offset, params, macro, label) {
10993
- const name = macro.toLowerCase();
10994
11072
  let values;
10995
11073
  const spans = /* @__PURE__ */ new Map();
10996
11074
  try {
@@ -11003,10 +11081,45 @@ function* argPieces(args, offset, params, macro, label) {
11003
11081
  offset,
11004
11082
  length: args.length,
11005
11083
  label,
11006
- macro: name
11084
+ macro: macro.toLowerCase()
11007
11085
  };
11008
11086
  return;
11009
11087
  }
11088
+ yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes");
11089
+ }
11090
+ /**
11091
+ * The code and text in the arguments `args` (at `offset`) of the widget
11092
+ * `macro`, the ones whose parameter declares what it holds. Such an argument
11093
+ * is checked when it is one quoted string, as a `string` parameter with that
11094
+ * `holds` of a macro is; any other expression is its value at run time.
11095
+ */
11096
+ function* widgetPieces(args, offset, params, macro, label) {
11097
+ const written = splitArgSpans(args);
11098
+ const declared = [];
11099
+ const values = {};
11100
+ const spans = /* @__PURE__ */ new Map();
11101
+ params.forEach(({ name, holds }, i) => {
11102
+ const span = written[i];
11103
+ const value = span && stringLiteralValue(args.slice(...span));
11104
+ if (!holds || value == null) return;
11105
+ const param = {
11106
+ name,
11107
+ type: "string",
11108
+ holds
11109
+ };
11110
+ declared.push(param);
11111
+ values[name] = value;
11112
+ spans.set(param, span);
11113
+ });
11114
+ yield* valuePieces(args, offset, declared, values, spans, macro, label, "javascript");
11115
+ }
11116
+ /**
11117
+ * The pieces of the `params` of `macro` with the `values` read from `args`
11118
+ * (at `offset`), whose `spans` tell where each was written and whose strings
11119
+ * are unescaped as `escapes` says.
11120
+ */
11121
+ function* valuePieces(args, offset, params, values, spans, macro, label, escapes) {
11122
+ const name = macro.toLowerCase();
11010
11123
  /** The pieces of the parameters `list`, with their values in `from`. */
11011
11124
  function* visit(list, from) {
11012
11125
  for (const param of list) {
@@ -11053,7 +11166,7 @@ function* argPieces(args, offset, params, macro, label) {
11053
11166
  }
11054
11167
  const at = offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
11055
11168
  const holds = stringHolds(param);
11056
- const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
11169
+ const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value, escapes);
11057
11170
  if (holds === "expression" || holds === "statements") {
11058
11171
  const piece = {
11059
11172
  kind: "code",
@@ -11119,20 +11232,21 @@ function attributeValues(src, token) {
11119
11232
  }
11120
11233
  /**
11121
11234
  * The `{$…}` expressions in the value of a code attribute (`onclick`, see
11122
- * isCodeAttribute), with where each is in the value.
11235
+ * isCodeAttribute), with where each is in the value. The parts of the value
11236
+ * are written out as they are (splitSigilTemplate decodes nothing), so each
11237
+ * starts where the one before it ends: an expression is not found by its
11238
+ * text, which a string of the code may repeat.
11123
11239
  */
11124
11240
  function sigilExpressions(value) {
11125
11241
  const found = [];
11126
11242
  let from = 0;
11127
- for (const part of splitSigilTemplate(value)) {
11128
- if (!("expr" in part)) continue;
11129
- const at = locate(value, part.expr, from);
11130
- from = at + part.expr.length;
11243
+ for (const part of splitSigilTemplate(value)) if ("expr" in part) {
11131
11244
  found.push({
11132
11245
  expr: part.expr,
11133
- at
11246
+ at: from + 1
11134
11247
  });
11135
- }
11248
+ from += part.expr.length + 2;
11249
+ } else from += ("text" in part ? part.text : part.verbatim).length;
11136
11250
  return found;
11137
11251
  }
11138
11252
  /**
@@ -11341,15 +11455,39 @@ var WIDGET_PARAMETERS = [{
11341
11455
  /**
11342
11456
  * The widget a {widget} definition's arguments declare: its name and its
11343
11457
  * parameters, the words after it that start with `@` (docs/widgets.md),
11344
- * separated by spaces or commas (`@a, @b`). Other words, such as `$name`, are
11345
- * not parameters.
11458
+ * separated by spaces or commas (`@a, @b`). A parameter may say what its
11459
+ * argument holds after a colon (`@target:passage`, one of the `holds` of a
11460
+ * macro parameter; another word is a `badHolds`). Other words, such as
11461
+ * `$name`, are not parameters.
11346
11462
  */
11347
11463
  function widgetDef({ name = "", parameters = "" }) {
11464
+ const params = [];
11465
+ const holds = {};
11466
+ const badHolds = [];
11467
+ for (const word of parameters.split(/[\s,]+/)) {
11468
+ if (!word.startsWith("@")) continue;
11469
+ const [param = word, written] = word.split(/:(.*)/s);
11470
+ params.push(param);
11471
+ if (written === void 0) continue;
11472
+ if (STRING_HOLDS.includes(written)) holds[param] = written;
11473
+ else badHolds.push({
11474
+ param,
11475
+ written
11476
+ });
11477
+ }
11348
11478
  return {
11349
11479
  name,
11350
- params: parameters.split(/[\s,]+/).filter((word) => word.startsWith("@"))
11480
+ params,
11481
+ ...Object.keys(holds).length > 0 ? { holds } : {},
11482
+ ...badHolds.length > 0 ? { badHolds } : {}
11351
11483
  };
11352
11484
  }
11485
+ /** Throw if a parameter of `def` declares what it holds wrongly. */
11486
+ function checkWidgetHolds({ name, badHolds = [] }) {
11487
+ const [bad] = badHolds;
11488
+ if (!bad) return;
11489
+ throw new Error(`spindle: The widget parameter ${bad.param} of {widget "${name}"} holds the unknown ${JSON.stringify(bad.written)}. Write one of ${STRING_HOLDS.join(", ")} after the colon (see docs/widgets.md#what-an-argument-holds).`);
11490
+ }
11353
11491
  /** Read the arguments of a {widget} definition (see widgetDef). */
11354
11492
  function parseWidgetDef(rawArgs) {
11355
11493
  return widgetDef(parseMacroArgs(rawArgs, WIDGET_PARAMETERS));
@@ -11426,12 +11564,14 @@ function blockWidgetNames(passages, parametersOf = registeredParameters) {
11426
11564
  * Register the widget a definition declares, with its body. Widgets whose
11427
11565
  * body renders {@children} take a closing tag, so they are registered as
11428
11566
  * block macros too: passages parsed later nest their content. A parameter
11429
- * that no namespace can hold throws (see registerWidget), registering
11430
- * nothing.
11567
+ * that no namespace can hold or declares what it holds wrongly throws (see
11568
+ * registerWidget and checkWidgetHolds), registering nothing.
11431
11569
  */
11432
- function registerWidgetDef({ name, params }, body) {
11570
+ function registerWidgetDef(def, body) {
11571
+ checkWidgetHolds(def);
11572
+ const { name, params, holds } = def;
11433
11573
  const isBlock = astContainsChildren(body);
11434
- registerWidget(name, body, params, isBlock);
11574
+ registerWidget(name, body, params, isBlock, holds);
11435
11575
  if (isBlock) registerBlockMacro(name);
11436
11576
  }
11437
11577
  /**
@@ -11483,14 +11623,50 @@ function useStoryFields(...keys) {
11483
11623
  });
11484
11624
  }
11485
11625
  //#endregion
11626
+ //#region src/utils/live-locals.ts
11627
+ /**
11628
+ * Read-only view of a locals scope that always reflects its current values.
11629
+ *
11630
+ * Used as the LocalsValuesContext value for one-shot detached renders
11631
+ * ({button}/{link} bodies). Those trees are unmounted right after rendering,
11632
+ * so the owning scope's re-render never reaches them; reading through
11633
+ * getValues() lets a macro see a local assigned earlier in the same body.
11634
+ */
11635
+ function liveLocalsView(getValues) {
11636
+ return new Proxy(createNamespace(), {
11637
+ get: (_, key) => typeof key === "string" ? ownValue(getValues(), key) : void 0,
11638
+ has: (_, key) => typeof key === "string" && hasOwn(getValues(), key),
11639
+ ownKeys: () => Reflect.ownKeys(getValues()),
11640
+ getOwnPropertyDescriptor: (_, key) => {
11641
+ const desc = Object.getOwnPropertyDescriptor(getValues(), key);
11642
+ return desc ? {
11643
+ ...desc,
11644
+ configurable: true
11645
+ } : void 0;
11646
+ }
11647
+ });
11648
+ }
11649
+ //#endregion
11486
11650
  //#region src/hooks/use-merged-locals.ts
11487
11651
  /**
11652
+ * The locals in scope, read as they are when code looks (a local the
11653
+ * preceding {set} assigned in this pass included, which the context value
11654
+ * only gains in the re-render that follows). The returned view is renewed
11655
+ * whenever the context value changes, so what depends on it re-renders and
11656
+ * recomputes as before.
11657
+ */
11658
+ function useLiveLocals() {
11659
+ const values = useContext(LocalsValuesContext);
11660
+ const { getValues } = useContext(LocalsUpdateContext);
11661
+ return useMemo(() => liveLocalsView(getValues), [getValues, values]);
11662
+ }
11663
+ /**
11488
11664
  * Return store variables, temporary, locals from context, and transient.
11489
11665
  * All four dicts use unprefixed keys suitable for evaluate/execute.
11490
11666
  */
11491
11667
  function useMergedLocals() {
11492
11668
  const { variables, temporary, transient, renderCounts } = useStoryFields("variables", "temporary", "transient", "renderCounts");
11493
- const localsValues = useContext(LocalsValuesContext);
11669
+ const localsValues = useLiveLocals();
11494
11670
  return useMemo(() => {
11495
11671
  return [
11496
11672
  variables,
@@ -11639,17 +11815,31 @@ function getPRNGPull() {
11639
11815
  * (see src/tooling.ts).
11640
11816
  */
11641
11817
  var TRANSFORM_CACHE_MAX = 500;
11642
- var NAMESPACES$2 = {
11643
- $: "variables",
11644
- _: "temporary",
11645
- "@": "locals",
11646
- "%": "transient"
11647
- };
11818
+ /**
11819
+ * The identifiers generated code reads the namespaces through, and the
11820
+ * compiled function takes them under (see src/expression.ts). Authored
11821
+ * JavaScript may declare identifiers of its own (`const variables = {}` in
11822
+ * a helper), so these are ones it cannot: an identifier that starts with
11823
+ * `_` or `$` and has more word characters after it is a sigil reference,
11824
+ * and the lexer refuses to declare one (`__variables` is the temporary
11825
+ * variable `_variables`, rewritten like any other). No declaration or
11826
+ * parameter of the author's can then capture a reference or clash with the
11827
+ * generated bindings.
11828
+ */
11829
+ var BINDINGS = {
11830
+ $: "__variables",
11831
+ _: "__temporary",
11832
+ "@": "__locals",
11833
+ "%": "__transient"
11834
+ };
11835
+ /** The identifier the functions that compiled code may call come under. */
11836
+ var FNS_BINDING = "__fns";
11648
11837
  /** Ends with an identifier character. */
11649
11838
  var IDENT_END_RE = /[\p{ID_Continue}$\u200c\u200d]$/u;
11650
11839
  /**
11651
11840
  * Transform expression: $var → variables["var"], _var → temporary["var"],
11652
- * @var → locals["var"], %var → transient["var"].
11841
+ * @var → locals["var"], %var → transient["var"], where `variables` and the
11842
+ * others stand for the generated names in BINDINGS.
11653
11843
  * The lexer (`lexJs`) finds the references: only in code (string, template
11654
11844
  * and regex literal text and comments are left untouched), only where an
11655
11845
  * identifier starts (not in `a$b`, nor as the property name in `obj._x`),
@@ -11672,7 +11862,7 @@ function transform(expr, goal = "expression") {
11672
11862
  result += expr.slice(at, ref.start);
11673
11863
  if (ref.shorthand) result += `${ref.name}: `;
11674
11864
  else if (IDENT_END_RE.test(result.slice(-2))) result += " ";
11675
- result += `${NAMESPACES$2[ref.sigil]}["${ref.name}"]`;
11865
+ result += `${BINDINGS[ref.sigil]}["${ref.name}"]`;
11676
11866
  at = ref.end;
11677
11867
  }
11678
11868
  result += expr.slice(at);
@@ -11686,15 +11876,28 @@ var transformCache = /* @__PURE__ */ new Map();
11686
11876
  //#region src/expression.ts
11687
11877
  var FN_CACHE_MAX = 500;
11688
11878
  var fnCache = /* @__PURE__ */ new Map();
11689
- var preamble = "const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=__fns;";
11690
- function getOrCompile(key, body) {
11879
+ var preamble = `const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=${FNS_BINDING};`;
11880
+ /**
11881
+ * Compile `source`: the function takes the namespaces and the function
11882
+ * table under the names the transform uses for the references (see
11883
+ * BINDINGS). The statements are a block of their own, so that they may
11884
+ * declare any name, those of the history functions the preamble declares
11885
+ * included.
11886
+ */
11887
+ function compile(source, goal) {
11888
+ const code = transform(source, goal);
11889
+ const body = goal === "statements" ? `{${code}\n}` : `return (${code}\n);`;
11890
+ return new Function(BINDINGS.$, BINDINGS._, BINDINGS["@"], FNS_BINDING, BINDINGS["%"], preamble + body);
11891
+ }
11892
+ function getOrCompile(source, goal) {
11893
+ const key = (goal === "statements" ? "s" : "e") + source;
11691
11894
  const cached = fnCache.get(key);
11692
11895
  if (cached) {
11693
11896
  fnCache.delete(key);
11694
11897
  fnCache.set(key, cached);
11695
11898
  return cached;
11696
11899
  }
11697
- const fn = new Function("variables", "temporary", "locals", "__fns", "transient", preamble + body);
11900
+ const fn = compile(source, goal);
11698
11901
  fnCache.set(key, fn);
11699
11902
  if (fnCache.size > FN_CACHE_MAX) {
11700
11903
  const oldest = fnCache.keys().next().value;
@@ -11785,16 +11988,14 @@ function run$1(fn, ...[variables, temporary, locals = EMPTY_NAMESPACE, transient
11785
11988
  * e.g. evaluate("$health + 10", variables, temporary) → number
11786
11989
  */
11787
11990
  function evaluate(expr, ...namespaces) {
11788
- const body = `return (${transform(expr)}\n);`;
11789
- return run$1(getOrCompile(body, body), ...namespaces);
11991
+ return run$1(getOrCompile(expr, "expression"), ...namespaces);
11790
11992
  }
11791
11993
  /**
11792
11994
  * Execute statements (no return value).
11793
11995
  * e.g. execute("$health = 100; $name = 'Hero'", variables, temporary)
11794
11996
  */
11795
11997
  function execute(code, ...namespaces) {
11796
- const transformed = transform(code, "statements");
11797
- run$1(getOrCompile("exec:" + transformed, transformed), ...namespaces);
11998
+ run$1(getOrCompile(code, "statements"), ...namespaces);
11798
11999
  }
11799
12000
  //#endregion
11800
12001
  //#region src/components/macros/display.ts
@@ -12142,7 +12343,7 @@ function VarDisplay({ node }) {
12142
12343
  const resolve = useInterpolate();
12143
12344
  const className = resolve(node.className);
12144
12345
  const id = resolve(node.id);
12145
- const localsValues = useContext(LocalsValuesContext);
12346
+ const localsValues = useLiveLocals();
12146
12347
  const parts = name.split(".");
12147
12348
  const root = parts[0];
12148
12349
  const storeValue = useStoryStore((s) => scope === "local" ? void 0 : ownValue(s[STORE_NAMESPACES[scope]], root));
@@ -12201,14 +12402,17 @@ function useRenderOptions() {
12201
12402
  //#endregion
12202
12403
  //#region src/components/macros/locals-scope.tsx
12203
12404
  /**
12204
- * Render `body` in a new locals scope: the locals of `parentValues`, with
12205
- * `ownKeys` (an iteration's loop variables, a widget's parameters) on top.
12206
- * Locals the body assigns are kept in this scope.
12405
+ * Render `body` in a new locals scope: the locals of the enclosing scope,
12406
+ * with `ownKeys` (an iteration's loop variables, a widget's parameters) on
12407
+ * top. Locals the body assigns are kept in this scope.
12207
12408
  */
12208
- function LocalsScope({ body, parentValues, ownKeys }) {
12409
+ function LocalsScope({ body, ownKeys }) {
12209
12410
  const options = useRenderOptions();
12210
12411
  const [localMutations, setLocalMutations] = useState({});
12211
- const localState = useMemo(() => createNamespace(parentValues, ownKeys, localMutations), [
12412
+ const enclosing = useContext(LocalsUpdateContext).getValues();
12413
+ const parentValues = useContext(LocalsValuesContext);
12414
+ const localState = useMemo(() => createNamespace(enclosing, ownKeys, localMutations), [
12415
+ enclosing,
12212
12416
  parentValues,
12213
12417
  ownKeys,
12214
12418
  localMutations
@@ -12246,7 +12450,6 @@ function WidgetInvocation(props) {
12246
12450
  return wrapContent(resolve(props.className), resolve(props.id), /* @__PURE__ */ jsx(WidgetContent, { ...props }));
12247
12451
  }
12248
12452
  function WidgetContent({ body, params, rawArgs, invocationChildren }) {
12249
- const parentValues = useRenderOptions().locals;
12250
12453
  const [mergedVars, mergedTemps, mergedLocals, mergedTrans] = useMergedLocals();
12251
12454
  const outerChildren = useContext(WidgetChildrenContext);
12252
12455
  const childrenValue = useMemo(() => widgetChildrenOf(invocationChildren, outerChildren), [invocationChildren, outerChildren]);
@@ -12262,16 +12465,16 @@ function WidgetContent({ body, params, rawArgs, invocationChildren }) {
12262
12465
  }
12263
12466
  values.push(value);
12264
12467
  }
12468
+ const paramsKey = params.join(" ");
12265
12469
  const ownKeys = useMemo(() => {
12266
12470
  const keys = createNamespace();
12267
12471
  for (let i = 0; i < params.length; i++) keys[params[i].startsWith("@") ? params[i].slice(1) : params[i]] = values[i];
12268
12472
  return keys;
12269
- }, values);
12473
+ }, [paramsKey, ...values]);
12270
12474
  return /* @__PURE__ */ jsx(WidgetChildrenContext.Provider, {
12271
12475
  value: childrenValue,
12272
12476
  children: /* @__PURE__ */ jsx(LocalsScope, {
12273
12477
  body,
12274
- parentValues,
12275
12478
  ownKeys
12276
12479
  })
12277
12480
  });
@@ -14051,6 +14254,29 @@ function extraKeys(collection) {
14051
14254
  const keys = Object.keys(collection);
14052
14255
  return Array.isArray(collection) ? keys.filter((k) => !isIndexKey(k)) : keys;
14053
14256
  }
14257
+ /** The built-in getter of each flag, with the letter `flags` lists it by. */
14258
+ var FLAG_GETTERS = [
14259
+ ["hasIndices", "d"],
14260
+ ["global", "g"],
14261
+ ["ignoreCase", "i"],
14262
+ ["multiline", "m"],
14263
+ ["dotAll", "s"],
14264
+ ["unicode", "u"],
14265
+ ["unicodeSets", "v"],
14266
+ ["sticky", "y"]
14267
+ ].flatMap(([name, letter]) => {
14268
+ const get = Object.getOwnPropertyDescriptor(RegExp.prototype, name)?.get;
14269
+ return get ? [[letter, get]] : [];
14270
+ });
14271
+ /** The pattern of a RegExp and its flags, as its slots hold them. */
14272
+ function regExpParts(re) {
14273
+ return [Reflect.get(RegExp.prototype, "source", re), FLAG_GETTERS.map(([letter, get]) => get.call(re) ? letter : "").join("")];
14274
+ }
14275
+ /** `/source/flags` of a RegExp, as its slots hold them (see regExpParts). */
14276
+ function regExpText(re) {
14277
+ const [source, flags] = regExpParts(re);
14278
+ return `/${source}/${flags}`;
14279
+ }
14054
14280
  /** The entries of a Map, as the built-in iterator gives them. */
14055
14281
  function mapEntries(map) {
14056
14282
  return isDraft(map) ? map.entries() : Map.prototype.entries.call(map);
@@ -14216,11 +14442,7 @@ function classData(value) {
14216
14442
  ];
14217
14443
  if (value instanceof RegExp) return [
14218
14444
  "RegExp",
14219
- [
14220
- Reflect.get(RegExp.prototype, "source", value),
14221
- Reflect.get(RegExp.prototype, "flags", value),
14222
- value.lastIndex
14223
- ],
14445
+ [...regExpParts(value), value.lastIndex],
14224
14446
  extra()
14225
14447
  ];
14226
14448
  return savedData(ownData(value));
@@ -14262,11 +14484,7 @@ function reducers() {
14262
14484
  const key = Symbol.keyFor(v);
14263
14485
  return key !== void 0 && [key];
14264
14486
  };
14265
- out[REGEXP_TAG] = (v) => v instanceof RegExp && v.lastIndex !== 0 && [
14266
- v.source,
14267
- v.flags,
14268
- v.lastIndex
14269
- ];
14487
+ out[REGEXP_TAG] = (v) => v instanceof RegExp && v.lastIndex !== 0 && [...regExpParts(v), v.lastIndex];
14270
14488
  out[KEYS_TAG] = (v) => {
14271
14489
  return isPlainData(v) && keyEntries(v);
14272
14490
  };
@@ -15001,7 +15219,7 @@ function getByPath(obj, segments) {
15001
15219
  return current;
15002
15220
  }
15003
15221
  /** Array indices ("0", "1", …) and "length": the keys an array holds. */
15004
- var isArrayKey = (key) => key === "length" || /^(0|[1-9]\d*)$/.test(key);
15222
+ var isArrayKey = (key) => key === "length" || isArrayIndex(key);
15005
15223
  /**
15006
15224
  * Built-ins whose content is not their properties: a property written into
15007
15225
  * one would be dropped by clones and saves (and by Immer, for Map and Set).
@@ -15155,7 +15373,7 @@ function deepClone(value, options = {}) {
15155
15373
  function cloneBuiltin(val) {
15156
15374
  if (val instanceof Date) return builtin(val, new Date(Date.prototype.getTime.call(val)));
15157
15375
  if (val instanceof RegExp) {
15158
- const copy = new RegExp(Reflect.get(RegExp.prototype, "source", val), Reflect.get(RegExp.prototype, "flags", val));
15376
+ const copy = new RegExp(...regExpParts(val));
15159
15377
  copy.lastIndex = val.lastIndex;
15160
15378
  return builtin(val, copy);
15161
15379
  }
@@ -15349,10 +15567,7 @@ function equalBuiltin(a, b, assumed) {
15349
15567
  const time = Date.prototype.getTime;
15350
15568
  return Object.is(time.call(a), time.call(b)) && equalExtraKeys(a, b, assumed);
15351
15569
  }
15352
- if (a instanceof RegExp) {
15353
- const text = RegExp.prototype.toString;
15354
- return text.call(a) === text.call(b) && a.lastIndex === b.lastIndex && equalExtraKeys(a, b, assumed);
15355
- }
15570
+ if (a instanceof RegExp) return regExpText(a) === regExpText(b) && a.lastIndex === b.lastIndex && equalExtraKeys(a, b, assumed);
15356
15571
  if (ArrayBuffer.isView(a)) {
15357
15572
  const v = b;
15358
15573
  return a.byteOffset === v.byteOffset && a.byteLength === v.byteLength && equal(a.buffer, v.buffer, assumed);
@@ -15380,11 +15595,15 @@ var BUILTIN_PROTOS = /* @__PURE__ */ new Set([
15380
15595
  RegExp.prototype
15381
15596
  ]);
15382
15597
  /**
15383
- * Equality of the extra keys (see extraKeys) of two built-ins of one
15384
- * class: those of a subclass instance are part of its value.
15598
+ * The extra keys (see extraKeys) of a built-in that is an instance of a
15599
+ * subclass: those are part of its value. A plain built-in has none.
15385
15600
  */
15601
+ function subclassFields(obj) {
15602
+ return BUILTIN_PROTOS.has(Object.getPrototypeOf(obj)) ? [] : extraKeys(obj);
15603
+ }
15604
+ /** Equality of the fields (see subclassFields) of two built-ins of one class. */
15386
15605
  function equalExtraKeys(a, b, assumed) {
15387
- return BUILTIN_PROTOS.has(Object.getPrototypeOf(a)) || equalKeys(a, b, assumed, extraKeys);
15606
+ return equalKeys(a, b, assumed, subclassFields);
15388
15607
  }
15389
15608
  /** `assumed` tracks the pairs of objects met (see Pairs). */
15390
15609
  function equal(a, b, assumed) {
@@ -15495,15 +15714,15 @@ function keyChanges(before, after, arrays) {
15495
15714
  kind: "holes",
15496
15715
  after: a.length - next
15497
15716
  });
15498
- return changes;
15499
15717
  }
15500
- for (const key of Object.keys(after)) if (hasOwn(before, key)) compare(key, before[key], after[key]);
15718
+ const keysOf = Array.isArray(after) ? subclassFields : Object.keys;
15719
+ for (const key of keysOf(after)) if (hasOwn(before, key)) compare(key, before[key], after[key]);
15501
15720
  else changes.push({
15502
15721
  key,
15503
15722
  kind: "added",
15504
15723
  after: after[key]
15505
15724
  });
15506
- for (const key of Object.keys(before)) if (!hasOwn(after, key)) changes.push({
15725
+ for (const key of keysOf(before)) if (!hasOwn(after, key)) changes.push({
15507
15726
  key,
15508
15727
  kind: "deleted"
15509
15728
  });
@@ -16919,7 +17138,7 @@ function routeStoreUpdate(recipe) {
16919
17138
  return;
16920
17139
  }
16921
17140
  if (activeScopes.length === 0) return void 0;
16922
- commitScopes(running());
17141
+ commitScopes(running$1());
16923
17142
  const inner = activeScopes[activeScopes.length - 1];
16924
17143
  const view = {
16925
17144
  ...useStoryStore.getState(),
@@ -17074,7 +17293,7 @@ function commitScopes(commits) {
17074
17293
  */
17075
17294
  var changesOf = (base, work) => changesBetween(base, work);
17076
17295
  /** Every running mutation, to commit with its code going on. */
17077
- var running = () => activeScopes.map((scope) => ({
17296
+ var running$1 = () => activeScopes.map((scope) => ({
17078
17297
  scope,
17079
17298
  keepRunning: true
17080
17299
  }));
@@ -17112,7 +17331,7 @@ function resync(scope) {
17112
17331
  */
17113
17332
  function runWithCommittedMutations(action) {
17114
17333
  if (activeScopes.length === 0) return action();
17115
- commitScopes(running());
17334
+ commitScopes(running$1());
17116
17335
  const suspended = activeScopes.splice(0);
17117
17336
  try {
17118
17337
  return action();
@@ -17128,7 +17347,7 @@ function runWithCommittedMutations(action) {
17128
17347
  * Nothing is committed when `run` throws.
17129
17348
  */
17130
17349
  function mutateState(run) {
17131
- commitScopes(running());
17350
+ commitScopes(running$1());
17132
17351
  const held = locateObjects(namespacesOf(getActiveMutationScope() ?? useStoryStore.getState()), []);
17133
17352
  const scope = startScope();
17134
17353
  const adopt = clonerFor(scope.work, held);
@@ -17137,7 +17356,7 @@ function mutateState(run) {
17137
17356
  } finally {
17138
17357
  activeScopes.pop();
17139
17358
  }
17140
- commitScopes([...running(), {
17359
+ commitScopes([...running$1(), {
17141
17360
  scope,
17142
17361
  keepRunning: false
17143
17362
  }]);
@@ -17160,7 +17379,7 @@ function executeMutation(code, mergedLocals, scopeUpdate) {
17160
17379
  } finally {
17161
17380
  activeScopes.pop();
17162
17381
  }
17163
- commitScopes([...running(), {
17382
+ commitScopes([...running$1(), {
17164
17383
  scope,
17165
17384
  keepRunning: false
17166
17385
  }]);
@@ -17960,6 +18179,12 @@ function loadedEntryMoment(payload) {
17960
18179
  if (typeof moment.variables !== "object" || moment.variables === null) return;
17961
18180
  return moment;
17962
18181
  }
18182
+ /** The variable paths `Story.set` writes while a save's hooks run. */
18183
+ var hookWrites = null;
18184
+ /** Note that `path` of the variables was written (see keepHookWrites). */
18185
+ function recordHookWrite(path) {
18186
+ hookWrites?.set(pathKey(path), path);
18187
+ }
17963
18188
  /**
17964
18189
  * Write the changes between `before` and `after` (the live variables around
17965
18190
  * the `beforesave` hooks) into the payload's snapshot of the saved moment. A
@@ -17973,10 +18198,22 @@ function loadedEntryMoment(payload) {
17973
18198
  * snapshot's own object of it (#302). Only the payload's copy changes: the
17974
18199
  * live history keeps the recorded snapshot (#159).
17975
18200
  */
17976
- function keepHookWrites(payload, before, after) {
18201
+ function keepHookWrites(payload, before, after, written) {
17977
18202
  const moment = payload.history[payload.historyIndex];
17978
18203
  if (!moment) return;
17979
18204
  const changes = changesBetween(before, after, true);
18205
+ const keys = new Set(changes.map((c) => pathKey(c.path)));
18206
+ for (const path of written) {
18207
+ if (underChange(path, keys)) continue;
18208
+ keys.add(pathKey(path));
18209
+ const value = getByPath(after, path);
18210
+ if (deepEqual(getByPath(moment.variables, path), value)) continue;
18211
+ changes.push({
18212
+ path,
18213
+ deleted: false,
18214
+ value
18215
+ });
18216
+ }
17980
18217
  if (changes.length === 0) return;
17981
18218
  const work = deepClone(moment.variables);
17982
18219
  const seen = existingObjects(locateObjects(after, changes), work);
@@ -18013,7 +18250,7 @@ function writeHookChange(work, after, change, own) {
18013
18250
  }
18014
18251
  function writeKey(holder, key, value, change) {
18015
18252
  const deleted = change?.deleted ?? false;
18016
- if (Array.isArray(holder)) {
18253
+ if (Array.isArray(holder) && (key === "length" || isIndexKey(key))) {
18017
18254
  const index = Number(key);
18018
18255
  if (deleted) {
18019
18256
  if (change && "hole" in change) delete holder[index];
@@ -18493,9 +18730,12 @@ var useStoryStore = create()(storyStore((set, get) => ({
18493
18730
  },
18494
18731
  beginSave: () => {
18495
18732
  const before = get().variables;
18733
+ const writes = /* @__PURE__ */ new Map();
18734
+ hookWrites = writes;
18496
18735
  return () => {
18736
+ if (hookWrites === writes) hookWrites = null;
18497
18737
  const payload = get().getSavePayload();
18498
- keepHookWrites(payload, before, get().variables);
18738
+ keepHookWrites(payload, before, get().variables, [...writes.values()]);
18499
18739
  return payload;
18500
18740
  };
18501
18741
  },
@@ -18666,20 +18906,22 @@ function tabIndexAttr(el) {
18666
18906
  function isTabStop(el) {
18667
18907
  const tabIndex = tabIndexAttr(el);
18668
18908
  if (tabIndex !== null && tabIndex < 0) return false;
18669
- if (el.hasAttribute("contenteditable") && !el.matches("a[href], button, input, select, textarea, iframe, summary") && (!el.isContentEditable || el.parentElement?.isContentEditable)) return false;
18909
+ if (tabIndex === null && el.hasAttribute("contenteditable") && !el.matches("a[href], button, input, select, textarea, iframe, summary") && (!el.isContentEditable || el.parentElement?.isContentEditable)) return false;
18670
18910
  if (el.localName === "summary") {
18671
18911
  const details = el.parentElement;
18672
18912
  if (details?.localName !== "details" || Array.from(details.children).find((c) => c.localName === "summary") !== el) return tabIndex !== null;
18673
18913
  }
18674
- if (el instanceof HTMLInputElement && el.type === "radio" && el.name) {
18675
- const group = Array.from((el.form ?? el.getRootNode()).querySelectorAll("input[type=\"radio\"]")).filter((r) => r.name === el.name && r.form === el.form && (tabIndexAttr(r) ?? 0) >= 0 && isAvailable(r));
18914
+ const input = el;
18915
+ if (el.localName === "input" && input.type === "radio" && input.name) {
18916
+ const group = Array.from((input.form ?? el.getRootNode()).querySelectorAll("input[type=\"radio\"]")).filter((r) => r.name === input.name && r.form === input.form && (tabIndexAttr(r) ?? 0) >= 0 && isAvailable(r));
18676
18917
  return el === (group.find((r) => r.checked) ?? group[0]);
18677
18918
  }
18678
18919
  return true;
18679
18920
  }
18680
18921
  /**
18681
- * The elements of `root` in the order Tab visits them: positive tabindexes
18682
- * first, ascending, then the others in document order.
18922
+ * The elements of `root` (the dialog panel, or an embedded document) in the
18923
+ * order Tab visits them: positive tabindexes first, ascending, then the
18924
+ * others in document order.
18683
18925
  */
18684
18926
  function focusables(root) {
18685
18927
  const stops = Array.from(root.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
@@ -18706,19 +18948,51 @@ var SEGMENTED_INPUTS = /* @__PURE__ */ new Set([
18706
18948
  ]);
18707
18949
  /** Whether the element has native tab stops inside it, in its shadow tree. */
18708
18950
  function hasNativeStops(el) {
18709
- if (el instanceof HTMLMediaElement) return el.controls;
18710
- return el instanceof HTMLInputElement && SEGMENTED_INPUTS.has(el.type) && !el.readOnly;
18951
+ if (!el) return false;
18952
+ if (el.localName === "audio" || el.localName === "video") return el.controls;
18953
+ const input = el;
18954
+ return el.localName === "input" && SEGMENTED_INPUTS.has(input.type) && !input.readOnly;
18711
18955
  }
18712
- /** The tab stops of an embedded document, in tab order. */
18713
- function frameStops(doc) {
18714
- if (!doc) return [];
18715
- return Array.from(doc.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
18956
+ /** Whether `el` is an iframe element, of this realm or of an embedded one. */
18957
+ function isFrame(el) {
18958
+ return el.localName === "iframe";
18959
+ }
18960
+ /** The document of a frame, or null when it is not accessible. */
18961
+ function frameDocument(frame) {
18962
+ try {
18963
+ return frame.contentDocument;
18964
+ } catch {
18965
+ return null;
18966
+ }
18967
+ }
18968
+ /** The iframe element that holds `doc`, null for the top document. */
18969
+ function frameOf(doc) {
18970
+ try {
18971
+ return doc.defaultView?.frameElement;
18972
+ } catch {
18973
+ return null;
18974
+ }
18975
+ }
18976
+ /**
18977
+ * The stop after (or before) `from` among `items`, the tab stops of `root`,
18978
+ * undefined past the end. `from` may be no stop of its own: then the next one
18979
+ * in document order. Outside `root`, the first (or last) stop.
18980
+ */
18981
+ function nextStop(items, root, from, backwards) {
18982
+ const at = from ? items.indexOf(from) : -1;
18983
+ if (at !== -1) return items[at + (backwards ? -1 : 1)];
18984
+ if (from && from !== root && root.contains(from)) {
18985
+ const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
18986
+ return backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
18987
+ }
18988
+ return backwards ? items[items.length - 1] : items[0];
18716
18989
  }
18717
18990
  function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18718
18991
  useLayoutEffect(() => {
18719
18992
  const panel = panelRef.current;
18720
18993
  if (!panel) return;
18721
- const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
18994
+ const focused = document.activeElement;
18995
+ const opener = focused instanceof HTMLElement || focused instanceof SVGElement ? focused : null;
18722
18996
  const entry = { panel };
18723
18997
  openModals.push(entry);
18724
18998
  const body = panel.querySelector(bodySelector) ?? panel;
@@ -18734,29 +19008,33 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18734
19008
  const panel = panelRef.current;
18735
19009
  if (!panel) return;
18736
19010
  const top = () => openModals[openModals.length - 1]?.panel === panel;
18737
- /**
18738
- * Move focus to the next (or previous) modal control from `from`. The
18739
- * order is computed here, never left to the browser: its positive-tabindex
18740
- * sequence spans the whole document and would lead out of the modal
18741
- * (#424). `from` may be an element of an embedded document, whose frame
18742
- * element then stands in for it.
18743
- */
18744
19011
  /** Focus `el`; a frame is entered at its first (or last) control (#460). */
18745
19012
  const enter = (el, backwards) => {
18746
- if (el instanceof HTMLIFrameElement) {
18747
- let inner = [];
18748
- try {
18749
- inner = frameStops(el.contentDocument);
18750
- } catch {}
19013
+ if (isFrame(el)) {
19014
+ const doc = frameDocument(el);
19015
+ const inner = doc ? focusables(doc) : [];
18751
19016
  const edge = backwards ? inner[inner.length - 1] : inner[0];
18752
- if (edge) {
18753
- edge.focus();
18754
- return;
18755
- }
19017
+ if (edge) return enter(edge, backwards);
18756
19018
  }
18757
19019
  el.focus();
18758
19020
  };
19021
+ /**
19022
+ * Move focus to the next (or previous) modal control from `from`. The
19023
+ * order is computed here, never left to the browser: its positive-tabindex
19024
+ * sequence spans the whole document and would lead out of the modal
19025
+ * (#424). `from` is an element of the dialog, or of an embedded document;
19026
+ * past the last control of a frame, focus goes on after the frame element
19027
+ * in the document that holds it.
19028
+ */
18759
19029
  const moveFocus = (from, backwards) => {
19030
+ const doc = from?.ownerDocument;
19031
+ const frame = doc && doc !== document ? frameOf(doc) : null;
19032
+ if (doc && frame) {
19033
+ const next = nextStop(focusables(doc), doc, from, backwards);
19034
+ if (next) enter(next, backwards);
19035
+ else moveFocus(frame, backwards);
19036
+ return;
19037
+ }
18760
19038
  const items = focusables(panel);
18761
19039
  const first = items[0];
18762
19040
  const last = items[items.length - 1];
@@ -18764,107 +19042,102 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18764
19042
  panel.focus();
18765
19043
  return;
18766
19044
  }
18767
- const at = from ? items.indexOf(from) : -1;
18768
- let next;
18769
- if (at !== -1) next = items[at + (backwards ? -1 : 1)];
18770
- else if (from && from !== panel && panel.contains(from)) {
18771
- const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
18772
- next = backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
18773
- } else next = backwards ? last : first;
19045
+ const next = nextStop(items, panel, from, backwards);
18774
19046
  enter(next ?? (backwards ? last : first), backwards);
18775
19047
  };
18776
19048
  let steppingNative = null;
18777
- const onKeyDown = (e) => {
18778
- if (!top()) return;
18779
- if (e.key === "Escape") {
18780
- if (!dismissible) return;
18781
- e.preventDefault();
18782
- e.stopPropagation();
18783
- onClose();
18784
- return;
18785
- }
18786
- if (e.key !== "Tab") return;
18787
- const active = document.activeElement;
18788
- if (hasNativeStops(active)) {
18789
- steppingNative = {
18790
- el: active,
18791
- backwards: e.shiftKey
18792
- };
18793
- return;
18794
- }
18795
- e.preventDefault();
18796
- moveFocus(active, e.shiftKey);
18797
- };
18798
- const onPointerDown = () => {
18799
- steppingNative = null;
18800
- };
18801
- const controller = new AbortController();
18802
- const { signal } = controller;
18803
- const frameDocs = /* @__PURE__ */ new Map();
18804
- const attachFrame = (frame) => {
18805
- let doc = null;
18806
- try {
18807
- doc = frame.contentDocument;
18808
- } catch {}
18809
- if (!doc || frameDocs.get(frame) === doc) return;
18810
- frameDocs.set(frame, doc);
18811
- const onFrameKeyDown = (e) => {
19049
+ const keyHandler = (doc, frame) => {
19050
+ return (e) => {
18812
19051
  if (!top()) return;
18813
- if (e.key !== "Tab") return onKeyDown(e);
18814
- const inner = frameStops(doc);
18815
- const active = doc.activeElement;
18816
- const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
18817
- if (!edge || active === edge || active === doc.body) {
19052
+ if (e.key === "Escape") {
19053
+ if (!dismissible) return;
18818
19054
  e.preventDefault();
18819
- moveFocus(frame, e.shiftKey);
19055
+ e.stopPropagation();
19056
+ onClose();
19057
+ return;
18820
19058
  }
19059
+ if (e.key !== "Tab") return;
19060
+ const active = doc.activeElement;
19061
+ if (frame) {
19062
+ steppingNative = null;
19063
+ const inner = focusables(doc);
19064
+ const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
19065
+ if (edge && active !== edge && active !== doc.body) return;
19066
+ }
19067
+ if (hasNativeStops(active)) {
19068
+ steppingNative = {
19069
+ el: active,
19070
+ from: frame ?? active,
19071
+ backwards: e.shiftKey
19072
+ };
19073
+ return;
19074
+ }
19075
+ e.preventDefault();
19076
+ moveFocus(frame ?? active, e.shiftKey);
18821
19077
  };
18822
- doc.addEventListener("keydown", onFrameKeyDown, { signal });
18823
- };
18824
- const attachFrames = () => {
18825
- panel.querySelectorAll("iframe").forEach(attachFrame);
18826
19078
  };
18827
- const onLoad = (e) => {
18828
- if (e.target instanceof HTMLIFrameElement) attachFrame(e.target);
19079
+ const onPointerDown = () => {
19080
+ steppingNative = null;
18829
19081
  };
18830
- panel.addEventListener("load", onLoad, {
18831
- capture: true,
18832
- signal
18833
- });
18834
- const frames = new MutationObserver(attachFrames);
18835
- frames.observe(panel, {
18836
- childList: true,
18837
- subtree: true
18838
- });
18839
- attachFrames();
18840
19082
  const onFocusIn = (e) => {
18841
19083
  const target = e.target;
18842
19084
  if (steppingNative && target !== steppingNative.el && top()) {
18843
- const { el, backwards } = steppingNative;
19085
+ const { from, backwards } = steppingNative;
18844
19086
  steppingNative = null;
18845
- moveFocus(el, backwards);
19087
+ moveFocus(from, backwards);
18846
19088
  return;
18847
19089
  }
18848
19090
  if (!top() || !(target instanceof Node) || panel.contains(target)) return;
18849
19091
  if (target === document.body || target === document.documentElement) return;
18850
19092
  moveFocus(null, false);
18851
19093
  };
18852
- document.addEventListener("keydown", onKeyDown, { signal });
18853
- document.addEventListener("pointerdown", onPointerDown, {
18854
- capture: true,
18855
- signal
18856
- });
18857
19094
  const onFocusOut = (e) => {
18858
19095
  const pending = steppingNative;
18859
19096
  if (!pending || e.target !== pending.el || e.relatedTarget || !top()) return;
18860
19097
  steppingNative = null;
18861
- moveFocus(pending.el, pending.backwards);
19098
+ moveFocus(pending.from, pending.backwards);
19099
+ };
19100
+ const controller = new AbortController();
19101
+ const { signal } = controller;
19102
+ const listen = (doc, frame) => {
19103
+ doc.addEventListener("keydown", keyHandler(doc, frame), { signal });
19104
+ doc.addEventListener("pointerdown", onPointerDown, {
19105
+ capture: true,
19106
+ signal
19107
+ });
19108
+ doc.addEventListener("focusout", onFocusOut, { signal });
18862
19109
  };
18863
- document.addEventListener("focusout", onFocusOut, { signal });
19110
+ const frameDocs = /* @__PURE__ */ new Map();
19111
+ const observers = [];
19112
+ const attachFrame = (frame) => {
19113
+ const doc = frameDocument(frame);
19114
+ if (!doc || frameDocs.get(frame) === doc) return;
19115
+ frameDocs.set(frame, doc);
19116
+ listen(doc, frame);
19117
+ watchFrames(doc);
19118
+ };
19119
+ const watchFrames = (root) => {
19120
+ const attachAll = () => root.querySelectorAll("iframe").forEach(attachFrame);
19121
+ root.addEventListener("load", (e) => {
19122
+ if (e.target instanceof Node && isFrame(e.target)) attachFrame(e.target);
19123
+ }, {
19124
+ capture: true,
19125
+ signal
19126
+ });
19127
+ const observer = new MutationObserver(attachAll);
19128
+ observer.observe(root, {
19129
+ childList: true,
19130
+ subtree: true
19131
+ });
19132
+ observers.push(observer);
19133
+ attachAll();
19134
+ };
19135
+ watchFrames(panel);
19136
+ listen(document, null);
18864
19137
  document.addEventListener("focusin", onFocusIn, { signal });
18865
19138
  return () => {
18866
19139
  controller.abort();
18867
- frames.disconnect();
19140
+ observers.forEach((o) => o.disconnect());
18868
19141
  };
18869
19142
  }, [dismissible, onClose]);
18870
19143
  }
@@ -19437,21 +19710,33 @@ var OPTIONAL_ACTION_FIELDS = [
19437
19710
  var actions = /* @__PURE__ */ new Map();
19438
19711
  var idCounters = /* @__PURE__ */ new Map();
19439
19712
  /**
19713
+ * IDs handed out and not yet registered, or registered: a control registers
19714
+ * in a layout effect, after every control of the same render has allocated its
19715
+ * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
19716
+ * Released when the last registration of an ID goes.
19717
+ */
19718
+ var reserved = /* @__PURE__ */ new Set();
19719
+ /**
19440
19720
  * The counters reset on every navigation, so a passage's controls get the
19441
19721
  * same IDs each time it is shown. Controls that stay mounted across
19442
19722
  * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19443
- * ID still registered (#233).
19723
+ * ID still registered (#233) and every one allocated but not registered yet
19724
+ * (#486).
19444
19725
  */
19445
19726
  function generateActionId(type, key, authorId) {
19446
- if (authorId) return authorId;
19727
+ if (authorId) {
19728
+ reserved.add(authorId);
19729
+ return authorId;
19730
+ }
19447
19731
  const base = `${type}:${key}`;
19448
19732
  let count = idCounters.get(base) ?? 0;
19449
19733
  let id;
19450
19734
  do {
19451
19735
  count++;
19452
19736
  id = count === 1 ? base : `${base}:${count}`;
19453
- } while (actions.has(id));
19737
+ } while (actions.has(id) || reserved.has(id));
19454
19738
  idCounters.set(base, count);
19739
+ reserved.add(id);
19455
19740
  return id;
19456
19741
  }
19457
19742
  function registerAction(action) {
@@ -19475,11 +19760,34 @@ function registerAction(action) {
19475
19760
  const index = current ? current.indexOf(entry) : -1;
19476
19761
  if (!current || index === -1) return;
19477
19762
  current.splice(index, 1);
19478
- if (current.length === 0) actions.delete(id);
19763
+ if (current.length === 0) {
19764
+ actions.delete(id);
19765
+ reserved.delete(id);
19766
+ }
19479
19767
  if (index === current.length) notify();
19480
19768
  }
19481
19769
  };
19482
19770
  }
19771
+ /** The promises of the performed actions that have not settled yet. */
19772
+ var running = /* @__PURE__ */ new Set();
19773
+ /**
19774
+ * Perform an action, as `Story.performAction()` does. One that returns a
19775
+ * promise is tracked until it settles, for `settleRunningActions()`, and the
19776
+ * promise is returned for the caller to await (its rejection stays the
19777
+ * caller's to handle).
19778
+ */
19779
+ function performRegisteredAction(action, value) {
19780
+ const result = action.perform(value);
19781
+ if (!result || typeof result.then !== "function") return result;
19782
+ const done = () => void running.delete(result);
19783
+ running.add(result);
19784
+ result.then(done, done);
19785
+ return result.then((v) => v);
19786
+ }
19787
+ /** Wait until every performed action has finished, whether or not it failed. */
19788
+ async function settleRunningActions() {
19789
+ while (running.size > 0) await Promise.allSettled(running);
19790
+ }
19483
19791
  function getActions() {
19484
19792
  return Array.from(actions.values(), listed);
19485
19793
  }
@@ -19492,6 +19800,7 @@ function listed(entries) {
19492
19800
  }
19493
19801
  function resetIdCounters() {
19494
19802
  idCounters.clear();
19803
+ for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
19495
19804
  }
19496
19805
  function notify() {
19497
19806
  emit("actionsChanged");
@@ -19772,6 +20081,7 @@ function createStoryAPI() {
19772
20081
  for (const [name] of entries) {
19773
20082
  const { isTransient, key } = parseName(name);
19774
20083
  warnIfUndeclared(isTransient, key);
20084
+ if (!isTransient) recordHookWrite(key.split("."));
19775
20085
  }
19776
20086
  if (entries.some(([k]) => k.includes("."))) {
19777
20087
  mutateState((work, adopt) => {
@@ -19855,7 +20165,7 @@ function createStoryAPI() {
19855
20165
  const action = getAction(id);
19856
20166
  if (!action) throw new Error(`spindle: Action "${id}" not found.`);
19857
20167
  if (action.disabled) throw new Error(`spindle: Action "${id}" is disabled.`);
19858
- action.perform(value);
20168
+ return performRegisteredAction(action, value);
19859
20169
  },
19860
20170
  on(event, callback) {
19861
20171
  if (event === "variableChanged") ensureVariableChangedSubscription();
@@ -19864,6 +20174,7 @@ function createStoryAPI() {
19864
20174
  return unsub;
19865
20175
  },
19866
20176
  async waitForActions() {
20177
+ await settleRunningActions();
19867
20178
  await new Promise((resolve) => {
19868
20179
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
19869
20180
  });
@@ -20190,10 +20501,12 @@ function validateMarkup(passages, options) {
20190
20501
  * an operator, a reference, a spread) is "not static", which is no error: the
20191
20502
  * value is simply not known without running the code.
20192
20503
  */
20193
- var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d+)?)(n?)/y;
20504
+ var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)(n?)/y;
20194
20505
  var IDENT_RE = /[A-Za-z_$][\w$]*/y;
20195
20506
  var KEY_RE = /[\w$]+/y;
20196
20507
  var ARROW_RE = /(?:async\s+)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*=>/y;
20508
+ /** The end of a line: the four line terminators of JavaScript. */
20509
+ var LINE_END_RE = /[\n\r\u2028\u2029]/g;
20197
20510
  var ARRAY_INDEX_RE = /^(?:0|[1-9]\d{0,8})$/;
20198
20511
  var UNSUPPORTED_UNDEFINED = {
20199
20512
  unsupported: "undefined",
@@ -20215,6 +20528,22 @@ function entryOrder(keys) {
20215
20528
  const all = [...keys];
20216
20529
  return [...all.filter((key) => ARRAY_INDEX_RE.test(key)).sort((a, b) => Number(a) - Number(b)), ...all.filter((key) => !ARRAY_INDEX_RE.test(key))];
20217
20530
  }
20531
+ /**
20532
+ * Where the regex literals in `src` are, by their start: JavaScript text
20533
+ * cannot tell a regex from a division without the code before it, which the
20534
+ * lexer reads. `handlers` see the same walk.
20535
+ */
20536
+ function regexLiterals(src, goal = "expression", handlers = {}) {
20537
+ const ends = /* @__PURE__ */ new Map();
20538
+ lexJs(src, {
20539
+ ...handlers,
20540
+ literal(text, index, nesting) {
20541
+ if (text.charAt(0) === "/" && !/^\/[/*]/.test(text)) ends.set(index, index + text.length);
20542
+ handlers.literal?.(text, index, nesting);
20543
+ }
20544
+ }, goal);
20545
+ return ends;
20546
+ }
20218
20547
  /** `String(value)` of a BigInt literal's digits, or `undefined` if they are no BigInt. */
20219
20548
  function bigintValue(digits) {
20220
20549
  try {
@@ -20228,9 +20557,15 @@ function bigintValue(digits) {
20228
20557
  * helpers that skip what is not read are shared (see macro-discovery.ts).
20229
20558
  */
20230
20559
  var Reader = class {
20231
- constructor(src) {
20560
+ /**
20561
+ * `regexes` (see regexLiterals) are read from `src` when they are first
20562
+ * needed, unless the caller has them already.
20563
+ */
20564
+ constructor(src, options = {}) {
20232
20565
  this.src = src;
20233
20566
  this.i = 0;
20567
+ this.goal = options.goal ?? "expression";
20568
+ this.regexes = options.regexes;
20234
20569
  }
20235
20570
  /** Skip whitespace and comments. */
20236
20571
  space() {
@@ -20238,8 +20573,8 @@ var Reader = class {
20238
20573
  for (;;) {
20239
20574
  while (/\s/.test(src.charAt(this.i))) this.i++;
20240
20575
  if (src.startsWith("//", this.i)) {
20241
- const end = src.indexOf("\n", this.i);
20242
- this.i = end < 0 ? src.length : end;
20576
+ LINE_END_RE.lastIndex = this.i;
20577
+ this.i = LINE_END_RE.test(src) ? LINE_END_RE.lastIndex - 1 : src.length;
20243
20578
  } else if (src.startsWith("/*", this.i)) {
20244
20579
  const end = src.indexOf("*/", this.i + 2);
20245
20580
  this.i = end < 0 ? src.length : end + 2;
@@ -20298,10 +20633,9 @@ var Reader = class {
20298
20633
  i++;
20299
20634
  while (/\s/.test(src.charAt(i))) i++;
20300
20635
  }
20301
- NUMBER_RE.lastIndex = i;
20302
- const match = NUMBER_RE.exec(src);
20636
+ const match = this.numberAt(i);
20303
20637
  if (match) {
20304
- this.i = NUMBER_RE.lastIndex;
20638
+ this.i = i + match[0].length;
20305
20639
  if (!match[1]) return { shape: { type: "number" } };
20306
20640
  if (sign === "+") return { throws: "Cannot convert a BigInt value to a number" };
20307
20641
  const digits = bigintValue(match[0].slice(0, -1));
@@ -20311,11 +20645,17 @@ var Reader = class {
20311
20645
  };
20312
20646
  }
20313
20647
  IDENT_RE.lastIndex = i;
20314
- if (IDENT_RE.exec(src)?.[0] === "Infinity") {
20648
+ const word = IDENT_RE.exec(src)?.[0];
20649
+ if (word === "Infinity" || word === "NaN") {
20315
20650
  this.i = IDENT_RE.lastIndex;
20316
20651
  return { shape: { type: "number" } };
20317
20652
  }
20318
20653
  }
20654
+ /** The numeric literal (a BigInt's `n` is `match[1]`) at `at`, if there is one. */
20655
+ numberAt(at) {
20656
+ NUMBER_RE.lastIndex = at;
20657
+ return NUMBER_RE.exec(this.src);
20658
+ }
20319
20659
  /** A keyword, a function, or a name (which is not static). */
20320
20660
  word() {
20321
20661
  const { src } = this;
@@ -20335,6 +20675,7 @@ var Reader = class {
20335
20675
  this.i = end;
20336
20676
  return { shape: { type: "null" } };
20337
20677
  case "NaN":
20678
+ case "Infinity":
20338
20679
  this.i = end;
20339
20680
  return { shape: { type: "number" } };
20340
20681
  case "undefined":
@@ -20475,14 +20816,22 @@ var Reader = class {
20475
20816
  const { src } = this;
20476
20817
  const c = src.charAt(this.i);
20477
20818
  if (c === "\"" || c === "'") return this.stringValue();
20819
+ if (/[\d.]/.test(c)) return this.numberKey();
20478
20820
  KEY_RE.lastIndex = this.i;
20479
20821
  const found = KEY_RE.exec(src)?.[0];
20480
20822
  if (found === void 0) return void 0;
20481
20823
  this.i = KEY_RE.lastIndex;
20482
- if (!/^\d/.test(found)) return found;
20483
- const digits = found.replace(/_/g, "");
20824
+ return found;
20825
+ }
20826
+ /** A number as a key: the whole literal, named as the runtime names it. */
20827
+ numberKey() {
20828
+ const match = this.numberAt(this.i);
20829
+ if (!match) return void 0;
20830
+ this.i += match[0].length;
20831
+ if (/[\w$]/.test(this.src.charAt(this.i))) return void 0;
20832
+ const digits = match[0].replace(/_/g, "");
20484
20833
  if (/^0\d/.test(digits)) return void 0;
20485
- if (digits.endsWith("n") && !/^0[xX]/.test(digits)) return bigintValue(digits.slice(0, -1));
20834
+ if (match[1]) return bigintValue(digits.slice(0, -1));
20486
20835
  const value = Number(digits);
20487
20836
  return Number.isNaN(value) ? void 0 : String(value);
20488
20837
  }
@@ -20525,6 +20874,14 @@ var Reader = class {
20525
20874
  this.space();
20526
20875
  return true;
20527
20876
  }
20877
+ if (c === "/") {
20878
+ this.regexes ??= regexLiterals(src, this.goal);
20879
+ const end = this.regexes.get(this.i);
20880
+ if (end !== void 0) {
20881
+ this.i = end;
20882
+ return true;
20883
+ }
20884
+ }
20528
20885
  if (c === "[" || c === "{" || c === "(") return this.skipBalanced();
20529
20886
  if (c === "]" || c === "}" || c === ")") return false;
20530
20887
  this.i++;
@@ -20779,6 +21136,7 @@ function checkReference(ref, declared) {
20779
21136
  const part = ref.path[i];
20780
21137
  if (current.type === "array") return null;
20781
21138
  if (current.type === "null") return null;
21139
+ if (current.type === "string" && isArrayIndex(part)) continue;
20782
21140
  const sample = PRIMITIVE_SAMPLES[current.type];
20783
21141
  if (sample && part in sample) {
20784
21142
  const memberType = typeof sample[part];
@@ -20808,10 +21166,28 @@ var BUILTIN_STORE_VAR_MACROS = [
20808
21166
  "textbox"
20809
21167
  ];
20810
21168
  var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
20811
- /** A reference written at `index` of `code`, with its dot path. */
20812
- function referenceAt(code, index, at) {
21169
+ /** A `.field` path written right after a reference, which may be empty. */
21170
+ var FIELD_PATH_RE = /(?:\.\w+)*/y;
21171
+ /**
21172
+ * The reference to variable `name`, which JavaScript reads at `[start, end)`
21173
+ * of `code` (the sigil and the name as written, which may be spelled with
21174
+ * escapes), with the dot path written after it.
21175
+ */
21176
+ function referenceAt(code, sigil, name, start, end, at) {
21177
+ FIELD_PATH_RE.lastIndex = end;
21178
+ const fields = FIELD_PATH_RE.exec(code)[0];
21179
+ return {
21180
+ sigil,
21181
+ name,
21182
+ path: fields ? fields.slice(1).split(".") : [],
21183
+ start: at(start),
21184
+ end: at(end + fields.length)
21185
+ };
21186
+ }
21187
+ /** A reference written at `index` of `term`, a `variable` parameter as written. */
21188
+ function termReferenceAt(term, index, at) {
20813
21189
  VAR_PATH_RE.lastIndex = index;
20814
- const match = VAR_PATH_RE.exec(code);
21190
+ const match = VAR_PATH_RE.exec(term);
20815
21191
  if (!match) return void 0;
20816
21192
  const [name, ...path] = match[2].split(".");
20817
21193
  return {
@@ -20856,46 +21232,51 @@ function scanCode(code, at, emit, goal = "expression") {
20856
21232
  }
20857
21233
  for (const ref of parsed.refs) {
20858
21234
  if (ref.sigil !== "$" && ref.sigil !== "%") continue;
20859
- const found = referenceAt(code, ref.start, at);
20860
- if (found) emit(found);
21235
+ emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
20861
21236
  }
20862
21237
  }
20863
21238
  /** `scanCode` for code acorn can't parse: lexed leniently. */
20864
21239
  function scanCodeLeniently(code, at, emit, goal) {
20865
21240
  lexJs(code, {
20866
- variable(sigil, _name, index) {
21241
+ variable(sigil, name, index, _nesting, end) {
20867
21242
  if (sigil !== "$" && sigil !== "%") return;
20868
- const found = referenceAt(code, index, at);
20869
- if (found) emit(found);
21243
+ emit(referenceAt(code, sigil, name, index, end, at));
20870
21244
  },
20871
21245
  literal() {}
20872
21246
  }, goal);
20873
21247
  }
21248
+ /** Report the references in the pieces of code and markup text of arguments. */
21249
+ function scanPieces(pieces, at, emit, options) {
21250
+ for (const piece of pieces) {
21251
+ const pieceAt = (i) => at(pieceOffset(piece, i));
21252
+ if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
21253
+ else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
21254
+ ...options,
21255
+ storeVarMacros: NO_STORE_VAR_MACROS
21256
+ });
21257
+ }
21258
+ }
20874
21259
  /**
20875
21260
  * Report the references in the arguments of a macro by what its parameters
20876
21261
  * say each holds (see ParameterDef.holds): code is scanned as code and
20877
21262
  * markup as markup, but literal text (a placeholder, a passage name) holds
20878
21263
  * none. A macro without declared parameters, or arguments that do not
20879
- * parse, are scanned as code.
21264
+ * parse, are scanned as code. The arguments of a widget that declares what
21265
+ * some parameters hold are also read by those (see widgetPieces).
20880
21266
  */
20881
- function scanArgs(token, params, at, emit, options) {
21267
+ function scanArgs(token, parametersOf, at, emit, options) {
20882
21268
  if (!token.rawArgs) return;
21269
+ const params = parametersOf(token.name);
21270
+ let byParameters = false;
20883
21271
  if (params) {
20884
21272
  if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
20885
21273
  const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
20886
- if (!pieces.some((piece) => piece.kind === "argument-error")) {
20887
- for (const piece of pieces) {
20888
- const pieceAt = (i) => at(pieceOffset(piece, i));
20889
- if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
20890
- else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
20891
- ...options,
20892
- storeVarMacros: NO_STORE_VAR_MACROS
20893
- });
20894
- }
20895
- return;
20896
- }
21274
+ byParameters = !pieces.some((piece) => piece.kind === "argument-error");
21275
+ if (byParameters) scanPieces(pieces, at, emit, options);
20897
21276
  }
20898
- scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
21277
+ if (!byParameters) scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
21278
+ const widget = parametersOf.widget?.(token.name);
21279
+ if (widget) scanPieces(widgetPieces(token.rawArgs, token.argsStart, widget, token.name, ""), at, emit, options);
20899
21280
  }
20900
21281
  /**
20901
21282
  * Report the variables the `variable` parameters of a macro name
@@ -20913,7 +21294,7 @@ function scanVariableParameters(token, params, at, emit) {
20913
21294
  for (const param of params) {
20914
21295
  const span = spans.get(param);
20915
21296
  if (param.type !== "variable" || !span) continue;
20916
- const ref = referenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
21297
+ const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
20917
21298
  if (ref) emit(ref);
20918
21299
  }
20919
21300
  }
@@ -20954,7 +21335,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
20954
21335
  else scanInterpolations(value, valueIn, emit, options);
20955
21336
  }
20956
21337
  else if (token.type === "macro" && !token.isClose) {
20957
- scanArgs(token, parametersOf(token.name), at, emit, options);
21338
+ scanArgs(token, parametersOf, at, emit, options);
20958
21339
  scanSelectors(content, token, at, emit, options);
20959
21340
  if (storeVarMacros.has(token.name.toLowerCase())) {
20960
21341
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
@@ -20997,7 +21378,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
20997
21378
  function collectVariableReferences(content, options) {
20998
21379
  const found = [];
20999
21380
  withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
21000
- return found;
21381
+ return found.sort((a, b) => a.start - b.start);
21001
21382
  }
21002
21383
  /**
21003
21384
  * The invalid variable references of the passages, against what is declared,
@@ -21206,14 +21587,43 @@ function resolveTransition(targetTags, nextTransition, storeDefault) {
21206
21587
  //#endregion
21207
21588
  //#region src/components/macros/PassageDisplay.tsx
21208
21589
  /**
21590
+ * Copy the live state cloneNode drops from `source` into its clone: the
21591
+ * pixels of each canvas and the values of form controls (cloneNode keeps
21592
+ * attributes only, and a canvas's bitmap is not one). Source and clone have
21593
+ * the same structure, so elements pair up by position. Best effort: a canvas
21594
+ * that can not be drawn from stays as cloned.
21595
+ */
21596
+ function copyLiveState(source, clone) {
21597
+ const pairs = (selector, each) => {
21598
+ const from = source.querySelectorAll(selector);
21599
+ const to = clone.querySelectorAll(selector);
21600
+ from.forEach((el, i) => to[i] && each(el, to[i]));
21601
+ };
21602
+ pairs("canvas", (from, to) => {
21603
+ if (!from.width || !from.height) return;
21604
+ try {
21605
+ if (to.width !== from.width) to.width = from.width;
21606
+ if (to.height !== from.height) to.height = from.height;
21607
+ to.getContext("2d")?.drawImage(from, 0, 0);
21608
+ } catch {}
21609
+ });
21610
+ pairs("input, textarea, select", (from, to) => {
21611
+ if (from instanceof HTMLInputElement && to instanceof HTMLInputElement) to.checked = from.checked;
21612
+ if (!(from instanceof HTMLInputElement && from.type === "file")) to.value = from.value;
21613
+ });
21614
+ }
21615
+ /**
21209
21616
  * Create a snapshot clone of a .passage element for outgoing transitions.
21210
21617
  * - Strips `id` attributes from the clone tree
21211
21618
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
21212
21619
  * - Pauses/mutes any <audio>/<video>
21620
+ * - Copies what cloneNode leaves behind: canvas pixels and the values of
21621
+ * form controls (#512)
21213
21622
  * - Adds `.passage-snapshot` class and `data-transition` attribute
21214
21623
  */
21215
21624
  function createSnapshot(passageEl, transitionType) {
21216
21625
  const clone = passageEl.cloneNode(true);
21626
+ copyLiveState(passageEl, clone);
21217
21627
  clone.removeAttribute("id");
21218
21628
  const idEls = clone.querySelectorAll("[id]");
21219
21629
  for (let i = 0; i < idEls.length; i++) idEls[i].removeAttribute("id");
@@ -21736,7 +22146,9 @@ defineMacro({
21736
22146
  * built-ins (see isAtomic) have their contents in the key: the bytes of a
21737
22147
  * buffer, the place of a view in its buffer, the text of a URL or
21738
22148
  * URLSearchParams, the class, message, cause and errors of an Error, the
21739
- * value of a boxed primitive (#418). A hole in an array reads as undefined.
22149
+ * value of a boxed primitive (#418). As for deepEqual and a save, -0 is not
22150
+ * 0 (#498) and a hole in an array is not an undefined element (#497), so
22151
+ * only the keys of -0 and of arrays with holes differ from JSON.stringify.
21740
22152
  *
21741
22153
  * An object met again, through a cycle or a second reference to it, is a
21742
22154
  * marker naming where it was first met rather than another copy of its
@@ -21750,6 +22162,8 @@ function stableKey(value) {
21750
22162
  return "<unkeyable>";
21751
22163
  }
21752
22164
  }
22165
+ /** The key of an array slot that holds no element. */
22166
+ var HOLE = "<hole>";
21753
22167
  /**
21754
22168
  * The key of `val`. `seen` numbers the objects keyed so far, in the order
21755
22169
  * they were first met.
@@ -21757,7 +22171,9 @@ function stableKey(value) {
21757
22171
  function keyOf(val, seen) {
21758
22172
  switch (typeof val) {
21759
22173
  case "string": return JSON.stringify(val);
21760
- case "number": return Number.isFinite(val) ? JSON.stringify(val) : String(val);
22174
+ case "number":
22175
+ if (Object.is(val, -0)) return "-0";
22176
+ return Number.isFinite(val) ? JSON.stringify(val) : String(val);
21761
22177
  case "boolean": return String(val);
21762
22178
  case "bigint": return `${val}n`;
21763
22179
  case "undefined": return "undefined";
@@ -21776,10 +22192,14 @@ function keyOf(val, seen) {
21776
22192
  };
21777
22193
  if (val instanceof Date || val instanceof RegExp) {
21778
22194
  if (className !== void 0 && extraKeys(obj).length) seen.set(obj, seen.size);
21779
- return withFields(val instanceof Date ? `Date(${Date.prototype.getTime.call(val)})` : `RegExp(${RegExp.prototype.toString.call(val)}@${val.lastIndex})`);
22195
+ return withFields(val instanceof Date ? `Date(${Date.prototype.getTime.call(val)})` : `RegExp(${regExpText(val)}@${val.lastIndex})`);
21780
22196
  }
21781
22197
  seen.set(obj, seen.size);
21782
- if (Array.isArray(val)) return withFields(`[${Array.from(val, (v) => keyOf(v, seen)).join(",")}]`);
22198
+ if (Array.isArray(val)) {
22199
+ const items = [];
22200
+ for (let i = 0; i < val.length; i++) items.push(i in val ? keyOf(val[i], seen) : HOLE);
22201
+ return withFields(`[${items.join(",")}]`);
22202
+ }
21783
22203
  const atomic = atomicKey(obj, seen);
21784
22204
  if (atomic !== void 0) return named(atomic);
21785
22205
  if (val instanceof Map) return withFields(`Map[${Array.from(mapEntries(val), ([k, v]) => `[${keyOf(k, seen)},${keyOf(v, seen)}]`).join(",")}]`);
@@ -21833,7 +22253,7 @@ function loopArgs(rawArgs, args) {
21833
22253
  listExpr
21834
22254
  };
21835
22255
  }
21836
- function ForIteration({ parentValues, itemVar, itemValue, indexVar, indexValue, children }) {
22256
+ function ForIteration({ itemVar, itemValue, indexVar, indexValue, children }) {
21837
22257
  const ownKeys = useMemo(() => ({
21838
22258
  [itemVar]: itemValue,
21839
22259
  ...indexVar ? { [indexVar]: indexValue } : void 0
@@ -21845,7 +22265,6 @@ function ForIteration({ parentValues, itemVar, itemValue, indexVar, indexValue,
21845
22265
  ]);
21846
22266
  return /* @__PURE__ */ jsx(LocalsScope, {
21847
22267
  body: children,
21848
- parentValues,
21849
22268
  ownKeys
21850
22269
  });
21851
22270
  }
@@ -21871,7 +22290,6 @@ defineMacro({
21871
22290
  }
21872
22291
  ],
21873
22292
  render({ rawArgs, children = [] }, ctx) {
21874
- const parentValues = useContext(LocalsValuesContext);
21875
22293
  const keys = ctx.hooks.useRef({
21876
22294
  contents: [],
21877
22295
  generations: [],
@@ -21905,7 +22323,6 @@ defineMacro({
21905
22323
  });
21906
22324
  keys.contents.length = keys.generations.length = list.length;
21907
22325
  const content = list.map((item, i) => /* @__PURE__ */ jsx(ForIteration, {
21908
- parentValues,
21909
22326
  itemVar,
21910
22327
  itemValue: item,
21911
22328
  indexVar,
@@ -21938,30 +22355,6 @@ defineMacro({
21938
22355
  }
21939
22356
  });
21940
22357
  //#endregion
21941
- //#region src/utils/live-locals.ts
21942
- /**
21943
- * Read-only view of a locals scope that always reflects its current values.
21944
- *
21945
- * Used as the LocalsValuesContext value for one-shot detached renders
21946
- * ({button}/{link} bodies). Those trees are unmounted right after rendering,
21947
- * so the owning scope's re-render never reaches them; reading through
21948
- * getValues() lets a macro see a local assigned earlier in the same body.
21949
- */
21950
- function liveLocalsView(getValues) {
21951
- return new Proxy(createNamespace(), {
21952
- get: (_, key) => typeof key === "string" ? ownValue(getValues(), key) : void 0,
21953
- has: (_, key) => typeof key === "string" && hasOwn(getValues(), key),
21954
- ownKeys: () => Reflect.ownKeys(getValues()),
21955
- getOwnPropertyDescriptor: (_, key) => {
21956
- const desc = Object.getOwnPropertyDescriptor(getValues(), key);
21957
- return desc ? {
21958
- ...desc,
21959
- configurable: true
21960
- } : void 0;
21961
- }
21962
- });
21963
- }
21964
- //#endregion
21965
22358
  //#region src/components/macros/Repeat.tsx
21966
22359
  var RepeatContext = createContext({ stop: () => {} });
21967
22360
  defineMacro({
@@ -22442,6 +22835,7 @@ defineMacro({
22442
22835
  try {
22443
22836
  const def = widgetDef(ctx.args);
22444
22837
  for (const param of def.params) checkVariableName(param.slice(1), param);
22838
+ checkWidgetHolds(def);
22445
22839
  parsed = def;
22446
22840
  } catch (err) {
22447
22841
  error = err;
@@ -22470,6 +22864,7 @@ defineMacro({
22470
22864
  //#region src/components/macros/StoryTitle.tsx
22471
22865
  defineMacro({
22472
22866
  name: "story-title",
22867
+ interpolate: true,
22473
22868
  render(_, ctx) {
22474
22869
  const name = useStoryStore((s) => s.storyData?.name || "");
22475
22870
  const cls = ctx.className ? `story-title ${ctx.className}` : "story-title";
@@ -22489,6 +22884,7 @@ function hotkeyTitle(label, key) {
22489
22884
  function defineMenubarAction(config) {
22490
22885
  defineMacro({
22491
22886
  name: config.name,
22887
+ interpolate: true,
22492
22888
  render(_, ctx) {
22493
22889
  if (config.hidden?.()) return null;
22494
22890
  const [dialogOpen, setDialogOpen] = useState(false);
@@ -22651,7 +23047,7 @@ function formatDate(iso) {
22651
23047
  year: "numeric"
22652
23048
  });
22653
23049
  }
22654
- function SaveManagerContent() {
23050
+ function SaveManagerContent({ className, id }) {
22655
23051
  const [mode, setMode] = useState("load");
22656
23052
  const [groups, setGroups] = useState([]);
22657
23053
  const [loading, setLoading] = useState(true);
@@ -22831,7 +23227,8 @@ function SaveManagerContent() {
22831
23227
  };
22832
23228
  const totalSaves = groups.reduce((n, g) => n + g.saves.length, 0);
22833
23229
  return /* @__PURE__ */ jsxs("div", {
22834
- class: "save-manager",
23230
+ id,
23231
+ class: className ? `save-manager ${className}` : "save-manager",
22835
23232
  children: [
22836
23233
  /* @__PURE__ */ jsx("div", {
22837
23234
  class: "saves-header",
@@ -22992,8 +23389,12 @@ function SaveManagerContent() {
22992
23389
  }
22993
23390
  defineMacro({
22994
23391
  name: "save-manager",
22995
- render() {
22996
- return /* @__PURE__ */ jsx(SaveManagerContent, {});
23392
+ interpolate: true,
23393
+ render(_props, ctx) {
23394
+ return /* @__PURE__ */ jsx(SaveManagerContent, {
23395
+ className: ctx.className,
23396
+ id: ctx.id
23397
+ });
22997
23398
  }
22998
23399
  });
22999
23400
  //#endregion
@@ -23043,10 +23444,11 @@ function SettingControl({ name, def }) {
23043
23444
  });
23044
23445
  }
23045
23446
  }
23046
- function SettingsControlsContent() {
23447
+ function SettingsControlsContent({ className, id }) {
23047
23448
  const defs = settings.getDefinitions();
23048
23449
  return /* @__PURE__ */ jsx("div", {
23049
- class: "settings-controls",
23450
+ id,
23451
+ class: className ? `settings-controls ${className}` : "settings-controls",
23050
23452
  children: Array.from(defs.entries()).map(([name, def]) => /* @__PURE__ */ jsx(SettingControl, {
23051
23453
  name,
23052
23454
  def
@@ -23055,8 +23457,12 @@ function SettingsControlsContent() {
23055
23457
  }
23056
23458
  defineMacro({
23057
23459
  name: "settings-controls",
23058
- render() {
23059
- return /* @__PURE__ */ jsx(SettingsControlsContent, {});
23460
+ interpolate: true,
23461
+ render(_props, ctx) {
23462
+ return /* @__PURE__ */ jsx(SettingsControlsContent, {
23463
+ className: ctx.className,
23464
+ id: ctx.id
23465
+ });
23060
23466
  }
23061
23467
  });
23062
23468
  //#endregion
@@ -23106,6 +23512,7 @@ defineMacro({
23106
23512
  defineMacro({
23107
23513
  name: "nobr",
23108
23514
  block: true,
23515
+ interpolate: true,
23109
23516
  render({ children = [] }, ctx) {
23110
23517
  return ctx.wrap(ctx.h(NobrContext.Provider, { value: true }, ctx.renderNodes(children, { nobr: true })));
23111
23518
  },
@@ -23193,6 +23600,7 @@ function useVariableAction(ctx, action) {
23193
23600
  function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? String(input) : "") {
23194
23601
  defineMacro({
23195
23602
  name,
23603
+ interpolate: true,
23196
23604
  storeVar: true,
23197
23605
  parameters: [VARIABLE_PARAMETER, {
23198
23606
  name: "placeholder",
@@ -23236,6 +23644,7 @@ defineInputMacro("textarea");
23236
23644
  //#region src/components/macros/Checkbox.tsx
23237
23645
  defineMacro({
23238
23646
  name: "checkbox",
23647
+ interpolate: true,
23239
23648
  storeVar: true,
23240
23649
  parameters: [VARIABLE_PARAMETER, {
23241
23650
  name: "label",
@@ -23248,7 +23657,7 @@ defineMacro({
23248
23657
  type: "checkbox",
23249
23658
  label: label || ctx.varName || "",
23250
23659
  value: !!ctx.value,
23251
- perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.value)
23660
+ perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.getValue())
23252
23661
  });
23253
23662
  return /* @__PURE__ */ jsxs("label", {
23254
23663
  id: ctx.id,
@@ -23256,7 +23665,7 @@ defineMacro({
23256
23665
  children: [/* @__PURE__ */ jsx("input", {
23257
23666
  type: "checkbox",
23258
23667
  checked: !!ctx.value,
23259
- onChange: () => ctx.setValue(!ctx.value)
23668
+ onChange: (e) => ctx.setValue(e.target.checked)
23260
23669
  }), label ? ` ${label}` : null]
23261
23670
  });
23262
23671
  }
@@ -23265,6 +23674,7 @@ defineMacro({
23265
23674
  //#region src/components/macros/Radiobutton.tsx
23266
23675
  defineMacro({
23267
23676
  name: "radiobutton",
23677
+ interpolate: true,
23268
23678
  storeVar: true,
23269
23679
  parameters: [
23270
23680
  VARIABLE_PARAMETER,
@@ -23306,6 +23716,7 @@ defineMacro({
23306
23716
  //#region src/components/macros/Listbox.tsx
23307
23717
  defineMacro({
23308
23718
  name: "listbox",
23719
+ interpolate: true,
23309
23720
  subMacros: ["option"],
23310
23721
  storeVar: true,
23311
23722
  parameters: [VARIABLE_PARAMETER],
@@ -23336,6 +23747,7 @@ defineMacro({
23336
23747
  defineMacro({
23337
23748
  name: "cycle",
23338
23749
  block: true,
23750
+ interpolate: true,
23339
23751
  storeVar: true,
23340
23752
  parameters: [VARIABLE_PARAMETER],
23341
23753
  render({ children = [] }, ctx) {
@@ -23369,6 +23781,7 @@ defineMacro({
23369
23781
  defineMacro({
23370
23782
  name: "span",
23371
23783
  block: true,
23784
+ interpolate: true,
23372
23785
  render({ children = [] }, ctx) {
23373
23786
  return ctx.wrap(ctx.renderNodes(children));
23374
23787
  },
@@ -23495,13 +23908,21 @@ function orStop(parse, where = "") {
23495
23908
  }
23496
23909
  }
23497
23910
  /**
23911
+ * What reading arguments depends on, with the macros and widgets known now:
23912
+ * the declared parameters of macros and what the parameters of widgets hold.
23913
+ * (The markup and the variable references are read by the same.)
23914
+ */
23915
+ function knownParameters() {
23916
+ return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
23917
+ }
23918
+ /**
23498
23919
  * The undeclared variables the passages refer to, with the macros known now:
23499
23920
  * the input macros that bind a variable (registered by author JS or
23500
23921
  * StoryInit) and the roles of their parameters decide what is a reference.
23501
23922
  */
23502
23923
  function variableErrors(storyData, schema) {
23503
23924
  const storeVarMacros = getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
23504
- return validatePassages(storyData.passages, schema, storeVarMacros);
23925
+ return validatePassages(storyData.passages, schema, storeVarMacros, knownParameters());
23505
23926
  }
23506
23927
  /**
23507
23928
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -23509,11 +23930,10 @@ function variableErrors(storyData, schema) {
23509
23930
  * known now.
23510
23931
  */
23511
23932
  function markupErrors(storyData, only) {
23512
- const macros = getMacroRegistry();
23513
23933
  return validateMarkup(storyData.passages.values(), {
23514
23934
  isKnownMacro: (name) => !!getMacro(name) || isSubMacro(name) || !!getWidget(name),
23515
- macroNames: macros.map((m) => m.name),
23516
- parametersOf: parameterLookup(macros),
23935
+ macroNames: getMacroRegistry().map((m) => m.name),
23936
+ parametersOf: knownParameters(),
23517
23937
  only
23518
23938
  }).map(formatDiagnostic);
23519
23939
  }
@@ -23584,11 +24004,9 @@ function boot() {
23584
24004
  const root = document.getElementById("root");
23585
24005
  if (!root) throw new Error("spindle: No <div id=\"root\"> element found.");
23586
24006
  render(/* @__PURE__ */ jsx(App, {}), root);
23587
- const pending = getReadyPromise();
23588
- if (pending) pending.then(passageShown).then(() => {
24007
+ (getReadyPromise() ?? Promise.resolve()).then(passageShown).then(() => {
23589
24008
  document.dispatchEvent(new CustomEvent(":storyready"));
23590
24009
  });
23591
- else document.dispatchEvent(new CustomEvent(":storyready"));
23592
24010
  }
23593
24011
  //#endregion
23594
24012
  //#region src/headless.ts