@rohal12/spindle 0.59.30 → 0.59.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.
@@ -3388,6 +3388,9 @@ var NameSet = class {
3388
3388
  delete(name) {
3389
3389
  this.names.delete(name);
3390
3390
  }
3391
+ clear() {
3392
+ this.names.clear();
3393
+ }
3391
3394
  };
3392
3395
  //#endregion
3393
3396
  //#region src/markup/ast.ts
@@ -3412,6 +3415,12 @@ var BLOCK_MACROS = new NameSet([
3412
3415
  "span",
3413
3416
  "nobr"
3414
3417
  ]);
3418
+ /**
3419
+ * The block widgets (those whose body renders `{@children}`), kept apart from
3420
+ * BLOCK_MACROS: a widget is redefined, so it is a block only while its latest
3421
+ * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3422
+ */
3423
+ var BLOCK_WIDGETS = new NameSet();
3415
3424
  /** Macros whose body is JavaScript source, kept verbatim. */
3416
3425
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3417
3426
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
@@ -3420,12 +3429,20 @@ function isRawMacro(name) {
3420
3429
  }
3421
3430
  /** Whether a macro takes a body closed by `{/name}`. */
3422
3431
  function isBlockMacro(name) {
3423
- return BLOCK_MACROS.has(name);
3432
+ return BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
3424
3433
  }
3425
3434
  /** Register a custom macro as a block macro so the parser nests children. */
3426
3435
  function registerBlockMacro(name) {
3427
3436
  BLOCK_MACROS.add(name);
3428
3437
  }
3438
+ /**
3439
+ * Record whether the widget `name` takes a body, as its latest definition
3440
+ * does. A block macro registered under the same name stays a block.
3441
+ */
3442
+ function setBlockWidget(name, isBlock) {
3443
+ if (isBlock) BLOCK_WIDGETS.add(name);
3444
+ else BLOCK_WIDGETS.delete(name);
3445
+ }
3429
3446
  /** Macros whose branches render as one: the node holds one per branch. */
