@rohal12/spindle 0.59.30 → 0.59.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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(() => {
@@ -19400,10 +19615,13 @@ var VOID_ELEMENTS = /* @__PURE__ */ new Set([
19400
19615
  * early, while text it leaves unescaped (in `<style>`, comments) would be
19401
19616
  * decoded wrongly.
19402
19617
  */
19403
- function passageMarkup(parent) {
19618
+ function passageMarkup(parent, inElement = false) {
19619
+ const escapeText = inElement && !isLiteralTextElement(parent);
19404
19620
  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}-->`;
19621
+ for (const node of Array.from(parent.childNodes)) if (node.nodeType === Node.TEXT_NODE) {
19622
+ const { data } = node;
19623
+ markup += escapeText ? escapeMarkupText(data, false, escapeTextReferences) : data;
19624
+ } else if (node.nodeType === Node.COMMENT_NODE) markup += `<!--${node.data}-->`;
19407
19625
  else if (node.nodeType === Node.ELEMENT_NODE) markup += elementMarkup(node);
19408
19626
  return markup;
19409
19627
  }
@@ -19415,7 +19633,7 @@ function elementMarkup(el) {
19415
19633
  markup += ">";
19416
19634
  if (el.namespaceURI === HTML_NAMESPACE && VOID_ELEMENTS.has(name)) return markup;
19417
19635
  const content = name === "template" ? el.content : el;
19418
- return `${markup}${passageMarkup(content)}</${name}>`;
19636
+ return `${markup}${passageMarkup(content, true)}</${name}>`;
19419
19637
  }
19420
19638
  /**
19421
19639
  * An attribute value quoted so that the passage parser reads it back:
@@ -19437,15 +19655,27 @@ function quoteAttribute(name, value) {
19437
19655
  const tag = tokens[0];
19438
19656
  return tokens.length === 1 && tag?.type === "html" && tag.attributes[probe] === quoted.slice(1, -1);
19439
19657
  };
19440
- return [`"${value}"`, `'${value}'`].find(readsBack) ?? `"${escapeTextQuotes(value, code)}"`;
19658
+ const text = escapeMarkupText(value, code, escapeAttributeReferences);
19659
+ return [`"${text}"`, `'${text}'`].find(readsBack) ?? `"${escapeMarkupText(text, code, escapeQuotes)}"`;
19660
+ }
19661
+ var escapeQuotes = (text) => text.replace(/"/g, "&quot;");
19662
+ var escapeAttributeReferences = (text) => text.replace(/&/g, "&amp;");
19663
+ /** Also `<`, which would start a tag in the passage. */
19664
+ var escapeTextReferences = (text) => escapeAttributeReferences(text).replace(/</g, "&lt;");
19665
+ /**
19666
+ * Elements whose text the renderer shows as written, with no character
19667
+ * references decoded: the one it treats as raw text (`style`, see
19668
+ * HtmlNodeRenderer), for which the browser did not decode any either.
19669
+ */
19670
+ function isLiteralTextElement(parent) {
19671
+ return parent.localName === "style" && parent.namespaceURI === HTML_NAMESPACE;
19441
19672
  }
19442
19673
  /**
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.
19674
+ * `value` with the text in it escaped by `escape`, but not markup
19675
+ * (`{print "a"}`) or, in a code attribute, sigil references (see
19676
+ * splitSigilTemplate), which are code.
19446
19677
  */
19447
- function escapeTextQuotes(value, code) {
19448
- const escape = (text) => text.replace(/"/g, "&quot;");
19678
+ function escapeMarkupText(value, code, escape) {
19449
19679
  if (code) return splitSigilTemplate(value).map((part) => "text" in part ? escape(part.text) : "expr" in part ? `{${part.expr}}` : part.verbatim).join("");
19450
19680
  let tokens;
19451
19681
  try {
@@ -20010,8 +20240,8 @@ function ensureVariableChangedSubscription() {
20010
20240
  const changed = {};
20011
20241
  const collect = (prev, next, prefix) => {
20012
20242
  for (const key of changedNames(prev, next)) changed[prefix + key] = {
20013
- from: ownValue(prev, key),
20014
- to: ownValue(next, key)
20243
+ from: readOnlyValue(ownValue(prev, key)),
20244
+ to: readOnlyValue(ownValue(next, key))
20015
20245
  };
20016
20246
  };
20017
20247
  collect(prevVars, state.variables, "");
@@ -20178,6 +20408,7 @@ function createStoryAPI() {
20178
20408
  await new Promise((resolve) => {
20179
20409
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
20180
20410
  });
20411
+ await new Promise((resolve) => setTimeout(resolve, 0));
20181
20412
  const isRendered = () => getRenderedNavigationId() === useStoryStore.getState().navigationId;
20182
20413
  if (getRenderedNavigationId() !== null && !isRendered() && !useStoryStore.getState().renderDeferred) await new Promise((resolve) => {
20183
20414
  const off = on("passagerender", () => {
@@ -21586,12 +21817,24 @@ function resolveTransition(targetTags, nextTransition, storeDefault) {
21586
21817
  }
21587
21818
  //#endregion
21588
21819
  //#region src/components/macros/PassageDisplay.tsx
21820
+ /** Input types whose `value` is not what the user sees or edits. */
21821
+ var VALUELESS_INPUTS = /* @__PURE__ */ new Set([
21822
+ "checkbox",
21823
+ "radio",
21824
+ "file",
21825
+ "hidden",
21826
+ "button",
21827
+ "submit",
21828
+ "reset",
21829
+ "image"
21830
+ ]);
21589
21831
  /**
21590
21832
  * 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.
21833
+ * pixels of each canvas, the state of form controls (cloneNode keeps
21834
+ * attributes only, and a canvas's bitmap is not one), and the visible frame
21835
+ * and position of media. Source and clone have the same structure, so
21836
+ * elements pair up by position. Best effort: a canvas or video that can not
21837
+ * be drawn from stays as cloned.
21595
21838
  */
21596
21839
  function copyLiveState(source, clone) {
21597
21840
  const pairs = (selector, each) => {
@@ -21608,22 +21851,80 @@ function copyLiveState(source, clone) {
21608
21851
  } catch {}
21609
21852
  });
21610
21853
  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;
21854
+ if (from instanceof HTMLSelectElement) {
21855
+ const select = to;
21856
+ if (!from.multiple) select.selectedIndex = from.selectedIndex;
21857
+ else for (let i = 0; i < from.options.length; i++) {
21858
+ const option = select.options[i];
21859
+ if (option) option.selected = from.options[i].selected;
21860
+ }
21861
+ } else if (from instanceof HTMLInputElement) {
21862
+ const input = to;
21863
+ input.checked = from.checked;
21864
+ input.indeterminate = from.indeterminate;
21865
+ if (!VALUELESS_INPUTS.has(from.type)) input.value = from.value;
21866
+ } else to.value = from.value;
21867
+ });
21868
+ pairs("audio, video", (from, to) => {
21869
+ to.pause?.();
21870
+ to.muted = true;
21871
+ to.removeAttribute("autoplay");
21872
+ try {
21873
+ to.currentTime = from.currentTime;
21874
+ } catch {}
21875
+ if (!(from instanceof HTMLVideoElement && to instanceof HTMLVideoElement)) return;
21876
+ if (from.readyState < 2 || !from.videoWidth || !from.videoHeight) return;
21877
+ try {
21878
+ const frame = document.createElement("canvas");
21879
+ frame.width = from.videoWidth;
21880
+ frame.height = from.videoHeight;
21881
+ frame.getContext("2d")?.drawImage(from, 0, 0);
21882
+ to.setAttribute("poster", frame.toDataURL("image/jpeg", .92));
21883
+ } catch {}
21884
+ });
21885
+ }
21886
+ /**
21887
+ * Scroll offsets of the elements of `source` (itself included) that are
21888
+ * scrolled, keyed by the matching element of `clone`. Applied once the clone
21889
+ * is in the page: a detached element has nothing to scroll.
21890
+ */
21891
+ function scrollOffsets(source, clone) {
21892
+ const from = [source, ...source.querySelectorAll("*")];
21893
+ const to = [clone, ...clone.querySelectorAll("*")];
21894
+ const offsets = [];
21895
+ from.forEach((el, i) => {
21896
+ if (to[i] && (el.scrollTop || el.scrollLeft)) offsets.push([
21897
+ to[i],
21898
+ el.scrollTop,
21899
+ el.scrollLeft
21900
+ ]);
21613
21901
  });
21902
+ return offsets;
21903
+ }
21904
+ var pendingScrolls = /* @__PURE__ */ new WeakMap();
21905
+ /** Add `snapshot` to `container`, scrolled as what it shows was. */
21906
+ function appendSnapshot(container, snapshot) {
21907
+ container.appendChild(snapshot);
21908
+ for (const [el, top, left] of pendingScrolls.get(snapshot) ?? []) {
21909
+ el.scrollTop = top;
21910
+ el.scrollLeft = left;
21911
+ }
21912
+ pendingScrolls.delete(snapshot);
21614
21913
  }
21615
21914
  /**
21616
21915
  * Create a snapshot clone of a .passage element for outgoing transitions.
21617
21916
  * - Strips `id` attributes from the clone tree
21618
21917
  * - Disables interaction (pointer-events, user-select, inert, aria-hidden)
21619
21918
  * - Pauses/mutes any <audio>/<video>
21620
- * - Copies what cloneNode leaves behind: canvas pixels and the values of
21621
- * form controls (#512)
21919
+ * - Copies what cloneNode leaves behind: canvas pixels, the state of form
21920
+ * controls, the visible frame of videos (#512, #525, #536) and, through
21921
+ * `appendSnapshot`, scroll offsets
21622
21922
  * - Adds `.passage-snapshot` class and `data-transition` attribute
21623
21923
  */
21624
21924
  function createSnapshot(passageEl, transitionType) {
21625
21925
  const clone = passageEl.cloneNode(true);
21626
21926
  copyLiveState(passageEl, clone);
21927
+ pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
21627
21928
  clone.removeAttribute("id");
21628
21929
  const idEls = clone.querySelectorAll("[id]");
21629
21930
  for (let i = 0; i < idEls.length; i++) idEls[i].removeAttribute("id");
@@ -21631,12 +21932,6 @@ function createSnapshot(passageEl, transitionType) {
21631
21932
  clone.style.userSelect = "none";
21632
21933
  clone.setAttribute("inert", "");
21633
21934
  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
21935
  clone.classList.remove("passage");
21641
21936
  clone.classList.add("passage-snapshot");
21642
21937
  clone.setAttribute("data-transition", transitionType);
@@ -21785,7 +22080,7 @@ defineMacro({
21785
22080
  return;
21786
22081
  }
21787
22082
  if (config.type === "fade-through") {
21788
- containerEl.appendChild(snapshot);
22083
+ appendSnapshot(containerEl, snapshot);
21789
22084
  setDisplayedPassage("");
21790
22085
  const incomingDelay = config.duration + config.pause;
21791
22086
  const t1 = setTimeout(() => {
@@ -21801,7 +22096,7 @@ defineMacro({
21801
22096
  return;
21802
22097
  }
21803
22098
  containerEl.classList.add("passage-container--crossfading");
21804
- containerEl.appendChild(snapshot);
22099
+ appendSnapshot(containerEl, snapshot);
21805
22100
  setDisplayedPassage(currentPassage);
21806
22101
  const t1 = setTimeout(() => {
21807
22102
  cleanupSnapshots(containerEl);
@@ -22380,7 +22675,7 @@ defineMacro({
22380
22675
  if (count === 0 && !stopped) return null;
22381
22676
  const content = /* @__PURE__ */ jsx(RepeatContext.Provider, {
22382
22677
  value: { stop },
22383
- children: /* @__PURE__ */ jsx("span", { children: ctx.renderNodes(children) }, count)
22678
+ children: /* @__PURE__ */ jsx(Fragment, { children: ctx.renderNodes(children) }, count)
22384
22679
  });
22385
22680
  if (ctx.className || ctx.id) return /* @__PURE__ */ jsx("span", {
22386
22681
  id: ctx.id,
@@ -23112,7 +23407,8 @@ function SaveManagerContent({ className, id }) {
23112
23407
  const playthrough = resolvePlaythroughId();
23113
23408
  try {
23114
23409
  await saveWithHooks(void 0, void 0, beginSave, async (payload) => {
23115
- return createSave(ifid, playthrough, payload);
23410
+ const saved = await createSave(ifid, playthrough, payload);
23411
+ await followSavedPlaythrough(playthrough, saved);
23116
23412
  });
23117
23413
  showStatus(temporary ? "Save created (temporary)" : "Save created");
23118
23414
  await refresh();
@@ -23124,7 +23420,9 @@ function SaveManagerContent({ className, id }) {
23124
23420
  const playthrough = resolvePlaythroughId();
23125
23421
  try {
23126
23422
  await saveWithHooks(void 0, void 0, beginSave, async (payload) => {
23127
- if (!await overwriteSave(saveId, payload, void 0, playthrough)) throw new Error("Save not found");
23423
+ const saved = await overwriteSave(saveId, payload, void 0, playthrough);
23424
+ if (!saved) throw new Error("Save not found");
23425
+ await followSavedPlaythrough(playthrough, saved);
23128
23426
  });
23129
23427
  showStatus("Save overwritten");
23130
23428
  await refresh();
@@ -23548,6 +23846,15 @@ defineMacro({
23548
23846
  });
23549
23847
  //#endregion
23550
23848
  //#region src/components/macros/Unset.tsx
23849
+ /** What `name` is as a variable reference, or null if it is no reference. */
23850
+ function referencePath(name) {
23851
+ try {
23852
+ return parseReferencePath(name);
23853
+ } catch (error) {
23854
+ if (error instanceof CodeSyntaxError) return null;
23855
+ throw error;
23856
+ }
23857
+ }
23551
23858
  defineMacro({
23552
23859
  name: "unset",
23553
23860
  parameters: [{
@@ -23559,12 +23866,13 @@ defineMacro({
23559
23866
  return useRunOnce("unset", rawArgs, () => {
23560
23867
  const state = useStoryStore.getState();
23561
23868
  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}"`);
23869
+ const path = referencePath(name);
23870
+ if (!path) throw new Error(`{unset} expects a variable ($name, _name, %name, or @name, or a field of one such as $name.field or $name["field"]), got "${name}"`);
23871
+ else if (path.nested) ctx.mutate(`delete ${name}`);
23872
+ else if (path.sigil === "$") state.deleteVariable(path.name);
23873
+ else if (path.sigil === "_") state.deleteTemporary(path.name);
23874
+ else if (path.sigil === "%") state.deleteTransient(path.name);
23875
+ else ctx.update(path.name, void 0);
23568
23876
  });
23569
23877
  }
23570
23878
  });
@@ -23972,7 +24280,7 @@ function boot() {
23972
24280
  throw new Error(`spindle: ${msg}`);
23973
24281
  }
23974
24282
  const schema = orStop(() => parseStoryVariables(storyVarsPassage.content));
23975
- for (const name of orStop(() => blockWidgetNames(storyData.passages.values()))) registerBlockMacro(name);
24283
+ for (const { name, block } of orStop(() => effectiveWidgets(storyData.passages.values()))) setBlockWidget(name, block);
23976
24284
  const errors = variableErrors(storyData, schema);
23977
24285
  errors.push(...markupErrors(storyData, (p) => p.name === "StoryInit"));
23978
24286
  let transientDefaults = {};