@rohal12/spindle 0.59.29 → 0.59.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -0
  2. package/dist/pkg/format.js +1 -1
  3. package/dist/pkg/headless.js +560 -272
  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 +494 -90
  7. package/package.json +1 -1
  8. package/src/action-registry.ts +59 -5
  9. package/src/automation/load-yaml.ts +111 -20
  10. package/src/automation/runner.ts +15 -13
  11. package/src/automation/types.ts +7 -5
  12. package/src/class-registry.ts +8 -5
  13. package/src/code-check.ts +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 +42 -0
  21. package/src/components/macros/Radiobutton.tsx +1 -0
  22. package/src/components/macros/SaveManager.tsx +19 -4
  23. package/src/components/macros/SettingsControls.tsx +19 -4
  24. package/src/components/macros/Span.tsx +1 -0
  25. package/src/components/macros/StoryTitle.tsx +1 -0
  26. package/src/components/macros/VarDisplay.tsx +2 -3
  27. package/src/components/macros/WidgetInvocation.tsx +5 -6
  28. package/src/components/macros/input-macro.ts +1 -0
  29. package/src/components/macros/locals-scope.tsx +19 -8
  30. package/src/components/macros/macro-args.ts +11 -3
  31. package/src/expression.ts +34 -18
  32. package/src/hooks/use-merged-locals.ts +17 -2
  33. package/src/hooks/use-modal-focus.ts +190 -129
  34. package/src/index.tsx +22 -12
  35. package/src/js-bindings.ts +332 -0
  36. package/src/js-lexer.ts +12 -3
  37. package/src/macro-discovery.ts +25 -22
  38. package/src/static-literal.ts +87 -16
  39. package/src/store.ts +4 -1
  40. package/src/story-api.ts +13 -4
  41. package/src/story-variables.ts +91 -28
  42. package/src/structural.ts +19 -15
  43. package/src/tooling.ts +21 -8
  44. package/src/transform.ts +22 -7
  45. package/src/utils/namespace.ts +4 -0
  46. package/src/utils/object-path.ts +2 -2
  47. package/src/utils/stable-key.ts +17 -6
  48. package/src/utils/value-kinds.ts +38 -1
  49. package/types/index.d.ts +12 -5
  50. package/types/tooling.d.ts +12 -2
