@rohal12/spindle 0.59.29 → 0.59.31

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 (62) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +947 -351
  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 +780 -107
  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 +19 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +87 -20
  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 +136 -10
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/Repeat.tsx +4 -2
  23. package/src/components/macros/SaveManager.tsx +30 -8
  24. package/src/components/macros/SettingsControls.tsx +19 -4
  25. package/src/components/macros/Span.tsx +1 -0
  26. package/src/components/macros/StoryTitle.tsx +1 -0
  27. package/src/components/macros/Unset.tsx +26 -13
  28. package/src/components/macros/VarDisplay.tsx +2 -3
  29. package/src/components/macros/WidgetInvocation.tsx +5 -6
  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 +247 -133
  36. package/src/index.tsx +32 -21
  37. package/src/js-bindings.ts +594 -0
  38. package/src/js-lexer.ts +76 -14
  39. package/src/macro-discovery.ts +83 -32
  40. package/src/markup/ast.ts +22 -1
  41. package/src/markup/render.tsx +44 -15
  42. package/src/parser.ts +41 -10
  43. package/src/prng.ts +24 -1
  44. package/src/saves/save-manager.ts +36 -9
  45. package/src/static-literal.ts +87 -16
  46. package/src/store.ts +83 -6
  47. package/src/story-api.ts +23 -6
  48. package/src/story-variables.ts +91 -28
  49. package/src/structural.ts +26 -15
  50. package/src/tooling.ts +24 -10
  51. package/src/transform.ts +22 -7
  52. package/src/utils/macro-names.ts +4 -0
  53. package/src/utils/namespace.ts +15 -2
  54. package/src/utils/object-path.ts +2 -2
  55. package/src/utils/stable-key.ts +17 -6
  56. package/src/utils/value-kinds.ts +38 -1
  57. package/src/widgets/ast-scanner.ts +4 -1
  58. package/src/widgets/register-widget-def.ts +2 -3
  59. package/src/widgets/widget-def.ts +36 -6
  60. package/src/widgets/widget-registry.ts +6 -2
  61. package/types/index.d.ts +12 -5
  62. package/types/tooling.d.ts +12 -2
@@ -3388,6 +3388,9 @@ var NameSet = class {
3388
3388
  delete(name) {
3389
3389
  this.names.delete(name);
3390
3390
  }
3391
+ clear() {
3392
+ this.names.clear();
3393
+ }
3391
3394
  };
3392
3395
  //#endregion
3393
3396
  //#region src/markup/ast.ts
@@ -3412,6 +3415,12 @@ var BLOCK_MACROS = new NameSet([
3412
3415
  "span",
3413
3416
  "nobr"
3414
3417
  ]);
3418
+ /**
3419
+ * The block widgets (those whose body renders `{@children}`), kept apart from
3420
+ * BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
3421
+ * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3422
+ */
3423
+ var BLOCK_WIDGETS = new NameSet();
3415
3424
  /** Macros whose body is JavaScript source, kept verbatim. */
3416
3425
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3417
3426
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
@@ -3420,12 +3429,20 @@ function isRawMacro(name) {
3420
3429
  }
3421
3430
  /** Whether a macro takes a body closed by `{/name}`. */
3422
3431
  function isBlockMacro(name) {
3423
- return BLOCK_MACROS.has(name);
3432
+ return BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
3424
3433
  }
3425
3434
  /** Register a custom macro as a block macro so the parser nests children. */
3426
3435
  function registerBlockMacro(name) {
3427
3436
  BLOCK_MACROS.add(name);
3428
3437
  }
3438
+ /**
3439
+ * Record whether the widget `name` takes a body, as its latest definition
3440
+ * does. A block macro registered under the same name stays a block.
3441
+ */
3442
+ function setBlockWidget(name, isBlock) {
3443
+ if (isBlock) BLOCK_WIDGETS.add(name);
3444
+ else BLOCK_WIDGETS.delete(name);
3445
+ }
3429
3446
  /** Macros whose branches render as one: the node holds one per branch. */