3430
3447
  var BRANCHING = /* @__PURE__ */ new Set([
3431
3448
  "if",
@@ -9009,15 +9026,15 @@ var SigilParser = class extends Parser {
9009
9026
  }
9010
9027
  const self = this;
9011
9028
  const prevType = self.type;
9012
- this.prevValue = self.value;
9013
- const property = type.keyword !== void 0 && (prevType === types$1.dot || prevType === types$1.questionDot) || (type === types$1._function || type === types$1._class) && notABody(self.input, self.pos);
9029
+ this.prevValue = isMemberDot(this.typeBeforeLast) ? void 0 : self.value;
9030
+ const property = type.keyword !== void 0 && isMemberDot(prevType) || (type === types$1._function || type === types$1._class) && notABody(self.input, self.pos);
9014
9031
  if (!property && (type === types$1._function || type === types$1._class)) {
9015
9032
  const before = type === types$1._function && prevType === types$1.name && this.prevValue === "async" && !this.breakHere ? this.typeBeforeLast : prevType;
9016
9033
  self.type = before === types$1.colon && this.colonEndsTernary ? types$1.parenL : before;
9017
9034
  }
9018
9035
  this.typeBeforeLast = prevType;
9019
9036
  super.finishToken(property ? types$1.name : type, value);
9020
- if (type === types$1.name && value === "of" && (prevType === types$1._const || prevType === types$1._var || this.prevValue === "let")) self.exprAllowed = false;
9037
+ if (type === types$1.name && (isMemberDot(prevType) || value === "of" && (prevType === types$1._const || prevType === types$1._var || this.prevValue === "let"))) self.exprAllowed = false;
9021
9038
  }
9022
9039
  braceIsBlock(prevType) {
9023
9040
  if (prevType === types$1.colon && this.colonEndsTernary) return false;
@@ -9059,6 +9076,10 @@ function transientAssignment(p, end) {
9059
9076
  return false;
9060
9077
  }
9061
9078
  }
9079
+ /** Is `type` the `.` or `?.` of a member access? */
9080
+ function isMemberDot(type) {
9081
+ return type === types$1.dot || type === types$1.questionDot;
9082
+ }
9062
9083
  var OPENERS = /* @__PURE__ */ new Set([
9063
9084
  types$1.parenL,
9064
9085
  types$1.bracketL,
@@ -9194,6 +9215,10 @@ function bracketsBefore(src, pos) {
9194
9215
  * sigil variable declared (`let _x`) or used as a property name (`a.@x`).
9195
9216
  */
9196
9217
  function parseCode(src, goal = "expression") {
9218
+ return parseWithAst(src, goal).out;
9219
+ }
9220
+ /** What parseCode finds in `src`, and the syntax tree it is in. */
9221
+ function parseWithAst(src, goal) {
9197
9222
  const percentAt = /* @__PURE__ */ new Map();
9198
9223
  for (;;) {
9199
9224
  const transientsRead = /* @__PURE__ */ new Set();
@@ -9205,7 +9230,10 @@ function parseCode(src, goal = "expression") {
9205
9230
  };
9206
9231
  walk(ast, src, out, false, false);
9207
9232
  out.refs.sort((a, b) => a.start - b.start);
9208
- return out;
9233
+ return {
9234
+ out,
9235
+ ast
9236
+ };
9209
9237
  } catch (error) {
9210
9238
  const pos = error.pos ?? -1;
9211
9239
  if (!(error instanceof SyntaxError) || percentAt.has(pos)) throw error;
@@ -9216,6 +9244,30 @@ function parseCode(src, goal = "expression") {
9216
9244
  }
9217
9245
  }
9218
9246
  /**
9247
+ * Read `src` as a reference path: a variable with any number of `.name` and
9248
+ * `[expression]` members after it (`$data["field"]`, `@list[_i].x`), and
9249
+ * nothing else. Returns null for any other code (`$a + 1`, `$a.b()`, `$a,
9250
+ * $b`, `$a = 1`), and throws a `CodeSyntaxError` for code that is not
9251
+ * well-formed.
9252
+ */
9253
+ function parseReferencePath(src) {
9254
+ const { ast } = parseWithAst(src, "expression");
9255
+ let node = ast.type === "ChainExpression" ? ast.expression : ast;
9256
+ let nested = false;
9257
+ while (node.type === "MemberExpression") {
9258
+ node = node.object;
9259
+ nested = true;
9260
+ }
9261
+ if (node.type !== "Identifier") return null;
9262
+ const sigil = sigilOf(node, src);
9263
+ if (!sigil || node.start !== 0) return null;
9264
+ return {
9265
+ sigil: sigil[0],
9266
+ name: sigil[1],
9267
+ nested
9268
+ };
9269
+ }
9270
+ /**
9219
9271
  * Parse `src` as `goal`, reading `%` as `percentAt` says where it says, and
9220
9272
  * noting where it read a transient in `transientsRead`.
9221
9273
  */
@@ -10101,9 +10153,14 @@ function withEntry(ns, key, value) {
10101
10153
  }
10102
10154
  /** An empty namespace that cannot change. */
10103
10155
  var EMPTY_NAMESPACE = Object.freeze(createNamespace());
10104
- /** The names whose own entries differ between `a` and `b`, `a`'s first. */
10156
+ /**
10157
+ * The names whose own entries differ between `a` and `b`, `a`'s first: an
10158
+ * entry one holds and the other lacks (also one holding `undefined`), or
10159
+ * values that are not the same by SameValue (#519): an unchanged NaN is no
10160
+ * change, 0 and -0 differ.
10161
+ */
10105
10162
  function changedNames(a, b) {
10106
- return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((name) => ownValue(a, name) !== ownValue(b, name));
10163
+ return [.../* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)])].filter((name) => hasOwn(a, name) !== hasOwn(b, name) || !Object.is(ownValue(a, name), ownValue(b, name)));
10107
10164
  }
10108
10165
  var isCount = (value) => typeof value === "number" && Number.isInteger(value) && value >= 0;
10109
10166
  /** The count of `name` in `counts`: its own entry, or 0. */
@@ -10126,7 +10183,9 @@ function createCounts(source, name) {
10126
10183
  //#region src/widgets/widget-registry.ts
10127
10184
  var widgets = new NameMap();
10128
10185
  /**
10129
- * Register a widget. Its `@` parameters become locals of its body, so one
10186
+ * Register a widget. A widget whose body renders {@children} takes a closing
10187
+ * tag, so it is a block macro to the parser too, for the passages parsed
10188
+ * later; the latest definition decides. Its `@` parameters become locals of its body, so one
10130
10189
  * that no namespace can hold (`@__proto__`) throws a TypeError and the
10131
10190
  * widget is not registered.
10132
10191
  */
@@ -10139,6 +10198,7 @@ function registerWidget(name, bodyAST, params, isBlock = false, holds = {}) {
10139
10198
  holds,
10140
10199
  isBlock
10141
10200
  });
10201
+ setBlockWidget(name, isBlock);
10142
10202
  }
10143
10203
  function getWidget(name) {
10144
10204
  return widgets.get(name);
@@ -11400,7 +11460,9 @@ function tokenTextContainsChildren(token, parametersOf = registeredParameters, s
11400
11460
  /**
11401
11461
  * Recursively scan an AST node array for a VariableNode
11402
11462
  * with scope 'local' and name 'children' (@children), in the content and in
11403
- * the attributes and labels that render markup.
11463
+ * the attributes and labels that render markup. A nested `{widget}` is not
11464
+ * entered: its slot belongs to the innermost widget (as widgetDefinitions
11465
+ * reads it), and a definition renders nothing of its own.
11404
11466
  */
11405
11467
  function astContainsChildren(nodes, parametersOf = registeredParameters) {
11406
11468
  for (const node of nodes) {
@@ -11418,6 +11480,7 @@ function astContainsChildren(nodes, parametersOf = registeredParameters) {
11418
11480
  }, parametersOf) || astContainsChildren(node.children, parametersOf)) return true;
11419
11481
  }
11420
11482
  if (node.type === "macro") {
11483
+ if (node.name.toLowerCase() === "widget") continue;
11421
11484
  if (tokenTextContainsChildren({
11422
11485
  isClose: false,
11423
11486
  nameStart: 0,
@@ -11550,29 +11613,40 @@ function widgetDefinitions(passages, parametersOf = registeredParameters) {
11550
11613
  return found;
11551
11614
  }
11552
11615
  /**
11553
- * The names of the block widgets (those whose body renders `{@children}`)
11554
- * that StoryInit and the passages tagged `widget` define, closed. They must
11555
- * be known as block macros before any passage is parsed, so that passages
11556
- * invoking them nest their content whatever the passage order.
11616
+ * The definitions the runtime ends up with, one per widget name: the closed
11617
+ * ones, the latest winning as registration replaces a widget. The widget
11618
+ * passages register before StoryInit runs, so StoryInit's definitions come
11619
+ * last whatever the passage order. Read with the flat scanner, so a nested
11620
+ * definition owns its own `{@children}`.
11557
11621
  */
11558
- function blockWidgetNames(passages, parametersOf = registeredParameters) {
11559
- return widgetDefinitions(passages, parametersOf).filter((def) => def.block && def.closeStart !== void 0).map((def) => def.name);
11622
+ function effectiveWidgetDefinitions(definitions) {
11623
+ const inInit = (def) => def.passage === "StoryInit";
11624
+ const effective = new NameMap();
11625
+ for (const def of [...definitions.filter((def) => !inInit(def)), ...definitions.filter(inInit)]) if (def.closeStart !== void 0) effective.set(def.name, def);
11626
+ return [...effective.values()];
11627
+ }
11628
+ /**
11629
+ * The widgets that StoryInit and the passages tagged `widget` define, as the
11630
+ * runtime ends up with them (see effectiveWidgetDefinitions). Whether each
11631
+ * takes a body must be known before any passage is parsed, so that passages
11632
+ * invoking them nest their content (or don't) whatever the passage order.
11633
+ */
11634
+ function effectiveWidgets(passages, parametersOf = registeredParameters) {
11635
+ return effectiveWidgetDefinitions(widgetDefinitions(passages, parametersOf));
11560
11636
  }
11561
11637
  //#endregion
11562
11638
  //#region src/widgets/register-widget-def.ts
11563
11639
  /**
11564
11640
  * Register the widget a definition declares, with its body. Widgets whose
11565
11641
  * body renders {@children} take a closing tag, so they are registered as
11566
- * block macros too: passages parsed later nest their content. A parameter
11642
+ * block macros too (see registerWidget). A parameter
11567
11643
  * that no namespace can hold or declares what it holds wrongly throws (see
11568
11644
  * registerWidget and checkWidgetHolds), registering nothing.
11569
11645
  */
11570
11646
  function registerWidgetDef(def, body) {
11571
11647
  checkWidgetHolds(def);
11572
11648
  const { name, params, holds } = def;
11573
- const isBlock = astContainsChildren(body);
11574
- registerWidget(name, body, params, isBlock, holds);
11575
- if (isBlock) registerBlockMacro(name);
11649
+ registerWidget(name, body, params, astContainsChildren(body), holds);
11576
11650
  }
11577
11651
  /**
11578
11652
  * Register the widgets `nodes` (a passage's markup) define at its top level,
@@ -11758,13 +11832,16 @@ function resetPRNG() {
11758
11832
  currentPull = 0;
11759
11833
  generator = null;
11760
11834
  }
11835
+ /** The position each running withoutDraws() takes its draws back to. */
11836
+ var neutralScopes = [];
11761
11837
  /**
11762
11838
  * Run `fn` without its draws advancing the sequence: the draws it makes are
11763
11839
  * taken back afterwards (also when it throws), so the next draws return the
11764
11840
  * same values again. Save and load event handlers run like this, so that
11765
11841
  * saving or loading never shifts the story's random sequence (a load replays
11766
11842
  * the saved passage from its entry state, without the save's handlers). A
11767
- * generator `fn` replaced (a restart or load it started) is kept.
11843
+ * generator `fn` replaced (a restart or load it started) is kept, and so are
11844
+ * the draws made before a navigation `fn` started (see keepDrawsSoFar()).
11768
11845
  */
11769
11846
  function withoutDraws(fn) {
11770
11847
  const start = {
@@ -11772,12 +11849,29 @@ function withoutDraws(fn) {
11772
11849
  seed: currentSeed,
11773
11850
  pull: currentPull
11774
11851
  };
11852
+ neutralScopes.push(start);
11775
11853
  try {
11776
11854
  return fn();
11777
11855
  } finally {
11856
+ neutralScopes.splice(neutralScopes.indexOf(start), 1);
11778
11857
  if (enabled && generation === start.generation && currentPull !== start.pull) moveTo(start.seed, start.pull);
11779
11858
  }
11780
11859
  }
11860
+ /**
11861
+ * Make the draws up to now part of the story: the position of the generator
11862
+ * is the one a history moment the story just entered records, and the
11863
+ * moment's passage replays its rolls from there. A running withoutDraws()
11864
+ * takes back only the draws made after this, so that the position the
11865
+ * passage renders from stays the recorded one (#535). Navigation calls this
11866
+ * once it has recorded the moment it enters.
11867
+ */
11868
+ function keepDrawsSoFar() {
11869
+ for (const scope of neutralScopes) {
11870
+ scope.generation = generation;
11871
+ scope.seed = currentSeed;
11872
+ scope.pull = currentPull;
11873
+ }
11874
+ }
11781
11875
  /** Returns the current PRNG state for snapshotting, or null if disabled. */
11782
11876
  function snapshotPRNG() {
11783
11877
  if (!enabled) return null;
@@ -12841,16 +12935,18 @@ function PlaceholderAttributes({ tag, attributes, placeholders, svg, children })
12841
12935
  if (!nodes) return [
12842
12936
  name,
12843
12937
  value,
12844
- written
12938
+ written,
12939
+ false
12845
12940
  ];
12846
12941
  const result = renderText(nodes, scope);
12847
12942
  for (const error of result.errors) errors.push([name, error]);
12848
12943
  return [
12849
12944
  name,
12850
12945
  result.text,
12851
- written
12946
+ written,
12947
+ true
12852
12948
  ];
12853
- }), svg);
12949
+ }), svg, tag);
12854
12950
  const ref = useDirectAttributes(direct);
12855
12951
  return withAttributeErrors(errors, h(tag, ref ? {
12856
12952
  ...props,
@@ -12929,7 +13025,8 @@ function convertDomNode(node, key, ph) {
12929
13025
  attributes.push([
12930
13026
  name,
12931
13027
  value,
12932
- value
13028
+ value,
13029
+ false
12933
13030
  ]);
12934
13031
  const parts = splitPlaceholderText(value, ph);
12935
13032
  if (parts.every((part) => typeof part === "string")) continue;
@@ -12947,7 +13044,7 @@ function convertDomNode(node, key, ph) {
12947
13044
  svg,
12948
13045
  children
12949
13046
  }, key);
12950
- const { props, direct } = splitAttributes(attributes, svg);
13047
+ const { props, direct } = splitAttributes(attributes, svg, tag);
12951
13048
  if (direct.length > 0) return /* @__PURE__ */ jsx(DirectAttributes, {
12952
13049
  tag,
12953
13050
  props,
@@ -13013,11 +13110,18 @@ var INLINE_ELEMENTS = /* @__PURE__ */ new Set([
13013
13110
  "wbr"
13014
13111
  ]);
13015
13112
  /**
13016
- * Attributes that Preact keeps as DOM properties on author HTML elements:
13017
- * the live state of form controls and media, which then follows its
13018
- * variable even after the reader changed it. Boolean ones written bare or
13019
- * as `=""` are passed as `true`, since '' is falsy (#177); one that only
13020
- * resolves to '' through an interpolation stays ''.
13113
+ * Attributes that Preact keeps as DOM properties on author HTML elements
13114
+ * when their value is bound to variables (`value="{$name}"`): the live state
13115
+ * of form controls and media, which then follows its variable even after the
13116
+ * reader changed it. Boolean ones written bare or as `=""` are passed as
13117
+ * `true`, since '' is falsy (#177); one that only resolves to '' through an
13118
+ * interpolation stays ''.
13119
+ *
13120
+ * A static `value`, `checked` or `selected` is the control's default, as in
13121
+ * HTML: set as an attribute, so a reset restores it and a rerender leaves
13122
+ * what the reader entered alone (#528). Not so for `muted`, which as an
13123
+ * attribute is ignored on an element made by script, nor for the `value` of
13124
+ * the controls that have no attribute for it.
13021
13125
  */
13022
13126
  var LIVE_PROPERTIES = /* @__PURE__ */ new Set([
13023
13127
  "value",
@@ -13088,6 +13192,14 @@ function setRawAttribute(el, name, value) {
13088
13192
  el.setAttributeNode(attr);
13089
13193
  }
13090
13194
  /**
13195
+ * Whether the static `name` attribute of `tag` is its default (#528). HTML has
13196
+ * no `value` attribute on `select` and `textarea`, so theirs stays a property.
13197
+ */
13198
+ function isNativeDefault(tag, name) {
13199
+ if (name === "muted") return false;
13200
+ return name !== "value" || tag !== "select" && tag !== "textarea";
13201
+ }
13202
+ /**
13091
13203
  * Split author attributes into Preact props and attributes to set directly.
13092
13204
  *
13093
13205
  * Author HTML means attributes, but as props Preact assigns names of DOM
@@ -13104,16 +13216,20 @@ function setRawAttribute(el, name, value) {
13104
13216
  * and `className` compat rewrites (dropping an empty `class`, turning
13105
13217
  * `className` into `class`) are set directly instead.
13106
13218
  */
13107
- function splitAttributes(attributes, svg) {
13219
+ function splitAttributes(attributes, svg, tag) {
13108
13220
  const props = {};
13109
13221
  const direct = [];
13110
- for (const [name, value, written] of attributes) {
13222
+ const defaults = [];
13223
+ for (const [name, value, written, bound] of attributes) {
13111
13224
  const lower = name.toLowerCase();
13112
13225
  if (BOOLEAN_ATTRIBUTES.has(lower) && written !== "" && value === "") continue;
13113
- else if (!svg && LIVE_PROPERTIES.has(lower)) props[lower] = lower !== "value" && written === "" ? true : value;
13114
- else if (!SETTABLE_NAME.test(name) || lower.startsWith("on") || lower === "translate" || svg && (SVG_DIRECT.has(name) || name === "__proto__")) direct.push([name, value]);
13226
+ else if (!svg && LIVE_PROPERTIES.has(lower)) {
13227
+ if (!bound && isNativeDefault(tag, lower)) defaults.push([name.toUpperCase(), lower === "value" ? value : ""]);
13228
+ else props[lower] = lower !== "value" && written === "" ? true : value;
13229
+ } else if (!SETTABLE_NAME.test(name) || lower.startsWith("on") || lower === "translate" || svg && (SVG_DIRECT.has(name) || name === "__proto__")) direct.push([name, value]);
13115
13230
  else props[svg ? name : name.toUpperCase()] = value;
13116
13231
  }
13232
+ for (const [name, value] of defaults) props[name] = value;
13117
13233
  return {
13118
13234
  props,
13119
13235
  direct
@@ -13248,8 +13364,9 @@ function HtmlNodeRenderer({ node }) {
13248
13364
  const { props, direct } = splitAttributes(Object.entries(node.attributes).map(([k, v]) => [
13249
13365
  k,
13250
13366
  resolveAttributeValue(k, v, scope, errors),
13251
- v
13252
- ]), inSvg || isSvgRoot);
13367
+ v,
13368
+ hasInterpolation(v)
13369
+ ]), inSvg || isSvgRoot, tag);
13253
13370
  const ref = useDirectAttributes(direct);
13254
13371
  if (ref) props.ref = ref;
13255
13372
  const isInline = INLINE_ELEMENTS.has(tag);
@@ -16232,14 +16349,34 @@ async function adoptPlaythroughNow(ifid, id) {
16232
16349
  * no number.
16233
16350
  */
16234
16351
  async function ensurePlaythrough(ifid, id, createdAt) {
16235
- const backend = await getBackend();
16236
- if (!(await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === id)) await backend.putPlaythrough({
16352
+ if (!await hasPlaythroughNow(ifid, id)) await (await getBackend()).putPlaythrough({
16237
16353
  id,
16238
16354
  ifid,
16239
16355
  createdAt,
16240
16356
  label: "Imported"
16241
16357
  });
16242
16358
  }
16359
+ /** Whether the story has a record of the playthrough `id`. */
16360
+ async function hasPlaythroughNow(ifid, id) {
16361
+ return (await (await getBackend()).getPlaythroughsByIfid(ifid)).some((p) => p.id === id);
16362
+ }
16363
+ /**
16364
+ * The playthrough a save of a game in `id` belongs to: `id` if it has a
16365
+ * record. Another tab may have deleted it since this tab cached it (#527),
16366
+ * and a save in a playthrough without a record is grouped as "Unknown" for
16367
+ * good. The save then joins the story's current playthrough (the one that
16368
+ * tab went on in), or a new one if that has no record either; callers hand
16369
+ * the result to the live game (see followSavedPlaythrough in the store).
16370
+ */
16371
+ async function livePlaythroughNow(ifid, id) {
16372
+ if (await hasPlaythroughNow(ifid, id)) return id;
16373
+ const current = await (await getBackend()).getMeta(currentPlaythroughKey(ifid));
16374
+ if (current && await hasPlaythroughNow(ifid, current)) {
16375
+ saveSessionPlaythrough(ifid, current);
16376
+ return current;
16377
+ }
16378
+ return startNewPlaythroughNow(ifid);
16379
+ }
16243
16380
  /**
16244
16381
  * Set up the save system for a story that boots: the story's current
16245
16382
  * playthrough (a new one if it has none) and the slots holding saves (see
@@ -16249,7 +16386,7 @@ function establishPlaythrough(ifid) {
16249
16386
  return inOrder(async () => {
16250
16387
  const backend = await getBackend();
16251
16388
  const own = loadSessionPlaythrough(ifid);
16252
- const id = own !== void 0 && (await backend.getPlaythroughsByIfid(ifid)).some((p) => p.id === own) ? own : await backend.getMeta(currentPlaythroughKey(ifid)) ?? await startNewPlaythroughNow(ifid);
16389
+ const id = own !== void 0 && await hasPlaythroughNow(ifid, own) ? own : await backend.getMeta(currentPlaythroughKey(ifid)) ?? await startNewPlaythroughNow(ifid);
16253
16390
  saveSessionPlaythrough(ifid, id);
16254
16391
  return {
16255
16392
  id,
@@ -16300,8 +16437,9 @@ function storedRecord(meta, payload) {
16300
16437
  }
16301
16438
  var createSave = queued(createSaveNow);
16302
16439
  async function createSaveNow(ifid, playthroughPromise, payload, custom = {}) {
16303
- const playthroughId = await playthroughPromise;
16304
- if (!playthroughId) throw new Error("No playthrough");
16440
+ const requested = await playthroughPromise;
16441
+ if (!requested) throw new Error("No playthrough");
16442
+ const playthroughId = await livePlaythroughNow(ifid, requested);
16305
16443
  const now = (/* @__PURE__ */ new Date()).toISOString();
16306
16444
  const record = storedRecord({
16307
16445
  id: randomUUID(),
@@ -16338,10 +16476,11 @@ async function createSaveNow(ifid, playthroughPromise, payload, custom = {}) {
16338
16476
  */
16339
16477
  var overwriteSave = queued(overwriteSaveNow);
16340
16478
  async function overwriteSaveNow(saveId, payload, custom, playthroughPromise) {
16341
- const playthroughId = await playthroughPromise;
16479
+ const requested = await playthroughPromise;
16342
16480
  const backend = await getBackend();
16343
16481
  const existing = await backend.getSave(saveId);
16344
16482
  if (!existing) return void 0;
16483
+ const playthroughId = requested ? await livePlaythroughNow(existing.meta.ifid, requested) : void 0;
16345
16484
  const updated = storedRecord({
16346
16485
  ...existing.meta,
16347
16486
  ...playthroughId ? { playthroughId } : {},
@@ -17955,6 +18094,16 @@ function enterStart(state, passage, variables, transientDefaults) {
17955
18094
  state.historyIndex = 0;
17956
18095
  }
17957
18096
  /**
18097
+ * Run `fn` (an event's handlers) and tell whether they replaced the game
18098
+ * state (a restart or load): what the caller was about to do to the game it
18099
+ * emitted from is then not to be done to the new one (#516, #517).
18100
+ */
18101
+ function replacesState(fn) {
18102
+ const applied = latestStateApplied;
18103
+ fn();
18104
+ return latestStateApplied !== applied;
18105
+ }
18106
+ /**
17958
18107
  * Move through history by `step` moments (back or forward), restoring the
17959
18108
  * snapshot recorded for the moment moved to: live variables may hold edits
17960
18109
  * made since the current moment was recorded.
@@ -17966,7 +18115,9 @@ function moveInHistory(get, set, step) {
17966
18115
  finishEnteredMoment(get, set);
17967
18116
  const previousPassage = get().currentPassage;
17968
18117
  const targetPassage = history[target].passage;
18118
+ const navigation = get().navigationId;
17969
18119
  emit("beforenavigate", targetPassage);
18120
+ if (get().navigationId !== navigation) return;
17970
18121
  const restoredVars = deepClone(reconstructVarsAt(target));
17971
18122
  set((state) => {
17972
18123
  state.historyIndex += step;
@@ -17978,6 +18129,7 @@ function moveInHistory(get, set, step) {
17978
18129
  reinitTriggerState();
17979
18130
  lastNavigationVars = get().variables;
17980
18131
  restorePRNGFromMoment(get().history[get().historyIndex]);
18132
+ keepDrawsSoFar();
17981
18133
  persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage));
17982
18134
  }
17983
18135
  /**
@@ -17996,6 +18148,7 @@ function recordStoryInitState() {
17996
18148
  useStoryStore.setState((state) => {
17997
18149
  state.history[0].prng = prng;
17998
18150
  });
18151
+ keepDrawsSoFar();
17999
18152
  }
18000
18153
  /**
18001
18154
  * Settles once the latest playthrough switch (init's lookup or creation, a
@@ -18099,6 +18252,18 @@ function switchToLoadedPlaythrough(ifid, id) {
18099
18252
  }));
18100
18253
  }
18101
18254
  /**
18255
+ * Move the running game to the playthrough a save it wrote was stored in,
18256
+ * when that is not the one it asked for: another tab deleted the game's
18257
+ * playthrough, and the save took the story's current one (#527). `requested`
18258
+ * is the playthrough the save was issued with (see resolvePlaythroughId). A
18259
+ * game that has switched since (a restart, a load) stays where it is.
18260
+ */
18261
+ async function followSavedPlaythrough(requested, saved) {
18262
+ const id = saved?.meta.playthroughId;
18263
+ const asked = await requested;
18264
+ if (id && id !== asked && knownPlaythroughId() === asked) switchToPlaythrough(id, Promise.resolve());
18265
+ }
18266
+ /**
18102
18267
  * A load from a slot reads the save in the order of storage operations and
18103
18268
  * applies it when the read completes. A restart, a boot or a direct load
18104
18269
  * (loadFromPayload) issued after it replaces the game state at once; the
@@ -18211,7 +18376,8 @@ function keepHookWrites(payload, before, after, written) {
18211
18376
  changes.push({
18212
18377
  path,
18213
18378
  deleted: false,
18214
- value
18379
+ value,
18380
+ absolute: true
18215
18381
  });
18216
18382
  }
18217
18383
  if (changes.length === 0) return;
@@ -18228,7 +18394,8 @@ function keepHookWrites(payload, before, after, written) {
18228
18394
  * value of it is written. Into an array, elements removed from the end are
18229
18395
  * removed at the same indices and elements added are appended; changes at
18230
18396
  * indices the array lacks are dropped (it was resized, so its indices do not
18231
- * line up with the live ones).
18397
+ * line up with the live ones). The hooks' explicit writes are not diffs: an
18398
+ * array's length or an element they set is set to that value (#515).
18232
18399
  */
18233
18400
  function writeHookChange(work, after, change, own) {
18234
18401
  const { path } = change;
@@ -18258,6 +18425,9 @@ function writeKey(holder, key, value, change) {
18258
18425
  } else if (change && "appended" in change) {
18259
18426
  holder.length += change.gap ?? 0;
18260
18427
  holder.push(value);
18428
+ } else if (change && "absolute" in change) {
18429
+ if (key === "length") holder.length = value;
18430
+ else holder[index] = value;
18261
18431
  } else if (key === "length" && change) holder.length += value;
18262
18432
  else if (index < holder.length) holder[index] = value;
18263
18433
  } else if (deleted) delete holder[key];
@@ -18506,7 +18676,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
18506
18676
  return;
18507
18677
  }
18508
18678
  const previousPassage = get().currentPassage;
18509
- emit("beforenavigate", passageName);
18679
+ if (replacesState(() => emit("beforenavigate", passageName))) return;
18510
18680
  const patchEntry = computeVarPatches(lastNavigationVars, get().variables);
18511
18681
  set((state) => {
18512
18682
  state.temporary = createNamespace();
@@ -18539,8 +18709,9 @@ var useStoryStore = create()(storyStore((set, get) => ({
18539
18709
  const deferred = deferredNavigations;
18540
18710
  deferredNavigations = [];
18541
18711
  finishEnteredMoment(get, set);
18712
+ keepDrawsSoFar();
18542
18713
  persistSessionThen(get, () => {
18543
- emit("afternavigate", passageName, previousPassage);
18714
+ if (replacesState(() => emit("afternavigate", passageName, previousPassage))) return;
18544
18715
  for (const next of deferred) get().navigate(next);
18545
18716
  });
18546
18717
  },
@@ -18629,7 +18800,8 @@ var useStoryStore = create()(storyStore((set, get) => ({
18629
18800
  set((state) => {
18630
18801
  state.saveError = null;
18631
18802
  });
18632
- await quickSave$1(storyData.ifid, playthrough, payload, slot, custom);
18803
+ const saved = await quickSave$1(storyData.ifid, playthrough, payload, slot, custom);
18804
+ await followSavedPlaythrough(playthrough, saved);
18633
18805
  recordKnownSave(set, slot, true);
18634
18806
  }), "spindle: failed to save", (err) => set((state) => {
18635
18807
  state.saveError = errorMessage(err, "Failed to save");
@@ -18730,10 +18902,12 @@ var useStoryStore = create()(storyStore((set, get) => ({
18730
18902
  },
18731
18903
  beginSave: () => {
18732
18904
  const before = get().variables;
18905
+ const replaced = latestStateApplied;
18733
18906
  const writes = /* @__PURE__ */ new Map();
18734
18907
  hookWrites = writes;
18735
18908
  return () => {
18736
18909
  if (hookWrites === writes) hookWrites = null;
18910
+ if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
18737
18911
  const payload = get().getSavePayload();
18738
18912
  keepHookWrites(payload, before, get().variables, [...writes.values()]);
18739
18913
  return payload;
@@ -18757,6 +18931,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
18757
18931
  } finally {
18758
18932
  leavingPlaythrough = null;
18759
18933
  }
18934
+ if (latestStateApplied !== replacement) return;
18760
18935
  const ifid = get().storyData?.ifid;
18761
18936
  if (playthroughId && ifid) switchToLoadedPlaythrough(ifid, playthroughId);
18762
18937
  const entry = loadedEntryMoment(payload);
@@ -18784,6 +18959,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
18784
18959
  reinitTriggerState();
18785
18960
  lastNavigationVars = reconstructVarsAt(get().historyIndex);
18786
18961
  restorePRNGFrom(entry?.prng !== void 0 ? entry.prng : payload.prng);
18962
+ keepDrawsSoFar();
18787
18963
  persistSessionThen(get, () => withoutDraws(() => emit("afterload", slot)));
18788
18964
  },
18789
18965
  getHistoryVariables: (index) => {
@@ -18987,21 +19163,60 @@ function nextStop(items, root, from, backwards) {
18987
19163
  }
18988
19164
  return backwards ? items[items.length - 1] : items[0];
18989
19165
  }
19166
+ /**
19167
+ * The focused element, through the accessible frame documents: a frame holding
19168
+ * the focus is followed to its own focused element, unless that is its body
19169
+ * (nothing focused in it) or its document can't be reached (then the frame
19170
+ * itself is the deepest). Elements of an embedded document are of another
19171
+ * realm's classes, hence the duck typing. A focusable SVG element (a link in an
19172
+ * illustration) counts (#483).
19173
+ */
19174
+ function activeChain() {
19175
+ const chain = [];
19176
+ let doc = document;
19177
+ while (doc) {
19178
+ const el = doc.activeElement;
19179
+ if (!el || chain.length > 0 && el === doc.body) break;
19180
+ if (typeof el.focus !== "function") break;
19181
+ chain.push(el);
19182
+ doc = isFrame(el) ? frameDocument(el) : null;
19183
+ }
19184
+ return chain;
19185
+ }
19186
+ /** Whether `el` is still part of a live document. */
19187
+ function isLive(el) {
19188
+ return el.isConnected && !!el.ownerDocument.defaultView;
19189
+ }
19190
+ /** Focus the deepest element of `chain` that is still there. */
19191
+ function restoreOpener(chain) {
19192
+ for (let i = chain.length - 1; i >= 0; i--) {
19193
+ const el = chain[i];
19194
+ if (isLive(el)) {
19195
+ el.focus();
19196
+ return;
19197
+ }
19198
+ }
19199
+ }
18990
19200
  function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
18991
19201
  useLayoutEffect(() => {
18992
19202
  const panel = panelRef.current;
18993
19203
  if (!panel) return;
18994
- const focused = document.activeElement;
18995
- const opener = focused instanceof HTMLElement || focused instanceof SVGElement ? focused : null;
18996
- const entry = { panel };
19204
+ const entry = {
19205
+ panel,
19206
+ opener: activeChain()
19207
+ };
18997
19208
  openModals.push(entry);
18998
19209
  const body = panel.querySelector(bodySelector) ?? panel;
18999
19210
  (Array.from(panel.querySelectorAll("[autofocus]")).find(isAvailable) ?? focusables(body)[0] ?? panel).focus();
19000
19211
  return () => {
19001
19212
  const i = openModals.indexOf(entry);
19002
19213
  if (i !== -1) openModals.splice(i, 1);
19214
+ for (const upper of openModals.slice(i === -1 ? openModals.length : i)) {
19215
+ const [outer] = upper.opener;
19216
+ if (!outer || panel.contains(outer) || !upper.opener.some(isLive)) upper.opener = entry.opener;
19217
+ }
19003
19218
  const active = document.activeElement;
19004
- if ((!active || active === document.body || panel.contains(active)) && opener?.isConnected) opener.focus();
19219
+ if (!active || active === document.body || panel.contains(active)) restoreOpener(entry.opener);
19005
19220
  };
19006
19221
  }, []);
19007
19222
  useLayoutEffect(() => {
@@ -19142,6 +19357,161 @@ function useModalFocus(panelRef, bodySelector, dismissible, onClose) {
19142
19357
  }, [dismissible, onClose]);
19143
19358
  }
19144
19359
  //#endregion
19360
+ //#region src/action-registry.ts
19361
+ /** The fields of a StoryAction that are left out when unset. */
19362
+ var OPTIONAL_ACTION_FIELDS = [
19363
+ "target",
19364
+ "variable",
19365
+ "options",
19366
+ "value",
19367
+ "disabled"
19368
+ ];
19369
+ /**
19370
+ * The registrations holding each ID, oldest first; the newest is the one
19371
+ * listed. Generated IDs don't collide, but author IDs can, and one control's
19372
+ * cleanup must not remove another control holding the same ID (#233).
19373
+ */
19374
+ var actions = /* @__PURE__ */ new Map();
19375
+ var idCounters = /* @__PURE__ */ new Map();
19376
+ /**
19377
+ * IDs handed out and not yet registered, or registered: a control registers
19378
+ * in a layout effect, after every control of the same render has allocated its
19379
+ * ID, so the registry alone can't tell that "link:Room:2" is taken (#486).
19380
+ * Released when the last registration of an ID goes.
19381
+ */
19382
+ var reserved = /* @__PURE__ */ new Set();
19383
+ /**
19384
+ * The counters reset on every navigation, so a passage's controls get the
19385
+ * same IDs each time it is shown. Controls that stay mounted across
19386
+ * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19387
+ * ID still registered (#233) and every one allocated but not registered yet
19388
+ * (#486).
19389
+ */
19390
+ function generateActionId(type, key, authorId) {
19391
+ if (authorId) {
19392
+ reserved.add(authorId);
19393
+ return authorId;
19394
+ }
19395
+ const base = `${type}:${key}`;
19396
+ let count = idCounters.get(base) ?? 0;
19397
+ let id;
19398
+ do {
19399
+ count++;
19400
+ id = count === 1 ? base : `${base}:${count}`;
19401
+ } while (actions.has(id) || reserved.has(id));
19402
+ idCounters.set(base, count);
19403
+ reserved.add(id);
19404
+ return id;
19405
+ }
19406
+ function registerAction(action) {
19407
+ const id = action.id;
19408
+ const entry = { action };
19409
+ const entries = actions.get(id);
19410
+ if (entries) {
19411
+ console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
19412
+ entries.push(entry);
19413
+ } else actions.set(id, [entry]);
19414
+ notify();
19415
+ return {
19416
+ update(next) {
19417
+ const current = actions.get(id);
19418
+ if (!current?.includes(entry)) return;
19419
+ entry.action = next;
19420
+ if (current[current.length - 1] === entry) notify();
19421
+ },
19422
+ unregister() {
19423
+ const current = actions.get(id);
19424
+ const index = current ? current.indexOf(entry) : -1;
19425
+ if (!current || index === -1) return;
19426
+ current.splice(index, 1);
19427
+ if (current.length === 0) {
19428
+ actions.delete(id);
19429
+ reserved.delete(id);
19430
+ }
19431
+ if (index === current.length) notify();
19432
+ }
19433
+ };
19434
+ }
19435
+ /** The promises of the performed actions that have not settled yet. */
19436
+ var running = /* @__PURE__ */ new Set();
19437
+ /**
19438
+ * Perform an action, as `Story.performAction()` does. One that returns a
19439
+ * promise is tracked until it settles, for `settleRunningActions()`, and the
19440
+ * promise is returned for the caller to await (its rejection stays the
19441
+ * caller's to handle).
19442
+ */
19443
+ function performRegisteredAction(action, value) {
19444
+ const result = action.perform(value);
19445
+ if (!result || typeof result.then !== "function") return result;
19446
+ const done = () => void running.delete(result);
19447
+ running.add(result);
19448
+ result.then(done, done);
19449
+ return result.then((v) => v);
19450
+ }
19451
+ /** Wait until every performed action has finished, whether or not it failed. */
19452
+ async function settleRunningActions() {
19453
+ while (running.size > 0) await Promise.allSettled(running);
19454
+ }
19455
+ function getActions() {
19456
+ return Array.from(actions.values(), listed);
19457
+ }
19458
+ function getAction(id) {
19459
+ const entries = actions.get(id);
19460
+ return entries && listed(entries);
19461
+ }
19462
+ function listed(entries) {
19463
+ return entries[entries.length - 1].action;
19464
+ }
19465
+ function resetIdCounters() {
19466
+ idCounters.clear();
19467
+ for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
19468
+ }
19469
+ function notify() {
19470
+ emit("actionsChanged");
19471
+ }
19472
+ //#endregion
19473
+ //#region src/hooks/use-action.ts
19474
+ function useAction(opts) {
19475
+ const idRef = useRef("");
19476
+ const performRef = useRef(opts.perform);
19477
+ performRef.current = opts.perform;
19478
+ if (!idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19479
+ const id = idRef.current;
19480
+ const buildAction = () => {
19481
+ const action = {
19482
+ id,
19483
+ type: opts.type,
19484
+ label: opts.label,
19485
+ perform: (...args) => performRef.current(...args)
19486
+ };
19487
+ for (const field of OPTIONAL_ACTION_FIELDS) if (opts[field] !== void 0) Object.assign(action, { [field]: opts[field] });
19488
+ return action;
19489
+ };
19490
+ const registration = useRef(null);
19491
+ useLayoutEffect(() => {
19492
+ const own = registerAction(buildAction());
19493
+ registration.current = own;
19494
+ return () => own.unregister();
19495
+ }, [id]);
19496
+ const registered = useRef(false);
19497
+ useLayoutEffect(() => {
19498
+ if (!registered.current) {
19499
+ registered.current = true;
19500
+ return;
19501
+ }
19502
+ registration.current?.update(buildAction());
19503
+ }, [
19504
+ opts.type,
19505
+ opts.label,
19506
+ opts.target,
19507
+ opts.variable,
19508
+ opts.disabled,
19509
+ opts.value,
19510
+ JSON.stringify(opts.options)
19511
+ ]);
19512
+ return id;
19513
+ }
19514
+ //#endregion
19145
19515
  //#region src/components/PassageDialog.tsx
19146
19516
  var DialogCloseContext = createContext(null);
19147
19517
  function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label, dismissible = true, showCloseButton = dismissible }) {
@@ -19204,12 +19574,10 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19204
19574
  "aria-modal": "true",
19205
19575
  "aria-label": label ?? passageName,
19206
19576
  tabIndex: -1,
19207
- children: [showCloseButton && /* @__PURE__ */ jsx("button", {
19208
- type: "button",
19209
- class: "dialog-close",
19210
- "aria-label": "Close",
19211
- onClick: stableOnClose,
19212
- children: "✕"
19577
+ children: [showCloseButton && /* @__PURE__ */ jsx(DialogCloseButton, {
19578
+ dialogName: passageName ?? label ?? "dialog",
19579
+ passageName,
19580
+ onClose: stableOnClose
19213
19581
  }), /* @__PURE__ */ jsx("div", {
19214
19582
  class: "dialog-body",
19215
19583
  children: /* @__PURE__ */ jsx(ViewScopeContext.Provider, {
@@ -19221,6 +19589,26 @@ function PassageDialog({ passageName, fallbackMarkup, panelClass, onClose, label
19221
19589
  })
19222
19590
  });
19223
19591
  }
19592
+ /**
19593
+ * The `✕` button, registered as a `close-dialog` action while the dialog is
19594
+ * shown, so whatever opened it through the API can close it too (#540).
19595
+ */
19596
+ function DialogCloseButton({ dialogName, passageName, onClose }) {
19597
+ useAction({
19598
+ type: "close-dialog",
19599
+ key: dialogName,
19600
+ label: "Close",
19601
+ target: passageName,
19602
+ perform: onClose
19603
+ });
19604
+ return /* @__PURE__ */ jsx("button", {
19605
+ type: "button",
19606
+ class: "dialog-close",
19607
+ "aria-label": "Close",
19608
+ onClick: onClose,
19609
+ children: "✕"
19610
+ });
19611
+ }
19224
19612
  //#endregion
19225
19613
  //#region src/components/TriggerDialogHost.tsx
19226
19614
  function TriggerDialogHost() {
@@ -19400,10 +19788,13 @@ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
19400
19788
  * early, while text it leaves unescaped (in `<style>`, comments) would be
19401
19789
  * decoded wrongly.
19402
19790
  */
19403
- function passageMarkup(parent) {
19791
+ function passageMarkup(parent, inElement = false) {
19792
+ const escapeText = inElement && !isLiteralTextElement(parent);
19404
19793
  let markup = "";
19405
- for (const node of Array.from(parent.childNodes)) if (node.nodeType === Node.TEXT_NODE) markup += node.data;
19406
- else if (node.nodeType === Node.COMMENT_NODE) markup += `<!--${node.data}-->`;
19794
+ for (const node of Array.from(parent.childNodes)) if (node.nodeType === Node.TEXT_NODE) {
19795
+ const { data } = node;
19796
+ markup += escapeText ? escapeMarkupText(data, false, escapeTextReferences) : data;
19797
+ } else if (node.nodeType === Node.COMMENT_NODE) markup += `<!--${node.data}-->`;
19407
19798
  else if (node.nodeType === Node.ELEMENT_NODE) markup += elementMarkup(node);
19408
19799
  return markup;
19409
19800
  }
@@ -19415,7 +19806,7 @@ function elementMarkup(el) {
19415
19806
  markup += ">";
19416
19807
  if (el.namespaceURI === HTML_NAMESPACE && VOID_ELEMENTS.has(name)) return markup;
19417
19808
  const content = name === "template" ? el.content : el;
19418
- return `${markup}${passageMarkup(content)}</${name}>`;
19809
+ return `${markup}${passageMarkup(content, true)}</${name}>`;
19419
19810
  }
19420
19811
  /**
19421
19812
  * An attribute value quoted so that the passage parser reads it back:
@@ -19437,15 +19828,27 @@ function quoteAttribute(name, value) {
19437
19828
  const tag = tokens[0];
19438
19829
  return tokens.length === 1 && tag?.type === "html" && tag.attributes[probe] === quoted.slice(1, -1);
19439
19830
  };
19440
- return [`"${value}"`, `'${value}'`].find(readsBack) ?? `"${escapeTextQuotes(value, code)}"`;
19831
+ const text = escapeMarkupText(value, code, escapeAttributeReferences);
19832
+ return [`"${text}"`, `'${text}'`].find(readsBack) ?? `"${escapeMarkupText(text, code, escapeQuotes)}"`;
19833
+ }
19834
+ var escapeQuotes = (text) => text.replace(/"/g, "&quot;");
19835
+ var escapeAttributeReferences = (text) => text.replace(/&/g, "&amp;");
19836
+ /** Also `<`, which would start a tag in the passage. */
19837
+ var escapeTextReferences = (text) => escapeAttributeReferences(text).replace(/</g, "&lt;");
19838
+ /**
19839
+ * Elements whose text the renderer shows as written, with no character
19840
+ * references decoded: the one it treats as raw text (`style`, see
19841
+ * HtmlNodeRenderer), for which the browser did not decode any either.
19842
+ */
19843
+ function isLiteralTextElement(parent) {
19844
+ return parent.localName === "style" && parent.namespaceURI === HTML_NAMESPACE;
19441
19845
  }
19442
19846
  /**
19443
- * `value` with the double quotes in its text written as `&quot;`, but not
19444
- * those in markup (`{print "a"}`) or, in a code attribute, in sigil
19445
- * references (see splitSigilTemplate), which are code.
19847
+ * `value` with the text in it escaped by `escape`, but not markup
19848
+ * (`{print "a"}`) or, in a code attribute, sigil references (see
19849
+ * splitSigilTemplate), which are code.
19446
19850
  */
19447
- function escapeTextQuotes(value, code) {
19448
- const escape = (text) => text.replace(/"/g, "&quot;");
19851
+ function escapeMarkupText(value, code, escape) {
19449
19852
  if (code) return splitSigilTemplate(value).map((part) => "text" in part ? escape(part.text) : "expr" in part ? `{${part.expr}}` : part.verbatim).join("");
19450
19853
  let tokens;
19451
19854
  try {
@@ -19693,161 +20096,6 @@ function editedItems(since, state) {
19693
20096
  return (list, item, index) => typeof item === "object" && item !== null ? through.has(item) : ends.get(list)?.has(String(index)) === true;
19694
20097
  }
19695
20098
  //#endregion
19696
- //#region src/action-registry.ts
19697
- /** The fields of a StoryAction that are left out when unset. */
19698
- var OPTIONAL_ACTION_FIELDS = [
19699
- "target",
19700
- "variable",
19701
- "options",
19702
- "value",
19703
- "disabled"
19704
- ];
19705
- /**
19706
- * The registrations holding each ID, oldest first; the newest is the one
19707
- * listed. Generated IDs don't collide, but author IDs can, and one control's
19708
- * cleanup must not remove another control holding the same ID (#233).
19709
- */
19710
- var actions = /* @__PURE__ */ new Map();
19711
- var idCounters = /* @__PURE__ */ new Map();
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
- /**
19720
- * The counters reset on every navigation, so a passage's controls get the
19721
- * same IDs each time it is shown. Controls that stay mounted across
19722
- * navigations (e.g. in StoryInterface) keep theirs, so allocation skips every
19723
- * ID still registered (#233) and every one allocated but not registered yet
19724
- * (#486).
19725
- */
19726
- function generateActionId(type, key, authorId) {
19727
- if (authorId) {
19728
- reserved.add(authorId);
19729
- return authorId;
19730
- }
19731
- const base = `${type}:${key}`;
19732
- let count = idCounters.get(base) ?? 0;
19733
- let id;
19734
- do {
19735
- count++;
19736
- id = count === 1 ? base : `${base}:${count}`;
19737
- } while (actions.has(id) || reserved.has(id));
19738
- idCounters.set(base, count);
19739
- reserved.add(id);
19740
- return id;
19741
- }
19742
- function registerAction(action) {
19743
- const id = action.id;
19744
- const entry = { action };
19745
- const entries = actions.get(id);
19746
- if (entries) {
19747
- console.warn(`spindle: two mounted controls share the action ID "${id}"; Story.getActions() lists only the newer one.`);
19748
- entries.push(entry);
19749
- } else actions.set(id, [entry]);
19750
- notify();
19751
- return {
19752
- update(next) {
19753
- const current = actions.get(id);
19754
- if (!current?.includes(entry)) return;
19755
- entry.action = next;
19756
- if (current[current.length - 1] === entry) notify();
19757
- },
19758
- unregister() {
19759
- const current = actions.get(id);
19760
- const index = current ? current.indexOf(entry) : -1;
19761
- if (!current || index === -1) return;
19762
- current.splice(index, 1);
19763
- if (current.length === 0) {
19764
- actions.delete(id);
19765
- reserved.delete(id);
19766
- }
19767
- if (index === current.length) notify();
19768
- }
19769
- };
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
- }
19791
- function getActions() {
19792
- return Array.from(actions.values(), listed);
19793
- }
19794
- function getAction(id) {
19795
- const entries = actions.get(id);
19796
- return entries && listed(entries);
19797
- }
19798
- function listed(entries) {
19799
- return entries[entries.length - 1].action;
19800
- }
19801
- function resetIdCounters() {
19802
- idCounters.clear();
19803
- for (const id of reserved) if (!actions.has(id)) reserved.delete(id);
19804
- }
19805
- function notify() {
19806
- emit("actionsChanged");
19807
- }
19808
- //#endregion
19809
- //#region src/hooks/use-action.ts
19810
- function useAction(opts) {
19811
- const idRef = useRef("");
19812
- const performRef = useRef(opts.perform);
19813
- performRef.current = opts.perform;
19814
- if (!idRef.current) idRef.current = generateActionId(opts.type, opts.key, opts.authorId);
19815
- const id = idRef.current;
19816
- const buildAction = () => {
19817
- const action = {
19818
- id,
19819
- type: opts.type,
19820
- label: opts.label,
19821
- perform: (...args) => performRef.current(...args)
19822
- };
19823
- for (const field of OPTIONAL_ACTION_FIELDS) if (opts[field] !== void 0) Object.assign(action, { [field]: opts[field] });
19824
- return action;
19825
- };
19826
- const registration = useRef(null);
19827
- useLayoutEffect(() => {
19828
- const own = registerAction(buildAction());
19829
- registration.current = own;
19830
- return () => own.unregister();
19831
- }, [id]);
19832
- const registered = useRef(false);
19833
- useLayoutEffect(() => {
19834
- if (!registered.current) {
19835
- registered.current = true;
19836
- return;
19837
- }
19838
- registration.current?.update(buildAction());
19839
- }, [
19840
- opts.type,
19841
- opts.label,
19842
- opts.target,
19843
- opts.variable,
19844
- opts.disabled,
19845
- opts.value,
19846
- JSON.stringify(opts.options)
19847
- ]);
19848
- return id;
19849
- }
19850
- //#endregion
19851
20099
  //#region src/utils/extract-text.ts
19852
20100
  /**
19853
20101
  * Collect plain text from AST nodes, ignoring non-text nodes.
@@ -20010,8 +20258,8 @@ function ensureVariableChangedSubscription() {
20010
20258
  const changed = {};
20011
20259
  const collect = (prev, next, prefix) => {
20012
20260
  for (const key of changedNames(prev, next)) changed[prefix + key] = {
20013
- from: ownValue(prev, key),
20014
- to: ownValue(next, key)
20261
+ from: readOnlyValue(ownValue(prev, key)),
20262
+ to: readOnlyValue(ownValue(next, key))
20015
20263
  };
20016
20264
  };
20017
20265
  collect(prevVars, state.variables, "");
@@ -20178,6 +20426,7 @@ function createStoryAPI() {
20178
20426
  await new Promise((resolve) => {
20179
20427
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
20180
20428
  });
20429
+ await new Promise((resolve) => setTimeout(resolve, 0));
20181
20430
  const isRendered = () => getRenderedNavigationId() === useStoryStore.getState().navigationId;
20182
20431
  if (getRenderedNavigationId() !== null && !isRendered() && !useStoryStore.getState().renderDeferred) await new Promise((resolve) => {
20183
20432
  const off = on("passagerender", () => {
@@ -21586,12 +21835,24 @@ function resolveTransition(targetTags, nextTransition, storeDefault) {
21586
21835
  }
21587
21836
  //#endregion
21588
21837
  //#region src/components/macros/PassageDisplay.tsx
21838
+ /** Input types whose `value` is not what the user sees or edits. */
21839
+ var VALUELESS_INPUTS = /* @__PURE__ */ new Set([
21840
+ "checkbox",
21841
+ "radio",
21842
+ "file",
21843
+ "hidden",
21844
+ "button",
21845
+ "submit",
21846
+ "reset",
21847
+ "image"
21848
+ ]);
21589
21849
  /**
21590
21850
  * 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.
21851
+ * pixels of each canvas, the state of form controls (cloneNode keeps
21852
+ * attributes only, and a canvas's bitmap is not one), and the visible frame
21853
+ * and position of media. Source and clone have the same structure, so
21854
+ * elements pair up by position. Best effort: a canvas or video that can not
21855
+ * be drawn from stays as cloned.
21595
21856
  */
21596
21857
  function copyLiveState(source, clone) {
21597
21858
  const pairs = (selector, each) => {
@@ -21608,22 +21869,80 @@ function copyLiveState(source, clone) {
21608
21869
  } catch {}
21609
21870
  });
21610
21871
  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;
21872
+ if (from instanceof HTMLSelectElement) {
21873
+ const select = to;
21874
+ if (!from.multiple) select.selectedIndex = from.selectedIndex;
21875
+ else for (let i = 0; i < from.options.length; i++) {
21876
+ const option = select.options[i];
21877
+ if (option) option.selected = from.options[i].selected;
21878
+ }
21879
+ } else if (from instanceof HTMLInputElement) {
21880
+ const input = to;
21881
+ input.checked = from.checked;
21882
+ input.indeterminate = from.indeterminate;
21883
+ if (!VALUELESS_INPUTS.has(from.type)) input.value = from.value;
21884
+ } else to.value = from.value;
21613
21885
  });
21886
+ pairs("audio, video", (from, to) => {
21887
+ to.pause?.();
21888
+ to.muted = true;
21889
+ to.removeAttribute("autoplay");
21890
+ try {
21891
+ to.currentTime = from.currentTime;
21892
+ } catch {}
21893
+ if (!(from instanceof HTMLVideoElement && to instanceof HTMLVideoElement)) return;
21894
+ if (from.readyState < 2 || !from.videoWidth || !from.videoHeight) return;
21895
+ try {
21896
+ const frame = document.createElement("canvas");
21897
+ frame.width = from.videoWidth;
21898
+ frame.height = from.videoHeight;
21899
+ frame.getContext("2d")?.drawImage(from, 0, 0);
21900
+ to.setAttribute("poster", frame.toDataURL("image/jpeg", .92));
21901
+ } catch {}
21902
+ });
21903
+ }
21904
+ /**
21905
+ * Scroll offsets of the elements of `source` (itself included) that are
21906
+ * scrolled, keyed by the matching element of `clone`. Applied once the clone
21907
+ * is in the page: a detached element has nothing to scroll.
21908
+ */
21909
+ function scrollOffsets(source, clone) {
21910
+ const from = [source, ...source.querySelectorAll("*")];
21911
+ const to = [clone, ...clone.querySelectorAll("*")];
21912
+ const offsets = [];
21913
+ from.forEach((el, i) => {
21914
+ if (to[i] && (el.scrollTop || el.scrollLeft)) offsets.push([
21915
+ to[i],
21916
+ el.scrollTop,
21917
+ el.scrollLeft
21918
+ ]);
21919
+ });
21920
+ return offsets;
21921
+ }
21922
+ var pendingScrolls = /* @__PURE__ */ new WeakMap();
21923
+ /** Add `snapshot` to `container`, scrolled as what it shows was. */
21924
+ function appendSnapshot(container, snapshot) {
21925
+ container.appendChild(snapshot);
21926
+ for (const [el, top, left] of pendingScrolls.get(snapshot) ?? []) {
21927
+ el.scrollTop = top;
21928
+ el.scrollLeft = left;
21929
+ }
21930
+ pendingScrolls.delete(snapshot);
21614
21931
  }
21615
21932
  /**
21616
21933
  * Create a snapshot clone of a .passage element for outgoing transitions.
21617
21934
  * - Strips `id` attributes from the clone tree
21618
21935
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
21619
21936
  * - Pauses/mutes any <audio>/<video>
21620
- * - Copies what cloneNode leaves behind: canvas pixels and the values of
21621
- * form controls (#512)
21937
+ * - Copies what cloneNode leaves behind: canvas pixels, the state of form
21938
+ * controls, the visible frame of videos (#512, #525, #536) and, through
21939
+ * `appendSnapshot`, scroll offsets
21622
21940
  * - Adds `.passage-snapshot` class and `data-transition` attribute
21623
21941
  */
21624
21942
  function createSnapshot(passageEl, transitionType) {
21625
21943
  const clone = passageEl.cloneNode(true);
21626
21944
  copyLiveState(passageEl, clone);
21945
+ pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
21627
21946
  clone.removeAttribute("id");
21628
21947
  const idEls = clone.querySelectorAll("[id]");
21629
21948
  for (let i = 0; i < idEls.length; i++) idEls[i].removeAttribute("id");
@@ -21631,12 +21950,6 @@ function createSnapshot(passageEl, transitionType) {
21631
21950
  clone.style.userSelect = "none";
21632
21951
  clone.setAttribute("inert", "");
21633
21952
  clone.setAttribute("aria-hidden", "true");
21634
- const mediaEls = clone.querySelectorAll("audio, video");
21635
- for (let i = 0; i < mediaEls.length; i++) {
21636
- const media = mediaEls[i];
21637
- media.pause?.();
21638
- media.muted = true;
21639
- }
21640
21953
  clone.classList.remove("passage");
21641
21954
  clone.classList.add("passage-snapshot");
21642
21955
  clone.setAttribute("data-transition", transitionType);
@@ -21785,7 +22098,7 @@ defineMacro({
21785
22098
  return;
21786
22099
  }
21787
22100
  if (config.type === "fade-through") {
21788
- containerEl.appendChild(snapshot);
22101
+ appendSnapshot(containerEl, snapshot);
21789
22102
  setDisplayedPassage("");
21790
22103
  const incomingDelay = config.duration + config.pause;
21791
22104
  const t1 = setTimeout(() => {
@@ -21801,7 +22114,7 @@ defineMacro({
21801
22114
  return;
21802
22115
  }
21803
22116
  containerEl.classList.add("passage-container--crossfading");
21804
- containerEl.appendChild(snapshot);
22117
+ appendSnapshot(containerEl, snapshot);
21805
22118
  setDisplayedPassage(currentPassage);
21806
22119
  const t1 = setTimeout(() => {
21807
22120
  cleanupSnapshots(containerEl);
@@ -22380,7 +22693,7 @@ defineMacro({
22380
22693
  if (count === 0 && !stopped) return null;
22381
22694
  const content = /* @__PURE__ */ jsx(RepeatContext.Provider, {
22382
22695
  value: { stop },
22383
- children: /* @__PURE__ */ jsx("span", { children: ctx.renderNodes(children) }, count)
22696
+ children: /* @__PURE__ */ jsx(Fragment, { children: ctx.renderNodes(children) }, count)
22384
22697
  });
22385
22698
  if (ctx.className || ctx.id) return /* @__PURE__ */ jsx("span", {
22386
22699
  id: ctx.id,
@@ -23008,16 +23321,25 @@ defineMacro({
23008
23321
  name: "noclose",
23009
23322
  type: "flag"
23010
23323
  }],
23011
- render({ children = [] }, ctx) {
23324
+ render({ rawArgs, children = [] }, ctx) {
23012
23325
  const [open, setOpen] = ctx.hooks.useState(false);
23013
23326
  const { noclose } = ctx.args;
23014
- const label = ctx.resolve(ctx.args.label ?? "");
23327
+ const label = ctx.resolve(ctx.args.label ?? "") ?? "";
23015
23328
  const passageName = ctx.collectText(children).trim().replace(/^["']|["']$/g, "");
23329
+ const openDialog = () => setOpen(true);
23330
+ ctx.useAction({
23331
+ type: "open-dialog",
23332
+ key: rawArgs,
23333
+ authorId: ctx.id,
23334
+ label,
23335
+ target: passageName,
23336
+ perform: openDialog
23337
+ });
23016
23338
  return /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("button", {
23017
23339
  type: "button",
23018
23340
  id: ctx.id,
23019
23341
  class: ctx.cls,
23020
- onClick: () => setOpen(true),
23342
+ onClick: openDialog,
23021
23343
  children: label
23022
23344
  }), open && /* @__PURE__ */ jsx(PassageDialog, {
23023
23345
  passageName,
@@ -23112,7 +23434,8 @@ function SaveManagerContent({ className, id }) {
23112
23434
  const playthrough = resolvePlaythroughId();
23113
23435
  try {
23114
23436
  await saveWithHooks(void 0, void 0, beginSave, async (payload) => {
23115
- return createSave(ifid, playthrough, payload);
23437
+ const saved = await createSave(ifid, playthrough, payload);
23438
+ await followSavedPlaythrough(playthrough, saved);
23116
23439
  });
23117
23440
  showStatus(temporary ? "Save created (temporary)" : "Save created");
23118
23441
  await refresh();
@@ -23124,7 +23447,9 @@ function SaveManagerContent({ className, id }) {
23124
23447
  const playthrough = resolvePlaythroughId();
23125
23448
  try {
23126
23449
  await saveWithHooks(void 0, void 0, beginSave, async (payload) => {
23127
- if (!await overwriteSave(saveId, payload, void 0, playthrough)) throw new Error("Save not found");
23450
+ const saved = await overwriteSave(saveId, payload, void 0, playthrough);
23451
+ if (!saved) throw new Error("Save not found");
23452
+ await followSavedPlaythrough(playthrough, saved);
23128
23453
  });
23129
23454
  showStatus("Save overwritten");
23130
23455
  await refresh();
@@ -23548,6 +23873,15 @@ defineMacro({
23548
23873
  });
23549
23874
  //#endregion
23550
23875
  //#region src/components/macros/Unset.tsx
23876
+ /** What `name` is as a variable reference, or null if it is no reference. */
23877
+ function referencePath(name) {
23878
+ try {
23879
+ return parseReferencePath(name);
23880
+ } catch (error) {
23881
+ if (error instanceof CodeSyntaxError) return null;
23882
+ throw error;
23883
+ }
23884
+ }
23551
23885
  defineMacro({
23552
23886
  name: "unset",
23553
23887
  parameters: [{
@@ -23559,12 +23893,13 @@ defineMacro({
23559
23893
  return useRunOnce("unset", rawArgs, () => {
23560
23894
  const state = useStoryStore.getState();
23561
23895
  const name = ctx.args.variable ?? "";
23562
- if (/^[$_%@][^.]*\./.test(name)) ctx.mutate(`delete ${name}`);
23563
- else if (name.startsWith("$")) state.deleteVariable(name.slice(1));
23564
- else if (name.startsWith("_")) state.deleteTemporary(name.slice(1));
23565
- else if (name.startsWith("%")) state.deleteTransient(name.slice(1));
23566
- else if (name.startsWith("@")) ctx.update(name.slice(1), void 0);
23567
- else throw new Error(`{unset} expects a variable ($name, _name, %name, or @name), got "${name}"`);
23896
+ const path = referencePath(name);
23897
+ if (!path) throw new Error(`{unset} expects a variable ($name, _name, %name, or @name, or a field of one such as $name.field or $name["field"]), got "${name}"`);
23898
+ else if (path.nested) ctx.mutate(`delete ${name}`);
23899
+ else if (path.sigil === "$") state.deleteVariable(path.name);
23900
+ else if (path.sigil === "_") state.deleteTemporary(path.name);
23901
+ else if (path.sigil === "%") state.deleteTransient(path.name);
23902
+ else ctx.update(path.name, void 0);
23568
23903
  });
23569
23904
  }
23570
23905
  });
@@ -23972,7 +24307,7 @@ function boot() {
23972
24307
  throw new Error(`spindle: ${msg}`);
23973
24308
  }
23974
24309
  const schema = orStop(() => parseStoryVariables(storyVarsPassage.content));
23975
- for (const name of orStop(() => blockWidgetNames(storyData.passages.values()))) registerBlockMacro(name);
24310
+ for (const { name, block } of orStop(() => effectiveWidgets(storyData.passages.values()))) setBlockWidget(name, block);
23976
24311
  const errors = variableErrors(storyData, schema);
23977
24312
  errors.push(...markupErrors(storyData, (p) => p.name === "StoryInit"));
23978
24313
  let transientDefaults = {};