@@ -9601,7 +9601,7 @@ function walkTokens(src, from, handlers, nesting, goal, oneTemplate) {
9601
9601
  if (t === types$1.name) {
9602
9602
  const sigil = sigilAt(src, tok.start, tok.value);
9603
9603
  const property = prev === types$1.dot || prev === types$1.questionDot || (sigil === "$" || sigil === "_") && keyPosition(src, tok.end, prev);
9604
- if (sigil && !property) handlers.variable?.(sigil, src.slice(tok.start + 1, tok.end), tok.start, nesting);
9604
+ if (sigil && !property) handlers.variable?.(sigil, tok.value.slice(1), tok.start, nesting, tok.end);
9605
9605
  else code(tok.start, tok.end);
9606
9606
  } else if (t === types$1.string || t === types$1.regexp || t === types$1.template || t === types$1.invalidTemplate) literal(tok.start, tok.end);
9607
9607
  else if (t === types$1.backQuote) {
@@ -10053,6 +10053,8 @@ function checkVariableName(name, label = name) {
10053
10053
  const error = variableNameError(name, label);
10054
10054
  if (error) throw new TypeError(`spindle: ${error}`);
10055
10055
  }
10056
+ /** Whether a property key is an array index (`"0"`, `"12"`; not `"01"`). */
10057
+ var isArrayIndex = (key) => /^(?:0|[1-9]\d*)$/.test(key);
10056
10058
  /** Whether `obj` holds `key` as an own property. */
10057
10059
  var hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
10058
10060
  /** `ns[key]` if `ns` holds it as an own property, else undefined. */
@@ -10542,10 +10544,12 @@ var LEADING_OPERATOR_RE = /^(?:[-+*/&|^=<>?:,.]|%(?![A-Za-z_]))/;
10542
10544
  * Where the rest of `src` is without the flag `word` as its last or first
10543
10545
  * term, or `null` if it has no such flag. Next to a binary operator the
10544
10546
  * word is an operand (`"a" + inline`), not a flag; the closing `/` of a
10545
- * regex literal is not one.
10547
+ * regex literal is not one. A word with nothing else beside it is the flag
10548
+ * only when `alone` says no argument is waiting for it (#499).
10546
10549
  */
10547
- function takeFlag(src, word) {
10550
+ function takeFlag(src, word, alone) {
10548
10551
  const spans = terms(src);
10552
+ if (spans.length === 1) return alone && slice(src, spans[0]) === word ? [src.length, src.length] : null;
10549
10553
  if (spans.length < 2) return null;
10550
10554
  if (slice(src, spans[spans.length - 1]) === word) {
10551
10555
  const rest = [0, spans[spans.length - 2][1]];
@@ -10592,8 +10596,9 @@ function trimmed(src, at) {
10592
10596
  */
10593
10597
  function readGroup(params, src, args, { at: srcAt, spans }) {
10594
10598
  let [text, at] = trimmed(src ?? "", srcAt);
10599
+ const alone = !params.some((p) => p.type !== "flag" && p.required);
10595
10600
  for (const flag of params.filter((p) => p.type === "flag")) {
10596
- const rest = src === null ? null : takeFlag(text, flag.name);
10601
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
10597
10602
  args[flag.name] = rest !== null;
10598
10603
  if (rest) [text, at] = trimmed(slice(text, rest), at + rest[0]);
10599
10604
  }
@@ -11014,24 +11019,50 @@ function nestedPiece(piece, toRoot, where) {
11014
11019
  ...nested
11015
11020
  };
11016
11021
  }
11022
+ /** An escape sequence of a JavaScript string literal (with its backslash). */
11023
+ var JS_ESCAPE_RE = /\\(?:u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|[0-3][0-7]{0,2}|[4-7][0-7]?|\r\n|[^])/y;
11024
+ /**
11025
+ * The escape written at `raw[i]` (a backslash): how long it is as written and
11026
+ * what it stands for, or none when it is not one under these `escapes`.
11027
+ */
11028
+ function escapeAt(raw, i, escapes) {
11029
+ if (escapes === "quotes") {
11030
+ const next = raw.charAt(i + 1);
11031
+ return /["'\\]/.test(next) ? {
11032
+ length: 2,
11033
+ text: next
11034
+ } : void 0;
11035
+ }
11036
+ JS_ESCAPE_RE.lastIndex = i;
11037
+ const written = JS_ESCAPE_RE.exec(raw)?.[0];
11038
+ const text = written && stringLiteralValue(`"${written}"`);
11039
+ return typeof text === "string" ? {
11040
+ length: written.length,
11041
+ text
11042
+ } : void 0;
11043
+ }
11017
11044
  /**
11018
11045
  * 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.
11046
+ * written as `raw` from `at` on (its escapes are those of `escapes`), is in
11047
+ * the source, and where the text ends. A character that an escape stands for
11048
+ * is where the escape begins. None when the text is where its length says, or
11049
+ * is not that string.
11023
11050
  */
11024
- function escapeOffsets(raw, at, value) {
11051
+ function escapeOffsets(raw, at, value, escapes) {
11025
11052
  const offsets = [];
11026
11053
  let escaped = false;
11027
11054
  let i = 0;
11028
11055
  while (offsets.length < value.length) {
11029
11056
  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++;
11057
+ const escape = raw[i] === "\\" ? escapeAt(raw, i, escapes) : void 0;
11058
+ if (!escape) {
11059
+ offsets.push(at + i++);
11060
+ continue;
11061
+ }
11062
+ if (!value.startsWith(escape.text, offsets.length)) return void 0;
11063
+ for (let k = 0; k < escape.text.length; k++) offsets.push(at + i);
11064
+ escaped = true;
11065
+ i += escape.length;
11035
11066
  }
11036
11067
  offsets.push(at + i);
11037
11068
  return escaped ? offsets : void 0;
@@ -11054,7 +11085,7 @@ function* argPieces(args, offset, params, macro, label) {
11054
11085
  };
11055
11086
  return;
11056
11087
  }
11057
- yield* valuePieces(args, offset, params, values, spans, macro, label);
11088
+ yield* valuePieces(args, offset, params, values, spans, macro, label, "quotes");
11058
11089
  }
11059
11090
  /**
11060
11091
  * The code and text in the arguments `args` (at `offset`) of the widget
@@ -11080,13 +11111,14 @@ function* widgetPieces(args, offset, params, macro, label) {
11080
11111
  values[name] = value;
11081
11112
  spans.set(param, span);
11082
11113
  });
11083
- yield* valuePieces(args, offset, declared, values, spans, macro, label);
11114
+ yield* valuePieces(args, offset, declared, values, spans, macro, label, "javascript");
11084
11115
  }
11085
11116
  /**
11086
11117
  * The pieces of the `params` of `macro` with the `values` read from `args`
11087
- * (at `offset`), whose `spans` tell where each was written.
11118
+ * (at `offset`), whose `spans` tell where each was written and whose strings
11119
+ * are unescaped as `escapes` says.
11088
11120
  */
11089
- function* valuePieces(args, offset, params, values, spans, macro, label) {
11121
+ function* valuePieces(args, offset, params, values, spans, macro, label, escapes) {
11090
11122
  const name = macro.toLowerCase();
11091
11123
  /** The pieces of the parameters `list`, with their values in `from`. */
11092
11124
  function* visit(list, from) {
@@ -11134,7 +11166,7 @@ function* valuePieces(args, offset, params, values, spans, macro, label) {
11134
11166
  }
11135
11167
  const at = offset + start + (value !== written && /^["']/.test(written) ? 1 : 0);
11136
11168
  const holds = stringHolds(param);
11137
- const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value);
11169
+ const sourceOffsets = escapeOffsets(args.slice(at - offset), at, value, escapes);
11138
11170
  if (holds === "expression" || holds === "statements") {
11139
11171
  const piece = {
11140
11172
  kind: "code",
@@ -11200,20 +11232,21 @@ function attributeValues(src, token) {
11200
11232
  }
11201
11233
  /**
11202
11234
  * The `{$…}` expressions in the value of a code attribute (`onclick`, see
11203
- * isCodeAttribute), with where each is in the value.
11235
+ * isCodeAttribute), with where each is in the value. The parts of the value
11236
+ * are written out as they are (splitSigilTemplate decodes nothing), so each
11237
+ * starts where the one before it ends: an expression is not found by its
11238
+ * text, which a string of the code may repeat.
11204
11239
  */
11205
11240
  function sigilExpressions(value) {
11206
11241
  const found = [];
11207
11242
  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;
11243
+ for (const part of splitSigilTemplate(value)) if ("expr" in part) {
11212
11244
  found.push({
11213
11245
  expr: part.expr,
11214
- at
11246
+ at: from + 1
11215
11247
  });
11216
- }
11248
+ from += part.expr.length + 2;
11249
+ } else from += ("text" in part ? part.text : part.verbatim).length;
11217
11250
  return found;
11218
11251
  }
11219
11252
  /**
@@ -11590,14 +11623,50 @@ function useStoryFields(...keys) {
11590
11623
  });
11591
11624
  }
11592
11625
  //#endregion
11626
+ //#region src/utils/live-locals.ts
11627
+ /**
11628
+ * Read-only view of a locals scope that always reflects its current values.
11629
+ *
11630
+ * Used as the LocalsValuesContext value for one-shot detached renders
11631
+ * ({button}/{link} bodies). Those trees are unmounted right after rendering,
11632
+ * so the owning scope's re-render never reaches them; reading through
11633
+ * getValues() lets a macro see a local assigned earlier in the same body.
11634
+ */
11635
+ function liveLocalsView(getValues) {
11636
+ return new Proxy(createNamespace(), {
11637
+ get: (_, key) => typeof key === "string" ? ownValue(getValues(), key) : void 0,
11638
+ has: (_, key) => typeof key === "string" && hasOwn(getValues(), key),
11639
+ ownKeys: () => Reflect.ownKeys(getValues()),
11640
+ getOwnPropertyDescriptor: (_, key) => {
11641
+ const desc = Object.getOwnPropertyDescriptor(getValues(), key);
11642
+ return desc ? {
11643
+ ...desc,
11644
+ configurable: true
11645
+ } : void 0;
11646
+ }
11647
+ });
11648
+ }
11649
+ //#endregion
11593
11650
  //#region src/hooks/use-merged-locals.ts
11594
11651
  /**
11652
+ * The locals in scope, read as they are when code looks (a local the
11653
+ * preceding {set} assigned in this pass included, which the context value
11654
+ * only gains in the re-render that follows). The returned view is renewed
11655
+ * whenever the context value changes, so what depends on it re-renders and
11656
+ * recomputes as before.
11657
+ */
11658
+ function useLiveLocals() {
11659
+ const values = useContext(LocalsValuesContext);
11660
+ const { getValues } = useContext(LocalsUpdateContext);
11661
+ return useMemo(() => liveLocalsView(getValues), [getValues, values]);
11662
+ }
11663
+ /**
11595
11664
  * Return store variables, temporary, locals from context, and transient.
11596
11665
  * All four dicts use unprefixed keys suitable for evaluate/execute.
11597
11666
  */
11598
11667
  function useMergedLocals() {
11599
11668
  const { variables, temporary, transient, renderCounts } = useStoryFields("variables", "temporary", "transient", "renderCounts");
11600
- const localsValues = useContext(LocalsValuesContext);
11669
+ const localsValues = useLiveLocals();
11601
11670
  return useMemo(() => {
11602
11671
  return [
11603
11672
  variables,
@@ -11746,17 +11815,31 @@ function getPRNGPull() {
11746
11815
  * (see src/tooling.ts).
11747
11816
  */
11748
11817
  var TRANSFORM_CACHE_MAX = 500;
11749
- var NAMESPACES$2 = {
11750
- $: "variables",
11751
- _: "temporary",
11752
- "@": "locals",
11753
- "%": "transient"
11754
- };
11818
+ /**
11819
+ * The identifiers generated code reads the namespaces through, and the
11820
+ * compiled function takes them under (see src/expression.ts). Authored
11821
+ * JavaScript may declare identifiers of its own (`const variables = {}` in
11822
+ * a helper), so these are ones it cannot: an identifier that starts with
11823
+ * `_` or `$` and has more word characters after it is a sigil reference,
11824
+ * and the lexer refuses to declare one (`__variables` is the temporary
11825
+ * variable `_variables`, rewritten like any other). No declaration or
11826
+ * parameter of the author's can then capture a reference or clash with the
11827
+ * generated bindings.
11828
+ */
11829
+ var BINDINGS = {
11830
+ $: "__variables",
11831
+ _: "__temporary",
11832
+ "@": "__locals",
11833
+ "%": "__transient"
11834
+ };
11835
+ /** The identifier the functions that compiled code may call come under. */
11836
+ var FNS_BINDING = "__fns";
11755
11837
  /** Ends with an identifier character. */
11756
11838
  var IDENT_END_RE = /[\p{ID_Continue}$\u200c\u200d]$/u;
11757
11839
  /**
11758
11840
  * Transform expression: $var → variables["var"], _var → temporary["var"],
11759
- * @var → locals["var"], %var → transient["var"].
11841
+ * @var → locals["var"], %var → transient["var"], where `variables` and the
11842
+ * others stand for the generated names in BINDINGS.
11760
11843
  * The lexer (`lexJs`) finds the references: only in code (string, template
11761
11844
  * and regex literal text and comments are left untouched), only where an
11762
11845
  * identifier starts (not in `a$b`, nor as the property name in `obj._x`),
@@ -11779,7 +11862,7 @@ function transform(expr, goal = "expression") {
11779
11862
  result += expr.slice(at, ref.start);
11780
11863
  if (ref.shorthand) result += `${ref.name}: `;
11781
11864
  else if (IDENT_END_RE.test(result.slice(-2))) result += " ";
11782
- result += `${NAMESPACES$2[ref.sigil]}["${ref.name}"]`;
11865
+ result += `${BINDINGS[ref.sigil]}["${ref.name}"]`;
11783
11866
  at = ref.end;
11784
11867
  }
11785
11868
  result += expr.slice(at);
@@ -11793,15 +11876,28 @@ var transformCache = /* @__PURE__ */ new Map();
11793
11876
  //#region src/expression.ts
11794
11877
  var FN_CACHE_MAX = 500;
11795
11878
  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) {
11879
+ var preamble = `const {currentPassage,previousPassage,visited,hasVisited,hasVisitedAny,hasVisitedAll,rendered,hasRendered,hasRenderedAny,hasRenderedAll,random,randomInt}=${FNS_BINDING};`;
11880
+ /**
11881
+ * Compile `source`: the function takes the namespaces and the function
11882
+ * table under the names the transform uses for the references (see
11883
+ * BINDINGS). The statements are a block of their own, so that they may
11884
+ * declare any name, those of the history functions the preamble declares
11885
+ * included.
11886
+ */
11887
+ function compile(source, goal) {
11888
+ const code = transform(source, goal);
11889
+ const body = goal === "statements" ? `{${code}\n}` : `return (${code}\n);`;
11890
+ return new Function(BINDINGS.$, BINDINGS._, BINDINGS["@"], FNS_BINDING, BINDINGS["%"], preamble + body);
11891
+ }
11892
+ function getOrCompile(source, goal) {
11893
+ const key = (goal === "statements" ? "s" : "e") + source;
11798
11894
  const cached = fnCache.get(key);
11799
11895
  if (cached) {
11800
11896
  fnCache.delete(key);
11801
11897
  fnCache.set(key, cached);
11802
11898
  return cached;
11803
11899
  }
11804
- const fn = new Function("variables", "temporary", "locals", "__fns", "transient", preamble + body);
11900
+ const fn = compile(source, goal);
11805
11901
  fnCache.set(key, fn);
11806
11902
  if (fnCache.size > FN_CACHE_MAX) {
11807
11903
  const oldest = fnCache.keys().next().value;
@@ -11892,16 +11988,14 @@ function run$1(fn, ...[variables, temporary, locals = EMPTY_NAMESPACE, transient
11892
11988
  * e.g. evaluate("$health + 10", variables, temporary) → number
11893
11989
  */
11894
11990
  function evaluate(expr, ...namespaces) {
11895
- const body = `return (${transform(expr)}\n);`;
11896
- return run$1(getOrCompile(body, body), ...namespaces);
11991
+ return run$1(getOrCompile(expr, "expression"), ...namespaces);
11897
11992
  }
11898
11993
  /**
11899
11994
  * Execute statements (no return value).
11900
11995
  * e.g. execute("$health = 100; $name = 'Hero'", variables, temporary)
11901
11996
  */
11902
11997
  function execute(code, ...namespaces) {
11903
- const transformed = transform(code, "statements");
11904
- run$1(getOrCompile("exec:" + transformed, transformed), ...namespaces);
11998
+ run$1(getOrCompile(code, "statements"), ...namespaces);
11905
11999
  }
11906
12000
  //#endregion
11907
12001
  //#region src/components/macros/display.ts
@@ -12249,7 +12343,7 @@ function VarDisplay({ node }) {
12249
12343
  const resolve = useInterpolate();
12250
12344
  const className = resolve(node.className);
12251
12345
  const id = resolve(node.id);
12252
- const localsValues = useContext(LocalsValuesContext);
12346
+ const localsValues = useLiveLocals();
12253
12347
  const parts = name.split(".");
12254
12348
  const root = parts[0];
12255
12349
  const storeValue = useStoryStore((s) => scope === "local" ? void 0 : ownValue(s[STORE_NAMESPACES[scope]], root));
@@ -12308,14 +12402,17 @@ function useRenderOptions() {
12308
12402
  //#endregion
12309
12403
  //#region src/components/macros/locals-scope.tsx
12310
12404
  /**
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.
12405
+ * Render `body` in a new locals scope: the locals of the enclosing scope,
12406
+ * with `ownKeys` (an iteration's loop variables, a widget's parameters) on
12407
+ * top. Locals the body assigns are kept in this scope.
12314
12408
  */
12315
- function LocalsScope({ body, parentValues, ownKeys }) {
12409
+ function LocalsScope({ body, ownKeys }) {
12316
12410
  const options = useRenderOptions();
12317
12411
  const [localMutations, setLocalMutations] = useState({});
12318
- const localState = useMemo(() => createNamespace(parentValues, ownKeys, localMutations), [
12412
+ const enclosing = useContext(LocalsUpdateContext).getValues();
12413
+ const parentValues = useContext(LocalsValuesContext);
12414
+ const localState = useMemo(() => createNamespace(enclosing, ownKeys, localMutations), [
12415
+ enclosing,
12319
12416
  parentValues,
12320
12417
  ownKeys,
12321
12418
  localMutations
@@ -12353,7 +12450,6 @@ function WidgetInvocation(props) {
12353
12450
  return wrapContent(resolve(props.className), resolve(props.id), /* @__PURE__ */ jsx(WidgetContent, { ...props }));
12354
12451
  }
12355
12452
  function WidgetContent({ body, params, rawArgs, invocationChildren }) {
12356
- const parentValues = useRenderOptions().locals;
12357
12453
  const [mergedVars, mergedTemps, mergedLocals, mergedTrans] = useMergedLocals();
12358
12454
  const outerChildren = useContext(WidgetChildrenContext);
12359
12455
  const childrenValue = useMemo(() => widgetChildrenOf(invocationChildren, outerChildren), [invocationChildren, outerChildren]);
@@ -12369,16 +12465,16 @@ function WidgetContent({ body, params, rawArgs, invocationChildren }) {
12369
12465
  }
12370
12466
  values.push(value);
12371
12467
  }
12468
+ const paramsKey = params.join(" ");
12372
12469
  const ownKeys = useMemo(() => {
12373
12470
  const keys = createNamespace();
12374
12471
  for (let i = 0; i < params.length; i++) keys[params[i].startsWith("@") ? params[i].slice(1) : params[i]] = values[i];
12375
12472
  return keys;
12376
- }, values);
12473
+ }, [paramsKey, ...values]);
12377
12474
  return /* @__PURE__ */ jsx(WidgetChildrenContext.Provider, {
12378
12475
  value: childrenValue,
12379
12476
  children: /* @__PURE__ */ jsx(LocalsScope, {
12380
12477
  body,
12381
- parentValues,
12382
12478
  ownKeys
12383
12479
  })
12384
12480
  });
@@ -14158,6 +14254,29 @@ function extraKeys(collection) {
14158
14254
  const keys = Object.keys(collection);
14159
14255
  return Array.isArray(collection) ? keys.filter((k) => !isIndexKey(k)) : keys;
14160
14256
  }
14257
+ /** The built-in getter of each flag, with the letter `flags` lists it by. */
14258
+ var FLAG_GETTERS = [
14259
+ ["hasIndices", "d"],
14260
+ ["global", "g"],
14261
+ ["ignoreCase", "i"],
14262
+ ["multiline", "m"],
14263
+ ["dotAll", "s"],
14264
+ ["unicode", "u"],
14265
+ ["unicodeSets", "v"],
14266
+ ["sticky", "y"]
14267
+ ].flatMap(([name, letter]) => {
14268
+ const get = Object.getOwnPropertyDescriptor(RegExp.prototype, name)?.get;
14269
+ return get ? [[letter, get]] : [];
14270
+ });
14271
+ /** The pattern of a RegExp and its flags, as its slots hold them. */
14272
+ function regExpParts(re) {
14273
+ return [Reflect.get(RegExp.prototype, "source", re), FLAG_GETTERS.map(([letter, get]) => get.call(re) ? letter : "").join("")];
14274
+ }
14275
+ /** `/source/flags` of a RegExp, as its slots hold them (see regExpParts). */
14276
+ function regExpText(re) {
14277
+ const [source, flags] = regExpParts(re);
14278
+ return `/${source}/${flags}`;
14279
+ }
14161
14280
  /** The entries of a Map, as the built-in iterator gives them. */
14162
14281
  function mapEntries(map) {
14163
14282
  return isDraft(map) ? map.entries() : Map.prototype.entries.call(map);
@@ -14323,11 +14442,7 @@ function classData(value) {
14323
14442
  ];
14324
14443
  if (value instanceof RegExp) return [
14325
14444
  "RegExp",
14326
- [
14327
- Reflect.get(RegExp.prototype, "source", value),
14328
- Reflect.get(RegExp.prototype, "flags", value),
14329
- value.lastIndex
14330
- ],
14445
+ [...regExpParts(value), value.lastIndex],
14331
14446
  extra()
14332
14447
  ];
14333
14448
  return savedData(ownData(value));
@@ -14369,11 +14484,7 @@ function reducers() {
14369
14484
  const key = Symbol.keyFor(v);
14370
14485
  return key !== void 0 && [key];
14371
14486
  };
14372
- out[REGEXP_TAG] = (v) => v instanceof RegExp && v.lastIndex !== 0 && [
14373
- v.source,
14374
- v.flags,
14375
- v.lastIndex
14376
- ];
14487
+ out[REGEXP_TAG] = (v) => v instanceof RegExp && v.lastIndex !== 0 && [...regExpParts(v), v.lastIndex];
14377
14488
  out[KEYS_TAG] = (v) => {
14378
14489
  return isPlainData(v) && keyEntries(v);
14379
14490
  };
@@ -15108,7 +15219,7 @@ function getByPath(obj, segments) {
15108
15219
  return current;
15109
15220
  }
15110
15221
  /** Array indices ("0", "1", …) and "length": the keys an array holds. */
15111
- var isArrayKey = (key) => key === "length" || /^(0|[1-9]\d*)$/.test(key);
15222
+ var isArrayKey = (key) => key === "length" || isArrayIndex(key);
15112
15223
  /**
15113
15224
  * Built-ins whose content is not their properties: a property written into
15114
15225
  * one would be dropped by clones and saves (and by Immer, for Map and Set).
@@ -15262,7 +15373,7 @@ function deepClone(value, options = {}) {
15262
15373
  function cloneBuiltin(val) {
15263
15374
  if (val instanceof Date) return builtin(val, new Date(Date.prototype.getTime.call(val)));
15264
15375
  if (val instanceof RegExp) {
15265
- const copy = new RegExp(Reflect.get(RegExp.prototype, "source", val), Reflect.get(RegExp.prototype, "flags", val));
15376
+ const copy = new RegExp(...regExpParts(val));
15266
15377
  copy.lastIndex = val.lastIndex;
15267
15378
  return builtin(val, copy);
15268
15379
  }
@@ -15456,10 +15567,7 @@ function equalBuiltin(a, b, assumed) {
15456
15567
  const time = Date.prototype.getTime;
15457
15568
  return Object.is(time.call(a), time.call(b)) && equalExtraKeys(a, b, assumed);
15458
15569
  }
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
- }
15570
+ if (a instanceof RegExp) return regExpText(a) === regExpText(b) && a.lastIndex === b.lastIndex && equalExtraKeys(a, b, assumed);
15463
15571
  if (ArrayBuffer.isView(a)) {
15464
15572
  const v = b;
15465
15573
  return a.byteOffset === v.byteOffset && a.byteLength === v.byteLength && equal(a.buffer, v.buffer, assumed);
@@ -15487,11 +15595,15 @@ var BUILTIN_PROTOS = /* @__PURE__ */ new Set([
15487
15595
  RegExp.prototype
15488
15596
  ]);
15489
15597
  /**
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.
15598
+ * The extra keys (see extraKeys) of a built-in that is an instance of a
15599
+ * subclass: those are part of its value. A plain built-in has none.
15492
15600
  */
15601
+ function subclassFields(obj) {
15602
+ return BUILTIN_PROTOS.has(Object.getPrototypeOf(obj)) ? [] : extraKeys(obj);
15603
+ }
15604
+ /** Equality of the fields (see subclassFields) of two built-ins of one class. */
15493
15605
  function equalExtraKeys(a, b, assumed) {
15494
- return BUILTIN_PROTOS.has(Object.getPrototypeOf(a)) || equalKeys(a, b, assumed, extraKeys);
15606
+ return equalKeys(a, b, assumed, subclassFields);
15495
15607
  }
15496
15608
  /** `assumed` tracks the pairs of objects met (see Pairs). */
15497
15609
  function equal(a, b, assumed) {
@@ -15602,15 +15714,15 @@ function keyChanges(before, after, arrays) {
15602
15714
  kind: "holes",
15603
15715
  after: a.length - next
15604
15716
  });
15605
- return changes;
15606
15717
  }
15607
- for (const key of Object.keys(after)) if (hasOwn(before, key)) compare(key, before[key], after[key]);
15718
+ const keysOf = Array.isArray(after) ? subclassFields : Object.keys;
15719
+ for (const key of keysOf(after)) if (hasOwn(before, key)) compare(key, before[key], after[key]);
15608
15720
  else changes.push({
15609
15721
  key,
15610
15722
  kind: "added",
15611
15723
  after: after[key]
15612
15724
  });
15613
- for (const key of Object.keys(before)) if (!hasOwn(after, key)) changes.push({
15725
+ for (const key of keysOf(before)) if (!hasOwn(after, key)) changes.push({
15614
15726
  key,
15615
15727
  kind: "deleted"
15616
15728
  });
@@ -17026,7 +17138,7 @@ function routeStoreUpdate(recipe) {
17026
17138
  return;
17027
17139
  }
17028
17140
  if (activeScopes.length === 0) return void 0;
17029
- commitScopes(running());
17141
+ commitScopes(running$1());
17030
17142
  const inner = activeScopes[activeScopes.length - 1];
17031
17143
  const view = {
17032
17144
  ...useStoryStore.getState(),
@@ -17181,7 +17293,7 @@ function commitScopes(commits) {
17181
17293
  */
17182
17294
  var changesOf = (base, work) => changesBetween(base, work);
17183
17295
  /** Every running mutation, to commit with its code going on. */
17184
- var running = () => activeScopes.map((scope) => ({
17296
+ var running$1 = () => activeScopes.map((scope) => ({
17185
17297
  scope,
17186
17298
  keepRunning: true
17187
17299
  }));
@@ -17219,7 +17331,7 @@ function resync(scope) {
17219
17331
  */
17220
17332
  function runWithCommittedMutations(action) {
17221
17333
  if (activeScopes.length === 0) return action();
17222
- commitScopes(running());
17334
+ commitScopes(running$1());
17223
17335
  const suspended = activeScopes.splice(0);
17224
17336
  try {
17225
17337
  return action();
@@ -17235,7 +17347,7 @@ function runWithCommittedMutations(action) {
17235
17347
  * Nothing is committed when `run` throws.
17236
17348
  */
17237
17349
  function mutateState(run) {
17238
- commitScopes(running());
17350
+ commitScopes(running$1());
17239
17351
  const held = locateObjects(namespacesOf(getActiveMutationScope() ?? useStoryStore.getState()), []);
17240
17352
  const scope = startScope();
17241
17353
  const adopt = clonerFor(scope.work, held);
@@ -17244,7 +17356,7 @@ function mutateState(run) {
17244
17356
  } finally {
17245
17357
  activeScopes.pop();
17246
17358
  }
17247
- commitScopes([...running(), {
17359
+ commitScopes([...running$1(), {
17248
17360
  scope,
17249
17361
  keepRunning: false
17250
17362
  }]);
@@ -17267,7 +17379,7 @@ function executeMutation(code, mergedLocals, scopeUpdate) {
17267
17379
  } finally {
17268
17380
  activeScopes.pop();
17269
17381
  }
17270
- commitScopes([...running(), {
17382
+ commitScopes([...running$1(), {
17271
17383
  scope,
17272
17384
  keepRunning: false
17273
17385
  }]);
@@ -18138,7 +18250,7 @@ function writeHookChange(work, after, change, own) {
18138
18250
  }
18139
18251
  function writeKey(holder, key, value, change) {
18140
18252
  const deleted = change?.deleted ?? false;
18141
- if (Array.isArray(holder)) {
18253
+ if (Array.isArray(holder) && (key === "length" || isIndexKey(key))) {
18142
18254
  const index = Number(key);
18143
18255
  if (deleted) {
18144
18256
  if (change && "hole" in change) delete holder[index];
@@ -18794,20 +18906,22 @@ function tabIndexAttr(el) {
18794
18906
  function isTabStop(el) {
18795
18907
  const tabIndex = tabIndexAttr(el);
18796
18908
  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;
18909
+ if (tabIndex === null && el.hasAttribute("contenteditable") && !el.matches("a[href], button, input, select, textarea, iframe, summary") && (!el.isContentEditable || el.parentElement?.isContentEditable)) return false;
18798
18910
  if (el.localName === "summary") {
18799
18911
  const details = el.parentElement;
18800
18912
  if (details?.localName !== "details" || Array.from(details.children).find((c) => c.localName === "summary") !== el) return tabIndex !== null;
18801
18913
  }
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));
18914
+ const input = el;
18915
+ if (el.localName === "input" && input.type === "radio" && input.name) {
18916
+ const group = Array.from((input.form ?? el.getRootNode()).querySelectorAll("input[type=\"radio\"]")).filter((r) => r.name === input.name && r.form === input.form && (tabIndexAttr(r) ?? 0) >= 0 && isAvailable(r));
18804
18917
  return el === (group.find((r) => r.checked) ?? group[0]);
18805
18918
  }
18806
18919
  return true;
18807
18920
  }
18808
18921
  /**
18809
- * The elements of `root` in the order Tab visits them: positive tabindexes
18810
- * first, ascending, then the others in document order.
18922
+ * The elements of `root` (the dialog panel, or an embedded document) in the
18923
+ * order Tab visits them: positive tabindexes first, ascending, then the
18924
+ * others in document order.
18811
18925
  */
18812
18926
  function focusables(root) {
18813
18927
  const stops = Array.from(root.querySelectorAll(FOCUSABLE)).filter((el) => isAvailable(el) && isTabStop(el));
@@ -18834,19 +18948,51 @@ var SEGMENTED_INPUTS = /* @__PURE__ */ new Set([
18834
18948
  ]);
18835
18949
  /** Whether the element has native tab stops inside it, in its shadow tree. */
18836
18950
  function hasNativeStops(el) {
18837
- if (el instanceof HTMLMediaElement) return el.controls;
18838
- return el instanceof HTMLInputElement && SEGMENTED_INPUTS.has(el.type) && !el.readOnly;
18951
+ if (!el) return false;
18952
+ if (el.localName === "audio" || el.localName === "video") return el.controls;
18953
+ const input = el;
18954
+ return el.localName === "input" && SEGMENTED_INPUTS.has(input.type) && !input.readOnly;
18839
18955
  }
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));
18956
+ /** Whether `el` is an iframe element, of this realm or of an embedded one. */
18957
+ function isFrame(el) {
18958
+ return el.localName === "iframe";
18959
+ }
18960
+ /** The document of a frame, or null when it is not accessible. */
18961
+ function frameDocument(frame) {
18962
+ try {
18963
+ return frame.contentDocument;
18964
+ } catch {
18965
+ return null;
18966
+ }
18967
+ }
18968
+ /** The iframe element that holds `doc`, null for the top document. */
18969
+ function frameOf(doc) {
18970
+ try {
18971
+ return doc.defaultView?.frameElement;
18972
+ } catch {
18973
+ return null;
18974
+ }
18975
+ }
18976
+ /**
18977
+ * The stop after (or before) `from` among `items`, the tab stops of `root`,
18978
+ * undefined past the end. `from` may be no stop of its own: then the next one
18979
+ * in document order. Outside `root`, the first (or last) stop.
18980
+ */
18981
+ function nextStop(items, root, from, backwards) {
18982
+ const at = from ? items.indexOf(from) : -1;
18983
+ if (at !== -1) return items[at + (backwards ? -1 : 1)];
18984
+ if (from && from !== root && root.contains(from)) {
18985
+ const after = (el) => !!(from.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING);
18986
+ return backwards ? items.filter((el) => !after(el)).pop() : items.find(after);
18987
+ }
18988
+ return backwards ? items[items.length - 1] : items[0];
18844
18989
  }
18845
18990
  function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18846
18991
  useLayoutEffect(() => {
18847
18992
  const panel = panelRef.current;
18848
18993
  if (!panel) return;
18849
- const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null;
18994
+ const focused = document.activeElement;
18995
+ const opener = focused instanceof HTMLElement || focused instanceof SVGElement ? focused : null;
18850
18996
  const entry = { panel };
18851
18997
  openModals.push(entry);
18852
18998
  const body = panel.querySelector(bodySelector) ?? panel;
@@ -18862,29 +19008,33 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18862
19008
  const panel = panelRef.current;
18863
19009
  if (!panel) return;
18864
19010
  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
19011
  /** Focus `el`; a frame is entered at its first (or last) control (#460). */
18873
19012
  const enter = (el, backwards) => {
18874
- if (el instanceof HTMLIFrameElement) {
18875
- let inner = [];
18876
- try {
18877
- inner = frameStops(el.contentDocument);
18878
- } catch {}
19013
+ if (isFrame(el)) {
19014
+ const doc = frameDocument(el);
19015
+ const inner = doc ? focusables(doc) : [];
18879
19016
  const edge = backwards ? inner[inner.length - 1] : inner[0];
18880
- if (edge) {
18881
- edge.focus();
18882
- return;
18883
- }
19017
+ if (edge) return enter(edge, backwards);
18884
19018
  }
18885
19019
  el.focus();
18886
19020
  };
19021
+ /**
19022
+ * Move focus to the next (or previous) modal control from `from`. The
19023
+ * order is computed here, never left to the browser: its positive-tabindex
19024
+ * sequence spans the whole document and would lead out of the modal
19025
+ * (#424). `from` is an element of the dialog, or of an embedded document;
19026
+ * past the last control of a frame, focus goes on after the frame element
19027
+ * in the document that holds it.
19028
+ */
18887
19029
  const moveFocus = (from, backwards) => {
19030
+ const doc = from?.ownerDocument;
19031
+ const frame = doc && doc !== document ? frameOf(doc) : null;
19032
+ if (doc && frame) {
19033
+ const next = nextStop(focusables(doc), doc, from, backwards);
19034
+ if (next) enter(next, backwards);
19035
+ else moveFocus(frame, backwards);
19036
+ return;
19037
+ }
18888
19038
  const items = focusables(panel);
18889
19039
  const first = items[0];
18890
19040
  const last = items[items.length - 1];
@@ -18892,107 +19042,102 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18892
19042
  panel.focus();
18893
19043
  return;
18894
19044
  }
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;
19045
+ const next = nextStop(items, panel, from, backwards);
18902
19046
  enter(next ?? (backwards ? last : first), backwards);
18903
19047
  };
18904
19048
  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) => {
19049
+ const keyHandler = (doc, frame) => {
19050
+ return (e) => {
18940
19051
  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) {
19052
+ if (e.key === "Escape") {
19053
+ if (!dismissible) return;
18946
19054
  e.preventDefault();
18947
- moveFocus(frame, e.shiftKey);
19055
+ e.stopPropagation();
19056
+ onClose();
19057
+ return;
19058
+ }
19059
+ if (e.key !== "Tab") return;
19060
+ const active = doc.activeElement;
19061
+ if (frame) {
19062
+ steppingNative = null;
19063
+ const inner = focusables(doc);
19064
+ const edge = e.shiftKey ? inner[0] : inner[inner.length - 1];
19065
+ if (edge && active !== edge && active !== doc.body) return;
18948
19066
  }
19067
+ if (hasNativeStops(active)) {
19068
+ steppingNative = {
19069
+ el: active,
19070
+ from: frame ?? active,
19071
+ backwards: e.shiftKey
19072
+ };
19073
+ return;
19074
+ }
19075
+ e.preventDefault();
19076
+ moveFocus(frame ?? active, e.shiftKey);
18949
19077
  };
18950
- doc.addEventListener("keydown", onFrameKeyDown, { signal });
18951
- };
18952
- const attachFrames = () => {
18953
- panel.querySelectorAll("iframe").forEach(attachFrame);
18954
19078
  };
18955
- const onLoad = (e) => {
18956
- if (e.target instanceof HTMLIFrameElement) attachFrame(e.target);
19079
+ const onPointerDown = () => {
19080
+ steppingNative = null;
18957
19081
  };
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
19082
  const onFocusIn = (e) => {
18969
19083
  const target = e.target;
18970
19084
  if (steppingNative && target !== steppingNative.el && top()) {
18971
- const { el, backwards } = steppingNative;
19085
+ const { from, backwards } = steppingNative;
18972
19086
  steppingNative = null;
18973
- moveFocus(el, backwards);
19087
+ moveFocus(from, backwards);
18974
19088
  return;
18975
19089
  }
18976
19090
  if (!top() || !(target instanceof Node) || panel.contains(target)) return;
18977
19091
  if (target === document.body || target === document.documentElement) return;
18978
19092
  moveFocus(null, false);
18979
19093
  };
18980
- document.addEventListener("keydown", onKeyDown, { signal });
18981
- document.addEventListener("pointerdown", onPointerDown, {
18982
- capture: true,
18983
- signal
18984
- });
18985
19094
  const onFocusOut = (e) => {
18986
19095
  const pending = steppingNative;
18987
19096
  if (!pending || e.target !== pending.el || e.relatedTarget || !top()) return;
18988
19097
  steppingNative = null;
18989
- moveFocus(pending.el, pending.backwards);
19098
+ moveFocus(pending.from, pending.backwards);
19099
+ };
19100
+ const controller = new AbortController();
19101
+ const { signal } = controller;
19102
+ const listen = (doc, frame) => {
19103
+ doc.addEventListener("keydown", keyHandler(doc, frame), { signal });
19104
+ doc.addEventListener("pointerdown", onPointerDown, {
19105
+ capture: true,
19106
+ signal
19107
+ });
19108
+ doc.addEventListener("focusout", onFocusOut, { signal });
18990
19109
  };
18991
- document.addEventListener("focusout", onFocusOut, { signal });
19110
+ const frameDocs = /* @__PURE__ */ new Map();
19111
+ const observers = [];
19112
+ const attachFrame = (frame) => {
19113
+ const doc = frameDocument(frame);
19114
+ if (!doc || frameDocs.get(frame) === doc) return;
19115
+ frameDocs.set(frame, doc);
19116
+ listen(doc, frame);
19117
+ watchFrames(doc);
19118
+ };
19119
+ const watchFrames = (root) => {
19120
+ const attachAll = () => root.querySelectorAll("iframe").forEach(attachFrame);
19121
+ root.addEventListener("load", (e) => {
19122
+ if (e.target instanceof Node && isFrame(e.target)) attachFrame(e.target);
19123
+ }, {
19124
+ capture: true,
19125
+ signal
19126
+ });
19127
+ const observer = new MutationObserver(attachAll);
19128
+ observer.observe(root, {
19129
+ childList: true,
19130
+ subtree: true
19131
+ });
19132
+ observers.push(observer);
19133
+ attachAll();
19134
+ };
19135
+ watchFrames(panel);
19136
+ listen(document, null);
18992
19137
  document.addEventListener("focusin", onFocusIn, { signal });
18993
19138
  return () => {
18994
19139
  controller.abort();
18995
- frames.disconnect();
19140
+ observers.forEach((o) => o.disconnect());
18996
19141
  };
18997
19142
  }, [dismissible, onClose]);
18998
19143
  }
@@ -19565,21 +19710,33 @@ var OPTIONAL_ACTION_FIELDS = [
19565
19710
  var actions = /* @__PURE__ */ new Map();
19566
19711
  var idCounters = /* @__PURE__ */ new Map();
19567
19712
  /**
19713
+ * IDs handed out and not yet registered, or registered: a control registers
19714
+ * in a layout effect, after every control of the same render has allocated its
19715
+ * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
19716
+ * Released when the last registration of an ID goes.
19717
+ */
19718
+ var reserved = /* @__PURE__ */ new Set();
19719
+ /**
19568
19720
  * The counters reset on every navigation, so a passage's controls get the
19569
19721
  * same IDs each time it is shown. Controls that stay mounted across
19570
19722
  * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19571
- * ID still registered (#233).
19723
+ * ID still registered (#233) and every one allocated but not registered yet
19724
+ * (#486).
19572
19725
  */
19573
19726
  function generateActionId(type, key, authorId) {
19574
- if (authorId) return authorId;
19727
+ if (authorId) {
19728
+ reserved.add(authorId);
19729
+ return authorId;
19730
+ }
19575
19731
  const base = `${type}:${key}`;
19576
19732
  let count = idCounters.get(base) ?? 0;
19577
19733
  let id;
19578
19734
  do {
19579
19735
  count++;
19580
19736
  id = count === 1 ? base : `${base}:${count}`;
19581
- } while (actions.has(id));
19737
+ } while (actions.has(id) || reserved.has(id));
19582
19738
  idCounters.set(base, count);
19739
+ reserved.add(id);
19583
19740
  return id;
19584
19741
  }
19585
19742
  function registerAction(action) {
@@ -19603,11 +19760,34 @@ function registerAction(action) {
19603
19760
  const index = current ? current.indexOf(entry) : -1;
19604
19761
  if (!current || index === -1) return;
19605
19762
  current.splice(index, 1);
19606
- if (current.length === 0) actions.delete(id);
19763
+ if (current.length === 0) {
19764
+ actions.delete(id);
19765
+ reserved.delete(id);
19766
+ }
19607
19767
  if (index === current.length) notify();
19608
19768
  }
19609
19769
  };
19610
19770
  }
19771
+ /** The promises of the performed actions that have not settled yet. */
19772
+ var running = /* @__PURE__ */ new Set();
19773
+ /**
19774
+ * Perform an action, as `Story.performAction()` does. One that returns a
19775
+ * promise is tracked until it settles, for `settleRunningActions()`, and the
19776
+ * promise is returned for the caller to await (its rejection stays the
19777
+ * caller's to handle).
19778
+ */
19779
+ function performRegisteredAction(action, value) {
19780
+ const result = action.perform(value);
19781
+ if (!result || typeof result.then !== "function") return result;
19782
+ const done = () => void running.delete(result);
19783
+ running.add(result);
19784
+ result.then(done, done);
19785
+ return result.then((v) => v);
19786
+ }
19787
+ /** Wait until every performed action has finished, whether or not it failed. */
19788
+ async function settleRunningActions() {
19789
+ while (running.size > 0) await Promise.allSettled(running);
19790
+ }
19611
19791
  function getActions() {
19612
19792
  return Array.from(actions.values(), listed);
19613
19793
  }
@@ -19620,6 +19800,7 @@ function listed(entries) {
19620
19800
  }
19621
19801
  function resetIdCounters() {
19622
19802
  idCounters.clear();
19803
+ for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
19623
19804
  }
19624
19805
  function notify() {
19625
19806
  emit("actionsChanged");
@@ -19984,7 +20165,7 @@ function createStoryAPI() {
19984
20165
  const action = getAction(id);
19985
20166
  if (!action) throw new Error(`spindle: Action "${id}" not found.`);
19986
20167
  if (action.disabled) throw new Error(`spindle: Action "${id}" is disabled.`);
19987
- action.perform(value);
20168
+ return performRegisteredAction(action, value);
19988
20169
  },
19989
20170
  on(event, callback) {
19990
20171
  if (event === "variableChanged") ensureVariableChangedSubscription();
@@ -19993,6 +20174,7 @@ function createStoryAPI() {
19993
20174
  return unsub;
19994
20175
  },
19995
20176
  async waitForActions() {
20177
+ await settleRunningActions();
19996
20178
  await new Promise((resolve) => {
19997
20179
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
19998
20180
  });
@@ -20319,10 +20501,12 @@ function validateMarkup(passages, options) {
20319
20501
  * an operator, a reference, a spread) is "not static", which is no error: the
20320
20502
  * value is simply not known without running the code.
20321
20503
  */
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;
20504
+ var NUMBER_RE = /(?:0[xX][\da-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?[\d_]*|\.\d[\d_]*)(?:[eE][+-]?\d[\d_]*)?)(n?)/y;
20323
20505
  var IDENT_RE = /[A-Za-z_$][\w$]*/y;
20324
20506
  var KEY_RE = /[\w$]+/y;
20325
20507
  var ARROW_RE = /(?:async\s+)?(?:\((?:[^()]|\([^()]*\))*\)|[A-Za-z_$][\w$]*)\s*=>/y;
20508
+ /** The end of a line: the four line terminators of JavaScript. */
20509
+ var LINE_END_RE = /[\n\r\u2028\u2029]/g;
20326
20510
  var ARRAY_INDEX_RE = /^(?:0|[1-9]\d{0,8})$/;
20327
20511
  var UNSUPPORTED_UNDEFINED = {
20328
20512
  unsupported: "undefined",
@@ -20344,6 +20528,22 @@ function entryOrder(keys) {
20344
20528
  const all = [...keys];
20345
20529
  return [...all.filter((key) => ARRAY_INDEX_RE.test(key)).sort((a, b) => Number(a) - Number(b)), ...all.filter((key) => !ARRAY_INDEX_RE.test(key))];
20346
20530
  }
20531
+ /**
20532
+ * Where the regex literals in `src` are, by their start: JavaScript text
20533
+ * cannot tell a regex from a division without the code before it, which the
20534
+ * lexer reads. `handlers` see the same walk.
20535
+ */
20536
+ function regexLiterals(src, goal = "expression", handlers = {}) {
20537
+ const ends = /* @__PURE__ */ new Map();
20538
+ lexJs(src, {
20539
+ ...handlers,
20540
+ literal(text, index, nesting) {
20541
+ if (text.charAt(0) === "/" && !/^\/[/*]/.test(text)) ends.set(index, index + text.length);
20542
+ handlers.literal?.(text, index, nesting);
20543
+ }
20544
+ }, goal);
20545
+ return ends;
20546
+ }
20347
20547
  /** `String(value)` of a BigInt literal's digits, or `undefined` if they are no BigInt. */
20348
20548
  function bigintValue(digits) {
20349
20549
  try {
@@ -20357,9 +20557,15 @@ function bigintValue(digits) {
20357
20557
  * helpers that skip what is not read are shared (see macro-discovery.ts).
20358
20558
  */
20359
20559
  var Reader = class {
20360
- constructor(src) {
20560
+ /**
20561
+ * `regexes` (see regexLiterals) are read from `src` when they are first
20562
+ * needed, unless the caller has them already.
20563
+ */
20564
+ constructor(src, options = {}) {
20361
20565
  this.src = src;
20362
20566
  this.i = 0;
20567
+ this.goal = options.goal ?? "expression";
20568
+ this.regexes = options.regexes;
20363
20569
  }
20364
20570
  /** Skip whitespace and comments. */
20365
20571
  space() {
@@ -20367,8 +20573,8 @@ var Reader = class {
20367
20573
  for (;;) {
20368
20574
  while (/\s/.test(src.charAt(this.i))) this.i++;
20369
20575
  if (src.startsWith("//", this.i)) {
20370
- const end = src.indexOf("\n", this.i);
20371
- this.i = end < 0 ? src.length : end;
20576
+ LINE_END_RE.lastIndex = this.i;
20577
+ this.i = LINE_END_RE.test(src) ? LINE_END_RE.lastIndex - 1 : src.length;
20372
20578
  } else if (src.startsWith("/*", this.i)) {
20373
20579
  const end = src.indexOf("*/", this.i + 2);
20374
20580
  this.i = end < 0 ? src.length : end + 2;
@@ -20427,10 +20633,9 @@ var Reader = class {
20427
20633
  i++;
20428
20634
  while (/\s/.test(src.charAt(i))) i++;
20429
20635
  }
20430
- NUMBER_RE.lastIndex = i;
20431
- const match = NUMBER_RE.exec(src);
20636
+ const match = this.numberAt(i);
20432
20637
  if (match) {
20433
- this.i = NUMBER_RE.lastIndex;
20638
+ this.i = i + match[0].length;
20434
20639
  if (!match[1]) return { shape: { type: "number" } };
20435
20640
  if (sign === "+") return { throws: "Cannot convert a BigInt value to a number" };
20436
20641
  const digits = bigintValue(match[0].slice(0, -1));
@@ -20440,11 +20645,17 @@ var Reader = class {
20440
20645
  };
20441
20646
  }
20442
20647
  IDENT_RE.lastIndex = i;
20443
- if (IDENT_RE.exec(src)?.[0] === "Infinity") {
20648
+ const word = IDENT_RE.exec(src)?.[0];
20649
+ if (word === "Infinity" || word === "NaN") {
20444
20650
  this.i = IDENT_RE.lastIndex;
20445
20651
  return { shape: { type: "number" } };
20446
20652
  }
20447
20653
  }
20654
+ /** The numeric literal (a BigInt's `n` is `match[1]`) at `at`, if there is one. */
20655
+ numberAt(at) {
20656
+ NUMBER_RE.lastIndex = at;
20657
+ return NUMBER_RE.exec(this.src);
20658
+ }
20448
20659
  /** A keyword, a function, or a name (which is not static). */
20449
20660
  word() {
20450
20661
  const { src } = this;
@@ -20464,6 +20675,7 @@ var Reader = class {
20464
20675
  this.i = end;
20465
20676
  return { shape: { type: "null" } };
20466
20677
  case "NaN":
20678
+ case "Infinity":
20467
20679
  this.i = end;
20468
20680
  return { shape: { type: "number" } };
20469
20681
  case "undefined":
@@ -20604,14 +20816,22 @@ var Reader = class {
20604
20816
  const { src } = this;
20605
20817
  const c = src.charAt(this.i);
20606
20818
  if (c === "\"" || c === "'") return this.stringValue();
20819
+ if (/[\d.]/.test(c)) return this.numberKey();
20607
20820
  KEY_RE.lastIndex = this.i;
20608
20821
  const found = KEY_RE.exec(src)?.[0];
20609
20822
  if (found === void 0) return void 0;
20610
20823
  this.i = KEY_RE.lastIndex;
20611
- if (!/^\d/.test(found)) return found;
20612
- const digits = found.replace(/_/g, "");
20824
+ return found;
20825
+ }
20826
+ /** A number as a key: the whole literal, named as the runtime names it. */
20827
+ numberKey() {
20828
+ const match = this.numberAt(this.i);
20829
+ if (!match) return void 0;
20830
+ this.i += match[0].length;
20831
+ if (/[\w$]/.test(this.src.charAt(this.i))) return void 0;
20832
+ const digits = match[0].replace(/_/g, "");
20613
20833
  if (/^0\d/.test(digits)) return void 0;
20614
- if (digits.endsWith("n") && !/^0[xX]/.test(digits)) return bigintValue(digits.slice(0, -1));
20834
+ if (match[1]) return bigintValue(digits.slice(0, -1));
20615
20835
  const value = Number(digits);
20616
20836
  return Number.isNaN(value) ? void 0 : String(value);
20617
20837
  }
@@ -20654,6 +20874,14 @@ var Reader = class {
20654
20874
  this.space();
20655
20875
  return true;
20656
20876
  }
20877
+ if (c === "/") {
20878
+ this.regexes ??= regexLiterals(src, this.goal);
20879
+ const end = this.regexes.get(this.i);
20880
+ if (end !== void 0) {
20881
+ this.i = end;
20882
+ return true;
20883
+ }
20884
+ }
20657
20885
  if (c === "[" || c === "{" || c === "(") return this.skipBalanced();
20658
20886
  if (c === "]" || c === "}" || c === ")") return false;
20659
20887
  this.i++;
@@ -20908,6 +21136,7 @@ function checkReference(ref, declared) {
20908
21136
  const part = ref.path[i];
20909
21137
  if (current.type === "array") return null;
20910
21138
  if (current.type === "null") return null;
21139
+ if (current.type === "string" && isArrayIndex(part)) continue;
20911
21140
  const sample = PRIMITIVE_SAMPLES[current.type];
20912
21141
  if (sample && part in sample) {
20913
21142
  const memberType = typeof sample[part];
@@ -20937,10 +21166,28 @@ var BUILTIN_STORE_VAR_MACROS = [
20937
21166
  "textbox"
20938
21167
  ];
20939
21168
  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) {
21169
+ /** A `.field` path written right after a reference, which may be empty. */
21170
+ var FIELD_PATH_RE = /(?:\.\w+)*/y;
21171
+ /**
21172
+ * The reference to variable `name`, which JavaScript reads at `[start, end)`
21173
+ * of `code` (the sigil and the name as written, which may be spelled with
21174
+ * escapes), with the dot path written after it.
21175
+ */
21176
+ function referenceAt(code, sigil, name, start, end, at) {
21177
+ FIELD_PATH_RE.lastIndex = end;
21178
+ const fields = FIELD_PATH_RE.exec(code)[0];
21179
+ return {
21180
+ sigil,
21181
+ name,
21182
+ path: fields ? fields.slice(1).split(".") : [],
21183
+ start: at(start),
21184
+ end: at(end + fields.length)
21185
+ };
21186
+ }
21187
+ /** A reference written at `index` of `term`, a `variable` parameter as written. */
21188
+ function termReferenceAt(term, index, at) {
20942
21189
  VAR_PATH_RE.lastIndex = index;
20943
- const match = VAR_PATH_RE.exec(code);
21190
+ const match = VAR_PATH_RE.exec(term);
20944
21191
  if (!match) return void 0;
20945
21192
  const [name, ...path] = match[2].split(".");
20946
21193
  return {
@@ -20985,46 +21232,51 @@ function scanCode(code, at, emit, goal = "expression") {
20985
21232
  }
20986
21233
  for (const ref of parsed.refs) {
20987
21234
  if (ref.sigil !== "$" && ref.sigil !== "%") continue;
20988
- const found = referenceAt(code, ref.start, at);
20989
- if (found) emit(found);
21235
+ emit(referenceAt(code, ref.sigil, ref.name, ref.start, ref.end, at));
20990
21236
  }
20991
21237
  }
20992
21238
  /** `scanCode` for code acorn can't parse: lexed leniently. */
20993
21239
  function scanCodeLeniently(code, at, emit, goal) {
20994
21240
  lexJs(code, {
20995
- variable(sigil, _name, index) {
21241
+ variable(sigil, name, index, _nesting, end) {
20996
21242
  if (sigil !== "$" && sigil !== "%") return;
20997
- const found = referenceAt(code, index, at);
20998
- if (found) emit(found);
21243
+ emit(referenceAt(code, sigil, name, index, end, at));
20999
21244
  },
21000
21245
  literal() {}
21001
21246
  }, goal);
21002
21247
  }
21248
+ /** Report the references in the pieces of code and markup text of arguments. */
21249
+ function scanPieces(pieces, at, emit, options) {
21250
+ for (const piece of pieces) {
21251
+ const pieceAt = (i) => at(pieceOffset(piece, i));
21252
+ if (piece.kind === "code") scanCode(piece.code, pieceAt, emit, piece.goal);
21253
+ else if (piece.kind === "text") scanInterpolations(piece.text, pieceAt, emit, {
21254
+ ...options,
21255
+ storeVarMacros: NO_STORE_VAR_MACROS
21256
+ });
21257
+ }
21258
+ }
21003
21259
  /**
21004
21260
  * Report the references in the arguments of a macro by what its parameters
21005
21261
  * say each holds (see ParameterDef.holds): code is scanned as code and
21006
21262
  * markup as markup, but literal text (a placeholder, a passage name) holds
21007
21263
  * none. A macro without declared parameters, or arguments that do not
21008
- * parse, are scanned as code.
21264
+ * parse, are scanned as code. The arguments of a widget that declares what
21265
+ * some parameters hold are also read by those (see widgetPieces).
21009
21266
  */
21010
- function scanArgs(token, params, at, emit, options) {
21267
+ function scanArgs(token, parametersOf, at, emit, options) {
21011
21268
  if (!token.rawArgs) return;
21269
+ const params = parametersOf(token.name);
21270
+ let byParameters = false;
21012
21271
  if (params) {
21013
21272
  if (options.all && !options.storeVarMacros.has(token.name.toLowerCase())) scanVariableParameters(token, params, at, emit);
21014
21273
  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
- }
21274
+ byParameters = !pieces.some((piece) => piece.kind === "argument-error");
21275
+ if (byParameters) scanPieces(pieces, at, emit, options);
21026
21276
  }
21027
- scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
21277
+ if (!byParameters) scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
21278
+ const widget = parametersOf.widget?.(token.name);
21279
+ if (widget) scanPieces(widgetPieces(token.rawArgs, token.argsStart, widget, token.name, ""), at, emit, options);
21028
21280
  }
21029
21281
  /**
21030
21282
  * Report the variables the `variable` parameters of a macro name
@@ -21042,7 +21294,7 @@ function scanVariableParameters(token, params, at, emit) {
21042
21294
  for (const param of params) {
21043
21295
  const span = spans.get(param);
21044
21296
  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));
21297
+ const ref = termReferenceAt(token.rawArgs.slice(span[0], span[1]), 0, (i) => at(token.argsStart + span[0] + i));
21046
21298
  if (ref) emit(ref);
21047
21299
  }
21048
21300
  }
@@ -21083,7 +21335,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
21083
21335
  else scanInterpolations(value, valueIn, emit, options);
21084
21336
  }
21085
21337
  else if (token.type === "macro" && !token.isClose) {
21086
- scanArgs(token, parametersOf(token.name), at, emit, options);
21338
+ scanArgs(token, parametersOf, at, emit, options);
21087
21339
  scanSelectors(content, token, at, emit, options);
21088
21340
  if (storeVarMacros.has(token.name.toLowerCase())) {
21089
21341
  const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
@@ -21126,7 +21378,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
21126
21378
  function collectVariableReferences(content, options) {
21127
21379
  const found = [];
21128
21380
  withParseCache(() => collectTokenRefs(content, tokensOf(content, false, options), (i) => i, (ref) => found.push(ref), options));
21129
- return found;
21381
+ return found.sort((a, b) => a.start - b.start);
21130
21382
  }
21131
21383
  /**
21132
21384
  * The invalid variable references of the passages, against what is declared,
@@ -21335,14 +21587,43 @@ function resolveTransition(targetTags, nextTransition, storeDefault) {
21335
21587
  //#endregion
21336
21588
  //#region src/components/macros/PassageDisplay.tsx
21337
21589
  /**
21590
+ * Copy the live state cloneNode drops from `source` into its clone: the
21591
+ * pixels of each canvas and the values of form controls (cloneNode keeps
21592
+ * attributes only, and a canvas's bitmap is not one). Source and clone have
21593
+ * the same structure, so elements pair up by position. Best effort: a canvas
21594
+ * that can not be drawn from stays as cloned.
21595
+ */
21596
+ function copyLiveState(source, clone) {
21597
+ const pairs = (selector, each) => {
21598
+ const from = source.querySelectorAll(selector);
21599
+ const to = clone.querySelectorAll(selector);
21600
+ from.forEach((el, i) => to[i] && each(el, to[i]));
21601
+ };
21602
+ pairs("canvas", (from, to) => {
21603
+ if (!from.width || !from.height) return;
21604
+ try {
21605
+ if (to.width !== from.width) to.width = from.width;
21606
+ if (to.height !== from.height) to.height = from.height;
21607
+ to.getContext("2d")?.drawImage(from, 0, 0);
21608
+ } catch {}
21609
+ });
21610
+ pairs("input, textarea, select", (from, to) => {
21611
+ if (from instanceof HTMLInputElement && to instanceof HTMLInputElement) to.checked = from.checked;
21612
+ if (!(from instanceof HTMLInputElement && from.type === "file")) to.value = from.value;
21613
+ });
21614
+ }
21615
+ /**
21338
21616
  * Create a snapshot clone of a .passage element for outgoing transitions.
21339
21617
  * - Strips `id` attributes from the clone tree
21340
21618
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
21341
21619
  * - Pauses/mutes any <audio>/<video>
21620
+ * - Copies what cloneNode leaves behind: canvas pixels and the values of
21621
+ * form controls (#512)
21342
21622
  * - Adds `.passage-snapshot` class and `data-transition` attribute
21343
21623
  */
21344
21624
  function createSnapshot(passageEl, transitionType) {
21345
21625
  const clone = passageEl.cloneNode(true);
21626
+ copyLiveState(passageEl, clone);
21346
21627
  clone.removeAttribute("id");
21347
21628
  const idEls = clone.querySelectorAll("[id]");
21348
21629
  for (let i = 0; i < idEls.length; i++) idEls[i].removeAttribute("id");
@@ -21865,7 +22146,9 @@ defineMacro({
21865
22146
  * built-ins (see isAtomic) have their contents in the key: the bytes of a
21866
22147
  * buffer, the place of a view in its buffer, the text of a URL or
21867
22148
  * 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.
22149
+ * value of a boxed primitive (#418). As for deepEqual and a save, -0 is not
22150
+ * 0 (#498) and a hole in an array is not an undefined element (#497), so
22151
+ * only the keys of -0 and of arrays with holes differ from JSON.stringify.
21869
22152
  *
21870
22153
  * An object met again, through a cycle or a second reference to it, is a
21871
22154
  * marker naming where it was first met rather than another copy of its
@@ -21879,6 +22162,8 @@ function stableKey(value) {
21879
22162
  return "<unkeyable>";
21880
22163
  }
21881
22164
  }
22165
+ /** The key of an array slot that holds no element. */
22166
+ var HOLE = "<hole>";
21882
22167
  /**
21883
22168
  * The key of `val`. `seen` numbers the objects keyed so far, in the order
21884
22169
  * they were first met.
@@ -21886,7 +22171,9 @@ function stableKey(value) {
21886
22171
  function keyOf(val, seen) {
21887
22172
  switch (typeof val) {
21888
22173
  case "string": return JSON.stringify(val);
21889
- case "number": return Number.isFinite(val) ? JSON.stringify(val) : String(val);
22174
+ case "number":
22175
+ if (Object.is(val, -0)) return "-0";
22176
+ return Number.isFinite(val) ? JSON.stringify(val) : String(val);
21890
22177
  case "boolean": return String(val);
21891
22178
  case "bigint": return `${val}n`;
21892
22179
  case "undefined": return "undefined";
@@ -21905,10 +22192,14 @@ function keyOf(val, seen) {
21905
22192
  };
21906
22193
  if (val instanceof Date || val instanceof RegExp) {
21907
22194
  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})`);
22195
+ return withFields(val instanceof Date ? `Date(${Date.prototype.getTime.call(val)})` : `RegExp(${regExpText(val)}@${val.lastIndex})`);
21909
22196
  }
21910
22197
  seen.set(obj, seen.size);
21911
- if (Array.isArray(val)) return withFields(`[${Array.from(val, (v) => keyOf(v, seen)).join(",")}]`);
22198
+ if (Array.isArray(val)) {
22199
+ const items = [];
22200
+ for (let i = 0; i < val.length; i++) items.push(i in val ? keyOf(val[i], seen) : HOLE);
22201
+ return withFields(`[${items.join(",")}]`);
22202
+ }
21912
22203
  const atomic = atomicKey(obj, seen);
21913
22204
  if (atomic !== void 0) return named(atomic);
21914
22205
  if (val instanceof Map) return withFields(`Map[${Array.from(mapEntries(val), ([k, v]) => `[${keyOf(k, seen)},${keyOf(v, seen)}]`).join(",")}]`);
@@ -21962,7 +22253,7 @@ function loopArgs(rawArgs, args) {
21962
22253
  listExpr
21963
22254
  };
21964
22255
  }
21965
- function ForIteration({ parentValues, itemVar, itemValue, indexVar, indexValue, children }) {
22256
+ function ForIteration({ itemVar, itemValue, indexVar, indexValue, children }) {
21966
22257
  const ownKeys = useMemo(() => ({
21967
22258
  [itemVar]: itemValue,
21968
22259
  ...indexVar ? { [indexVar]: indexValue } : void 0
@@ -21974,7 +22265,6 @@ function ForIteration({ parentValues, itemVar, itemValue, indexVar, indexValue,
21974
22265
  ]);
21975
22266
  return /* @__PURE__ */ jsx(LocalsScope, {
21976
22267
  body: children,
21977
- parentValues,
21978
22268
  ownKeys
21979
22269
  });
21980
22270
  }
@@ -22000,7 +22290,6 @@ defineMacro({
22000
22290
  }
22001
22291
  ],
22002
22292
  render({ rawArgs, children = [] }, ctx) {
22003
- const parentValues = useContext(LocalsValuesContext);
22004
22293
  const keys = ctx.hooks.useRef({
22005
22294
  contents: [],
22006
22295
  generations: [],
@@ -22034,7 +22323,6 @@ defineMacro({
22034
22323
  });
22035
22324
  keys.contents.length = keys.generations.length = list.length;
22036
22325
  const content = list.map((item, i) => /* @__PURE__ */ jsx(ForIteration, {
22037
- parentValues,
22038
22326
  itemVar,
22039
22327
  itemValue: item,
22040
22328
  indexVar,
@@ -22067,30 +22355,6 @@ defineMacro({
22067
22355
  }
22068
22356
  });
22069
22357
  //#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
22358
  //#region src/components/macros/Repeat.tsx
22095
22359
  var RepeatContext = createContext({ stop: () => {} });
22096
22360
  defineMacro({
@@ -22600,6 +22864,7 @@ defineMacro({
22600
22864
  //#region src/components/macros/StoryTitle.tsx
22601
22865
  defineMacro({
22602
22866
  name: "story-title",
22867
+ interpolate: true,
22603
22868
  render(_, ctx) {
22604
22869
  const name = useStoryStore((s) => s.storyData?.name || "");
22605
22870
  const cls = ctx.className ? `story-title ${ctx.className}` : "story-title";
@@ -22619,6 +22884,7 @@ function hotkeyTitle(label, key) {
22619
22884
  function defineMenubarAction(config) {
22620
22885
  defineMacro({
22621
22886
  name: config.name,
22887
+ interpolate: true,
22622
22888
  render(_, ctx) {
22623
22889
  if (config.hidden?.()) return null;
22624
22890
  const [dialogOpen, setDialogOpen] = useState(false);
@@ -22781,7 +23047,7 @@ function formatDate(iso) {
22781
23047
  year: "numeric"
22782
23048
  });
22783
23049
  }
22784
- function SaveManagerContent() {
23050
+ function SaveManagerContent({ className, id }) {
22785
23051
  const [mode, setMode] = useState("load");
22786
23052
  const [groups, setGroups] = useState([]);
22787
23053
  const [loading, setLoading] = useState(true);
@@ -22961,7 +23227,8 @@ function SaveManagerContent() {
22961
23227
  };
22962
23228
  const totalSaves = groups.reduce((n, g) => n + g.saves.length, 0);
22963
23229
  return /* @__PURE__ */ jsxs("div", {
22964
- class: "save-manager",
23230
+ id,
23231
+ class: className ? `save-manager ${className}` : "save-manager",
22965
23232
  children: [
22966
23233
  /* @__PURE__ */ jsx("div", {
22967
23234
  class: "saves-header",
@@ -23122,8 +23389,12 @@ function SaveManagerContent() {
23122
23389
  }
23123
23390
  defineMacro({
23124
23391
  name: "save-manager",
23125
- render() {
23126
- return /* @__PURE__ */ jsx(SaveManagerContent, {});
23392
+ interpolate: true,
23393
+ render(_props, ctx) {
23394
+ return /* @__PURE__ */ jsx(SaveManagerContent, {
23395
+ className: ctx.className,
23396
+ id: ctx.id
23397
+ });
23127
23398
  }
23128
23399
  });
23129
23400
  //#endregion
@@ -23173,10 +23444,11 @@ function SettingControl({ name, def }) {
23173
23444
  });
23174
23445
  }
23175
23446
  }
23176
- function SettingsControlsContent() {
23447
+ function SettingsControlsContent({ className, id }) {
23177
23448
  const defs = settings.getDefinitions();
23178
23449
  return /* @__PURE__ */ jsx("div", {
23179
- class: "settings-controls",
23450
+ id,
23451
+ class: className ? `settings-controls ${className}` : "settings-controls",
23180
23452
  children: Array.from(defs.entries()).map(([name, def]) => /* @__PURE__ */ jsx(SettingControl, {
23181
23453
  name,
23182
23454
  def
@@ -23185,8 +23457,12 @@ function SettingsControlsContent() {
23185
23457
  }
23186
23458
  defineMacro({
23187
23459
  name: "settings-controls",
23188
- render() {
23189
- return /* @__PURE__ */ jsx(SettingsControlsContent, {});
23460
+ interpolate: true,
23461
+ render(_props, ctx) {
23462
+ return /* @__PURE__ */ jsx(SettingsControlsContent, {
23463
+ className: ctx.className,
23464
+ id: ctx.id
23465
+ });
23190
23466
  }
23191
23467
  });
23192
23468
  //#endregion
@@ -23236,6 +23512,7 @@ defineMacro({
23236
23512
  defineMacro({
23237
23513
  name: "nobr",
23238
23514
  block: true,
23515
+ interpolate: true,
23239
23516
  render({ children = [] }, ctx) {
23240
23517
  return ctx.wrap(ctx.h(NobrContext.Provider, { value: true }, ctx.renderNodes(children, { nobr: true })));
23241
23518
  },
@@ -23323,6 +23600,7 @@ function useVariableAction(ctx, action) {
23323
23600
  function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? String(input) : "") {
23324
23601
  defineMacro({
23325
23602
  name,
23603
+ interpolate: true,
23326
23604
  storeVar: true,
23327
23605
  parameters: [VARIABLE_PARAMETER, {
23328
23606
  name: "placeholder",
@@ -23366,6 +23644,7 @@ defineInputMacro("textarea");
23366
23644
  //#region src/components/macros/Checkbox.tsx
23367
23645
  defineMacro({
23368
23646
  name: "checkbox",
23647
+ interpolate: true,
23369
23648
  storeVar: true,
23370
23649
  parameters: [VARIABLE_PARAMETER, {
23371
23650
  name: "label",
@@ -23378,7 +23657,7 @@ defineMacro({
23378
23657
  type: "checkbox",
23379
23658
  label: label || ctx.varName || "",
23380
23659
  value: !!ctx.value,
23381
- perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.value)
23660
+ perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.getValue())
23382
23661
  });
23383
23662
  return /* @__PURE__ */ jsxs("label", {
23384
23663
  id: ctx.id,
@@ -23386,7 +23665,7 @@ defineMacro({
23386
23665
  children: [/* @__PURE__ */ jsx("input", {
23387
23666
  type: "checkbox",
23388
23667
  checked: !!ctx.value,
23389
- onChange: () => ctx.setValue(!ctx.value)
23668
+ onChange: (e) => ctx.setValue(e.target.checked)
23390
23669
  }), label ? ` ${label}` : null]
23391
23670
  });
23392
23671
  }
@@ -23395,6 +23674,7 @@ defineMacro({
23395
23674
  //#region src/components/macros/Radiobutton.tsx
23396
23675
  defineMacro({
23397
23676
  name: "radiobutton",
23677
+ interpolate: true,
23398
23678
  storeVar: true,
23399
23679
  parameters: [
23400
23680
  VARIABLE_PARAMETER,
@@ -23436,6 +23716,7 @@ defineMacro({
23436
23716
  //#region src/components/macros/Listbox.tsx
23437
23717
  defineMacro({
23438
23718
  name: "listbox",
23719
+ interpolate: true,
23439
23720
  subMacros: ["option"],
23440
23721
  storeVar: true,
23441
23722
  parameters: [VARIABLE_PARAMETER],
@@ -23466,6 +23747,7 @@ defineMacro({
23466
23747
  defineMacro({
23467
23748
  name: "cycle",
23468
23749
  block: true,
23750
+ interpolate: true,
23469
23751
  storeVar: true,
23470
23752
  parameters: [VARIABLE_PARAMETER],
23471
23753
  render({ children = [] }, ctx) {
@@ -23499,6 +23781,7 @@ defineMacro({
23499
23781
  defineMacro({
23500
23782
  name: "span",
23501
23783
  block: true,
23784
+ interpolate: true,
23502
23785
  render({ children = [] }, ctx) {
23503
23786
  return ctx.wrap(ctx.renderNodes(children));
23504
23787
  },
@@ -23625,13 +23908,21 @@ function orStop(parse, where = "") {
23625
23908
  }
23626
23909
  }
23627
23910
  /**
23911
+ * What reading arguments depends on, with the macros and widgets known now:
23912
+ * the declared parameters of macros and what the parameters of widgets hold.
23913
+ * (The markup and the variable references are read by the same.)
23914
+ */
23915
+ function knownParameters() {
23916
+ return parameterLookup([...getMacroRegistry(), ...widgetMacros()]);
23917
+ }
23918
+ /**
23628
23919
  * The undeclared variables the passages refer to, with the macros known now:
23629
23920
  * the input macros that bind a variable (registered by author JS or
23630
23921
  * StoryInit) and the roles of their parameters decide what is a reference.
23631
23922
  */
23632
23923
  function variableErrors(storyData, schema) {
23633
23924
  const storeVarMacros = getMacroRegistry().filter((m) => m.storeVar).map((m) => m.name);
23634
- return validatePassages(storyData.passages, schema, storeVarMacros);
23925
+ return validatePassages(storyData.passages, schema, storeVarMacros, knownParameters());
23635
23926
  }
23636
23927
  /**
23637
23928
  * The markup errors (malformed markup, unknown macros, syntax errors in
@@ -23639,11 +23930,10 @@ function variableErrors(storyData, schema) {
23639
23930
  * known now.
23640
23931
  */
23641
23932
  function markupErrors(storyData, only) {
23642
- const macros = getMacroRegistry();
23643
23933
  return validateMarkup(storyData.passages.values(), {
23644
23934
  isKnownMacro: (name) => !!getMacro(name) || isSubMacro(name) || !!getWidget(name),
23645
- macroNames: macros.map((m) => m.name),
23646
- parametersOf: parameterLookup([...macros, ...widgetMacros()]),
23935
+ macroNames: getMacroRegistry().map((m) => m.name),
23936
+ parametersOf: knownParameters(),
23647
23937
  only
23648
23938
  }).map(formatDiagnostic);
23649
23939
  }
@@ -23714,11 +24004,9 @@ function boot() {
23714
24004
  const root = document.getElementById("root");
23715
24005
  if (!root) throw new Error("spindle: No <div id=\"root\"> element found.");
23716
24006
  render(/* @__PURE__ */ jsx(App, {}), root);
23717
- const pending = getReadyPromise();
23718
- if (pending) pending.then(passageShown).then(() => {
24007
+ (getReadyPromise() ?? Promise.resolve()).then(passageShown).then(() => {
23719
24008
  document.dispatchEvent(new CustomEvent(":storyready"));
23720
24009
  });
23721
- else document.dispatchEvent(new CustomEvent(":storyready"));
23722
24010
  }
23723
24011
  //#endregion
23724
24012
  //#region src/headless.ts