3430
3447
  var BRANCHING = /* @__PURE__ */ new Set([
3431
3448
  "if",
@@ -9009,15 +9026,15 @@ var SigilParser = class extends Parser {
9009
9026
  }
9010
9027
  const self = this;
9011
9028
  const prevType = self.type;
9012
- this.prevValue = self.value;
9013
- const property = type.keyword !== void 0 && (prevType === types$1.dot || prevType === types$1.questionDot) || (type === types$1._function || type === types$1._class) && notABody(self.input, self.pos);
9029
+ this.prevValue = isMemberDot(this.typeBeforeLast) ? void 0 : self.value;
9030
+ const property = type.keyword !== void 0 && isMemberDot(prevType) || (type === types$1._function || type === types$1._class) && notABody(self.input, self.pos);
9014
9031
  if (!property && (type === types$1._function || type === types$1._class)) {
9015
9032
  const before = type === types$1._function && prevType === types$1.name && this.prevValue === "async" && !this.breakHere ? this.typeBeforeLast : prevType;
9016
9033
  self.type = before === types$1.colon && this.colonEndsTernary ? types$1.parenL : before;
9017
9034
  }
9018
9035
  this.typeBeforeLast = prevType;
9019
9036
  super.finishToken(property ? types$1.name : type, value);
9020
- if (type === types$1.name && value === "of" && (prevType === types$1._const || prevType === types$1._var || this.prevValue === "let")) self.exprAllowed = false;
9037
+ if (type === types$1.name && (isMemberDot(prevType) || value === "of" && (prevType === types$1._const || prevType === types$1._var || this.prevValue === "let"))) self.exprAllowed = false;
9021
9038
  }
9022
9039
  braceIsBlock(prevType) {
9023
9040
  if (prevType === types$1.colon && this.colonEndsTernary) return false;
@@ -9059,6 +9076,10 @@ function transientAssignment(p, end) {
9059
9076
  return false;
9060
9077
  }
9061
9078
  }
9079
+ /** Is `type` the `.` or `?.` of a member access? */
9080
+ function isMemberDot(type) {
9081
+ return type === types$1.dot || type === types$1.questionDot;
9082
+ }
9062
9083
  var OPENERS = /* @__PURE__ */ new Set([
9063
9084
  types$1.parenL,
9064
9085
  types$1.bracketL,
@@ -9194,6 +9215,10 @@ function bracketsBefore(src, pos) {
9194
9215
  * sigil variable declared (`let _x`) or used as a property name (`a.@x`).
9195
9216
  */
9196
9217
  function parseCode(src, goal = "expression") {
9218
+ return parseWithAst(src, goal).out;
9219
+ }
9220
+ /** What parseCode finds in `src`, and the syntax tree it is in. */
9221
+ function parseWithAst(src, goal) {
9197
9222
  const percentAt = /* @__PURE__ */ new Map();
9198
9223
  for (;;) {
9199
9224
  const transientsRead = /* @__PURE__ */ new Set();
@@ -9205,7 +9230,10 @@ function parseCode(src, goal = "expression") {
9205
9230
  };
9206
9231
  walk(ast, src, out, false, false);
9207
9232
  out.refs.sort((a, b) => a.start - b.start);
9208
- return out;
9233
+ return {
9234
+ out,
9235
+ ast
9236
+ };
9209
9237
  } catch (error) {
9210
9238
  const pos = error.pos ?? -1;
9211
9239
  if (!(error instanceof SyntaxError) || percentAt.has(pos)) throw error;
@@ -9216,6 +9244,30 @@ function parseCode(src, goal = "expression") {
9216
9244
  }
9217
9245
  }
9218
9246
  /**
9247
+ * Read `src` as a reference path: a variable with any number of `.name` and
9248
+ * `[expression]` members after it (`$data["field"]`, `@list[_i].x`), and
9249
+ * nothing else. Returns null for any other code (`$a + 1`, `$a.b()`, `$a,
9250
+ * $b`, `$a = 1`), and throws a `CodeSyntaxError` for code that is not
9251
+ * well-formed.
9252
+ */
9253
+ function parseReferencePath(src) {
9254
+ const { ast } = parseWithAst(src, "expression");
9255
+ let node = ast.type === "ChainExpression" ? ast.expression : ast;
9256
+ let nested = false;
9257
+ while (node.type === "MemberExpression") {
9258
+ node = node.object;
9259
+ nested = true;
9260
+ }
9261
+ if (node.type !== "Identifier") return null;
9262
+ const sigil = sigilOf(node, src);
9263
+ if (!sigil || node.start !== 0) return null;
9264
+ return {
9265
+ sigil: sigil[0],
9266
+ name: sigil[1],
9267
+ nested
9268
+ };
9269
+ }
9270
+ /**
9219
9271
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
9220
9272
  * noting where it read a transient in `transientsRead`.
9221
9273
  */
@@ -9601,7 +9653,7 @@ function walkTokens(src, from, handlers, nesting, goal, oneTemplate) {
9601
9653
  if (t === types$1.name) {
9602
9654
  const sigil = sigilAt(src, tok.start, tok.value);
9603
9655
  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);
9656
+ if (sigil && !property) handlers.variable?.(sigil, tok.value.slice(1), tok.start, nesting, tok.end);
9605
9657
  else code(tok.start, tok.end);
9606
9658
  } else if (t === types$1.string || t === types$1.regexp || t === types$1.template || t === types$1.invalidTemplate) literal(tok.start, tok.end);
9607
9659
  else if (t === types$1.backQuote) {
@@ -10053,6 +10105,8 @@ function checkVariableName(name, label = name) {
10053
10105
  const error = variableNameError(name, label);
10054
10106
  if (error) throw new TypeError(`spindle: ${error}`);
10055
10107
  }
10108
+ /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
10109
+ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
10056
10110
  /** Whether `obj` holds `key` as an own property. */
10057
10111
  var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10058
10112
  /** `ns[key]` if `ns` holds it as an own property, else undefined. */
@@ -10099,9 +10153,14 @@ function withEntry(ns, key, value) {
10099
10153
  }
10100
10154
  /** An empty namespace that cannot change. */
10101
10155
  var EMPTY_NAMESPACE = Object.freeze(createNamespace());
10102
- /** The names whose own entries differ between `a` and `b`, `a`'s first. */
10156
+ /**
10157
+ * The names whose own entries differ between `a` and `b`, `a`'s first: an
10158
+ * entry one holds and the other lacks (also one holding `undefined`), or
10159
+ * values that are not the same by SameValue (#519): an unchanged NaN is no
10160
+ * change, 0 and -0 differ.
10161
+ */
10103
10162
  function changedNames(a, b) {
10104
- return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((name) => ownValue(a, name) !== ownValue(b, name));
10163
+ return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((name) => hasOwn(a, name) !== hasOwn(b, name) || !Object.is(ownValue(a, name), ownValue(b, name)));
10105
10164
  }
10106
10165
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10107
10166
  /** The count of `name` in `counts`: its own entry, or 0. */
@@ -10124,7 +10183,9 @@ function createCounts(source, name) {
10124
10183
  //#region src/widgets/widget-registry.ts
10125
10184
  var widgets = new NameMap();
10126
10185
  /**
10127
- * Register a widget. Its `@` parameters become locals of its body, so one
10186
+ * Register a widget. A widget whose body renders {@children} takes a closing
10187
+ * tag, so it is a block macro to the parser too, for the passages parsed
10188
+ * later; the latest definition decides. Its `@` parameters become locals of its body, so one
10128
10189
  * that no namespace can hold (`@__proto__`) throws a TypeError and the
10129
10190
  * widget is not registered.
10130
10191
  */
@@ -10137,6 +10198,7 @@ function registerWidget(name, bodyAST, params, isBlock = false, holds = {}) {
10137
10198
  holds,
10138
10199
  isBlock
10139
10200
  });
10201
+ setBlockWidget(name, isBlock);
10140
10202
  }
10141
10203
  function getWidget(name) {
10142
10204
  return widgets.get(name);
@@ -10542,10 +10604,12 @@ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
10542
10604
  * Where the rest of `src` is without the flag `word` as its last or first
10543
10605
  * term, or `null` if it has no such flag. Next to a binary operator the
10544
10606
  * word is an operand (`"a" + inline`), not a flag; the closing `/` of a
10545
- * regex literal is not one.
10607
+ * regex literal is not one. A word with nothing else beside it is the flag
10608
+ * only when `alone` says no argument is waiting for it (#499).
10546
10609
  */
10547
- function takeFlag(src, word) {
10610
+ function takeFlag(src, word, alone) {
10548
10611
  const spans = terms(src);
10612
+ if (spans.length === 1) return alone && slice(src, spans[0]) === word ? [src.length, src.length] : null;
10549
10613
  if (spans.length < 2) return null;
10550
10614
  if (slice(src, spans[spans.length - 1]) === word) {
10551
10615
  const rest = [0, spans[spans.length - 2][1]];
@@ -10592,8 +10656,9 @@ function trimmed(src, at) {
10592
10656
  */
10593
10657
  function readGroup(params, src, args, { at: srcAt, spans }) {
10594
10658
  let [text, at] = trimmed(src ?? "", srcAt);
10659
+ const alone = !params.some((p) => p.type !== "flag" && p.required);
10595
10660
  for (const flag of params.filter((p) => p.type === "flag")) {
10596
- const rest = src === null ? null : takeFlag(text, flag.name);
10661
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
10597
10662
  args[flag.name] = rest !== null;
10598
10663
  if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
10599
10664
  }
@@ -11014,24 +11079,50 @@ function nestedPiece(piece, toRoot, where) {
11014
11079
  ...nested
11015
11080
  };
11016
11081
  }
11082
+ /** An escape sequence of a JavaScript string literal (with its backslash). */
11083
+ 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;
11084
+ /**
11085
+ * The escape written at `raw[i]` (a backslash): how long it is as written and
11086
+ * what it stands for, or none when it is not one under these `escapes`.
11087
+ */
11088
+ function escapeAt(raw, i, escapes) {
11089
+ if (escapes === "quotes") {
11090
+ const next = raw.charAt(i + 1);
11091
+ return /["'\\]/.test(next) ? {
11092
+ length: 2,
11093
+ text: next
11094
+ } : void 0;
11095
+ }
11096
+ JS_ESCAPE_RE.lastIndex = i;
11097
+ const written = JS_ESCAPE_RE.exec(raw)?.[0];
11098
+ const text = written && stringLiteralValue(`"${written}"`);
11099
+ return typeof text === "string" ? {
11100
+ length: written.length,
11101
+ text
11102
+ } : void 0;
11103
+ }
11017
11104
  /**
11018
11105
  * Where each character of `value`, the unescaped text of a quoted string
11019
- * written as `raw` from `at` on (a backslash before a quote or a backslash
11020
- * is dropped), is
11021
- * in the source, and where the text ends. None when the text is where its
11022
- * length says, or is not that string.
11106
+ * written as `raw` from `at` on (its escapes are those of `escapes`), is in
11107
+ * the source, and where the text ends. A character that an escape stands for
11108
+ * is where the escape begins. None when the text is where its length says, or
11109
+ * is not that string.
11023
11110
  */
11024
- function escapeOffsets(raw, at, value) {
11111
+ function escapeOffsets(raw, at, value, escapes) {
11025
11112
  const offsets = [];
11026
11113
  let escaped = false;
11027
11114
  let i = 0;
11028
11115
  while (offsets.length < value.length) {
11029
11116
  if (i >= raw.length) return void 0;
11030
- offsets.push(at + i);
11031
- if (raw[i] === "\\" && /["'\\]/.test(raw.charAt(i + 1))) {
11032
- escaped = true;
11033
- i += 2;
11034
- } else i++;
11117
+ const escape = raw[i] === "\\" ? escapeAt(raw, i, escapes) : void 0;
11118
+ if (!escape) {
11119
+ offsets.push(at + i++);
11120
+ continue;
11121
+ }
11122
+ if (!value.startsWith(escape.text, offsets.length)) return void 0;
11123
+ for (let k = 0; k < escape.text.length; k++) offsets.push(at + i);
11124
+ escaped = true;
11125
+ i += escape.length;
11035
11126
  }
11036
11127
  offsets.push(at + i);
11037
11128
  return escaped ? offsets : void 0;
@@ -11054,7 +11145,7 @@ function* argPieces(args, offset, params, macro, label) {
11054
11145
  };
11055
11146
  return;
11056
11147
  }
11057
- yield* valuePieces(args, offset, params, values, spans, macro, label);
11148
+ yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes");
11058
11149
  }
11059
11150
  /**
11060
11151
  * The code and text in the arguments `args` (at `offset`) of the widget
@@ -11080,13 +11171,14 @@ function* widgetPieces(args, offset, params, macro, label) {
11080
11171
  values[name] = value;
11081
11172
  spans.set(param, span);
11082
11173
  });
11083
- yield* valuePieces(args, offset, declared, values, spans, macro, label);
11174
+ yield* valuePieces(args, offset, declared, values, spans, macro, label, "javascript");
11084
11175
  }
11085
11176
  /**
11086
11177
  * The pieces of the `params` of `macro` with the `values` read from `args`
11087
- * (at `offset`), whose `spans` tell where each was written.
11178
+ * (at `offset`), whose `spans` tell where each was written and whose strings
11179
+ * are unescaped as `escapes` says.
11088
11180
  */
11089
- function* valuePieces(args, offset, params, values, spans, macro, label) {
11181
+ function* valuePieces(args, offset, params, values, spans, macro, label, escapes) {
11090
11182
  const name = macro.toLowerCase();
11091
11183
  /** The pieces of the parameters `list`, with their values in `from`. */
11092
11184
  function* visit(list, from) {
@@ -11134,7 +11226,7 @@ function* valuePieces(args, offset, params, values, spans, macro, label) {
11134
11226
  }
11135
11227
  const at = offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
11136
11228
  const holds = stringHolds(param);
11137
- const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
11229
+ const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value, escapes);
11138
11230
  if (holds === "expression" || holds === "statements") {
11139
11231
  const piece = {
11140
11232
  kind: "code",
@@ -11200,20 +11292,21 @@ function attributeValues(src, token) {
11200
11292
  }
11201
11293
  /**
11202
11294
  * The `{$…}` expressions in the value of a code attribute (`onclick`, see
11203
- * isCodeAttribute), with where each is in the value.
11295
+ * isCodeAttribute), with where each is in the value. The parts of the value
11296
+ * are written out as they are (splitSigilTemplate decodes nothing), so each
11297
+ * starts where the one before it ends: an expression is not found by its
11298
+ * text, which a string of the code may repeat.
11204
11299
  */
11205
11300
  function sigilExpressions(value) {
11206
11301
  const found = [];
11207
11302
  let from = 0;
11208
- for (const part of splitSigilTemplate(value)) {
11209
- if (!("expr" in part)) continue;
11210
- const at = locate(value, part.expr, from);
11211
- from = at + part.expr.length;
11303
+ for (const part of splitSigilTemplate(value)) if ("expr" in part) {
11212
11304
  found.push({
11213
11305
  expr: part.expr,
11214
- at
11306
+ at: from + 1
11215
11307
  });
11216
- }
11308
+ from += part.expr.length + 2;
11309
+ } else from += ("text" in part ? part.text : part.verbatim).length;
11217
11310
  return found;
11218
11311
  }
11219
11312
  /**
@@ -11367,7 +11460,9 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
11367
11460
  /**
11368
11461
  * Recursively scan an AST node array for a VariableNode
11369
11462
  * with scope 'local' and name 'children' (@children), in the content and in
11370
- * the attributes and labels that render markup.
11463
+ * the attributes and labels that render markup. A nested `{widget}` is not
11464
+ * entered: its slot belongs to the innermost widget (as widgetDefinitions
11465
+ * reads it), and a definition renders nothing of its own.
11371
11466
  */
11372
11467
  function astContainsChildren(nodes, parametersOf = registeredParameters) {
11373
11468
  for (const node of nodes) {
@@ -11385,6 +11480,7 @@ function astContainsChildren(nodes, parametersOf = registeredParameters) {
11385
11480
  }, parametersOf) || astContainsChildren(node.children, parametersOf)) return true;
11386
11481
  }
11387
11482
  if (node.type === "macro") {
11483
+ if (node.name.toLowerCase() === "widget") continue;
11388
11484
  if (tokenTextContainsChildren({
11389
11485
  isClose: false,
11390
11486
  nameStart: 0,
@@ -11517,29 +11613,40 @@ function widgetDefinitions(passages, parametersOf = registeredParameters) {
11517
11613
  return found;
11518
11614
  }
11519
11615
  /**
11520
- * The names of the block widgets (those whose body renders `{@children}`)
11521
- * that StoryInit and the passages tagged `widget` define, closed. They must
11522
- * be known as block macros before any passage is parsed, so that passages
11523
- * invoking them nest their content whatever the passage order.
11616
+ * The definitions the runtime ends up with, one per widget name: the closed
11617
+ * ones, the latest winning as registration replaces a widget. The widget
11618
+ * passages register before StoryInit runs, so StoryInit's definitions come
11619
+ * last whatever the passage order. Read with the flat scanner, so a nested
11620
+ * definition owns its own `{@children}`.
11524
11621
  */
11525
- function blockWidgetNames(passages, parametersOf = registeredParameters) {
11526
- return widgetDefinitions(passages, parametersOf).filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name);
11622
+ function effectiveWidgetDefinitions(definitions) {
11623
+ const inInit = (def) => def.passage === "StoryInit";
11624
+ const effective = new NameMap();
11625
+ for (const def of [...definitions.filter((def) => !inInit(def)), ...definitions.filter(inInit)]) if (def.closeStart !== void 0) effective.set(def.name, def);
11626
+ return [...effective.values()];
11627
+ }
11628
+ /**
11629
+ * The widgets that StoryInit and the passages tagged `widget` define, as the
11630
+ * runtime ends up with them (see effectiveWidgetDefinitions). Whether each
11631
+ * takes a body must be known before any passage is parsed, so that passages
11632
+ * invoking them nest their content (or don't) whatever the passage order.
11633
+ */
11634
+ function effectiveWidgets(passages, parametersOf = registeredParameters) {
11635
+ return effectiveWidgetDefinitions(widgetDefinitions(passages, parametersOf));
11527
11636
  }
11528
11637
  //#endregion
11529
11638
  //#region src/widgets/register-widget-def.ts
11530
11639
  /**
11531
11640
  * Register the widget a definition declares, with its body. Widgets whose
11532
11641
  * body renders {@children} take a closing tag, so they are registered as
11533
- * block macros too: passages parsed later nest their content. A parameter
11642
+ * block macros too (see registerWidget). A parameter
11534
11643
  * that no namespace can hold or declares what it holds wrongly throws (see
11535
11644
  * registerWidget and checkWidgetHolds), registering nothing.
11536
11645
  */
11537
11646
  function registerWidgetDef(def, body) {
11538
11647
  checkWidgetHolds(def);
11539
11648
  const { name, params, holds } = def;
11540
- const isBlock = astContainsChildren(body);
11541
- registerWidget(name, body, params, isBlock, holds);
11542
- if (isBlock) registerBlockMacro(name);
11649
+ registerWidget(name, body, params, astContainsChildren(body), holds);
11543
11650
  }
11544
11651
  /**
11545
11652
  * Register the widgets `nodes` (a passage's markup) define at its top level,
@@ -11590,14 +11697,50 @@ function useStoryFields(...keys) {
11590
11697
  });
11591
11698
  }
11592
11699
  //#endregion
11700
+ //#region src/utils/live-locals.ts
11701
+ /**
11702
+ * Read-only view of a locals scope that always reflects its current values.
11703
+ *
11704
+ * Used as the LocalsValuesContext value for one-shot detached renders
11705
+ * ({button}/{link} bodies). Those trees are unmounted right after rendering,
11706
+ * so the owning scope's re-render never reaches them; reading through
11707
+ * getValues() lets a macro see a local assigned earlier in the same body.
11708
+ */
11709
+ function liveLocalsView(getValues) {
11710
+ return new Proxy(createNamespace(), {
11711
+ get: (_, key) => typeof key === "string" ? ownValue(getValues(), key) : void 0,
11712
+ has: (_, key) => typeof key === "string" && hasOwn(getValues(), key),
11713
+ ownKeys: () => Reflect.ownKeys(getValues()),
11714
+ getOwnPropertyDescriptor: (_, key) => {
11715
+ const desc = Object.getOwnPropertyDescriptor(getValues(), key);
11716
+ return desc ? {
11717
+ ...desc,
11718
+ configurable: true
11719
+ } : void 0;
11720
+ }
11721
+ });
11722
+ }
11723
+ //#endregion
11593
11724
  //#region src/hooks/use-merged-locals.ts
11594
11725
  /**
11726
+ * The locals in scope, read as they are when code looks (a local the
11727
+ * preceding {set} assigned in this pass included, which the context value
11728
+ * only gains in the re-render that follows). The returned view is renewed
11729
+ * whenever the context value changes, so what depends on it re-renders and
11730
+ * recomputes as before.
11731
+ */
11732
+ function useLiveLocals() {
11733
+ const values = useContext(LocalsValuesContext);
11734
+ const { getValues } = useContext(LocalsUpdateContext);
11735
+ return useMemo(() => liveLocalsView(getValues), [getValues, values]);
11736
+ }
11737
+ /**
11595
11738
  * Return store variables, temporary, locals from context, and transient.
11596
11739
  * All four dicts use unprefixed keys suitable for evaluate/execute.
11597
11740
  */
11598
11741
  function useMergedLocals() {
11599
11742
  const { variables, temporary, transient, renderCounts } = useStoryFields("variables", "temporary", "transient", "renderCounts");
11600
- const localsValues = useContext(LocalsValuesContext);
11743
+ const localsValues = useLiveLocals();
11601
11744
  return useMemo(() => {
11602
11745
  return [
11603
11746
  variables,
@@ -11689,13 +11832,16 @@ function resetPRNG() {
11689
11832
  currentPull = 0;
11690
11833
  generator = null;
11691
11834
  }
11835
+ /** The position each running withoutDraws() takes its draws back to. */
11836
+ var neutralScopes = [];
11692
11837
  /**
11693
11838
  * Run `fn` without its draws advancing the sequence: the draws it makes are
11694
11839
  * taken back afterwards (also when it throws), so the next draws return the
11695
11840
  * same values again. Save and load event handlers run like this, so that
11696
11841
  * saving or loading never shifts the story's random sequence (a load replays
11697
11842
  * the saved passage from its entry state, without the save's handlers). A
11698
- * generator `fn` replaced (a restart or load it started) is kept.
11843
+ * generator `fn` replaced (a restart or load it started) is kept, and so are
11844
+ * the draws made before a navigation `fn` started (see keepDrawsSoFar()).
11699
11845
  */
11700
11846
  function withoutDraws(fn) {
11701
11847
  const start = {
@@ -11703,12 +11849,29 @@ function withoutDraws(fn) {
11703
11849
  seed: currentSeed,
11704
11850
  pull: currentPull
11705
11851
  };
11852
+ neutralScopes.push(start);
11706
11853
  try {
11707
11854
  return fn();
11708
11855
  } finally {
11856
+ neutralScopes.splice(neutralScopes.indexOf(start), 1);
11709
11857
  if (enabled && generation === start.generation && currentPull !== start.pull) moveTo(start.seed, start.pull);
11710
11858
  }
11711
11859
  }
11860
+ /**
11861
+ * Make the draws up to now part of the story: the position of the generator
11862
+ * is the one a history moment the story just entered records, and the
11863
+ * moment's passage replays its rolls from there. A running withoutDraws()
11864
+ * takes back only the draws made after this, so that the position the
11865
+ * passage renders from stays the recorded one (#535). Navigation calls this
11866
+ * once it has recorded the moment it enters.
11867
+ */
11868
+ function keepDrawsSoFar() {
11869
+ for (const scope of neutralScopes) {
11870
+ scope.generation = generation;
11871
+ scope.seed = currentSeed;
11872
+ scope.pull = currentPull;
11873
+ }
11874
+ }
11712
11875
  /** Returns the current PRNG state for snapshotting, or null if disabled. */
11713
11876
  function snapshotPRNG() {
11714
11877
  if (!enabled) return null;
@@ -11746,17 +11909,31 @@ function getPRNGPull() {
11746
11909
  * (see src/tooling.ts).
11747
11910
  */
11748
11911
  var TRANSFORM_CACHE_MAX = 500;
11749
- var NAMESPACES$2 = {
11750
- $: "variables",
11751
- _: "temporary",
11752
- "@": "locals",
11753
- "%": "transient"
11754
- };
11912
+ /**
11913
+ * The identifiers generated code reads the namespaces through, and the
11914
+ * compiled function takes them under (see src/expression.ts). Authored
11915
+ * JavaScript may declare identifiers of its own (`const variables = {}` in
11916
+ * a helper), so these are ones it cannot: an identifier that starts with
11917
+ * `_` or `$` and has more word characters after it is a sigil reference,
11918
+ * and the lexer refuses to declare one (`__variables` is the temporary
11919
+ * variable `_variables`, rewritten like any other). No declaration or
11920
+ * parameter of the author's can then capture a reference or clash with the
11921
+ * generated bindings.
11922
+ */
11923
+ var BINDINGS = {
11924
+ $: "__variables",
11925
+ _: "__temporary",
11926
+ "@": "__locals",
11927
+ "%": "__transient"
11928
+ };
11929
+ /** The identifier the functions that compiled code may call come under. */
11930
+ var FNS_BINDING = "__fns";
11755
11931
  /** Ends with an identifier character. */
11756
11932
  var IDENT_END_RE = /[\p{ID_Continue}$\u200c\u200d]$/u;
11757
11933
  /**
11758
11934
  * Transform expression: $var → variables["var"], _var → temporary["var"],
11759
- * @var → locals["var"], %var → transient["var"].
11935
+ * @var → locals["var"], %var → transient["var"], where `variables` and the
11936
+ * others stand for the generated names in BINDINGS.
11760
11937
  * The lexer (`lexJs`) finds the references: only in code (string, template
11761
11938
  * and regex literal text and comments are left untouched), only where an
11762
11939
  * identifier starts (not in `a$b`, nor as the property name in `obj._x`),
@@ -11779,7 +11956,7 @@ function transform(expr, goal = "expression") {
11779
11956
  result += expr.slice(at, ref.start);
11780
11957
  if (ref.shorthand) result += `${ref.name}: `;
11781
11958
  else if (IDENT_END_RE.test(result.slice(-2))) result += " ";
11782
- result += `${NAMESPACES$2[ref.sigil]}["${ref.name}"]`;
11959
+ result += `${BINDINGS[ref.sigil]}["${ref.name}"]`;
11783
11960
  at = ref.end;
11784
11961
  }
11785
11962
  result += expr.slice(at);
@@ -11793,15 +11970,28 @@ var transformCache = /* @__PURE__ */ new Map();
11793
11970
  //#region src/expression.ts
11794
11971
  var FN_CACHE_MAX = 500;
11795
11972
  var fnCache = /* @__PURE__ */ new Map();
11796
- var preamble = "const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=__fns;";
11797
- function getOrCompile(key, body) {
11973
+ var preamble = `const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=${FNS_BINDING};`;
11974
+ /**
11975
+ * Compile `source`: the function takes the namespaces and the function
11976
+ * table under the names the transform uses for the references (see
11977
+ * BINDINGS). The statements are a block of their own, so that they may
11978
+ * declare any name, those of the history functions the preamble declares
11979
+ * included.
11980
+ */
11981
+ function compile(source, goal) {
11982
+ const code = transform(source, goal);
11983
+ const body = goal === "statements" ? `{${code}\n}` : `return (${code}\n);`;
11984
+ return new Function(BINDINGS.$, BINDINGS._, BINDINGS["@"], FNS_BINDING, BINDINGS["%"], preamble + body);
11985
+ }
11986
+ function getOrCompile(source, goal) {
11987
+ const key = (goal === "statements" ? "s" : "e") + source;
11798
11988
  const cached = fnCache.get(key);
11799
11989
  if (cached) {
11800
11990
  fnCache.delete(key);
11801
11991
  fnCache.set(key, cached);
11802
11992
  return cached;
11803
11993
  }
11804
- const fn = new Function("variables", "temporary", "locals", "__fns", "transient", preamble + body);
11994
+ const fn = compile(source, goal);
11805
11995
  fnCache.set(key, fn);
11806
11996
  if (fnCache.size > FN_CACHE_MAX) {
11807
11997
  const oldest = fnCache.keys().next().value;
@@ -11892,16 +12082,14 @@ function run$1(fn, ...[variables, temporary, locals = EMPTY_NAMESPACE, transient
11892
12082
  * e.g. evaluate("$health + 10", variables, temporary) → number
11893
12083
  */
11894
12084
  function evaluate(expr, ...namespaces) {
11895
- const body = `return (${transform(expr)}\n);`;
11896
- return run$1(getOrCompile(body, body), ...namespaces);
12085
+ return run$1(getOrCompile(expr, "expression"), ...namespaces);
11897
12086
  }
11898
12087
  /**
11899
12088
  * Execute statements (no return value).
11900
12089
  * e.g. execute("$health = 100; $name = 'Hero'", variables, temporary)
11901
12090
  */
11902
12091
  function execute(code, ...namespaces) {
11903
- const transformed = transform(code, "statements");
11904
- run$1(getOrCompile("exec:" + transformed, transformed), ...namespaces);
12092
+ run$1(getOrCompile(code, "statements"), ...namespaces);
11905
12093
  }
11906
12094
  //#endregion
11907
12095
  //#region src/components/macros/display.ts
@@ -12249,7 +12437,7 @@ function VarDisplay({ node }) {
12249
12437
  const resolve = useInterpolate();
12250
12438
  const className = resolve(node.className);
12251
12439
  const id = resolve(node.id);
12252
- const localsValues = useContext(LocalsValuesContext);
12440
+ const localsValues = useLiveLocals();
12253
12441
  const parts = name.split(".");
12254
12442
  const root = parts[0];
12255
12443
  const storeValue = useStoryStore((s) => scope === "local" ? void 0 : ownValue(s[STORE_NAMESPACES[scope]], root));
@@ -12308,14 +12496,17 @@ function useRenderOptions() {
12308
12496
  //#endregion
12309
12497
  //#region src/components/macros/locals-scope.tsx
12310
12498
  /**
12311
- * Render `body` in a new locals scope: the locals of `parentValues`, with
12312
- * `ownKeys` (an iteration's loop variables, a widget's parameters) on top.
12313
- * Locals the body assigns are kept in this scope.
12499
+ * Render `body` in a new locals scope: the locals of the enclosing scope,
12500
+ * with `ownKeys` (an iteration's loop variables, a widget's parameters) on
12501
+ * top. Locals the body assigns are kept in this scope.
12314
12502
  */
12315
- function LocalsScope({ body, parentValues, ownKeys }) {
12503
+ function LocalsScope({ body, ownKeys }) {
12316
12504
  const options = useRenderOptions();
12317
12505
  const [localMutations, setLocalMutations] = useState({});
12318
- const localState = useMemo(() => createNamespace(parentValues, ownKeys, localMutations), [
12506
+ const enclosing = useContext(LocalsUpdateContext).getValues();
12507
+ const parentValues = useContext(LocalsValuesContext);
12508
+ const localState = useMemo(() => createNamespace(enclosing, ownKeys, localMutations), [
12509
+ enclosing,
12319
12510
  parentValues,
12320
12511
  ownKeys,
12321
12512
  localMutations
@@ -12353,7 +12544,6 @@ function WidgetInvocation(props) {
12353
12544
  return wrapContent(resolve(props.className), resolve(props.id), /* @__PURE__ */ jsx(WidgetContent, { ...props }));
12354
12545
  }
12355
12546
  function WidgetContent({ body, params, rawArgs, invocationChildren }) {
12356
- const parentValues = useRenderOptions().locals;
12357
12547
  const [mergedVars, mergedTemps, mergedLocals, mergedTrans] = useMergedLocals();
12358
12548
  const outerChildren = useContext(WidgetChildrenContext);
12359
12549
  const childrenValue = useMemo(() => widgetChildrenOf(invocationChildren, outerChildren), [invocationChildren, outerChildren]);
@@ -12369,16 +12559,16 @@ function WidgetContent({ body, params, rawArgs, invocationChildren }) {
12369
12559
  }
12370
12560
  values.push(value);
12371
12561
  }
12562
+ const paramsKey = params.join(" ");
12372
12563
  const ownKeys = useMemo(() => {
12373
12564
  const keys = createNamespace();
12374
12565
  for (let i = 0; i < params.length; i++) keys[params[i].startsWith("@") ? params[i].slice(1) : params[i]] = values[i];
12375
12566
  return keys;
12376
- }, values);
12567
+ }, [paramsKey, ...values]);
12377
12568
  return /* @__PURE__ */ jsx(WidgetChildrenContext.Provider, {
12378
12569
  value: childrenValue,
12379
12570
  children: /* @__PURE__ */ jsx(LocalsScope, {
12380
12571
  body,
12381
- parentValues,
12382
12572
  ownKeys
12383
12573
  })
12384
12574
  });
@@ -12745,16 +12935,18 @@ function PlaceholderAttributes({ tag, attributes, placeholders, svg, children })
12745
12935
  if (!nodes) return [
12746
12936
  name,
12747
12937
  value,
12748
- written
12938
+ written,
12939
+ false
12749
12940
  ];
12750
12941
  const result = renderText(nodes, scope);
12751
12942
  for (const error of result.errors) errors.push([name, error]);
12752
12943
  return [
12753
12944
  name,
12754
12945
  result.text,
12755
- written
12946
+ written,
12947
+ true
12756
12948
  ];
12757
- }), svg);
12949
+ }), svg, tag);
12758
12950
  const ref = useDirectAttributes(direct);
12759
12951
  return withAttributeErrors(errors, h(tag, ref ? {
12760
12952
  ...props,
@@ -12833,7 +13025,8 @@ function convertDomNode(node, key, ph) {
12833
13025
  attributes.push([
12834
13026
  name,
12835
13027
  value,
12836
- value
13028
+ value,
13029
+ false
12837
13030
  ]);
12838
13031
  const parts = splitPlaceholderText(value, ph);
12839
13032
  if (parts.every((part) => typeof part === "string")) continue;
@@ -12851,7 +13044,7 @@ function convertDomNode(node, key, ph) {
12851
13044
  svg,
12852
13045
  children
12853
13046
  }, key);
12854
- const { props, direct } = splitAttributes(attributes, svg);
13047
+ const { props, direct } = splitAttributes(attributes, svg, tag);
12855
13048
  if (direct.length > 0) return /* @__PURE__ */ jsx(DirectAttributes, {
12856
13049
  tag,
12857
13050
  props,
@@ -12917,11 +13110,18 @@ var INLINE_ELEMENTS = /* @__PURE__ */ new Set([
12917
13110
  "wbr"
12918
13111
  ]);
12919
13112
  /**
12920
- * Attributes that Preact keeps as DOM properties on author HTML elements:
12921
- * the live state of form controls and media, which then follows its
12922
- * variable even after the reader changed it. Boolean ones written bare or
12923
- * as `=""` are passed as `true`, since '' is falsy (#177); one that only
12924
- * resolves to '' through an interpolation stays ''.
13113
+ * Attributes that Preact keeps as DOM properties on author HTML elements
13114
+ * when their value is bound to variables (`value="{$name}"`): the live state
13115
+ * of form controls and media, which then follows its variable even after the
13116
+ * reader changed it. Boolean ones written bare or as `=""` are passed as
13117
+ * `true`, since '' is falsy (#177); one that only resolves to '' through an
13118
+ * interpolation stays ''.
13119
+ *
13120
+ * A static `value`, `checked` or `selected` is the control's default, as in
13121
+ * HTML: set as an attribute, so a reset restores it and a rerender leaves
13122
+ * what the reader entered alone (#528). Not so for `muted`, which as an
13123
+ * attribute is ignored on an element made by script, nor for the `value` of
13124
+ * the controls that have no attribute for it.
12925
13125
  */
12926
13126
  var LIVE_PROPERTIES = /* @__PURE__ */ new Set([
12927
13127
  "value",
@@ -12992,6 +13192,14 @@ function setRawAttribute(el, name, value) {
12992
13192
  el.setAttributeNode(attr);
12993
13193
  }
12994
13194
  /**
13195
+ * Whether the static `name` attribute of `tag` is its default (#528). HTML has
13196
+ * no `value` attribute on `select` and `textarea`, so theirs stays a property.
13197
+ */
13198
+ function isNativeDefault(tag, name) {
13199
+ if (name === "muted") return false;
13200
+ return name !== "value" || tag !== "select" && tag !== "textarea";
13201
+ }
13202
+ /**
12995
13203
  * Split author attributes into Preact props and attributes to set directly.
12996
13204
  *
12997
13205
  * Author HTML means attributes, but as props Preact assigns names of DOM
@@ -13008,16 +13216,20 @@ function setRawAttribute(el, name, value) {
13008
13216
  * and `className` compat rewrites (dropping an empty `class`, turning
13009
13217
  * `className` into `class`) are set directly instead.
13010
13218
  */
13011
- function splitAttributes(attributes, svg) {
13219
+ function splitAttributes(attributes, svg, tag) {
13012
13220
  const props = {};
13013
13221
  const direct = [];
13014
- for (const [name, value, written] of attributes) {
13222
+ const defaults = [];
13223
+ for (const [name, value, written, bound] of attributes) {
13015
13224
  const lower = name.toLowerCase();
13016
13225
  if (BOOLEAN_ATTRIBUTES.has(lower) && written !== "" && value === "") continue;
13017
- else if (!svg && LIVE_PROPERTIES.has(lower)) props[lower] = lower !== "value" && written === "" ? true : value;
13018
- else if (!SETTABLE_NAME.test(name) || lower.startsWith("on") || lower === "translate" || svg && (SVG_DIRECT.has(name) || name === "__proto__")) direct.push([name, value]);
13226
+ else if (!svg && LIVE_PROPERTIES.has(lower)) {
13227
+ if (!bound && isNativeDefault(tag, lower)) defaults.push([name.toUpperCase(), lower === "value" ? value : ""]);
13228
+ else props[lower] = lower !== "value" && written === "" ? true : value;
13229
+ } else if (!SETTABLE_NAME.test(name) || lower.startsWith("on") || lower === "translate" || svg && (SVG_DIRECT.has(name) || name === "__proto__")) direct.push([name, value]);
13019
13230
  else props[svg ? name : name.toUpperCase()] = value;
13020
13231
  }
13232
+ for (const [name, value] of defaults) props[name] = value;
13021
13233
  return {
13022
13234
  props,
13023
13235
  direct
@@ -13152,8 +13364,9 @@ function HtmlNodeRenderer({ node }) {
13152
13364
  const { props, direct } = splitAttributes(Object.entries(node.attributes).map(([k, v]) => [
13153
13365
  k,
13154
13366
  resolveAttributeValue(k, v, scope, errors),
13155
- v
13156
- ]), inSvg || isSvgRoot);
13367
+ v,
13368
+ hasInterpolation(v)
13369
+ ]), inSvg || isSvgRoot, tag);
13157
13370
  const ref = useDirectAttributes(direct);
13158
13371
  if (ref) props.ref = ref;
13159
13372
  const isInline = INLINE_ELEMENTS.has(tag);
@@ -14158,6 +14371,29 @@ function extraKeys(collection) {
14158
14371
  const keys = Object.keys(collection);
14159
14372
  return Array.isArray(collection) ? keys.filter((k) => !isIndexKey(k)) : keys;
14160
14373
  }
14374
+ /** The built-in getter of each flag, with the letter `flags` lists it by. */
14375
+ var FLAG_GETTERS = [
14376
+ ["hasIndices", "d"],
14377
+ ["global", "g"],
14378
+ ["ignoreCase", "i"],
14379
+ ["multiline", "m"],
14380
+ ["dotAll", "s"],
14381
+ ["unicode", "u"],
14382
+ ["unicodeSets", "v"],
14383
+ ["sticky", "y"]
14384
+ ].flatMap(([name, letter]) => {
14385
+ const get = Object.getOwnPropertyDescriptor(RegExp.prototype, name)?.get;
14386
+ return get ? [[letter, get]] : [];
14387
+ });
14388
+ /** The pattern of a RegExp and its flags, as its slots hold them. */
14389
+ function regExpParts(re) {
14390
+ return [Reflect.get(RegExp.prototype, "source", re), FLAG_GETTERS.map(([letter, get]) => get.call(re) ? letter : "").join("")];
14391
+ }
14392
+ /** `/source/flags` of a RegExp, as its slots hold them (see regExpParts). */
14393
+ function regExpText(re) {
14394
+ const [source, flags] = regExpParts(re);
14395
+ return `/${source}/${flags}`;
14396
+ }
14161
14397
  /** The entries of a Map, as the built-in iterator gives them. */
14162
14398
  function mapEntries(map) {
14163
14399
  return isDraft(map) ? map.entries() : Map.prototype.entries.call(map);
@@ -14323,11 +14559,7 @@ function classData(value) {
14323
14559
  ];
14324
14560
  if (value instanceof RegExp) return [
14325
14561
  "RegExp",
14326
- [
14327
- Reflect.get(RegExp.prototype, "source", value),
14328
- Reflect.get(RegExp.prototype, "flags", value),
14329
- value.lastIndex
14330
- ],
14562
+ [...regExpParts(value), value.lastIndex],
14331
14563
  extra()
14332
14564
  ];
14333
14565
  return savedData(ownData(value));
@@ -14369,11 +14601,7 @@ function reducers() {
14369
14601
  const key = Symbol.keyFor(v);
14370
14602
  return key !== void 0 && [key];
14371
14603
  };
14372
- out[REGEXP_TAG] = (v) => v instanceof RegExp && v.lastIndex !== 0 && [
14373
- v.source,
14374
- v.flags,
14375
- v.lastIndex
14376
- ];
14604
+ out[REGEXP_TAG] = (v) => v instanceof RegExp && v.lastIndex !== 0 && [...regExpParts(v), v.lastIndex];
14377
14605
  out[KEYS_TAG] = (v) => {
14378
14606
  return isPlainData(v) && keyEntries(v);
14379
14607
  };
@@ -15108,7 +15336,7 @@ function getByPath(obj, segments) {
15108
15336
  return current;
15109
15337
  }
15110
15338
  /** Array indices ("0", "1", …) and "length": the keys an array holds. */
15111
- var isArrayKey = (key) => key === "length" || /^(0|[1-9]\d*)$/.test(key);
15339
+ var isArrayKey = (key) => key === "length" || isArrayIndex(key);
15112
15340
  /**
15113
15341
  * Built-ins whose content is not their properties: a property written into
15114
15342
  * one would be dropped by clones and saves (and by Immer, for Map and Set).
@@ -15262,7 +15490,7 @@ function deepClone(value, options = {}) {
15262
15490
  function cloneBuiltin(val) {
15263
15491
  if (val instanceof Date) return builtin(val, new Date(Date.prototype.getTime.call(val)));
15264
15492
  if (val instanceof RegExp) {
15265
- const copy = new RegExp(Reflect.get(RegExp.prototype, "source", val), Reflect.get(RegExp.prototype, "flags", val));
15493
+ const copy = new RegExp(...regExpParts(val));
15266
15494
  copy.lastIndex = val.lastIndex;
15267
15495
  return builtin(val, copy);
15268
15496
  }
@@ -15456,10 +15684,7 @@ function equalBuiltin(a, b, assumed) {
15456
15684
  const time = Date.prototype.getTime;
15457
15685
  return Object.is(time.call(a), time.call(b)) && equalExtraKeys(a, b, assumed);
15458
15686
  }
15459
- if (a instanceof RegExp) {
15460
- const text = RegExp.prototype.toString;
15461
- return text.call(a) === text.call(b) && a.lastIndex === b.lastIndex && equalExtraKeys(a, b, assumed);
15462
- }
15687
+ if (a instanceof RegExp) return regExpText(a) === regExpText(b) && a.lastIndex === b.lastIndex && equalExtraKeys(a, b, assumed);
15463
15688
  if (ArrayBuffer.isView(a)) {
15464
15689
  const v = b;
15465
15690
  return a.byteOffset === v.byteOffset && a.byteLength === v.byteLength && equal(a.buffer, v.buffer, assumed);
@@ -15487,11 +15712,15 @@ var BUILTIN_PROTOS = /* @__PURE__ */ new Set([
15487
15712
  RegExp.prototype
15488
15713
  ]);
15489
15714
  /**
15490
- * Equality of the extra keys (see extraKeys) of two built-ins of one
15491
- * class: those of a subclass instance are part of its value.
15715
+ * The extra keys (see extraKeys) of a built-in that is an instance of a
15716
+ * subclass: those are part of its value. A plain built-in has none.
15492
15717
  */
15718
+ function subclassFields(obj) {
15719
+ return BUILTIN_PROTOS.has(Object.getPrototypeOf(obj)) ? [] : extraKeys(obj);
15720
+ }
15721
+ /** Equality of the fields (see subclassFields) of two built-ins of one class. */
15493
15722
  function equalExtraKeys(a, b, assumed) {
15494
- return BUILTIN_PROTOS.has(Object.getPrototypeOf(a)) || equalKeys(a, b, assumed, extraKeys);
15723
+ return equalKeys(a, b, assumed, subclassFields);
15495
15724
  }
15496
15725
  /** `assumed` tracks the pairs of objects met (see Pairs). */
15497
15726
  function equal(a, b, assumed) {
@@ -15602,15 +15831,15 @@ function keyChanges(before, after, arrays) {
15602
15831
  kind: "holes",
15603
15832
  after: a.length - next
15604
15833
  });
15605
- return changes;
15606
15834
  }
15607
- for (const key of Object.keys(after)) if (hasOwn(before, key)) compare(key, before[key], after[key]);
15835
+ const keysOf = Array.isArray(after) ? subclassFields : Object.keys;
15836
+ for (const key of keysOf(after)) if (hasOwn(before, key)) compare(key, before[key], after[key]);
15608
15837
  else changes.push({
15609
15838
  key,
15610
15839
  kind: "added",
15611
15840
  after: after[key]
15612
15841
  });
15613
- for (const key of Object.keys(before)) if (!hasOwn(after, key)) changes.push({
15842
+ for (const key of keysOf(before)) if (!hasOwn(after, key)) changes.push({
15614
15843
  key,
15615
15844
  kind: "deleted"
15616
15845
  });
@@ -16120,14 +16349,34 @@ async function adoptPlaythroughNow(ifid, id) {
16120
16349
  * no number.
16121
16350
  */
16122
16351
  async function ensurePlaythrough(ifid, id, createdAt) {
16123
- const backend = await getBackend();
16124
- if (!(await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === id)) await backend.putPlaythrough({
16352
+ if (!await hasPlaythroughNow(ifid, id)) await (await getBackend()).putPlaythrough({
16125
16353
  id,
16126
16354
  ifid,
16127
16355
  createdAt,
16128
16356
  label: "Imported"
16129
16357
  });
16130
16358
  }
16359
+ /** Whether the story has a record of the playthrough `id`. */
16360
+ async function hasPlaythroughNow(ifid, id) {
16361
+ return (await (await getBackend()).getPlaythroughsByIfid(ifid)).some((p) => p.id === id);
16362
+ }
16363
+ /**
16364
+ * The playthrough a save of a game in `id` belongs to: `id` if it has a
16365
+ * record. Another tab may have deleted it since this tab cached it (#527),
16366
+ * and a save in a playthrough without a record is grouped as "Unknown" for
16367
+ * good. The save then joins the story's current playthrough (the one that
16368
+ * tab went on in), or a new one if that has no record either; callers hand
16369
+ * the result to the live game (see followSavedPlaythrough in the store).
16370
+ */
16371
+ async function livePlaythroughNow(ifid, id) {
16372
+ if (await hasPlaythroughNow(ifid, id)) return id;
16373
+ const current = await (await getBackend()).getMeta(currentPlaythroughKey(ifid));
16374
+ if (current && await hasPlaythroughNow(ifid, current)) {
16375
+ saveSessionPlaythrough(ifid, current);
16376
+ return current;
16377
+ }
16378
+ return startNewPlaythroughNow(ifid);
16379
+ }
16131
16380
  /**
16132
16381
  * Set up the save system for a story that boots: the story's current
16133
16382
  * playthrough (a new one if it has none) and the slots holding saves (see
@@ -16137,7 +16386,7 @@ function establishPlaythrough(ifid) {
16137
16386
  return inOrder(async () => {
16138
16387
  const backend = await getBackend();
16139
16388
  const own = loadSessionPlaythrough(ifid);
16140
- const id = own !== void 0 && (await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === own) ? own : await backend.getMeta(currentPlaythroughKey(ifid)) ?? await startNewPlaythroughNow(ifid);
16389
+ const id = own !== void 0 && await hasPlaythroughNow(ifid, own) ? own : await backend.getMeta(currentPlaythroughKey(ifid)) ?? await startNewPlaythroughNow(ifid);
16141
16390
  saveSessionPlaythrough(ifid, id);
16142
16391
  return {
16143
16392
  id,
@@ -16188,8 +16437,9 @@ function storedRecord(meta, payload) {
16188
16437
  }
16189
16438
  var createSave = queued(createSaveNow);
16190
16439
  async function createSaveNow(ifid, playthroughPromise, payload, custom = {}) {
16191
- const playthroughId = await playthroughPromise;
16192
- if (!playthroughId) throw new Error("No playthrough");
16440
+ const requested = await playthroughPromise;
16441
+ if (!requested) throw new Error("No playthrough");
16442
+ const playthroughId = await livePlaythroughNow(ifid, requested);
16193
16443
  const now = (/* @__PURE__ */ new Date()).toISOString();
16194
16444
  const record = storedRecord({
16195
16445
  id: randomUUID(),
@@ -16226,10 +16476,11 @@ async function createSaveNow(ifid, playthroughPromise, payload, custom = {}) {
16226
16476
  */
16227
16477
  var overwriteSave = queued(overwriteSaveNow);
16228
16478
  async function overwriteSaveNow(saveId, payload, custom, playthroughPromise) {
16229
- const playthroughId = await playthroughPromise;
16479
+ const requested = await playthroughPromise;
16230
16480
  const backend = await getBackend();
16231
16481
  const existing = await backend.getSave(saveId);
16232
16482
  if (!existing) return void 0;
16483
+ const playthroughId = requested ? await livePlaythroughNow(existing.meta.ifid, requested) : void 0;
16233
16484
  const updated = storedRecord({
16234
16485
  ...existing.meta,
16235
16486
  ...playthroughId ? { playthroughId } : {},
@@ -17026,7 +17277,7 @@ function routeStoreUpdate(recipe) {
17026
17277
  return;
17027
17278
  }
17028
17279
  if (activeScopes.length === 0) return void 0;
17029
- commitScopes(running());
17280
+ commitScopes(running$1());
17030
17281
  const inner = activeScopes[activeScopes.length - 1];
17031
17282
  const view = {
17032
17283
  ...useStoryStore.getState(),
@@ -17181,7 +17432,7 @@ function commitScopes(commits) {
17181
17432
  */
17182
17433
  var changesOf = (base, work) => changesBetween(base, work);
17183
17434
  /** Every running mutation, to commit with its code going on. */
17184
- var running = () => activeScopes.map((scope) => ({
17435
+ var running$1 = () => activeScopes.map((scope) => ({
17185
17436
  scope,
17186
17437
  keepRunning: true
17187
17438
  }));
@@ -17219,7 +17470,7 @@ function resync(scope) {
17219
17470
  */
17220
17471
  function runWithCommittedMutations(action) {
17221
17472
  if (activeScopes.length === 0) return action();
17222
- commitScopes(running());
17473
+ commitScopes(running$1());
17223
17474
  const suspended = activeScopes.splice(0);
17224
17475
  try {
17225
17476
  return action();
@@ -17235,7 +17486,7 @@ function runWithCommittedMutations(action) {
17235
17486
  * Nothing is committed when `run` throws.
17236
17487
  */
17237
17488
  function mutateState(run) {
17238
- commitScopes(running());
17489
+ commitScopes(running$1());
17239
17490
  const held = locateObjects(namespacesOf(getActiveMutationScope() ?? useStoryStore.getState()), []);
17240
17491
  const scope = startScope();
17241
17492
  const adopt = clonerFor(scope.work, held);
@@ -17244,7 +17495,7 @@ function mutateState(run) {
17244
17495
  } finally {
17245
17496
  activeScopes.pop();
17246
17497
  }
17247
- commitScopes([...running(), {
17498
+ commitScopes([...running$1(), {
17248
17499
  scope,
17249
17500
  keepRunning: false
17250
17501
  }]);
@@ -17267,7 +17518,7 @@ function executeMutation(code, mergedLocals, scopeUpdate) {
17267
17518
  } finally {
17268
17519
  activeScopes.pop();
17269
17520
  }
17270
- commitScopes([...running(), {
17521
+ commitScopes([...running$1(), {
17271
17522
  scope,
17272
17523
  keepRunning: false
17273
17524
  }]);
@@ -17843,6 +18094,16 @@ function enterStart(state, passage, variables, transientDefaults) {
17843
18094
  state.historyIndex = 0;
17844
18095
  }
17845
18096
  /**
18097
+ * Run `fn` (an event's handlers) and tell whether they replaced the game
18098
+ * state (a restart or load): what the caller was about to do to the game it
18099
+ * emitted from is then not to be done to the new one (#516, #517).
18100
+ */
18101
+ function replacesState(fn) {
18102
+ const applied = latestStateApplied;
18103
+ fn();
18104
+ return latestStateApplied !== applied;
18105
+ }
18106
+ /**
17846
18107
  * Move through history by `step` moments (back or forward), restoring the
17847
18108
  * snapshot recorded for the moment moved to: live variables may hold edits
17848
18109
  * made since the current moment was recorded.
@@ -17854,7 +18115,9 @@ function moveInHistory(get, set, step) {
17854
18115
  finishEnteredMoment(get, set);
17855
18116
  const previousPassage = get().currentPassage;
17856
18117
  const targetPassage = history[target].passage;
18118
+ const navigation = get().navigationId;
17857
18119
  emit("beforenavigate", targetPassage);
18120
+ if (get().navigationId !== navigation) return;
17858
18121
  const restoredVars = deepClone(reconstructVarsAt(target));
17859
18122
  set((state) => {
17860
18123
  state.historyIndex += step;
@@ -17866,6 +18129,7 @@ function moveInHistory(get, set, step) {
17866
18129
  reinitTriggerState();
17867
18130
  lastNavigationVars = get().variables;
17868
18131
  restorePRNGFromMoment(get().history[get().historyIndex]);
18132
+ keepDrawsSoFar();
17869
18133
  persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage));
17870
18134
  }
17871
18135
  /**
@@ -17884,6 +18148,7 @@ function recordStoryInitState() {
17884
18148
  useStoryStore.setState((state) => {
17885
18149
  state.history[0].prng = prng;
17886
18150
  });
18151
+ keepDrawsSoFar();
17887
18152
  }
17888
18153
  /**
17889
18154
  * Settles once the latest playthrough switch (init's lookup or creation, a
@@ -17987,6 +18252,18 @@ function switchToLoadedPlaythrough(ifid, id) {
17987
18252
  }));
17988
18253
  }
17989
18254
  /**
18255
+ * Move the running game to the playthrough a save it wrote was stored in,
18256
+ * when that is not the one it asked for: another tab deleted the game's
18257
+ * playthrough, and the save took the story's current one (#527). `requested`
18258
+ * is the playthrough the save was issued with (see resolvePlaythroughId). A
18259
+ * game that has switched since (a restart, a load) stays where it is.
18260
+ */
18261
+ async function followSavedPlaythrough(requested, saved) {
18262
+ const id = saved?.meta.playthroughId;
18263
+ const asked = await requested;
18264
+ if (id && id !== asked && knownPlaythroughId() === asked) switchToPlaythrough(id, Promise.resolve());
18265
+ }
18266
+ /**
17990
18267
  * A load from a slot reads the save in the order of storage operations and
17991
18268
  * applies it when the read completes. A restart, a boot or a direct load
17992
18269
  * (loadFromPayload) issued after it replaces the game state at once; the
@@ -18099,7 +18376,8 @@ function keepHookWrites(payload, before, after, written) {
18099
18376
  changes.push({
18100
18377
  path,
18101
18378
  deleted: false,
18102
- value
18379
+ value,
18380
+ absolute: true
18103
18381
  });
18104
18382
  }
18105
18383
  if (changes.length === 0) return;
@@ -18116,7 +18394,8 @@ function keepHookWrites(payload, before, after, written) {
18116
18394
  * value of it is written. Into an array, elements removed from the end are
18117
18395
  * removed at the same indices and elements added are appended; changes at
18118
18396
  * indices the array lacks are dropped (it was resized, so its indices do not
18119
- * line up with the live ones).
18397
+ * line up with the live ones). The hooks' explicit writes are not diffs: an
18398
+ * array's length or an element they set is set to that value (#515).
18120
18399
  */
18121
18400
  function writeHookChange(work, after, change, own) {
18122
18401
  const { path } = change;
@@ -18138,7 +18417,7 @@ function writeHookChange(work, after, change, own) {
18138
18417
  }
18139
18418
  function writeKey(holder, key, value, change) {
18140
18419
  const deleted = change?.deleted ?? false;
18141
- if (Array.isArray(holder)) {
18420
+ if (Array.isArray(holder) && (key === "length" || isIndexKey(key))) {
18142
18421
  const index = Number(key);
18143
18422
  if (deleted) {
18144
18423
  if (change && "hole" in change) delete holder[index];
@@ -18146,6 +18425,9 @@ function writeKey(holder, key, value, change) {
18146
18425
  } else if (change && "appended" in change) {
18147
18426
  holder.length += change.gap ?? 0;
18148
18427
  holder.push(value);
18428
+ } else if (change && "absolute" in change) {
18429
+ if (key === "length") holder.length = value;
18430
+ else holder[index] = value;
18149
18431
  } else if (key === "length" && change) holder.length += value;
18150
18432
  else if (index < holder.length) holder[index] = value;
18151
18433
  } else if (deleted) delete holder[key];
@@ -18394,7 +18676,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
18394
18676
  return;
18395
18677
  }
18396
18678
  const previousPassage = get().currentPassage;
18397
- emit("beforenavigate", passageName);
18679
+ if (replacesState(() => emit("beforenavigate", passageName))) return;
18398
18680
  const patchEntry = computeVarPatches(lastNavigationVars, get().variables);
18399
18681
  set((state) => {
18400
18682
  state.temporary = createNamespace();
@@ -18427,8 +18709,9 @@ var useStoryStore = create()(storyStore((set, get) => ({
18427
18709
  const deferred = deferredNavigations;
18428
18710
  deferredNavigations = [];
18429
18711
  finishEnteredMoment(get, set);
18712
+ keepDrawsSoFar();
18430
18713
  persistSessionThen(get, () => {
18431
- emit("afternavigate", passageName, previousPassage);
18714
+ if (replacesState(() => emit("afternavigate", passageName, previousPassage))) return;
18432
18715
  for (const next of deferred) get().navigate(next);
18433
18716
  });
18434
18717
  },
@@ -18517,7 +18800,8 @@ var useStoryStore = create()(storyStore((set, get) => ({
18517
18800
  set((state) => {
18518
18801
  state.saveError = null;
18519
18802
  });
18520
- await quickSave$1(storyData.ifid, playthrough, payload, slot, custom);
18803
+ const saved = await quickSave$1(storyData.ifid, playthrough, payload, slot, custom);
18804
+ await followSavedPlaythrough(playthrough, saved);
18521
18805
  recordKnownSave(set, slot, true);
18522
18806
  }), "spindle: failed to save", (err) => set((state) => {
18523
18807
  state.saveError = errorMessage(err, "Failed to save");
@@ -18618,10 +18902,12 @@ var useStoryStore = create()(storyStore((set, get) => ({
18618
18902
  },
18619
18903
  beginSave: () => {
18620
18904
  const before = get().variables;
18905
+ const replaced = latestStateApplied;
18621
18906
  const writes = /* @__PURE__ */ new Map();
18622
18907
  hookWrites = writes;
18623
18908
  return () => {
18624
18909
  if (hookWrites === writes) hookWrites = null;
18910
+ if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
18625
18911
  const payload = get().getSavePayload();
18626
18912
  keepHookWrites(payload, before, get().variables, [...writes.values()]);
18627
18913
  return payload;
@@ -18645,6 +18931,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
18645
18931
  } finally {
18646
18932
  leavingPlaythrough = null;
18647
18933
  }
18934
+ if (latestStateApplied !== replacement) return;
18648
18935
  const ifid = get().storyData?.ifid;
18649
18936
  if (playthroughId && ifid) switchToLoadedPlaythrough(ifid, playthroughId);
18650
18937
  const entry = loadedEntryMoment(payload);
@@ -18672,6 +18959,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
18672
18959
  reinitTriggerState();
18673
18960
  lastNavigationVars = reconstructVarsAt(get().historyIndex);
18674
18961
  restorePRNGFrom(entry?.prng !== void 0 ? entry.prng : payload.prng);
18962
+ keepDrawsSoFar();
18675
18963
  persistSessionThen(get, () => withoutDraws(() => emit("afterload", slot)));
18676
18964
  },
18677
18965
  getHistoryVariables: (index) => {
@@ -18794,20 +19082,22 @@ function tabIndexAttr(el) {
18794
19082
  function isTabStop(el) {
18795
19083
  const tabIndex = tabIndexAttr(el);
18796
19084
  if (tabIndex !== null && tabIndex < 0) return false;
18797
- if (el.hasAttribute("contenteditable") && !el.matches("a[href], button, input, select, textarea, iframe, summary") && (!el.isContentEditable || el.parentElement?.isContentEditable)) return false;
19085
+ if (tabIndex === null && el.hasAttribute("contenteditable") && !el.matches("a[href], button, input, select, textarea, iframe, summary") && (!el.isContentEditable || el.parentElement?.isContentEditable)) return false;
18798
19086
  if (el.localName === "summary") {
18799
19087
  const details = el.parentElement;
18800
19088
  if (details?.localName !== "details" || Array.from(details.children).find((c) => c.localName === "summary") !== el) return tabIndex !== null;
18801
19089
  }
18802
- if (el instanceof HTMLInputElement && el.type === "radio" && el.name) {
18803
- 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));
19090
+ const input = el;
19091
+ if (el.localName === "input" && input.type === "radio" && input.name) {
19092
+ 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));
18804
19093
  return el === (group.find((r) => r.checked) ?? group[0]);
18805
19094
  }
18806
19095
  return true;
18807
19096
  }
18808
19097
  /**
18809
- * The elements of `root` in the order Tab visits them: positive tabindexes
18810
- * first, ascending, then the others in document order.
19098
+ * The elements of `root` (the dialog panel, or an embedded document) in the
19099
+ * order Tab visits them: positive tabindexes first, ascending, then the
19100
+ * others in document order.
18811
19101
  */
18812
19102
  function focusables(root) {
18813
19103
  const stops = Array.from(root.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
@@ -18834,57 +19124,132 @@ var SEGMENTED_INPUTS = /* @__PURE__ */ new Set([
18834
19124
  ]);
18835
19125
  /** Whether the element has native tab stops inside it, in its shadow tree. */
18836
19126
  function hasNativeStops(el) {
18837
- if (el instanceof HTMLMediaElement) return el.controls;
18838
- return el instanceof HTMLInputElement && SEGMENTED_INPUTS.has(el.type) && !el.readOnly;
19127
+ if (!el) return false;
19128
+ if (el.localName === "audio" || el.localName === "video") return el.controls;
19129
+ const input = el;
19130
+ return el.localName === "input" && SEGMENTED_INPUTS.has(input.type) && !input.readOnly;
19131
+ }
19132
+ /** Whether `el` is an iframe element, of this realm or of an embedded one. */
19133
+ function isFrame(el) {
19134
+ return el.localName === "iframe";
19135
+ }
19136
+ /** The document of a frame, or null when it is not accessible. */
19137
+ function frameDocument(frame) {
19138
+ try {
19139
+ return frame.contentDocument;
19140
+ } catch {
19141
+ return null;
19142
+ }
19143
+ }
19144
+ /** The iframe element that holds `doc`, null for the top document. */
19145
+ function frameOf(doc) {
19146
+ try {
19147
+ return doc.defaultView?.frameElement;
19148
+ } catch {
19149
+ return null;
19150
+ }
19151
+ }
19152
+ /**
19153
+ * The stop after (or before) `from` among `items`, the tab stops of `root`,
19154
+ * undefined past the end. `from` may be no stop of its own: then the next one
19155
+ * in document order. Outside `root`, the first (or last) stop.
19156
+ */
19157
+ function nextStop(items, root, from, backwards) {
19158
+ const at = from ? items.indexOf(from) : -1;
19159
+ if (at !== -1) return items[at + (backwards ? -1 : 1)];
19160
+ if (from && from !== root && root.contains(from)) {
19161
+ const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
19162
+ return backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
19163
+ }
19164
+ return backwards ? items[items.length - 1] : items[0];
19165
+ }
19166
+ /**
19167
+ * The focused element, through the accessible frame documents: a frame holding
19168
+ * the focus is followed to its own focused element, unless that is its body
19169
+ * (nothing focused in it) or its document can't be reached (then the frame
19170
+ * itself is the deepest). Elements of an embedded document are of another
19171
+ * realm's classes, hence the duck typing. A focusable SVG element (a link in an
19172
+ * illustration) counts (#483).
19173
+ */
19174
+ function activeChain() {
19175
+ const chain = [];
19176
+ let doc = document;
19177
+ while (doc) {
19178
+ const el = doc.activeElement;
19179
+ if (!el || chain.length > 0 && el === doc.body) break;
19180
+ if (typeof el.focus !== "function") break;
19181
+ chain.push(el);
19182
+ doc = isFrame(el) ? frameDocument(el) : null;
19183
+ }
19184
+ return chain;
19185
+ }
19186
+ /** Whether `el` is still part of a live document. */
19187
+ function isLive(el) {
19188
+ return el.isConnected && !!el.ownerDocument.defaultView;
18839
19189
  }
18840
- /** The tab stops of an embedded document, in tab order. */
18841
- function frameStops(doc) {
18842
- if (!doc) return [];
18843
- return Array.from(doc.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
19190
+ /** Focus the deepest element of `chain` that is still there. */
19191
+ function restoreOpener(chain) {
19192
+ for (let i = chain.length - 1; i >= 0; i--) {
19193
+ const el = chain[i];
19194
+ if (isLive(el)) {
19195
+ el.focus();
19196
+ return;
19197
+ }
19198
+ }
18844
19199
  }
18845
19200
  function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18846
19201
  useLayoutEffect(() => {
18847
19202
  const panel = panelRef.current;
18848
19203
  if (!panel) return;
18849
- const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
18850
- const entry = { panel };
19204
+ const entry = {
19205
+ panel,
19206
+ opener: activeChain()
19207
+ };
18851
19208
  openModals.push(entry);
18852
19209
  const body = panel.querySelector(bodySelector) ?? panel;
18853
19210
  (Array.from(panel.querySelectorAll("[autofocus]")).find(isAvailable) ?? focusables(body)[0] ?? panel).focus();
18854
19211
  return () => {
18855
19212
  const i = openModals.indexOf(entry);
18856
19213
  if (i !== -1) openModals.splice(i, 1);
19214
+ for (const upper of openModals.slice(i === -1 ? openModals.length : i)) {
19215
+ const [outer] = upper.opener;
19216
+ if (!outer || panel.contains(outer) || !upper.opener.some(isLive)) upper.opener = entry.opener;
19217
+ }
18857
19218
  const active = document.activeElement;
18858
- if ((!active || active === document.body || panel.contains(active)) && opener?.isConnected) opener.focus();
19219
+ if (!active || active === document.body || panel.contains(active)) restoreOpener(entry.opener);
18859
19220
  };
18860
19221
  }, []);
18861
19222
  useLayoutEffect(() => {
18862
19223
  const panel = panelRef.current;
18863
19224
  if (!panel) return;
18864
19225
  const top = () => openModals[openModals.length - 1]?.panel === panel;
18865
- /**
18866
- * Move focus to the next (or previous) modal control from `from`. The
18867
- * order is computed here, never left to the browser: its positive-tabindex
18868
- * sequence spans the whole document and would lead out of the modal
18869
- * (#424). `from` may be an element of an embedded document, whose frame
18870
- * element then stands in for it.
18871
- */
18872
19226
  /** Focus `el`; a frame is entered at its first (or last) control (#460). */
18873
19227
  const enter = (el, backwards) => {
18874
- if (el instanceof HTMLIFrameElement) {
18875
- let inner = [];
18876
- try {
18877
- inner = frameStops(el.contentDocument);
18878
- } catch {}
19228
+ if (isFrame(el)) {
19229
+ const doc = frameDocument(el);
19230
+ const inner = doc ? focusables(doc) : [];
18879
19231
  const edge = backwards ? inner[inner.length - 1] : inner[0];
18880
- if (edge) {
18881
- edge.focus();
18882
- return;
18883
- }
19232
+ if (edge) return enter(edge, backwards);
18884
19233
  }
18885
19234
  el.focus();
18886
19235
  };
19236
+ /**
19237
+ * Move focus to the next (or previous) modal control from `from`. The
19238
+ * order is computed here, never left to the browser: its positive-tabindex
19239
+ * sequence spans the whole document and would lead out of the modal
19240
+ * (#424). `from` is an element of the dialog, or of an embedded document;
19241
+ * past the last control of a frame, focus goes on after the frame element
19242
+ * in the document that holds it.
19243
+ */
18887
19244
  const moveFocus = (from, backwards) => {
19245
+ const doc = from?.ownerDocument;
19246
+ const frame = doc && doc !== document ? frameOf(doc) : null;
19247
+ if (doc && frame) {
19248
+ const next = nextStop(focusables(doc), doc, from, backwards);
19249
+ if (next) enter(next, backwards);
19250
+ else moveFocus(frame, backwards);
19251
+ return;
19252
+ }
18888
19253
  const items = focusables(panel);
18889
19254
  const first = items[0];
18890
19255
  const last = items[items.length - 1];
@@ -18892,107 +19257,102 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18892
19257
  panel.focus();
18893
19258
  return;
18894
19259
  }
18895
- const at = from ? items.indexOf(from) : -1;
18896
- let next;
18897
- if (at !== -1) next = items[at + (backwards ? -1 : 1)];
18898
- else if (from && from !== panel && panel.contains(from)) {
18899
- const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
18900
- next = backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
18901
- } else next = backwards ? last : first;
19260
+ const next = nextStop(items, panel, from, backwards);
18902
19261
  enter(next ?? (backwards ? last : first), backwards);
18903
19262
  };
18904
19263
  let steppingNative = null;
18905
- const onKeyDown = (e) => {
18906
- if (!top()) return;
18907
- if (e.key === "Escape") {
18908
- if (!dismissible) return;
18909
- e.preventDefault();
18910
- e.stopPropagation();
18911
- onClose();
18912
- return;
18913
- }
18914
- if (e.key !== "Tab") return;
18915
- const active = document.activeElement;
18916
- if (hasNativeStops(active)) {
18917
- steppingNative = {
18918
- el: active,
18919
- backwards: e.shiftKey
18920
- };
18921
- return;
18922
- }
18923
- e.preventDefault();
18924
- moveFocus(active, e.shiftKey);
18925
- };
18926
- const onPointerDown = () => {
18927
- steppingNative = null;
18928
- };
18929
- const controller = new AbortController();
18930
- const { signal } = controller;
18931
- const frameDocs = /* @__PURE__ */ new Map();
18932
- const attachFrame = (frame) => {
18933
- let doc = null;
18934
- try {
18935
- doc = frame.contentDocument;
18936
- } catch {}
18937
- if (!doc || frameDocs.get(frame) === doc) return;
18938
- frameDocs.set(frame, doc);
18939
- const onFrameKeyDown = (e) => {
19264
+ const keyHandler = (doc, frame) => {
19265
+ return (e) => {
18940
19266
  if (!top()) return;
18941
- if (e.key !== "Tab") return onKeyDown(e);
18942
- const inner = frameStops(doc);
18943
- const active = doc.activeElement;
18944
- const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
18945
- if (!edge || active === edge || active === doc.body) {
19267
+ if (e.key === "Escape") {
19268
+ if (!dismissible) return;
18946
19269
  e.preventDefault();
18947
- moveFocus(frame, e.shiftKey);
19270
+ e.stopPropagation();
19271
+ onClose();
19272
+ return;
18948
19273
  }
19274
+ if (e.key !== "Tab") return;
19275
+ const active = doc.activeElement;
19276
+ if (frame) {
19277
+ steppingNative = null;
19278
+ const inner = focusables(doc);
19279
+ const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
19280
+ if (edge && active !== edge && active !== doc.body) return;
19281
+ }
19282
+ if (hasNativeStops(active)) {
19283
+ steppingNative = {
19284
+ el: active,
19285
+ from: frame ?? active,
19286
+ backwards: e.shiftKey
19287
+ };
19288
+ return;
19289
+ }
19290
+ e.preventDefault();
19291
+ moveFocus(frame ?? active, e.shiftKey);
18949
19292
  };
18950
- doc.addEventListener("keydown", onFrameKeyDown, { signal });
18951
19293
  };
18952
- const attachFrames = () => {
18953
- panel.querySelectorAll("iframe").forEach(attachFrame);
18954
- };
18955
- const onLoad = (e) => {
18956
- if (e.target instanceof HTMLIFrameElement) attachFrame(e.target);
19294
+ const onPointerDown = () => {
19295
+ steppingNative = null;
18957
19296
  };
18958
- panel.addEventListener("load", onLoad, {
18959
- capture: true,
18960
- signal
18961
- });
18962
- const frames = new MutationObserver(attachFrames);
18963
- frames.observe(panel, {
18964
- childList: true,
18965
- subtree: true
18966
- });
18967
- attachFrames();
18968
19297
  const onFocusIn = (e) => {
18969
19298
  const target = e.target;
18970
19299
  if (steppingNative && target !== steppingNative.el && top()) {
18971
- const { el, backwards } = steppingNative;
19300
+ const { from, backwards } = steppingNative;
18972
19301
  steppingNative = null;
18973
- moveFocus(el, backwards);
19302
+ moveFocus(from, backwards);
18974
19303
  return;
18975
19304
  }
18976
19305
  if (!top() || !(target instanceof Node) || panel.contains(target)) return;
18977
19306
  if (target === document.body || target === document.documentElement) return;
18978
19307
  moveFocus(null, false);
18979
19308
  };
18980
- document.addEventListener("keydown", onKeyDown, { signal });
18981
- document.addEventListener("pointerdown", onPointerDown, {
18982
- capture: true,
18983
- signal
18984
- });
18985
19309
  const onFocusOut = (e) => {
18986
19310
  const pending = steppingNative;
18987
19311
  if (!pending || e.target !== pending.el || e.relatedTarget || !top()) return;
18988
19312
  steppingNative = null;
18989
- moveFocus(pending.el, pending.backwards);
19313
+ moveFocus(pending.from, pending.backwards);
19314
+ };
19315
+ const controller = new AbortController();
19316
+ const { signal } = controller;
19317
+ const listen = (doc, frame) => {
19318
+ doc.addEventListener("keydown", keyHandler(doc, frame), { signal });
19319
+ doc.addEventListener("pointerdown", onPointerDown, {
19320
+ capture: true,
19321
+ signal
19322
+ });
19323
+ doc.addEventListener("focusout", onFocusOut, { signal });
18990
19324
  };
18991
- document.addEventListener("focusout", onFocusOut, { signal });
19325
+ const frameDocs = /* @__PURE__ */ new Map();
19326
+ const observers = [];
19327
+ const attachFrame = (frame) => {
19328
+ const doc = frameDocument(frame);
19329
+ if (!doc || frameDocs.get(frame) === doc) return;
19330
+ frameDocs.set(frame, doc);
19331
+ listen(doc, frame);
19332
+ watchFrames(doc);
19333
+ };
19334
+ const watchFrames = (root) => {
19335
+ const attachAll = () => root.querySelectorAll("iframe").forEach(attachFrame);
19336
+ root.addEventListener("load", (e) => {
19337
+ if (e.target instanceof Node && isFrame(e.target)) attachFrame(e.target);
19338
+ }, {
19339
+ capture: true,
19340
+ signal
19341
+ });
19342
+ const observer = new MutationObserver(attachAll);
19343
+ observer.observe(root, {
19344
+ childList: true,
19345
+ subtree: true
19346
+ });
19347
+ observers.push(observer);
19348
+ attachAll();
19349
+ };
19350
+ watchFrames(panel);
19351
+ listen(document, null);
18992
19352
  document.addEventListener("focusin", onFocusIn, { signal });
18993
19353
  return () => {
18994
19354
  controller.abort();
18995
- frames.disconnect();
19355
+ observers.forEach((o) => o.disconnect());
18996
19356
  };
18997
19357
  }, [dismissible, onClose]);
18998
19358
  }
@@ -19255,10 +19615,13 @@ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
19255
19615
  * early, while text it leaves unescaped (in `<style>`, comments) would be
19256
19616
  * decoded wrongly.
19257
19617
  */
19258
- function passageMarkup(parent) {
19618
+ function passageMarkup(parent, inElement = false) {
19619
+ const escapeText = inElement && !isLiteralTextElement(parent);
19259
19620
  let markup = "";
19260
- for (const node of Array.from(parent.childNodes)) if (node.nodeType === Node.TEXT_NODE) markup += node.data;
19261
- else if (node.nodeType === Node.COMMENT_NODE) markup += `<!--${node.data}-->`;
19621
+ for (const node of Array.from(parent.childNodes)) if (node.nodeType === Node.TEXT_NODE) {
19622
+ const { data } = node;
19623
+ markup += escapeText ? escapeMarkupText(data, false, escapeTextReferences) : data;
19624
+ } else if (node.nodeType === Node.COMMENT_NODE) markup += `<!--${node.data}-->`;
19262
19625
  else if (node.nodeType === Node.ELEMENT_NODE) markup += elementMarkup(node);
19263
19626
  return markup;
19264
19627
  }
@@ -19270,7 +19633,7 @@ function elementMarkup(el) {
19270
19633
  markup += ">";
19271
19634
  if (el.namespaceURI === HTML_NAMESPACE && VOID_ELEMENTS.has(name)) return markup;
19272
19635
  const content = name === "template" ? el.content : el;
19273
- return `${markup}${passageMarkup(content)}</${name}>`;
19636
+ return `${markup}${passageMarkup(content, true)}</${name}>`;
19274
19637
  }
19275
19638
  /**
19276
19639
  * An attribute value quoted so that the passage parser reads it back:
@@ -19292,15 +19655,27 @@ function quoteAttribute(name, value) {
19292
19655
  const tag = tokens[0];
19293
19656
  return tokens.length === 1 && tag?.type === "html" && tag.attributes[probe] === quoted.slice(1, -1);
19294
19657
  };
19295
- return [`"${value}"`, `'${value}'`].find(readsBack) ?? `"${escapeTextQuotes(value, code)}"`;
19658
+ const text = escapeMarkupText(value, code, escapeAttributeReferences);
19659
+ return [`"${text}"`, `'${text}'`].find(readsBack) ?? `"${escapeMarkupText(text, code, escapeQuotes)}"`;
19296
19660
  }
19661
+ var escapeQuotes = (text) => text.replace(/"/g, "&quot;");
19662
+ var escapeAttributeReferences = (text) => text.replace(/&/g, "&amp;");
19663
+ /** Also `<`, which would start a tag in the passage. */
19664
+ var escapeTextReferences = (text) => escapeAttributeReferences(text).replace(/</g, "&lt;");
19297
19665
  /**
19298
- * `value` with the double quotes in its text written as `&quot;`, but not
19299
- * those in markup (`{print "a"}`) or, in a code attribute, in sigil
19300
- * references (see splitSigilTemplate), which are code.
19666
+ * Elements whose text the renderer shows as written, with no character
19667
+ * references decoded: the one it treats as raw text (`style`, see
19668
+ * HtmlNodeRenderer), for which the browser did not decode any either.
19301
19669
  */
19302
- function escapeTextQuotes(value, code) {
19303
- const escape = (text) => text.replace(/"/g, "&quot;");
19670
+ function isLiteralTextElement(parent) {
19671
+ return parent.localName === "style" && parent.namespaceURI === HTML_NAMESPACE;
19672
+ }
19673
+ /**
19674
+ * `value` with the text in it escaped by `escape`, but not markup
19675
+ * (`{print "a"}`) or, in a code attribute, sigil references (see
19676
+ * splitSigilTemplate), which are code.
19677
+ */
19678
+ function escapeMarkupText(value, code, escape) {
19304
19679
  if (code) return splitSigilTemplate(value).map((part) => "text" in part ? escape(part.text) : "expr" in part ? `{${part.expr}}` : part.verbatim).join("");
19305
19680
  let tokens;
19306
19681
  try {
@@ -19565,21 +19940,33 @@ var OPTIONAL_ACTION_FIELDS = [
19565
19940
  var actions = /* @__PURE__ */ new Map();
19566
19941
  var idCounters = /* @__PURE__ */ new Map();
19567
19942
  /**
19943
+ * IDs handed out and not yet registered, or registered: a control registers
19944
+ * in a layout effect, after every control of the same render has allocated its
19945
+ * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
19946
+ * Released when the last registration of an ID goes.
19947
+ */
19948
+ var reserved = /* @__PURE__ */ new Set();
19949
+ /**
19568
19950
  * The counters reset on every navigation, so a passage's controls get the
19569
19951
  * same IDs each time it is shown. Controls that stay mounted across
19570
19952
  * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19571
- * ID still registered (#233).
19953
+ * ID still registered (#233) and every one allocated but not registered yet
19954
+ * (#486).
19572
19955
  */
19573
19956
  function generateActionId(type, key, authorId) {
19574
- if (authorId) return authorId;
19957
+ if (authorId) {
19958
+ reserved.add(authorId);
19959
+ return authorId;
19960
+ }
19575
19961
  const base = `${type}:${key}`;
19576
19962
  let count = idCounters.get(base) ?? 0;
19577
19963
  let id;
19578
19964
  do {
19579
19965
  count++;
19580
19966
  id = count === 1 ? base : `${base}:${count}`;
19581
- } while (actions.has(id));
19967
+ } while (actions.has(id) || reserved.has(id));
19582
19968
  idCounters.set(base, count);
19969
+ reserved.add(id);
19583
19970
  return id;
19584
19971
  }
19585
19972
  function registerAction(action) {
@@ -19603,11 +19990,34 @@ function registerAction(action) {
19603
19990
  const index = current ? current.indexOf(entry) : -1;
19604
19991
  if (!current || index === -1) return;
19605
19992
  current.splice(index, 1);
19606
- if (current.length === 0) actions.delete(id);
19993
+ if (current.length === 0) {
19994
+ actions.delete(id);
19995
+ reserved.delete(id);
19996
+ }
19607
19997
  if (index === current.length) notify();
19608
19998
  }
19609
19999
  };
19610
20000
  }
20001
+ /** The promises of the performed actions that have not settled yet. */
20002
+ var running = /* @__PURE__ */ new Set();
20003
+ /**
20004
+ * Perform an action, as `Story.performAction()` does. One that returns a
20005
+ * promise is tracked until it settles, for `settleRunningActions()`, and the
20006
+ * promise is returned for the caller to await (its rejection stays the
20007
+ * caller's to handle).
20008
+ */
20009
+ function performRegisteredAction(action, value) {
20010
+ const result = action.perform(value);
20011
+ if (!result || typeof result.then !== "function") return result;
20012
+ const done = () => void running.delete(result);
20013
+ running.add(result);
20014
+ result.then(done, done);
20015
+ return result.then((v) => v);
20016
+ }
20017
+ /** Wait until every performed action has finished, whether or not it failed. */
20018
+ async function settleRunningActions() {
20019
+ while (running.size > 0) await Promise.allSettled(running);
20020
+ }
19611
20021
  function getActions() {
19612
20022
  return Array.from(actions.values(), listed);
19613
20023
  }
@@ -19620,6 +20030,7 @@ function listed(entries) {
19620
20030
  }
19621
20031
  function resetIdCounters() {
19622
20032
  idCounters.clear();
20033
+ for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
19623
20034
  }
19624
20035
  function notify() {
19625
20036
  emit("actionsChanged");
@@ -19829,8 +20240,8 @@ function ensureVariableChangedSubscription() {
19829
20240
  const changed = {};
19830
20241
  const collect = (prev, next, prefix) => {
19831
20242
  for (const key of changedNames(prev, next)) changed[prefix + key] = {
19832
- from: ownValue(prev, key),
19833
- to: ownValue(next, key)
20243
+ from: readOnlyValue(ownValue(prev, key)),
20244
+ to: readOnlyValue(ownValue(next, key))
19834
20245
  };
19835
20246
  };
19836
20247
  collect(prevVars, state.variables, "");
@@ -19984,7 +20395,7 @@ function createStoryAPI() {
19984
20395
  const action = getAction(id);
19985
20396
  if (!action) throw new Error(`spindle: Action "${id}" not found.`);
19986
20397
  if (action.disabled) throw new Error(`spindle: Action "${id}" is disabled.`);
19987
- action.perform(value);
20398
+ return performRegisteredAction(action, value);
19988
20399
  },
19989
20400
  on(event, callback) {
19990
20401
  if (event === "variableChanged") ensureVariableChangedSubscription();
@@ -19993,9 +20404,11 @@ function createStoryAPI() {
19993
20404
  return unsub;
19994
20405
  },
19995
20406
  async waitForActions() {
20407
+ await settleRunningActions();
19996
20408
  await new Promise((resolve) => {
19997
20409
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
19998
20410
  });
20411
+ await new Promise((resolve) => setTimeout(resolve, 0));
19999
20412
  const isRendered = () => getRenderedNavigationId() === useStoryStore.getState().navigationId;
20000
20413
  if (getRenderedNavigationId() !== null && !isRendered() && !useStoryStore.getState().renderDeferred) await new Promise((resolve) => {
20001
20414
  const off = on("passagerender", () => {
@@ -20319,10 +20732,12 @@ function validateMarkup(passages, options) {
20319
20732
  * an operator, a reference, a spread) is "not static", which is no error: the
20320
20733
  * value is simply not known without running the code.
20321
20734
  */
20322
- var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d+)?)(n?)/y;
20735
+ 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;
20323
20736
  var IDENT_RE = /[A-Za-z_$][\w$]*/y;
20324
20737
  var KEY_RE = /[\w$]+/y;
20325
20738
  var ARROW_RE = /(?:async\s+)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*=>/y;
20739
+ /** The end of a line: the four line terminators of JavaScript. */
20740
+ var LINE_END_RE = /[\n\r\u2028\u2029]/g;
20326
20741
  var ARRAY_INDEX_RE = /^(?:0|[1-9]\d{0,8})$/;
20327
20742
  var UNSUPPORTED_UNDEFINED = {
20328
20743
  unsupported: "undefined",
@@ -20344,6 +20759,22 @@ function entryOrder(keys) {
20344
20759
  const all = [...keys];
20345
20760
  return [...all.filter((key) => ARRAY_INDEX_RE.test(key)).sort((a, b) => Number(a) - Number(b)), ...all.filter((key) => !ARRAY_INDEX_RE.test(key))];
20346
20761
  }
20762
+ /**
20763
+ * Where the regex literals in `src` are, by their start: JavaScript text
20764
+ * cannot tell a regex from a division without the code before it, which the
20765
+ * lexer reads. `handlers` see the same walk.
20766
+ */
20767
+ function regexLiterals(src, goal = "expression", handlers = {}) {
20768
+ const ends = /* @__PURE__ */ new Map();
20769
+ lexJs(src, {
20770
+ ...handlers,
20771
+ literal(text, index, nesting) {
20772
+ if (text.charAt(0) === "/" && !/^\/[/*]/.test(text)) ends.set(index, index + text.length);
20773
+ handlers.literal?.(text, index, nesting);
20774
+ }
20775
+ }, goal);
20776
+ return ends;
20777
+ }
20347
20778
  /** `String(value)` of a BigInt literal's digits, or `undefined` if they are no BigInt. */
20348
20779
  function bigintValue(digits) {
20349
20780
  try {
@@ -20357,9 +20788,15 @@ function bigintValue(digits) {
20357
20788
  * helpers that skip what is not read are shared (see macro-discovery.ts).
20358
20789
  */
20359
20790
  var Reader = class {
20360
- constructor(src) {
20791
+ /**
20792
+ * `regexes` (see regexLiterals) are read from `src` when they are first
20793
+ * needed, unless the caller has them already.
20794
+ */
20795
+ constructor(src, options = {}) {
20361
20796
  this.src = src;
20362
20797
  this.i = 0;
20798
+ this.goal = options.goal ?? "expression";
20799
+ this.regexes = options.regexes;
20363
20800
  }
20364
20801
  /** Skip whitespace and comments. */
20365
20802
  space() {
@@ -20367,8 +20804,8 @@ var Reader = class {
20367
20804
  for (;;) {
20368
20805
  while (/\s/.test(src.charAt(this.i))) this.i++;
20369
20806
  if (src.startsWith("//", this.i)) {
20370
- const end = src.indexOf("\n", this.i);
20371
- this.i = end < 0 ? src.length : end;
20807
+ LINE_END_RE.lastIndex = this.i;
20808
+ this.i = LINE_END_RE.test(src) ? LINE_END_RE.lastIndex - 1 : src.length;
20372
20809
  } else if (src.startsWith("/*", this.i)) {
20373
20810
  const end = src.indexOf("*/", this.i + 2);
20374
20811
  this.i = end < 0 ? src.length : end + 2;
@@ -20427,10 +20864,9 @@ var Reader = class {
20427
20864
  i++;
20428
20865
  while (/\s/.test(src.charAt(i))) i++;
20429
20866
  }
20430
- NUMBER_RE.lastIndex = i;
20431
- const match = NUMBER_RE.exec(src);
20867
+ const match = this.numberAt(i);
20432
20868
  if (match) {
20433
- this.i = NUMBER_RE.lastIndex;
20869
+ this.i = i + match[0].length;
20434
20870
  if (!match[1]) return { shape: { type: "number" } };
20435
20871
  if (sign === "+") return { throws: "Cannot convert a BigInt value to a number" };
20436
20872
  const digits = bigintValue(match[0].slice(0, -1));
@@ -20440,11 +20876,17 @@ var Reader = class {
20440
20876
  };
20441
20877
  }
20442
20878
  IDENT_RE.lastIndex = i;
20443
- if (IDENT_RE.exec(src)?.[0] === "Infinity") {
20879
+ const word = IDENT_RE.exec(src)?.[0];
20880
+ if (word === "Infinity" || word === "NaN") {
20444
20881
  this.i = IDENT_RE.lastIndex;
20445
20882
  return { shape: { type: "number" } };
20446
20883
  }
20447
20884
  }
20885
+ /** The numeric literal (a BigInt's `n` is `match[1]`) at `at`, if there is one. */
20886
+ numberAt(at) {
20887
+ NUMBER_RE.lastIndex = at;
20888
+ return NUMBER_RE.exec(this.src);
20889
+ }
20448
20890
  /** A keyword, a function, or a name (which is not static). */
20449
20891
  word() {
20450
20892
  const { src } = this;
@@ -20464,6 +20906,7 @@ var Reader = class {
20464
20906
  this.i = end;
20465
20907
  return { shape: { type: "null" } };
20466
20908
  case "NaN":
20909
+ case "Infinity":
20467
20910
  this.i = end;
20468
20911
  return { shape: { type: "number" } };
20469
20912
  case "undefined":
@@ -20604,14 +21047,22 @@ var Reader = class {
20604
21047
  const { src } = this;
20605
21048
  const c = src.charAt(this.i);
20606
21049
  if (c === "\"" || c === "'") return this.stringValue();
21050
+ if (/[\d.]/.test(c)) return this.numberKey();
20607
21051
  KEY_RE.lastIndex = this.i;
20608
21052
  const found = KEY_RE.exec(src)?.[0];
20609
21053
  if (found === void 0) return void 0;
20610
21054
  this.i = KEY_RE.lastIndex;
20611
- if (!/^\d/.test(found)) return found;
20612
- const digits = found.replace(/_/g, "");
21055
+ return found;
21056
+ }
21057
+ /** A number as a key: the whole literal, named as the runtime names it. */
21058
+ numberKey() {
21059
+ const match = this.numberAt(this.i);
21060
+ if (!match) return void 0;
21061
+ this.i += match[0].length;
21062
+ if (/[\w$]/.test(this.src.charAt(this.i))) return void 0;
21063
+ const digits = match[0].replace(/_/g, "");
20613
21064
  if (/^0\d/.test(digits)) return void 0;
20614
- if (digits.endsWith("n") && !/^0[xX]/.test(digits)) return bigintValue(digits.slice(0, -1));
21065
+ if (match[1]) return bigintValue(digits.slice(0, -1));
20615
21066
  const value = Number(digits);
20616
21067
  return Number.isNaN(value) ? void 0 : String(value);
20617
21068
  }
@@ -20654,6 +21105,14 @@ var Reader = class {
20654
21105
  this.space();
20655
21106
  return true;
20656
21107
  }
21108
+ if (c === "/") {
21109
+ this.regexes ??= regexLiterals(src, this.goal);
21110
+ const end = this.regexes.get(this.i);
21111
+ if (end !== void 0) {
21112
+ this.i = end;
21113
+ return true;
21114
+ }
21115
+ }
20657
21116
  if (c === "[" || c === "{" || c === "(") return this.skipBalanced();
20658
21117
  if (c === "]" || c === "}" || c === ")") return false;
20659
21118
  this.i++;
@@ -20908,6 +21367,7 @@ function checkReference(ref, declared) {
20908
21367
  const part = ref.path[i];
20909
21368
  if (current.type === "array") return null;
20910
21369
  if (current.type === "null") return null;
21370
+ if (current.type === "string" && isArrayIndex(part)) continue;
20911
21371
  const sample = PRIMITIVE_SAMPLES[current.type];
20912
21372
  if (sample && part in sample) {
20913
21373
  const memberType = typeof sample[part];
@@ -20937,10 +21397,28 @@ var BUILTIN_STORE_VAR_MACROS = [
20937
21397
  "textbox"
20938
21398
  ];
20939
21399
  var NO_STORE_VAR_MACROS = /* @__PURE__ */ new Set();
20940
- /** A reference written at `index` of `code`, with its dot path. */
20941
- function referenceAt(code, index, at) {
21400
+ /** A `.field` path written right after a reference, which may be empty. */
21401
+ var FIELD_PATH_RE = /(?:\.\w+)*/y;
21402
+ /**
21403
+ * The reference to variable `name`, which JavaScript reads at `[start, end)`
21404
+ * of `code` (the sigil and the name as written, which may be spelled with
21405
+ * escapes), with the dot path written after it.
21406
+ */
21407
+ function referenceAt(code, sigil, name, start, end, at) {
21408
+ FIELD_PATH_RE.lastIndex = end;
21409
+ const fields = FIELD_PATH_RE.exec(code)[0];
21410
+ return {
21411
+ sigil,
21412
+ name,
21413
+ path: fields ? fields.slice(1).split(".") : [],
21414
+ start: at(start),
21415
+ end: at(end + fields.length)
21416
+ };
21417
+ }
21418
+ /** A reference written at `index` of `term`, a `variable` parameter as written. */
21419
+ function termReferenceAt(term, index, at) {
20942
21420
  VAR_PATH_RE.lastIndex = index;
20943
- const match = VAR_PATH_RE.exec(code);
21421
+ const match = VAR_PATH_RE.exec(term);
20944
21422
  if (!match) return void 0;
20945
21423
  const [name, ...path] = match[2].split(".");
20946
21424
  return {
@@ -20985,46 +21463,51 @@ function scanCode(code, at, emit, goal = "expression") {
20985
21463
  }
20986
21464
  for (const ref of parsed.refs) {
20987
21465
  if (ref.sigil !== "$" && ref.sigil !== "%") continue;
20988
- const found = referenceAt(code, ref.start, at);
20989
- if (found) emit(found);
21466
+ emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
20990
21467
  }
20991
21468
  }
20992
21469
  /** `scanCode` for code acorn can't parse: lexed leniently. */
20993
21470
  function scanCodeLeniently(code, at, emit, goal) {
20994
21471
  lexJs(code, {
20995
- variable(sigil, _name, index) {
21472
+ variable(sigil, name, index, _nesting, end) {
20996
21473
  if (sigil !== "$" && sigil !== "%") return;
20997
- const found = referenceAt(code, index, at);
20998
- if (found) emit(found);
21474
+ emit(referenceAt(code, sigil, name, index, end, at));
20999
21475
  },
21000
21476
  literal() {}
21001
21477
  }, goal);
21002
21478
  }
21479
+ /** Report the references in the pieces of code and markup text of arguments. */
21480
+ function scanPieces(pieces, at, emit, options) {
21481
+ for (const piece of pieces) {
21482
+ const pieceAt = (i) => at(pieceOffset(piece, i));
21483
+ if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
21484
+ else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
21485
+ ...options,
21486
+ storeVarMacros: NO_STORE_VAR_MACROS
21487
+ });
21488
+ }
21489
+ }
21003
21490
  /**
21004
21491
  * Report the references in the arguments of a macro by what its parameters
21005
21492
  * say each holds (see ParameterDef.holds): code is scanned as code and
21006
21493
  * markup as markup, but literal text (a placeholder, a passage name) holds
21007
21494
  * none. A macro without declared parameters, or arguments that do not
21008
- * parse, are scanned as code.
21495
+ * parse, are scanned as code. The arguments of a widget that declares what
21496
+ * some parameters hold are also read by those (see widgetPieces).
21009
21497
  */
21010
- function scanArgs(token, params, at, emit, options) {
21498
+ function scanArgs(token, parametersOf, at, emit, options) {
21011
21499
  if (!token.rawArgs) return;
21500
+ const params = parametersOf(token.name);
21501
+ let byParameters = false;
21012
21502
  if (params) {
21013
21503
  if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
21014
21504
  const pieces = [...argPieces(token.rawArgs, token.argsStart, params, token.name, "")];
21015
- if (!pieces.some((piece) => piece.kind === "argument-error")) {
21016
- for (const piece of pieces) {
21017
- const pieceAt = (i) => at(pieceOffset(piece, i));
21018
- if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
21019
- else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
21020
- ...options,
21021
- storeVarMacros: NO_STORE_VAR_MACROS
21022
- });
21023
- }
21024
- return;
21025
- }
21505
+ byParameters = !pieces.some((piece) => piece.kind === "argument-error");
21506
+ if (byParameters) scanPieces(pieces, at, emit, options);
21026
21507
  }
21027
- scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
21508
+ if (!byParameters) scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
21509
+ const widget = parametersOf.widget?.(token.name);
21510
+ if (widget) scanPieces(widgetPieces(token.rawArgs, token.argsStart, widget, token.name, ""), at, emit, options);
21028
21511
  }
21029
21512
  /**
21030
21513
  * Report the variables the `variable` parameters of a macro name
@@ -21042,7 +21525,7 @@ function scanVariableParameters(token, params, at, emit) {
21042
21525
  for (const param of params) {
21043
21526
  const span = spans.get(param);
21044
21527
  if (param.type !== "variable" || !span) continue;
21045
- const ref = referenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
21528
+ const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
21046
21529
  if (ref) emit(ref);
21047
21530
  }
21048
21531
  }
@@ -21083,7 +21566,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
21083
21566
  else scanInterpolations(value, valueIn, emit, options);
21084
21567
  }
21085
21568
  else if (token.type === "macro" && !token.isClose) {
21086
- scanArgs(token, parametersOf(token.name), at, emit, options);
21569
+ scanArgs(token, parametersOf, at, emit, options);
21087
21570
  scanSelectors(content, token, at, emit, options);
21088
21571
  if (storeVarMacros.has(token.name.toLowerCase())) {
21089
21572
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
@@ -21126,7 +21609,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
21126
21609
  function collectVariableReferences(content, options) {
21127
21610
  const found = [];
21128
21611
  withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
21129
- return found;
21612
+ return found.sort((a, b) => a.start - b.start);
21130
21613
  }
21131
21614
  /**
21132
21615
  * The invalid variable references of the passages, against what is declared,
@@ -21334,15 +21817,114 @@ function resolveTransition(targetTags, nextTransition, storeDefault) {
21334
21817
  }
21335
21818
  //#endregion
21336
21819
  //#region src/components/macros/PassageDisplay.tsx
21820
+ /** Input types whose `value` is not what the user sees or edits. */
21821
+ var VALUELESS_INPUTS = /* @__PURE__ */ new Set([
21822
+ "checkbox",
21823
+ "radio",
21824
+ "file",
21825
+ "hidden",
21826
+ "button",
21827
+ "submit",
21828
+ "reset",
21829
+ "image"
21830
+ ]);
21831
+ /**
21832
+ * Copy the live state cloneNode drops from `source` into its clone: the
21833
+ * pixels of each canvas, the state of form controls (cloneNode keeps
21834
+ * attributes only, and a canvas's bitmap is not one), and the visible frame
21835
+ * and position of media. Source and clone have the same structure, so
21836
+ * elements pair up by position. Best effort: a canvas or video that can not
21837
+ * be drawn from stays as cloned.
21838
+ */
21839
+ function copyLiveState(source, clone) {
21840
+ const pairs = (selector, each) => {
21841
+ const from = source.querySelectorAll(selector);
21842
+ const to = clone.querySelectorAll(selector);
21843
+ from.forEach((el, i) => to[i] && each(el, to[i]));
21844
+ };
21845
+ pairs("canvas", (from, to) => {
21846
+ if (!from.width || !from.height) return;
21847
+ try {
21848
+ if (to.width !== from.width) to.width = from.width;
21849
+ if (to.height !== from.height) to.height = from.height;
21850
+ to.getContext("2d")?.drawImage(from, 0, 0);
21851
+ } catch {}
21852
+ });
21853
+ pairs("input, textarea, select", (from, to) => {
21854
+ if (from instanceof HTMLSelectElement) {
21855
+ const select = to;
21856
+ if (!from.multiple) select.selectedIndex = from.selectedIndex;
21857
+ else for (let i = 0; i < from.options.length; i++) {
21858
+ const option = select.options[i];
21859
+ if (option) option.selected = from.options[i].selected;
21860
+ }
21861
+ } else if (from instanceof HTMLInputElement) {
21862
+ const input = to;
21863
+ input.checked = from.checked;
21864
+ input.indeterminate = from.indeterminate;
21865
+ if (!VALUELESS_INPUTS.has(from.type)) input.value = from.value;
21866
+ } else to.value = from.value;
21867
+ });
21868
+ pairs("audio, video", (from, to) => {
21869
+ to.pause?.();
21870
+ to.muted = true;
21871
+ to.removeAttribute("autoplay");
21872
+ try {
21873
+ to.currentTime = from.currentTime;
21874
+ } catch {}
21875
+ if (!(from instanceof HTMLVideoElement && to instanceof HTMLVideoElement)) return;
21876
+ if (from.readyState < 2 || !from.videoWidth || !from.videoHeight) return;
21877
+ try {
21878
+ const frame = document.createElement("canvas");
21879
+ frame.width = from.videoWidth;
21880
+ frame.height = from.videoHeight;
21881
+ frame.getContext("2d")?.drawImage(from, 0, 0);
21882
+ to.setAttribute("poster", frame.toDataURL("image/jpeg", .92));
21883
+ } catch {}
21884
+ });
21885
+ }
21886
+ /**
21887
+ * Scroll offsets of the elements of `source` (itself included) that are
21888
+ * scrolled, keyed by the matching element of `clone`. Applied once the clone
21889
+ * is in the page: a detached element has nothing to scroll.
21890
+ */
21891
+ function scrollOffsets(source, clone) {
21892
+ const from = [source, ...source.querySelectorAll("*")];
21893
+ const to = [clone, ...clone.querySelectorAll("*")];
21894
+ const offsets = [];
21895
+ from.forEach((el, i) => {
21896
+ if (to[i] && (el.scrollTop || el.scrollLeft)) offsets.push([
21897
+ to[i],
21898
+ el.scrollTop,
21899
+ el.scrollLeft
21900
+ ]);
21901
+ });
21902
+ return offsets;
21903
+ }
21904
+ var pendingScrolls = /* @__PURE__ */ new WeakMap();
21905
+ /** Add `snapshot` to `container`, scrolled as what it shows was. */
21906
+ function appendSnapshot(container, snapshot) {
21907
+ container.appendChild(snapshot);
21908
+ for (const [el, top, left] of pendingScrolls.get(snapshot) ?? []) {
21909
+ el.scrollTop = top;
21910
+ el.scrollLeft = left;
21911
+ }
21912
+ pendingScrolls.delete(snapshot);
21913
+ }
21337
21914
  /**
21338
21915
  * Create a snapshot clone of a .passage element for outgoing transitions.
21339
21916
  * - Strips `id` attributes from the clone tree
21340
21917
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
21341
21918
  * - Pauses/mutes any <audio>/<video>
21919
+ * - Copies what cloneNode leaves behind: canvas pixels, the state of form
21920
+ * controls, the visible frame of videos (#512, #525, #536) and, through
21921
+ * `appendSnapshot`, scroll offsets
21342
21922
  * - Adds `.passage-snapshot` class and `data-transition` attribute
21343
21923
  */
21344
21924
  function createSnapshot(passageEl, transitionType) {
21345
21925
  const clone = passageEl.cloneNode(true);
21926
+ copyLiveState(passageEl, clone);
21927
+ pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
21346
21928
  clone.removeAttribute("id");
21347
21929
  const idEls = clone.querySelectorAll("[id]");
21348
21930
  for (let i = 0; i < idEls.length; i++) idEls[i].removeAttribute("id");
@@ -21350,12 +21932,6 @@ function createSnapshot(passageEl, transitionType) {
21350
21932
  clone.style.userSelect = "none";
21351
21933
  clone.setAttribute("inert", "");
21352
21934
  clone.setAttribute("aria-hidden", "true");
21353
- const mediaEls = clone.querySelectorAll("audio, video");
21354
- for (let i = 0; i < mediaEls.length; i++) {
21355
- const media = mediaEls[i];
21356
- media.pause?.();
21357
- media.muted = true;
21358
- }
21359
21935
  clone.classList.remove("passage");
21360
21936
  clone.classList.add("passage-snapshot");
21361
21937
  clone.setAttribute("data-transition", transitionType);
@@ -21504,7 +22080,7 @@ defineMacro({
21504
22080
  return;
21505
22081
  }
21506
22082
  if (config.type === "fade-through") {
21507
- containerEl.appendChild(snapshot);
22083
+ appendSnapshot(containerEl, snapshot);
21508
22084
  setDisplayedPassage("");
21509
22085
  const incomingDelay = config.duration + config.pause;
21510
22086
  const t1 = setTimeout(() => {
@@ -21520,7 +22096,7 @@ defineMacro({
21520
22096
  return;
21521
22097
  }
21522
22098
  containerEl.classList.add("passage-container--crossfading");
21523
- containerEl.appendChild(snapshot);
22099
+ appendSnapshot(containerEl, snapshot);
21524
22100
  setDisplayedPassage(currentPassage);
21525
22101
  const t1 = setTimeout(() => {
21526
22102
  cleanupSnapshots(containerEl);
@@ -21865,7 +22441,9 @@ defineMacro({
21865
22441
  * built-ins (see isAtomic) have their contents in the key: the bytes of a
21866
22442
  * buffer, the place of a view in its buffer, the text of a URL or
21867
22443
  * URLSearchParams, the class, message, cause and errors of an Error, the
21868
- * value of a boxed primitive (#418). A hole in an array reads as undefined.
22444
+ * value of a boxed primitive (#418). As for deepEqual and a save, -0 is not
22445
+ * 0 (#498) and a hole in an array is not an undefined element (#497), so
22446
+ * only the keys of -0 and of arrays with holes differ from JSON.stringify.
21869
22447
  *
21870
22448
  * An object met again, through a cycle or a second reference to it, is a
21871
22449
  * marker naming where it was first met rather than another copy of its
@@ -21879,6 +22457,8 @@ function stableKey(value) {
21879
22457
  return "<unkeyable>";
21880
22458
  }
21881
22459
  }
22460
+ /** The key of an array slot that holds no element. */
22461
+ var HOLE = "<hole>";
21882
22462
  /**
21883
22463
  * The key of `val`. `seen` numbers the objects keyed so far, in the order
21884
22464
  * they were first met.
@@ -21886,7 +22466,9 @@ function stableKey(value) {
21886
22466
  function keyOf(val, seen) {
21887
22467
  switch (typeof val) {
21888
22468
  case "string": return JSON.stringify(val);
21889
- case "number": return Number.isFinite(val) ? JSON.stringify(val) : String(val);
22469
+ case "number":
22470
+ if (Object.is(val, -0)) return "-0";
22471
+ return Number.isFinite(val) ? JSON.stringify(val) : String(val);
21890
22472
  case "boolean": return String(val);
21891
22473
  case "bigint": return `${val}n`;
21892
22474
  case "undefined": return "undefined";
@@ -21905,10 +22487,14 @@ function keyOf(val, seen) {
21905
22487
  };
21906
22488
  if (val instanceof Date || val instanceof RegExp) {
21907
22489
  if (className !== void 0 && extraKeys(obj).length) seen.set(obj, seen.size);
21908
- return withFields(val instanceof Date ? `Date(${Date.prototype.getTime.call(val)})` : `RegExp(${RegExp.prototype.toString.call(val)}@${val.lastIndex})`);
22490
+ return withFields(val instanceof Date ? `Date(${Date.prototype.getTime.call(val)})` : `RegExp(${regExpText(val)}@${val.lastIndex})`);
21909
22491
  }
21910
22492
  seen.set(obj, seen.size);
21911
- if (Array.isArray(val)) return withFields(`[${Array.from(val, (v) => keyOf(v, seen)).join(",")}]`);
22493
+ if (Array.isArray(val)) {
22494
+ const items = [];
22495
+ for (let i = 0; i < val.length; i++) items.push(i in val ? keyOf(val[i], seen) : HOLE);
22496
+ return withFields(`[${items.join(",")}]`);
22497
+ }
21912
22498
  const atomic = atomicKey(obj, seen);
21913
22499
  if (atomic !== void 0) return named(atomic);
21914
22500
  if (val instanceof Map) return withFields(`Map[${Array.from(mapEntries(val), ([k, v]) => `[${keyOf(k, seen)},${keyOf(v, seen)}]`).join(",")}]`);
@@ -21962,7 +22548,7 @@ function loopArgs(rawArgs, args) {
21962
22548
  listExpr
21963
22549
  };
21964
22550
  }
21965
- function ForIteration({ parentValues, itemVar, itemValue, indexVar, indexValue, children }) {
22551
+ function ForIteration({ itemVar, itemValue, indexVar, indexValue, children }) {
21966
22552
  const ownKeys = useMemo(() => ({
21967
22553
  [itemVar]: itemValue,
21968
22554
  ...indexVar ? { [indexVar]: indexValue } : void 0
@@ -21974,7 +22560,6 @@ function ForIteration({ parentValues, itemVar, itemValue, indexVar, indexValue,
21974
22560
  ]);
21975
22561
  return /* @__PURE__ */ jsx(LocalsScope, {
21976
22562
  body: children,
21977
- parentValues,
21978
22563
  ownKeys
21979
22564
  });
21980
22565
  }
@@ -22000,7 +22585,6 @@ defineMacro({
22000
22585
  }
22001
22586
  ],
22002
22587
  render({ rawArgs, children = [] }, ctx) {
22003
- const parentValues = useContext(LocalsValuesContext);
22004
22588
  const keys = ctx.hooks.useRef({
22005
22589
  contents: [],
22006
22590
  generations: [],
@@ -22034,7 +22618,6 @@ defineMacro({
22034
22618
  });
22035
22619
  keys.contents.length = keys.generations.length = list.length;
22036
22620
  const content = list.map((item, i) => /* @__PURE__ */ jsx(ForIteration, {
22037
- parentValues,
22038
22621
  itemVar,
22039
22622
  itemValue: item,
22040
22623
  indexVar,
@@ -22067,30 +22650,6 @@ defineMacro({
22067
22650
  }
22068
22651
  });
22069
22652
  //#endregion
22070
- //#region src/utils/live-locals.ts
22071
- /**
22072
- * Read-only view of a locals scope that always reflects its current values.
22073
- *
22074
- * Used as the LocalsValuesContext value for one-shot detached renders
22075
- * ({button}/{link} bodies). Those trees are unmounted right after rendering,
22076
- * so the owning scope's re-render never reaches them; reading through
22077
- * getValues() lets a macro see a local assigned earlier in the same body.
22078
- */
22079
- function liveLocalsView(getValues) {
22080
- return new Proxy(createNamespace(), {
22081
- get: (_, key) => typeof key === "string" ? ownValue(getValues(), key) : void 0,
22082
- has: (_, key) => typeof key === "string" && hasOwn(getValues(), key),
22083
- ownKeys: () => Reflect.ownKeys(getValues()),
22084
- getOwnPropertyDescriptor: (_, key) => {
22085
- const desc = Object.getOwnPropertyDescriptor(getValues(), key);
22086
- return desc ? {
22087
- ...desc,
22088
- configurable: true
22089
- } : void 0;
22090
- }
22091
- });
22092
- }
22093
- //#endregion
22094
22653
  //#region src/components/macros/Repeat.tsx
22095
22654
  var RepeatContext = createContext({ stop: () => {} });
22096
22655
  defineMacro({
@@ -22116,7 +22675,7 @@ defineMacro({
22116
22675
  if (count === 0 && !stopped) return null;
22117
22676
  const content = /* @__PURE__ */ jsx(RepeatContext.Provider, {
22118
22677
  value: { stop },
22119
- children: /* @__PURE__ */ jsx("span", { children: ctx.renderNodes(children) }, count)
22678
+ children: /* @__PURE__ */ jsx(Fragment, { children: ctx.renderNodes(children) }, count)
22120
22679
  });
22121
22680
  if (ctx.className || ctx.id) return /* @__PURE__ */ jsx("span", {
22122
22681
  id: ctx.id,
@@ -22600,6 +23159,7 @@ defineMacro({
22600
23159
  //#region src/components/macros/StoryTitle.tsx
22601
23160
  defineMacro({
22602
23161
  name: "story-title",
23162
+ interpolate: true,
22603
23163
  render(_, ctx) {
22604
23164
  const name = useStoryStore((s) => s.storyData?.name || "");
22605
23165
  const cls = ctx.className ? `story-title ${ctx.className}` : "story-title";
@@ -22619,6 +23179,7 @@ function hotkeyTitle(label, key) {
22619
23179
  function defineMenubarAction(config) {
22620
23180
  defineMacro({
22621
23181
  name: config.name,
23182
+ interpolate: true,
22622
23183
  render(_, ctx) {
22623
23184
  if (config.hidden?.()) return null;
22624
23185
  const [dialogOpen, setDialogOpen] = useState(false);
@@ -22781,7 +23342,7 @@ function formatDate(iso) {
22781
23342
  year: "numeric"
22782
23343
  });
22783
23344
  }
22784
- function SaveManagerContent() {
23345
+ function SaveManagerContent({ className, id }) {
22785
23346
  const [mode, setMode] = useState("load");
22786
23347
  const [groups, setGroups] = useState([]);
22787
23348
  const [loading, setLoading] = useState(true);
@@ -22846,7 +23407,8 @@ function SaveManagerContent() {
22846
23407
  const playthrough = resolvePlaythroughId();
22847
23408
  try {
22848
23409
  await saveWithHooks(void 0, void 0, beginSave, async (payload) => {
22849
- return createSave(ifid, playthrough, payload);
23410
+ const saved = await createSave(ifid, playthrough, payload);
23411
+ await followSavedPlaythrough(playthrough, saved);
22850
23412
  });
22851
23413
  showStatus(temporary ? "Save created (temporary)" : "Save created");
22852
23414
  await refresh();
@@ -22858,7 +23420,9 @@ function SaveManagerContent() {
22858
23420
  const playthrough = resolvePlaythroughId();
22859
23421
  try {
22860
23422
  await saveWithHooks(void 0, void 0, beginSave, async (payload) => {
22861
- if (!await overwriteSave(saveId, payload, void 0, playthrough)) throw new Error("Save not found");
23423
+ const saved = await overwriteSave(saveId, payload, void 0, playthrough);
23424
+ if (!saved) throw new Error("Save not found");
23425
+ await followSavedPlaythrough(playthrough, saved);
22862
23426
  });
22863
23427
  showStatus("Save overwritten");
22864
23428
  await refresh();
@@ -22961,7 +23525,8 @@ function SaveManagerContent() {
22961
23525
  };
22962
23526
  const totalSaves = groups.reduce((n, g) => n + g.saves.length, 0);
22963
23527
  return /* @__PURE__ */ jsxs("div", {
22964
- class: "save-manager",
23528
+ id,
23529
+ class: className ? `save-manager ${className}` : "save-manager",
22965
23530
  children: [
22966
23531
  /* @__PURE__ */ jsx("div", {
22967
23532
  class: "saves-header",
@@ -23122,8 +23687,12 @@ function SaveManagerContent() {
23122
23687
  }
23123
23688
  defineMacro({
23124
23689
  name: "save-manager",
23125
- render() {
23126
- return /* @__PURE__ */ jsx(SaveManagerContent, {});
23690
+ interpolate: true,
23691
+ render(_props, ctx) {
23692
+ return /* @__PURE__ */ jsx(SaveManagerContent, {
23693
+ className: ctx.className,
23694
+ id: ctx.id
23695
+ });
23127
23696
  }
23128
23697
  });
23129
23698
  //#endregion
@@ -23173,10 +23742,11 @@ function SettingControl({ name, def }) {
23173
23742
  });
23174
23743
  }
23175
23744
  }
23176
- function SettingsControlsContent() {
23745
+ function SettingsControlsContent({ className, id }) {
23177
23746
  const defs = settings.getDefinitions();
23178
23747
  return /* @__PURE__ */ jsx("div", {
23179
- class: "settings-controls",
23748
+ id,
23749
+ class: className ? `settings-controls ${className}` : "settings-controls",
23180
23750
  children: Array.from(defs.entries()).map(([name, def]) => /* @__PURE__ */ jsx(SettingControl, {
23181
23751
  name,
23182
23752
  def
@@ -23185,8 +23755,12 @@ function SettingsControlsContent() {
23185
23755
  }
23186
23756
  defineMacro({
23187
23757
  name: "settings-controls",
23188
- render() {
23189
- return /* @__PURE__ */ jsx(SettingsControlsContent, {});
23758
+ interpolate: true,
23759
+ render(_props, ctx) {
23760
+ return /* @__PURE__ */ jsx(SettingsControlsContent, {
23761
+ className: ctx.className,
23762
+ id: ctx.id
23763
+ });
23190
23764
  }
23191
23765
  });
23192
23766
  //#endregion
@@ -23236,6 +23810,7 @@ defineMacro({
23236
23810
  defineMacro({
23237
23811
  name: "nobr",
23238
23812
  block: true,
23813
+ interpolate: true,
23239
23814
  render({ children = [] }, ctx) {
23240
23815
  return ctx.wrap(ctx.h(NobrContext.Provider, { value: true }, ctx.renderNodes(children, { nobr: true })));
23241
23816
  },
@@ -23271,6 +23846,15 @@ defineMacro({
23271
23846
  });
23272
23847
  //#endregion
23273
23848
  //#region src/components/macros/Unset.tsx
23849
+ /** What `name` is as a variable reference, or null if it is no reference. */
23850
+ function referencePath(name) {
23851
+ try {
23852
+ return parseReferencePath(name);
23853
+ } catch (error) {
23854
+ if (error instanceof CodeSyntaxError) return null;
23855
+ throw error;
23856
+ }
23857
+ }
23274
23858
  defineMacro({
23275
23859
  name: "unset",
23276
23860
  parameters: [{
@@ -23282,12 +23866,13 @@ defineMacro({
23282
23866
  return useRunOnce("unset", rawArgs, () => {
23283
23867
  const state = useStoryStore.getState();
23284
23868
  const name = ctx.args.variable ?? "";
23285
- if (/^[$_%@][^.]*\./.test(name)) ctx.mutate(`delete ${name}`);
23286
- else if (name.startsWith("$")) state.deleteVariable(name.slice(1));
23287
- else if (name.startsWith("_")) state.deleteTemporary(name.slice(1));
23288
- else if (name.startsWith("%")) state.deleteTransient(name.slice(1));
23289
- else if (name.startsWith("@")) ctx.update(name.slice(1), void 0);
23290
- else throw new Error(`{unset} expects a variable ($name, _name, %name, or @name), got "${name}"`);
23869
+ const path = referencePath(name);
23870
+ if (!path) throw new Error(`{unset} expects a variable ($name, _name, %name, or @name, or a field of one such as $name.field or $name["field"]), got "${name}"`);
23871
+ else if (path.nested) ctx.mutate(`delete ${name}`);
23872
+ else if (path.sigil === "$") state.deleteVariable(path.name);
23873
+ else if (path.sigil === "_") state.deleteTemporary(path.name);
23874
+ else if (path.sigil === "%") state.deleteTransient(path.name);
23875
+ else ctx.update(path.name, void 0);
23291
23876
  });
23292
23877
  }
23293
23878
  });
@@ -23323,6 +23908,7 @@ function useVariableAction(ctx, action) {
23323
23908
  function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? String(input) : "") {
23324
23909
  defineMacro({
23325
23910
  name,
23911
+ interpolate: true,
23326
23912
  storeVar: true,
23327
23913
  parameters: [VARIABLE_PARAMETER, {
23328
23914
  name: "placeholder",
@@ -23366,6 +23952,7 @@ defineInputMacro("textarea");
23366
23952
  //#region src/components/macros/Checkbox.tsx
23367
23953
  defineMacro({
23368
23954
  name: "checkbox",
23955
+ interpolate: true,
23369
23956
  storeVar: true,
23370
23957
  parameters: [VARIABLE_PARAMETER, {
23371
23958
  name: "label",
@@ -23378,7 +23965,7 @@ defineMacro({
23378
23965
  type: "checkbox",
23379
23966
  label: label || ctx.varName || "",
23380
23967
  value: !!ctx.value,
23381
- perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.value)
23968
+ perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.getValue())
23382
23969
  });
23383
23970
  return /* @__PURE__ */ jsxs("label", {
23384
23971
  id: ctx.id,
@@ -23386,7 +23973,7 @@ defineMacro({
23386
23973
  children: [/* @__PURE__ */ jsx("input", {
23387
23974
  type: "checkbox",
23388
23975
  checked: !!ctx.value,
23389
- onChange: () => ctx.setValue(!ctx.value)
23976
+ onChange: (e) => ctx.setValue(e.target.checked)
23390
23977
  }), label ? ` ${label}` : null]
23391
23978
  });
23392
23979
  }
@@ -23395,6 +23982,7 @@ defineMacro({
23395
23982
  //#region src/components/macros/Radiobutton.tsx
23396
23983
  defineMacro({
23397
23984
  name: "radiobutton",
23985
+ interpolate: true,
23398
23986
  storeVar: true,
23399
23987
  parameters: [
23400
23988
  VARIABLE_PARAMETER,
@@ -23436,6 +24024,7 @@ defineMacro({
23436
24024
  //#region src/components/macros/Listbox.tsx
23437
24025
  defineMacro({
23438
24026
  name: "listbox",
24027
+ interpolate: true,
23439
24028
  subMacros: ["option"],
23440
24029
  storeVar: true,
23441
24030
  parameters: [VARIABLE_PARAMETER],
@@ -23466,6 +24055,7 @@ defineMacro({
23466
24055
  defineMacro({
23467
24056
  name: "cycle",
23468
24057
  block: true,
24058
+ interpolate: true,
23469
24059
  storeVar: true,
23470
24060
  parameters: [VARIABLE_PARAMETER],
23471
24061
  render({ children = [] }, ctx) {
@@ -23499,6 +24089,7 @@ defineMacro({
23499
24089
  defineMacro({
23500
24090
  name: "span",
23501
24091
  block: true,
24092
+ interpolate: true,
23502
24093
  render({ children = [] }, ctx) {
23503
24094
  return ctx.wrap(ctx.renderNodes(children));
23504
24095
  },
@@ -23625,13 +24216,21 @@ function orStop(parse, where = "") {
23625
24216
  }
23626
24217
  }
23627
24218
  /**
24219
+ * What reading arguments depends on, with the macros and widgets known now:
24220
+ * the declared parameters of macros and what the parameters of widgets hold.
24221
+ * (The markup and the variable references are read by the same.)
24222
+ */
24223
+ function knownParameters() {
24224
+ return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
24225
+ }
24226
+ /**
23628
24227
  * The undeclared variables the passages refer to, with the macros known now:
23629
24228
  * the input macros that bind a variable (registered by author JS or
23630
24229
  * StoryInit) and the roles of their parameters decide what is a reference.
23631
24230
  */
23632
24231
  function variableErrors(storyData, schema) {
23633
24232
  const storeVarMacros = getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
23634
- return validatePassages(storyData.passages, schema, storeVarMacros);
24233
+ return validatePassages(storyData.passages, schema, storeVarMacros, knownParameters());
23635
24234
  }
23636
24235
  /**
23637
24236
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -23639,11 +24238,10 @@ function variableErrors(storyData, schema) {
23639
24238
  * known now.
23640
24239
  */
23641
24240
  function markupErrors(storyData, only) {
23642
- const macros = getMacroRegistry();
23643
24241
  return validateMarkup(storyData.passages.values(), {
23644
24242
  isKnownMacro: (name) => !!getMacro(name) || isSubMacro(name) || !!getWidget(name),
23645
- macroNames: macros.map((m) => m.name),
23646
- parametersOf: parameterLookup([...macros, ...widgetMacros()]),
24243
+ macroNames: getMacroRegistry().map((m) => m.name),
24244
+ parametersOf: knownParameters(),
23647
24245
  only
23648
24246
  }).map(formatDiagnostic);
23649
24247
  }
@@ -23682,7 +24280,7 @@ function boot() {
23682
24280
  throw new Error(`spindle: ${msg}`);
23683
24281
  }
23684
24282
  const schema = orStop(() => parseStoryVariables(storyVarsPassage.content));
23685
- for (const name of orStop(() => blockWidgetNames(storyData.passages.values()))) registerBlockMacro(name);
24283
+ for (const { name, block } of orStop(() => effectiveWidgets(storyData.passages.values()))) setBlockWidget(name, block);
23686
24284
  const errors = variableErrors(storyData, schema);
23687
24285
  errors.push(...markupErrors(storyData, (p) => p.name === "StoryInit"));
23688
24286
  let transientDefaults = {};
@@ -23714,11 +24312,9 @@ function boot() {
23714
24312
  const root = document.getElementById("root");
23715
24313
  if (!root) throw new Error("spindle: No <div id=\"root\"> element found.");
23716
24314
  render(/* @__PURE__ */ jsx(App, {}), root);
23717
- const pending = getReadyPromise();
23718
- if (pending) pending.then(passageShown).then(() => {
24315
+ (getReadyPromise() ?? Promise.resolve()).then(passageShown).then(() => {
23719
24316
  document.dispatchEvent(new CustomEvent(":storyready"));
23720
24317
  });
23721
- else document.dispatchEvent(new CustomEvent(":storyready"));
23722
24318
  }
23723
24319
  //#endregion
23724
24320
  //#region src/headless.ts