@rohal12/spindle 0.64.30 → 0.64.32

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.
@@ -9359,13 +9359,13 @@ var VALID_EVENTS = /* @__PURE__ */ new Set([
9359
9359
  "dialogrender",
9360
9360
  "dialogclose"
9361
9361
  ]);
9362
- var listeners$2 = /* @__PURE__ */ new Map();
9362
+ var listeners$3 = /* @__PURE__ */ new Map();
9363
9363
  function on(event, cb) {
9364
9364
  if (!VALID_EVENTS.has(event)) throw new Error(`spindle: Unknown event "${event}".`);
9365
- let set = listeners$2.get(event);
9365
+ let set = listeners$3.get(event);
9366
9366
  if (!set) {
9367
9367
  set = /* @__PURE__ */ new Set();
9368
- listeners$2.set(event, set);
9368
+ listeners$3.set(event, set);
9369
9369
  }
9370
9370
  set.add(cb);
9371
9371
  return () => {
@@ -9374,7 +9374,7 @@ function on(event, cb) {
9374
9374
  }
9375
9375
  /** Call `call` with each listener of `event`. */
9376
9376
  function forEachListener(event, call) {
9377
- const set = listeners$2.get(event);
9377
+ const set = listeners$3.get(event);
9378
9378
  if (!set) return;
9379
9379
  for (const cb of [...set]) call(cb);
9380
9380
  }
@@ -9507,13 +9507,13 @@ function registerAction(action, dialog = null, panel = null, element = null) {
9507
9507
  console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
9508
9508
  entries.push(entry);
9509
9509
  } else actions.set(id, [entry]);
9510
- notify();
9510
+ notify$1();
9511
9511
  return {
9512
9512
  update(next) {
9513
9513
  const current = actions.get(id);
9514
9514
  if (!current?.includes(entry)) return;
9515
9515
  entry.action = next;
9516
- if (current[current.length - 1] === entry) notify();
9516
+ if (current[current.length - 1] === entry) notify$1();
9517
9517
  },
9518
9518
  unregister() {
9519
9519
  const current = actions.get(id);
@@ -9524,7 +9524,7 @@ function registerAction(action, dialog = null, panel = null, element = null) {
9524
9524
  actions.delete(id);
9525
9525
  reserved.delete(id);
9526
9526
  }
9527
- if (index === current.length) notify();
9527
+ if (index === current.length) notify$1();
9528
9528
  }
9529
9529
  };
9530
9530
  }
@@ -9594,7 +9594,7 @@ function resetIdCounters() {
9594
9594
  idCounters.clear();
9595
9595
  for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
9596
9596
  }
9597
- function notify() {
9597
+ function notify$1() {
9598
9598
  emit("actionsChanged");
9599
9599
  }
9600
9600
  // src/components/dialog-close-context.ts
@@ -13916,6 +13916,204 @@ function lastEnd(body) {
13916
13916
  const branch = last(body.branches);
13917
13917
  return last(branch?.children ?? body.children)?.end ?? branch?.tag.end;
13918
13918
  }
13919
+ // src/components/macros/arg-utils.ts
13920
+ /**
13921
+ * Shared helpers for macros that split or read their raw argument text by
13922
+ * hand. Their lexical model is the expression lexer's (`js-lexer.ts`):
13923
+ * string, template and regex literals and comments are opaque (a backslash
13924
+ * inside a literal escapes the character after it, and `${…}` parts of a
13925
+ * template are code), `/` opens a regex only where an operand is expected,
13926
+ * and `(`/`[`/`{` nest.
13927
+ */
13928
+ /** True for a whitespace character. */
13929
+ function isWhitespace(ch) {
13930
+ return /\s/.test(ch);
13931
+ }
13932
+ function isOpener(ch) {
13933
+ return ch === "(" || ch === "[" || ch === "{";
13934
+ }
13935
+ function isCloser(ch) {
13936
+ return ch === ")" || ch === "]" || ch === "}";
13937
+ }
13938
+ /**
13939
+ * Given the index of an opening quote (`"`, `'` or a backtick), return the
13940
+ * index just past its closing quote, or `src.length` if it is unterminated.
13941
+ * A backslash escapes the character after it, so a quote preceded by an even
13942
+ * run of backslashes still closes the string and one preceded by an odd run
13943
+ * does not. Inside a template literal, `${…}` interpolations are lexed as
13944
+ * code, so quotes, backticks, braces and regexes inside them do not end it.
13945
+ */
13946
+ function skipString(src, start) {
13947
+ return src[start] === "`" ? lexTemplate(src, start) : scanStringLiteral(src, start).end;
13948
+ }
13949
+ /**
13950
+ * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
13951
+ * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
13952
+ * are kept as written, so code and regex text inside the string survive.
13953
+ */
13954
+ function unescapeQuoted(body) {
13955
+ return body.replace(/\\(["'\\])/g, "$1");
13956
+ }
13957
+ /**
13958
+ * Read the `"…"` or `'…'` string whose opening quote is at `start`.
13959
+ * Returns its unescaped value and the index just past the closing quote, or
13960
+ * `null` if there is no such quote at `start` or the string is unterminated.
13961
+ * With `tolerant`, an unterminated string instead extends to its scanned end.
13962
+ */
13963
+ function readQuoted(src, start, tolerant = false) {
13964
+ const quote = src[start];
13965
+ if (quote !== "\"" && quote !== "'") return null;
13966
+ const { end, closed } = scanStringLiteral(src, start);
13967
+ if (!closed && !tolerant) return null;
13968
+ return {
13969
+ value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
13970
+ end
13971
+ };
13972
+ }
13973
+ /**
13974
+ * The unescaped value of `src` when it is exactly one `"…"` or `'…'` string
13975
+ * (as with `readQuoted`), otherwise `null`.
13976
+ */
13977
+ function readWholeQuoted(src) {
13978
+ const quoted = readQuoted(src, 0);
13979
+ return quoted && quoted.end === src.length ? quoted.value : null;
13980
+ }
13981
+ /** A dialog body's passage name, optionally enclosed in matching quotes. */
13982
+ function readPassageBody(src) {
13983
+ const name = src.trim();
13984
+ return readWholeQuoted(name) ?? name;
13985
+ }
13986
+ /**
13987
+ * Strip an optional quote from each end of an unquoted-or-loosely-quoted
13988
+ * argument (`"Red`, `Red'`), leaving at least one character. This is the
13989
+ * lenient fallback for labels that are not one well-formed quoted string.
13990
+ */
13991
+ function stripLooseQuotes(src) {
13992
+ return /^["']?(.+?)["']?$/s.exec(src)?.[1] ?? src;
13993
+ }
13994
+ /** An operator character, or an operator keyword, at the end of code. */
13995
+ var TRAILING_OPERATOR_RE = /(?:[-+*/%&|^!~=<>?:,.]|(?:^|[^\w$@.])(?:typeof|void|new|delete|in|instanceof|await|yield))$/;
13996
+ /**
13997
+ * Whether `src` ends with an operator that still needs an operand (`$a +`,
13998
+ * `$a+`, `$x ==`, `typeof`), so it cannot be a complete value on its own.
13999
+ * Only code counts: the closing `/` of a regex literal is not division, a
14000
+ * variable reference (`$a`, `%name`, ...) is an operand, trailing comments are skipped,
14001
+ * and a postfix `++` or `--` completes its operand.
14002
+ */
14003
+ function endsWithOperator(src) {
14004
+ let end = -1;
14005
+ lexJs(src, {
14006
+ code(ch, i, nesting) {
14007
+ if (nesting === 0 && !isWhitespace(ch)) end = i + 1;
14008
+ },
14009
+ literal(text, _i, nesting) {
14010
+ const comment = text.startsWith("//") || text.startsWith("/*");
14011
+ if (nesting === 0 && !comment) end = -1;
14012
+ },
14013
+ variable(_sigil, _name, _i, nesting) {
14014
+ if (nesting === 0) end = -1;
14015
+ }
14016
+ });
14017
+ if (end < 0) return false;
14018
+ const code = src.slice(0, end);
14019
+ if (/(?:\+\+|--)$/.test(code)) return false;
14020
+ return TRAILING_OPERATOR_RE.test(code);
14021
+ }
14022
+ /**
14023
+ * Indices of the characters in `src` that satisfy `isSeparator` and sit at
14024
+ * depth 0: in code outside string, template and regex literals and comments,
14025
+ * and outside `()`, `[]` and `{}` pairs.
14026
+ */
14027
+ function topLevelIndices(src, isSeparator) {
14028
+ const indices = [];
14029
+ let depth = 0;
14030
+ lexJs(src, { code(ch, i, nesting) {
14031
+ if (nesting > 0) return;
14032
+ if (isOpener(ch)) depth++;
14033
+ else if (isCloser(ch)) depth--;
14034
+ else if (depth === 0 && isSeparator(ch)) indices.push(i);
14035
+ } });
14036
+ return indices;
14037
+ }
14038
+ /**
14039
+ * The segments of `src` between its depth-0 separators (see
14040
+ * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
14041
+ * `n` separators always give `n + 1` segments.
14042
+ */
14043
+ function topLevelSpans(src, isSeparator) {
14044
+ const spans = [];
14045
+ let from = 0;
14046
+ for (const i of topLevelIndices(src, isSeparator)) {
14047
+ spans.push([from, i]);
14048
+ from = i + 1;
14049
+ }
14050
+ spans.push([from, src.length]);
14051
+ return spans;
14052
+ }
14053
+ /**
14054
+ * Check whether a whitespace-delimited token looks like a standalone value
14055
+ * (not an operator or partial expression): it starts like a value and does
14056
+ * not end with an operator still waiting for its operand.
14057
+ */
14058
+ function isStandaloneValue(token) {
14059
+ return startsLikeValue(token) && !endsWithOperator(token);
14060
+ }
14061
+ function startsLikeValue(token) {
14062
+ const first = token[0];
14063
+ if (first === "\"" || first === "'" || first === "`") return true;
14064
+ if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
14065
+ if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
14066
+ if (first === "(" || first === "[" || first === "{") return true;
14067
+ if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
14068
+ if (first === "!" && token.length > 1 && token[1] !== "=") return true;
14069
+ return false;
14070
+ }
14071
+ /**
14072
+ * Try to split a raw string on whitespace at depth 0 (respecting strings,
14073
+ * template literals, parentheses, brackets, and braces). Each resulting token
14074
+ * must pass `isStandaloneValue()` or the split is rejected and `null` is
14075
+ * returned. The spans are those of the tokens in `raw`.
14076
+ */
14077
+ function trySplitOnWhitespace(raw) {
14078
+ const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
14079
+ if (args.length < 2) return null;
14080
+ for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
14081
+ return args;
14082
+ }
14083
+ /** `span` less the whitespace at its ends. */
14084
+ function trimmed$1(src, [start, end]) {
14085
+ const text = src.slice(start, end);
14086
+ const lead = text.length - text.trimStart().length;
14087
+ return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
14088
+ }
14089
+ /**
14090
+ * Where the arguments in `raw` are written (see `splitArgs`), as spans of
14091
+ * `raw`.
14092
+ */
14093
+ function splitArgSpans(raw) {
14094
+ const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
14095
+ const hasComma = args.length > 1;
14096
+ const last = args[args.length - 1];
14097
+ if (last[0] === last[1]) args.pop();
14098
+ if (!hasComma && args.length === 1) {
14099
+ const [start, end] = args[0];
14100
+ const split = trySplitOnWhitespace(raw.slice(start, end));
14101
+ if (split) return split.map(([a, b]) => [start + a, start + b]);
14102
+ }
14103
+ return args;
14104
+ }
14105
+ /**
14106
+ * Split rawArgs by commas, respecting parentheses, brackets, braces, and
14107
+ * strings. When no top-level commas are present, also supports adjacent quoted
14108
+ * string literals separated by whitespace (e.g. `"Label" "target"`).
14109
+ */
14110
+ function splitArgs(raw) {
14111
+ return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
14112
+ }
14113
+ /** `text` as a regular expression source that matches it literally. */
14114
+ function escapeRegExp(text) {
14115
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14116
+ }
13919
14117
  // src/markup/code-end.ts
13920
14118
  /**
13921
14119
  * A quote directly after a letter/digit is an apostrophe (don't), not a
@@ -14020,6 +14218,8 @@ function scanLenient(input, start) {
14020
14218
  * input (see `OnOpenCodeEnd`); the ends it finds are the same.
14021
14219
  */
14022
14220
  function jsCodeEnd(onOpenEnd) {
14221
+ let indexedInput = "";
14222
+ const rawClosers = /* @__PURE__ */ new Map();
14023
14223
  return {
14024
14224
  closeBrace(input, codeStart, lenientStart) {
14025
14225
  let ranOut = false;
@@ -14030,10 +14230,18 @@ function jsCodeEnd(onOpenEnd) {
14030
14230
  return end;
14031
14231
  },
14032
14232
  rawBodyEnd(input, bodyStart, name) {
14033
- const closer = `\\{/${name}\\s*\\}`;
14034
- const first = new RegExp(closer, "gi");
14035
- first.lastIndex = bodyStart;
14036
- const firstAt = first.exec(input)?.index ?? -1;
14233
+ if (indexedInput !== input) {
14234
+ indexedInput = input;
14235
+ rawClosers.clear();
14236
+ }
14237
+ name = name.toLowerCase();
14238
+ const closer = `\\{/${escapeRegExp(name)}\\s*\\}`;
14239
+ let candidates = rawClosers.get(name);
14240
+ if (!candidates) {
14241
+ candidates = Array.from(input.matchAll(new RegExp(closer, "gi")), (m) => m.index);
14242
+ rawClosers.set(name, candidates);
14243
+ }
14244
+ const firstAt = candidates[upperBound(candidates, bodyStart - 1)] ?? -1;
14037
14245
  if (firstAt === -1) return -1;
14038
14246
  const at = new RegExp(closer, "iy");
14039
14247
  let ranOut = false;
@@ -14046,7 +14254,7 @@ function jsCodeEnd(onOpenEnd) {
14046
14254
  onRunOut: () => ranOut = true
14047
14255
  });
14048
14256
  if (end !== -1) return end;
14049
- if (onOpenEnd && (ranOut || new RegExp(`\\{/${name}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
14257
+ if (onOpenEnd && (ranOut || new RegExp(`\\{/${escapeRegExp(name)}\\s*$`, "i").test(input))) onOpenEnd(input, bodyStart);
14050
14258
  return firstAt;
14051
14259
  }
14052
14260
  };
@@ -14055,12 +14263,13 @@ function jsCodeEnd(onOpenEnd) {
14055
14263
  var defaultCodeEnd = jsCodeEnd();
14056
14264
  /**
14057
14265
  * Index possible brace ends for repeated recovery attempts in one template.
14058
- * Within plain code, nested braces must close first. At a quote, slash or
14059
- * escape we stop making lexical assumptions, but the remaining raw `}`s
14060
- * still bound how many pending braces could close. Indexing visits each
14061
- * opener once, so unmatched plain-code openers can skip suffix scans.
14266
+ * Within plain code, nested braces must close first. At a quote, slash,
14267
+ * escape or HTML-style comment we stop making lexical assumptions, but the
14268
+ * remaining raw `}`s still bound how many pending braces could close.
14269
+ * Indexing visits each opener once, so unmatched plain-code openers can
14270
+ * skip suffix scans.
14062
14271
  */
14063
- function indexCodeEnds(input) {
14272
+ function indexCodeEnds(input, closeBrace = defaultCodeEnd.closeBrace) {
14064
14273
  const possible = /* @__PURE__ */ new Set();
14065
14274
  const pending = [];
14066
14275
  let remaining = 0;
@@ -14080,12 +14289,12 @@ function indexCodeEnds(input) {
14080
14289
  remaining--;
14081
14290
  const open = pending.pop();
14082
14291
  if (open !== void 0) possible.add(open);
14083
- } else if (/['"`/\\]/.test(c)) uncertain();
14292
+ } else if (/['"`/\\]/.test(c) || input.startsWith("<!--", i) || input.startsWith("-->", i)) uncertain();
14084
14293
  }
14085
14294
  return (start, codeStart = start, limit = input.length) => {
14086
14295
  if (start > lastBrace || codeStart >= limit) return -1;
14087
14296
  const source = limit === input.length ? input : input.slice(0, limit);
14088
- if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return defaultCodeEnd.closeBrace(source, codeStart, start);
14297
+ if (input[start - 1] !== "{" || possible.has(start - 1) || input.slice(start, codeStart).includes("{")) return closeBrace(source, codeStart, start);
14089
14298
  const base = Math.max(0, codeStart - 1);
14090
14299
  const end = parsedCodeEnd(source.slice(base), codeStart - base, "expression");
14091
14300
  return end < 0 ? -1 : base + end;
@@ -14441,10 +14650,10 @@ function createListeners() {
14441
14650
  // src/runtime-errors.ts
14442
14651
  var errors = [];
14443
14652
  var nextId = 1;
14444
- var listeners$1 = createListeners();
14653
+ var listeners$2 = createListeners();
14445
14654
  function update(next) {
14446
14655
  errors = next;
14447
- listeners$1.notify();
14656
+ listeners$2.notify();
14448
14657
  }
14449
14658
  /**
14450
14659
  * Show `error` on the page, after `context` (what failed). The same error
@@ -14484,205 +14693,7 @@ function getRuntimeErrors() {
14484
14693
  return errors;
14485
14694
  }
14486
14695
  /** Call `listener` whenever the shown errors change; returns unsubscribe. */
14487
- var subscribeRuntimeErrors = listeners$1.subscribe;
14488
- // src/components/macros/arg-utils.ts
14489
- /**
14490
- * Shared helpers for macros that split or read their raw argument text by
14491
- * hand. Their lexical model is the expression lexer's (`js-lexer.ts`):
14492
- * string, template and regex literals and comments are opaque (a backslash
14493
- * inside a literal escapes the character after it, and `${…}` parts of a
14494
- * template are code), `/` opens a regex only where an operand is expected,
14495
- * and `(`/`[`/`{` nest.
14496
- */
14497
- /** True for a whitespace character. */
14498
- function isWhitespace(ch) {
14499
- return /\s/.test(ch);
14500
- }
14501
- function isOpener(ch) {
14502
- return ch === "(" || ch === "[" || ch === "{";
14503
- }
14504
- function isCloser(ch) {
14505
- return ch === ")" || ch === "]" || ch === "}";
14506
- }
14507
- /**
14508
- * Given the index of an opening quote (`"`, `'` or a backtick), return the
14509
- * index just past its closing quote, or `src.length` if it is unterminated.
14510
- * A backslash escapes the character after it, so a quote preceded by an even
14511
- * run of backslashes still closes the string and one preceded by an odd run
14512
- * does not. Inside a template literal, `${…}` interpolations are lexed as
14513
- * code, so quotes, backticks, braces and regexes inside them do not end it.
14514
- */
14515
- function skipString(src, start) {
14516
- return src[start] === "`" ? lexTemplate(src, start) : scanStringLiteral(src, start).end;
14517
- }
14518
- /**
14519
- * Undo the escapes allowed in a literal quoted macro argument: `\"`, `\'`
14520
- * and `\\` become `"`, `'` and `\`. Other backslash sequences (`\n`, `\d`)
14521
- * are kept as written, so code and regex text inside the string survive.
14522
- */
14523
- function unescapeQuoted(body) {
14524
- return body.replace(/\\(["'\\])/g, "$1");
14525
- }
14526
- /**
14527
- * Read the `"…"` or `'…'` string whose opening quote is at `start`.
14528
- * Returns its unescaped value and the index just past the closing quote, or
14529
- * `null` if there is no such quote at `start` or the string is unterminated.
14530
- * With `tolerant`, an unterminated string instead extends to its scanned end.
14531
- */
14532
- function readQuoted(src, start, tolerant = false) {
14533
- const quote = src[start];
14534
- if (quote !== "\"" && quote !== "'") return null;
14535
- const { end, closed } = scanStringLiteral(src, start);
14536
- if (!closed && !tolerant) return null;
14537
- return {
14538
- value: unescapeQuoted(src.slice(start + 1, closed ? end - 1 : end)),
14539
- end
14540
- };
14541
- }
14542
- /**
14543
- * The unescaped value of `src` when it is exactly one `"…"` or `'…'` string
14544
- * (as with `readQuoted`), otherwise `null`.
14545
- */
14546
- function readWholeQuoted(src) {
14547
- const quoted = readQuoted(src, 0);
14548
- return quoted && quoted.end === src.length ? quoted.value : null;
14549
- }
14550
- /** A dialog body's passage name, optionally enclosed in matching quotes. */
14551
- function readPassageBody(src) {
14552
- const name = src.trim();
14553
- return readWholeQuoted(name) ?? name;
14554
- }
14555
- /**
14556
- * Strip an optional quote from each end of an unquoted-or-loosely-quoted
14557
- * argument (`"Red`, `Red'`), leaving at least one character. This is the
14558
- * lenient fallback for labels that are not one well-formed quoted string.
14559
- */
14560
- function stripLooseQuotes(src) {
14561
- return /^["']?(.+?)["']?$/s.exec(src)?.[1] ?? src;
14562
- }
14563
- /** An operator character, or an operator keyword, at the end of code. */
14564
- var TRAILING_OPERATOR_RE = /(?:[-+*/%&|^!~=<>?:,.]|(?:^|[^\w$@.])(?:typeof|void|new|delete|in|instanceof|await|yield))$/;
14565
- /**
14566
- * Whether `src` ends with an operator that still needs an operand (`$a +`,
14567
- * `$a+`, `$x ==`, `typeof`), so it cannot be a complete value on its own.
14568
- * Only code counts: the closing `/` of a regex literal is not division, a
14569
- * variable reference (`$a`, `%name`, ...) is an operand, trailing comments are skipped,
14570
- * and a postfix `++` or `--` completes its operand.
14571
- */
14572
- function endsWithOperator(src) {
14573
- let end = -1;
14574
- lexJs(src, {
14575
- code(ch, i, nesting) {
14576
- if (nesting === 0 && !isWhitespace(ch)) end = i + 1;
14577
- },
14578
- literal(text, _i, nesting) {
14579
- const comment = text.startsWith("//") || text.startsWith("/*");
14580
- if (nesting === 0 && !comment) end = -1;
14581
- },
14582
- variable(_sigil, _name, _i, nesting) {
14583
- if (nesting === 0) end = -1;
14584
- }
14585
- });
14586
- if (end < 0) return false;
14587
- const code = src.slice(0, end);
14588
- if (/(?:\+\+|--)$/.test(code)) return false;
14589
- return TRAILING_OPERATOR_RE.test(code);
14590
- }
14591
- /**
14592
- * Indices of the characters in `src` that satisfy `isSeparator` and sit at
14593
- * depth 0: in code outside string, template and regex literals and comments,
14594
- * and outside `()`, `[]` and `{}` pairs.
14595
- */
14596
- function topLevelIndices(src, isSeparator) {
14597
- const indices = [];
14598
- let depth = 0;
14599
- lexJs(src, { code(ch, i, nesting) {
14600
- if (nesting > 0) return;
14601
- if (isOpener(ch)) depth++;
14602
- else if (isCloser(ch)) depth--;
14603
- else if (depth === 0 && isSeparator(ch)) indices.push(i);
14604
- } });
14605
- return indices;
14606
- }
14607
- /**
14608
- * The segments of `src` between its depth-0 separators (see
14609
- * `topLevelIndices`), as spans: untrimmed, and empty segments are kept, so
14610
- * `n` separators always give `n + 1` segments.
14611
- */
14612
- function topLevelSpans(src, isSeparator) {
14613
- const spans = [];
14614
- let from = 0;
14615
- for (const i of topLevelIndices(src, isSeparator)) {
14616
- spans.push([from, i]);
14617
- from = i + 1;
14618
- }
14619
- spans.push([from, src.length]);
14620
- return spans;
14621
- }
14622
- /**
14623
- * Check whether a whitespace-delimited token looks like a standalone value
14624
- * (not an operator or partial expression): it starts like a value and does
14625
- * not end with an operator still waiting for its operand.
14626
- */
14627
- function isStandaloneValue(token) {
14628
- return startsLikeValue(token) && !endsWithOperator(token);
14629
- }
14630
- function startsLikeValue(token) {
14631
- const first = token[0];
14632
- if (first === "\"" || first === "'" || first === "`") return true;
14633
- if (/^[$_@]\w|^%[A-Za-z_]/.test(token)) return true;
14634
- if (/^[+-]?(?:\d|\.\d)/.test(token)) return true;
14635
- if (first === "(" || first === "[" || first === "{") return true;
14636
- if (/^(?:true|false|null|undefined)(?![\w$])/.test(token)) return true;
14637
- if (first === "!" && token.length > 1 && token[1] !== "=") return true;
14638
- return false;
14639
- }
14640
- /**
14641
- * Try to split a raw string on whitespace at depth 0 (respecting strings,
14642
- * template literals, parentheses, brackets, and braces). Each resulting token
14643
- * must pass `isStandaloneValue()` or the split is rejected and `null` is
14644
- * returned. The spans are those of the tokens in `raw`.
14645
- */
14646
- function trySplitOnWhitespace(raw) {
14647
- const args = topLevelSpans(raw, isWhitespace).filter(([a, b]) => b > a);
14648
- if (args.length < 2) return null;
14649
- for (const [a, b] of args) if (!isStandaloneValue(raw.slice(a, b))) return null;
14650
- return args;
14651
- }
14652
- /** `span` less the whitespace at its ends. */
14653
- function trimmed$1(src, [start, end]) {
14654
- const text = src.slice(start, end);
14655
- const lead = text.length - text.trimStart().length;
14656
- return [start + lead, Math.max(start + lead, end - (text.length - text.trimEnd().length))];
14657
- }
14658
- /**
14659
- * Where the arguments in `raw` are written (see `splitArgs`), as spans of
14660
- * `raw`.
14661
- */
14662
- function splitArgSpans(raw) {
14663
- const args = topLevelSpans(raw, (ch) => ch === ",").map((span) => trimmed$1(raw, span));
14664
- const hasComma = args.length > 1;
14665
- const last = args[args.length - 1];
14666
- if (last[0] === last[1]) args.pop();
14667
- if (!hasComma && args.length === 1) {
14668
- const [start, end] = args[0];
14669
- const split = trySplitOnWhitespace(raw.slice(start, end));
14670
- if (split) return split.map(([a, b]) => [start + a, start + b]);
14671
- }
14672
- return args;
14673
- }
14674
- /**
14675
- * Split rawArgs by commas, respecting parentheses, brackets, braces, and
14676
- * strings. When no top-level commas are present, also supports adjacent quoted
14677
- * string literals separated by whitespace (e.g. `"Label" "target"`).
14678
- */
14679
- function splitArgs(raw) {
14680
- return splitArgSpans(raw).map(([a, b]) => raw.slice(a, b));
14681
- }
14682
- /** `text` as a regular expression source that matches it literally. */
14683
- function escapeRegExp(text) {
14684
- return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
14685
- }
14696
+ var subscribeRuntimeErrors = listeners$2.subscribe;
14686
14697
  // src/components/macros/macro-args.ts
14687
14698
  /**
14688
14699
  * The macro argument layer: reads a macro's raw argument text into the
@@ -14862,14 +14873,28 @@ function trimmed(src, at) {
14862
14873
  function readGroup(params, src, args, { at: srcAt, spans, toolingSpans }) {
14863
14874
  let [text, at] = trimmed(src ?? "", srcAt);
14864
14875
  const alone = !params.some((p) => p.type !== "flag" && p.required);
14865
- for (const flag of params.filter((p) => p.type === "flag")) {
14866
- const rest = src === null ? null : takeFlag(text, flag.name, alone);
14867
- args[flag.name] = rest !== null;
14868
- if (rest) {
14869
- const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
14870
- toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
14871
- [text, at] = trimmed(slice(text, rest), at + rest[0]);
14876
+ const flags = params.filter((p) => p.type === "flag");
14877
+ for (const flag of flags) args[flag.name] = false;
14878
+ const byName = new Map(flags.map((flag) => [flag.name, flag]));
14879
+ while (text && byName.size) {
14880
+ const parts = terms(text);
14881
+ if (parts.length === 0) break;
14882
+ let changed = false;
14883
+ for (const name of [slice(text, parts[parts.length - 1]), slice(text, parts[0])]) {
14884
+ const flag = byName.get(name);
14885
+ if (!flag || args[flag.name]) continue;
14886
+ const rest = src === null ? null : takeFlag(text, flag.name, alone);
14887
+ if (rest) {
14888
+ args[flag.name] = true;
14889
+ byName.delete(flag.name);
14890
+ changed = true;
14891
+ const flagSpan = rest[0] > 0 ? [0, text.indexOf(flag.name) + flag.name.length] : [text.lastIndexOf(flag.name), text.length];
14892
+ toolingSpans?.set(flag, [at + flagSpan[0], at + flagSpan[1]]);
14893
+ [text, at] = trimmed(slice(text, rest), at + rest[0]);
14894
+ break;
14895
+ }
14872
14896
  }
14897
+ if (!changed) break;
14873
14898
  }
14874
14899
  const positional = params.filter((p) => p.type !== "flag");
14875
14900
  if (positional.length === 0) return;
@@ -15130,13 +15155,13 @@ function parseOrError(code, goal) {
15130
15155
  parses?.set(key, result);
15131
15156
  return result;
15132
15157
  }
15133
- /** Where character `index` of the code or text of `piece` is in the source. */
15158
+ /** Where boundary `index` of a piece's code, text or name is in the source. */
15134
15159
  function pieceOffset(piece, index) {
15135
15160
  return piece.sourceOffsets?.[index] ?? piece.offset + index;
15136
15161
  }
15137
15162
  /** How much of a piece's own text or code there is (not its source extent). */
15138
15163
  function extentOf(piece) {
15139
- return piece.kind === "code" ? piece.code.length : piece.kind === "text" ? piece.text.length : piece.length;
15164
+ return piece.kind === "code" ? piece.code.length : piece.kind === "text" ? piece.text.length : piece.kind === "passage" ? piece.name.length : piece.length;
15140
15165
  }
15141
15166
  /** Macros whose whole argument text is one expression: branch conditions. */
15142
15167
  var CONDITION_MACROS = /* @__PURE__ */ new Set([
@@ -15333,13 +15358,17 @@ function* codeAndText(src, tokens, parametersOf) {
15333
15358
  if (close > t + 1) {
15334
15359
  const text = src.slice(token.end, tokens[close].start);
15335
15360
  const written = text.trim();
15361
+ const at = token.end + text.indexOf(written);
15362
+ const nameValue = readPassageBody(written);
15363
+ const sourceOffsets = readWholeQuoted(written) !== null ? escapeOffsets(written.slice(1, -1), at + 1, nameValue, "quotes", true) : void 0;
15336
15364
  yield {
15337
15365
  kind: "passage",
15338
- name: readPassageBody(written),
15339
- offset: token.end + text.indexOf(written),
15366
+ name: nameValue,
15367
+ offset: at,
15340
15368
  length: written.length,
15341
15369
  macro: name,
15342
- label: src.slice(token.start, token.end)
15370
+ label: src.slice(token.start, token.end),
15371
+ ...sourceOffsets && { sourceOffsets }
15343
15372
  };
15344
15373
  }
15345
15374
  }
@@ -15429,7 +15458,7 @@ function nestedPiece(piece, toRoot, where) {
15429
15458
  nested: true,
15430
15459
  where
15431
15460
  };
15432
- if (piece.kind === "passage" || piece.kind === "argument-error") {
15461
+ if (piece.kind === "argument-error") {
15433
15462
  const length = toRoot(piece.offset + piece.length) - offset;
15434
15463
  return {
15435
15464
  ...piece,
@@ -15439,7 +15468,7 @@ function nestedPiece(piece, toRoot, where) {
15439
15468
  }
15440
15469
  const extent = extentOf(piece);
15441
15470
  const sourceOffsets = piece.sourceOffsets ? piece.sourceOffsets.map(toRoot) : toRoot(piece.offset + extent) - offset !== extent ? Array.from({ length: extent + 1 }, (_, i) => toRoot(piece.offset + i)) : void 0;
15442
- return sourceOffsets ? {
15471
+ const mapped = sourceOffsets ? {
15443
15472
  ...piece,
15444
15473
  ...nested,
15445
15474
  sourceOffsets
@@ -15447,6 +15476,10 @@ function nestedPiece(piece, toRoot, where) {
15447
15476
  ...piece,
15448
15477
  ...nested
15449
15478
  };
15479
+ return mapped.kind === "passage" ? {
15480
+ ...mapped,
15481
+ length: toRoot(piece.offset + mapped.length) - offset
15482
+ } : mapped;
15450
15483
  }
15451
15484
  /** An escape sequence of a JavaScript string literal (with its backslash). */
15452
15485
  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;
@@ -15475,9 +15508,10 @@ function escapeAt(raw, i, escapes) {
15475
15508
  * written as `raw` from `at` on (its escapes are those of `escapes`), is in
15476
15509
  * the source, and where the text ends. A character that an escape stands for
15477
15510
  * is where the escape begins. None when the text is where its length says, or
15478
- * is not that string.
15511
+ * is not that string. With `includeLinear`, return the map even without
15512
+ * escapes (a passage piece's offset includes the opening quote).
15479
15513
  */
15480
- function escapeOffsets(raw, at, value, escapes) {
15514
+ function escapeOffsets(raw, at, value, escapes, includeLinear = false) {
15481
15515
  const offsets = [];
15482
15516
  let escaped = false;
15483
15517
  let i = 0;
@@ -15493,8 +15527,14 @@ function escapeOffsets(raw, at, value, escapes) {
15493
15527
  escaped = true;
15494
15528
  i += escape.length;
15495
15529
  }
15530
+ while (raw[i] === "\\") {
15531
+ const escape = escapeAt(raw, i, escapes);
15532
+ if (!escape || escape.text.length !== 0) break;
15533
+ escaped = true;
15534
+ i += escape.length;
15535
+ }
15496
15536
  offsets.push(at + i);
15497
- return escaped ? offsets : void 0;
15537
+ return escaped || includeLinear ? offsets : void 0;
15498
15538
  }
15499
15539
  /** The code and text in the arguments `args` (at `offset`) of `macro`. */
15500
15540
  function* argPieces(args, offset, params, macro, label, navigation = []) {
@@ -15562,20 +15602,21 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
15562
15602
  const [start, end] = span;
15563
15603
  const written = args.slice(start, end);
15564
15604
  /** The name as written (quotes included), at the argument. */
15565
- const passage = (passageName) => ({
15605
+ const passage = (passageName, at, mode = escapes) => ({
15566
15606
  kind: "passage",
15567
15607
  name: passageName,
15568
15608
  offset: offset + start,
15569
15609
  length: end - start,
15570
15610
  macro: name,
15571
15611
  label,
15612
+ sourceOffsets: escapeOffsets(args.slice(at - offset), at, passageName, mode, true),
15572
15613
  ...navigation.includes(param.name) && { navigation: true }
15573
15614
  });
15574
15615
  const goal = codeGoal(param);
15575
15616
  if (param.type === "passage") {
15576
15617
  const target = passageTarget(value);
15577
15618
  if (target.kind === "name") {
15578
- yield passage(target.name);
15619
+ yield passage(target.name, offset + start + 1, "javascript");
15579
15620
  continue;
15580
15621
  }
15581
15622
  }
@@ -15608,7 +15649,7 @@ function* valuePieces(args, offset, params, values, spans, macro, label, escapes
15608
15649
  };
15609
15650
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
15610
15651
  yield piece;
15611
- } else if (holds === "passage") yield passage(value);
15652
+ } else if (holds === "passage") yield passage(value, at);
15612
15653
  else if (holds === "markup") {
15613
15654
  const piece = textPiece(value, at, `In the ${param.name} of {${macro}}: `);
15614
15655
  if (sourceOffsets) piece.sourceOffsets = sourceOffsets;
@@ -15690,9 +15731,8 @@ function locate(text, part, from) {
15690
15731
  return anywhere >= 0 ? anywhere : from;
15691
15732
  }
15692
15733
  // src/widgets/ast-scanner.ts
15693
- /** The declared parameters of the macros registered so far. */
15694
- var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
15695
- registeredParameters.source = getMacroParameters.source;
15734
+ /** Snapshot effective macro metadata once per scan. */
15735
+ var registeredParameters = () => parameterLookup(getMacroRegistry());
15696
15736
  /**
15697
15737
  * Whether the text of an attribute value or macro label renders a
15698
15738
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -15719,7 +15759,7 @@ function textContainsChildren(text, parametersOf, hooks, budget = new MarkupExpa
15719
15759
  * are read from it); a token made from an AST has none. Discovery hooks
15720
15760
  * also apply inside these texts, before widgets have been registered.
15721
15761
  */
15722
- function tokenTextContainsChildren(token, parametersOf = registeredParameters, src = "", hooks, budget) {
15762
+ function tokenTextContainsChildren(token, parametersOf = registeredParameters(), src = "", hooks, budget) {
15723
15763
  for (const piece of codeAndText(src, [token], parametersOf)) if (piece.kind === "text" && textContainsChildren(piece.text, parametersOf, hooks, budget)) return true;
15724
15764
  return false;
15725
15765
  }
@@ -15730,7 +15770,7 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
15730
15770
  * entered: its slot belongs to the innermost widget (as widgetDefinitions
15731
15771
  * reads it), and a definition renders nothing of its own.
15732
15772
  */
15733
- function astContainsChildren(nodes, parametersOf = registeredParameters, hooks, budget) {
15773
+ function astContainsChildren(nodes, parametersOf = registeredParameters(), hooks, budget) {
15734
15774
  const pending = [...nodes];
15735
15775
  while (pending.length) {
15736
15776
  const node = pending.pop();
@@ -15837,7 +15877,7 @@ function nameSpan(rawArgs) {
15837
15877
  * here as it is to the parser, and does not make a block widget (#387). In
15838
15878
  * nested definitions, it belongs to the innermost.
15839
15879
  */
15840
- function widgetDefinitions(passages, parametersOf = registeredParameters) {
15880
+ function widgetDefinitions(passages, parametersOf = registeredParameters()) {
15841
15881
  const list = [...passages];
15842
15882
  const scan = (replacesDo) => {
15843
15883
  const found = [];
@@ -15902,7 +15942,7 @@ function effectiveWidgetDefinitions(definitions) {
15902
15942
  * takes a body must be known before any passage is parsed, so that passages
15903
15943
  * invoking them nest their content (or don't) whatever the passage order.
15904
15944
  */
15905
- function effectiveWidgets(passages, parametersOf = registeredParameters) {
15945
+ function effectiveWidgets(passages, parametersOf = registeredParameters()) {
15906
15946
  return effectiveWidgetDefinitions(widgetDefinitions(passages, parametersOf));
15907
15947
  }
15908
15948
  // src/widgets/register-widget-def.ts
@@ -17625,7 +17665,7 @@ function HtmlNodeRenderer({ node }) {
17625
17665
  value: childNamespace,
17626
17666
  children
17627
17667
  });
17628
- const element = authorElement(namespace === "svg" ? svgTagName(node.tag) : node.tag, props, children, namespace === "math");
17668
+ const element = authorElement(namespace === "svg" ? svgTagName(node.tag) : tag, props, children, namespace === "math");
17629
17669
  return withAttributeErrors(errors, isRawRoot ? /* @__PURE__ */ jsx(RawTextContext.Provider, {
17630
17670
  value: true,
17631
17671
  children: element
@@ -21934,13 +21974,37 @@ function parseStoryData() {
21934
21974
  userScript
21935
21975
  };
21936
21976
  }
21977
+ // src/utils/variable-writes.ts
21978
+ /** Explicit writes, including assignments that leave a binding unchanged. */
21979
+ var listeners$1 = /* @__PURE__ */ new Set();
21980
+ function notifyVariableWrite(path) {
21981
+ for (const listener of listeners$1) listener(path);
21982
+ }
21983
+ /** Observe writes to a binding, its parent, or one of its children. */
21984
+ function subscribeVariableWrites(binding, onWrite) {
21985
+ const listener = (path) => {
21986
+ const length = Math.min(path.length, binding.length);
21987
+ for (let i = 0; i < length; i++) if (path[i] !== binding[i]) return;
21988
+ onWrite();
21989
+ };
21990
+ listeners$1.add(listener);
21991
+ return () => {
21992
+ listeners$1.delete(listener);
21993
+ };
21994
+ }
21937
21995
  // src/settings.ts
21938
21996
  var definitions = /* @__PURE__ */ new Map();
21939
21997
  var values = createNamespace();
21940
21998
  var storageLoaded = false;
21941
21999
  var unsubscribeStoryData = null;
21942
22000
  var listeners = /* @__PURE__ */ new Set();
21943
- /** Call `listener` after a setting changes; returns the unsubscribe. */
22001
+ var revision = 0;
22002
+ var getSettingsRevision = () => revision;
22003
+ function notify() {
22004
+ revision++;
22005
+ for (const listener of [...listeners]) listener();
22006
+ }
22007
+ /** Call `listener` after a definition or value changes; returns the unsubscribe. */
21944
22008
  function subscribeSettings(listener) {
21945
22009
  listeners.add(listener);
21946
22010
  return () => listeners.delete(listener);
@@ -21978,6 +22042,7 @@ function define(name, def) {
21978
22042
  definitions.set(name, def);
21979
22043
  if (!hasOwn(values, name)) values[name] = def.config.default;
21980
22044
  loadFromStorage();
22045
+ notify();
21981
22046
  }
21982
22047
  /** The value of setting `name` if it has the type of `fallback`, else that. */
21983
22048
  function valueOf(name, fallback) {
@@ -22025,7 +22090,7 @@ var settings = {
22025
22090
  values[name] = value;
22026
22091
  persist();
22027
22092
  if (unchanged) return;
22028
- for (const listener of [...listeners]) listener();
22093
+ notify();
22029
22094
  emit("settingchanged", name, value);
22030
22095
  },
22031
22096
  getAll() {
@@ -22139,6 +22204,7 @@ function defineMacro(config, source = "builtin") {
22139
22204
  ctx.value = getByPath(useStoryFields("variables").variables, segments);
22140
22205
  ctx.getValue = () => getByPath(readState().variables, segments);
22141
22206
  ctx.setValue = displayOnly ? refuse : (value) => {
22207
+ notifyVariableWrite(segments);
22142
22208
  runAsControlEdit(segments, () => {
22143
22209
  mutateState((work, adopt) => {
22144
22210
  setByPath(work.variables, segments, adopt(value), { createMissing: true });
@@ -22467,10 +22533,14 @@ function observableText(el, skip, visibilityRoot) {
22467
22533
  const localTarget = (use) => {
22468
22534
  use = instances.source(use);
22469
22535
  const href = use.getAttribute("href") ?? use.getAttributeNS("http://www.w3.org/1999/xlink", "href");
22470
- if (!href?.startsWith("#") || href.length === 1) return;
22536
+ if (!href) return;
22471
22537
  let id;
22472
22538
  try {
22473
- id = decodeURIComponent(href.slice(1));
22539
+ const url = new URL(href, use.baseURI);
22540
+ const current = new URL(use.ownerDocument.URL);
22541
+ if (url.href.split("#")[0] !== current.href.split("#")[0]) return;
22542
+ if (url.hash.length <= 1) return;
22543
+ id = decodeURIComponent(url.hash.slice(1));
22474
22544
  } catch {
22475
22545
  return;
22476
22546
  }
@@ -22529,7 +22599,7 @@ function observableText(el, skip, visibilityRoot) {
22529
22599
  } finally {
22530
22600
  instances.dispose();
22531
22601
  }
22532
- return out.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\s+$/g, "");
22602
+ return out.split("\n").map((line) => line.trimEnd()).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+/, "").trimEnd();
22533
22603
  }
22534
22604
  /**
22535
22605
  * The trimmed text of each error shown in the element, leaving out those
@@ -22849,7 +22919,11 @@ function createStoryAPI() {
22849
22919
  for (const [name] of entries) {
22850
22920
  const { isTransient, key } = parseName(name);
22851
22921
  warnIfUndeclared(isTransient, key);
22852
- if (!isTransient) recordHookWrite(key.split("."));
22922
+ if (!isTransient) {
22923
+ const path = key.split(".");
22924
+ recordHookWrite(path);
22925
+ notifyVariableWrite(path);
22926
+ }
22853
22927
  }
22854
22928
  if (entries.some(([k]) => k.includes("."))) {
22855
22929
  mutateState((work, adopt) => {
@@ -25119,7 +25193,10 @@ defineMacro({
25119
25193
  class: ctx.className ?? "story",
25120
25194
  children: [!renderDeferred && readyPassage && /* @__PURE__ */ jsx("div", {
25121
25195
  hidden: true,
25122
- children: renderPassageContent(readyPassage)
25196
+ children: /* @__PURE__ */ jsx(InterfaceContext.Provider, {
25197
+ value: false,
25198
+ children: renderPassageContent(readyPassage)
25199
+ })
25123
25200
  }, `ready-${navigationId}`), /* @__PURE__ */ jsx("div", {
25124
25201
  class: "passage-container",
25125
25202
  ref: containerRef,
@@ -26054,44 +26131,49 @@ function hotkeyTitle(label, key) {
26054
26131
  return key ? `${label} (${key})` : label;
26055
26132
  }
26056
26133
  function defineMenubarAction(config) {
26134
+ function Button({ className, id }) {
26135
+ const [dialogOpen, setDialogOpen] = useState(false);
26136
+ const setup = config.setup?.() ?? { perform: () => {} };
26137
+ const { disabled, title = config.title } = setup;
26138
+ const cls = className ? `menubar-button ${className}` : "menubar-button";
26139
+ const perform = config.dialog ? () => setDialogOpen(true) : config.confirm ? () => {
26140
+ if (confirm(config.confirm)) setup.perform();
26141
+ } : setup.perform;
26142
+ const action = useControlAction({
26143
+ type: config.actionType,
26144
+ key: config.name,
26145
+ authorId: id,
26146
+ label: typeof config.label === "string" ? config.label : config.name,
26147
+ disabled,
26148
+ perform: config.dialog ? () => setDialogOpen(true) : setup.perform
26149
+ });
26150
+ return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
26151
+ type: "button",
26152
+ ...actionAttributes(action, {
26153
+ id,
26154
+ cls
26155
+ }),
26156
+ onClick: perform,
26157
+ disabled,
26158
+ title,
26159
+ children: config.label
26160
+ }), config.dialog && dialogOpen && /* @__PURE__ */ jsx(PassageDialog, {
26161
+ passageName: config.dialog.passageName,
26162
+ fallbackMarkup: config.dialog.fallbackMarkup,
26163
+ panelClass: config.dialog.panelClass,
26164
+ label: typeof config.label === "string" ? config.label : config.name,
26165
+ onClose: () => setDialogOpen(false),
26166
+ showCloseButton: config.dialog.showCloseButton
26167
+ })] });
26168
+ }
26057
26169
  defineMacro({
26058
26170
  name: config.name,
26059
26171
  interpolate: true,
26060
26172
  render(_, ctx) {
26061
- if (config.hidden?.()) return null;
26062
- const [dialogOpen, setDialogOpen] = useState(false);
26063
- const setup = config.setup?.() ?? { perform: () => {} };
26064
- const { disabled, title = config.title } = setup;
26065
- const cls = ctx.className ? `menubar-button ${ctx.className}` : "menubar-button";
26066
- const perform = config.dialog ? () => setDialogOpen(true) : config.confirm ? () => {
26067
- if (confirm(config.confirm)) setup.perform();
26068
- } : setup.perform;
26069
- const action = useControlAction({
26070
- type: config.actionType,
26071
- key: config.name,
26072
- authorId: ctx.id,
26073
- label: typeof config.label === "string" ? config.label : config.name,
26074
- disabled,
26075
- perform: config.dialog ? () => setDialogOpen(true) : setup.perform
26173
+ return config.useHidden?.() ? null : /* @__PURE__ */ jsx(Button, {
26174
+ className: ctx.className,
26175
+ id: ctx.id
26076
26176
  });
26077
- return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
26078
- type: "button",
26079
- ...actionAttributes(action, {
26080
- id: ctx.id,
26081
- cls
26082
- }),
26083
- onClick: perform,
26084
- disabled,
26085
- title,
26086
- children: config.label
26087
- }), config.dialog && dialogOpen && /* @__PURE__ */ jsx(PassageDialog, {
26088
- passageName: config.dialog.passageName,
26089
- fallbackMarkup: config.dialog.fallbackMarkup,
26090
- panelClass: config.dialog.panelClass,
26091
- label: typeof config.label === "string" ? config.label : config.name,
26092
- onClose: () => setDialogOpen(false),
26093
- showCloseButton: config.dialog.showCloseButton
26094
- })] });
26095
26177
  }
26096
26178
  });
26097
26179
  }
@@ -26160,7 +26242,7 @@ defineMenubarAction({
26160
26242
  name: "settings",
26161
26243
  label: "Settings",
26162
26244
  actionType: "dialog",
26163
- hidden: () => !settings.hasAny(),
26245
+ useHidden: () => !useSyncExternalStore(subscribeSettings, settings.hasAny),
26164
26246
  dialog: {
26165
26247
  passageName: "Settings",
26166
26248
  fallbackMarkup: "{settings-controls}",
@@ -26688,6 +26770,7 @@ function SettingControl({ name, def }) {
26688
26770
  });
26689
26771
  }
26690
26772
  function SettingsControlsContent({ className, id }) {
26773
+ useSyncExternalStore(subscribeSettings, getSettingsRevision);
26691
26774
  const defs = settings.getDefinitions();
26692
26775
  return /* @__PURE__ */ jsx("div", {
26693
26776
  id,
@@ -26825,19 +26908,142 @@ var VARIABLE_PARAMETER = {
26825
26908
  type: "variable",
26826
26909
  required: true
26827
26910
  };
26911
+ var formResets = /* @__PURE__ */ new WeakMap();
26912
+ /** Read every reset value before any binding write can trigger a rerender. */
26913
+ function subscribeFormReset(form, read) {
26914
+ let subscription = formResets.get(form);
26915
+ if (!subscription) {
26916
+ const readers = /* @__PURE__ */ new Set();
26917
+ const reset = (event) => {
26918
+ const pending = Array.from(readers, (reader) => ({
26919
+ reader,
26920
+ ...reader.prepare()
26921
+ }));
26922
+ setTimeout(() => {
26923
+ for (const { off } of pending) off();
26924
+ if (event.defaultPrevented) return;
26925
+ const snapshot = form.ownerDocument.createElement("form");
26926
+ const restoreDefaults = snapshot.reset.bind(snapshot);
26927
+ const controls = pending.map(({ reader, read }) => {
26928
+ const element = reader.element.cloneNode(true);
26929
+ element.removeAttribute("form");
26930
+ snapshot.appendChild(element);
26931
+ return {
26932
+ read,
26933
+ element
26934
+ };
26935
+ });
26936
+ restoreDefaults();
26937
+ const commits = controls.map(({ read, element }) => read(element));
26938
+ for (const commit of commits) commit();
26939
+ }, 0);
26940
+ };
26941
+ subscription = {
26942
+ readers,
26943
+ reset
26944
+ };
26945
+ formResets.set(form, subscription);
26946
+ form.addEventListener("reset", subscription.reset);
26947
+ }
26948
+ const { readers, reset } = subscription;
26949
+ readers.add(read);
26950
+ return () => {
26951
+ readers.delete(read);
26952
+ if (readers.size === 0) {
26953
+ form.removeEventListener("reset", reset);
26954
+ formResets.delete(form);
26955
+ }
26956
+ };
26957
+ }
26958
+ /** Native defaults belong to the binding's initial rendered control value. */
26959
+ function setResetDefault(control) {
26960
+ if (control.tagName === "SELECT") {
26961
+ const options = Array.from(control.options);
26962
+ const selected = options.map((option) => option.selected);
26963
+ options.forEach((option, i) => option.defaultSelected = selected[i]);
26964
+ } else if (control.tagName === "INPUT" && ["checkbox", "radio"].includes(control.type)) control.defaultChecked = control.checked;
26965
+ else control.defaultValue = control.value;
26966
+ }
26828
26967
  /**
26829
26968
  * Register the automation action of a macro bound to a story variable: keyed
26830
26969
  * by the variable (or `key`), with the variable's value unless `action`
26831
26970
  * gives another.
26832
26971
  */
26833
- function useVariableAction(ctx, action) {
26834
- return useControlAction({
26972
+ function useVariableAction(ctx, action, onReset) {
26973
+ const registered = useControlAction({
26835
26974
  key: `$${ctx.varName}`,
26836
26975
  authorId: ctx.id,
26837
26976
  variable: ctx.varName,
26838
26977
  value: ctx.value,
26839
26978
  ...action
26840
26979
  });
26980
+ const control = useRef(null);
26981
+ const [, refresh] = useState(0);
26982
+ const initialized = useRef(null);
26983
+ const subscription = useRef(null);
26984
+ const resetValue = useRef({
26985
+ read: onReset,
26986
+ set: ctx.setValue,
26987
+ get: ctx.getValue,
26988
+ name: ctx.varName
26989
+ });
26990
+ resetValue.current = {
26991
+ read: onReset,
26992
+ set: ctx.setValue,
26993
+ get: ctx.getValue,
26994
+ name: ctx.varName
26995
+ };
26996
+ const ref = useCallback((element) => {
26997
+ control.current = element;
26998
+ registered.ref(element);
26999
+ }, [registered.ref]);
27000
+ useLayoutEffect(() => {
27001
+ const element = control.current;
27002
+ const form = element?.form;
27003
+ if (subscription.current?.element === element && subscription.current?.form === form) return;
27004
+ subscription.current?.off();
27005
+ subscription.current = null;
27006
+ if (!element || !onReset) return;
27007
+ if (initialized.current !== element) {
27008
+ setResetDefault(element);
27009
+ initialized.current = element;
27010
+ }
27011
+ if (!form) return;
27012
+ subscription.current = {
27013
+ element,
27014
+ form,
27015
+ off: subscribeFormReset(form, {
27016
+ element,
27017
+ prepare: () => {
27018
+ const before = resetValue.current.get();
27019
+ let changed = false;
27020
+ const offWrite = subscribeVariableWrites(resetValue.current.name.split("."), () => changed = true);
27021
+ const offStore = useStoryStore.subscribe(() => {
27022
+ changed ||= !Object.is(resetValue.current.get(), before);
27023
+ });
27024
+ return {
27025
+ off: () => {
27026
+ offWrite();
27027
+ offStore();
27028
+ },
27029
+ read: (snapshot) => {
27030
+ const value = changed ? void 0 : resetValue.current.read(snapshot);
27031
+ return () => {
27032
+ if (control.current !== element || element.form !== form) return;
27033
+ if (changed) refresh((version) => version + 1);
27034
+ else resetValue.current.set(value);
27035
+ };
27036
+ }
27037
+ };
27038
+ }
27039
+ })
27040
+ };
27041
+ });
27042
+ useLayoutEffect(() => () => subscription.current?.off(), []);
27043
+ return {
27044
+ ...registered,
27045
+ ref
27046
+ };
26841
27047
  }
26842
27048
  /**
26843
27049
  * Define a text input macro, `{name $var "placeholder"}`: an `<input>` of
@@ -26857,14 +27063,17 @@ function defineInputMacro(name, type, toValue = (input) => input !== void 0 ? St
26857
27063
  holds: "text"
26858
27064
  }],
26859
27065
  render(_props, ctx) {
26860
- const placeholder = ctx.args.placeholder ?? "";
27066
+ const { placeholder = "" } = ctx.args;
27067
+ const typed = ctx.hooks.useRef(null);
27068
+ const shown = typed.current !== null && toValue(typed.current) === ctx.value && type === "number" ? typed.current : display(ctx.value);
26861
27069
  const action = useVariableAction(ctx, {
26862
27070
  type: name,
26863
27071
  label: placeholder || ctx.varName,
26864
27072
  perform: (v) => ctx.setValue(toValue(v))
27073
+ }, (control) => {
27074
+ typed.current = control.value;
27075
+ return toValue(control.value);
26865
27076
  });
26866
- const typed = ctx.hooks.useRef(null);
26867
- const shown = typed.current !== null && toValue(typed.current) === ctx.value && type === "number" ? typed.current : display(ctx.value);
26868
27077
  return h(type ? "input" : "textarea", {
26869
27078
  type,
26870
27079
  ...actionAttributes(action, ctx),
@@ -26902,7 +27111,7 @@ defineMacro({
26902
27111
  label: label || ctx.varName || "",
26903
27112
  value: !!ctx.value,
26904
27113
  perform: (v) => ctx.setValue(v !== void 0 ? !!v : !ctx.getValue())
26905
- });
27114
+ }, (control) => control.checked);
26906
27115
  return /* @__PURE__ */ jsxs("label", {
26907
27116
  id: ctx.id,
26908
27117
  class: ctx.cls,
@@ -26938,11 +27147,17 @@ defineMacro({
26938
27147
  const radioValue = ctx.args.value ?? "";
26939
27148
  const label = ctx.args.label ?? "";
26940
27149
  const view = ctx.hooks.useContext(ViewScopeContext);
27150
+ const initialValue = ctx.hooks.useRef(ctx.value);
26941
27151
  const action = useVariableAction(ctx, {
26942
27152
  type: "radiobutton",
26943
27153
  key: `$${ctx.varName}:${radioValue}`,
26944
27154
  label: label || radioValue,
26945
27155
  perform: () => ctx.setValue(radioValue)
27156
+ }, (control) => {
27157
+ const radio = control;
27158
+ const group = radio.form?.elements.namedItem(radio.name);
27159
+ const selected = group && ("length" in group ? Array.from(group).find((node) => node.checked) : group.checked ? group : void 0);
27160
+ return selected ? selected.value : initialValue.current;
26946
27161
  });
26947
27162
  return /* @__PURE__ */ jsxs("label", {
26948
27163
  id: ctx.id,
@@ -26974,7 +27189,7 @@ defineMacro({
26974
27189
  perform: (v) => {
26975
27190
  if (v !== void 0) ctx.setValue(String(v));
26976
27191
  }
26977
- });
27192
+ }, (control) => control.value);
26978
27193
  return /* @__PURE__ */ jsx("select", {
26979
27194
  ...actionAttributes(action, ctx),
26980
27195
  value: display(ctx.value),