@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.
package/src/store.ts CHANGED
@@ -68,6 +68,7 @@ import {
68
68
  restorePRNG,
69
69
  resetPRNG,
70
70
  withoutDraws,
71
+ keepDrawsSoFar,
71
72
  type PRNGSnapshot,
72
73
  } from './prng';
73
74
  import { errorMessage } from './utils/error-message';
@@ -481,6 +482,17 @@ function enterStart(
481
482
  state.historyIndex = 0;
482
483
  }
483
484
 
485
+ /**
486
+ * Run `fn` (an event's handlers) and tell whether they replaced the game
487
+ * state (a restart or load): what the caller was about to do to the game it
488
+ * emitted from is then not to be done to the new one (#516, #517).
489
+ */
490
+ function replacesState(fn: () => void): boolean {
491
+ const applied = latestStateApplied;
492
+ fn();
493
+ return latestStateApplied !== applied;
494
+ }
495
+
484
496
  /**
485
497
  * Move through history by `step` moments (back or forward), restoring the
486
498
  * snapshot recorded for the moment moved to: live variables may hold edits
@@ -494,7 +506,13 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
494
506
 
495
507
  const previousPassage = get().currentPassage;
496
508
  const targetPassage = history[target]!.passage;
509
+ // The target is a place in the history as it is now: a callback that went
510
+ // elsewhere (a restart, a load, a navigation or traversal of its own) took
511
+ // the game on, and this traversal is dropped rather than applied to a
512
+ // history that is no longer the one it was computed from (#516)
513
+ const navigation = get().navigationId;
497
514
  emit('beforenavigate', targetPassage);
515
+ if (get().navigationId !== navigation) return;
498
516
 
499
517
  const restoredVars = deepClone(reconstructVarsAt(target));
500
518
 
@@ -510,6 +528,7 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
510
528
  reinitTriggerState();
511
529
  lastNavigationVars = get().variables;
512
530
  restorePRNGFromMoment(get().history[get().historyIndex]);
531
+ keepDrawsSoFar();
513
532
  persistSessionThen(get, () =>
514
533
  emit('afternavigate', targetPassage, previousPassage),
515
534
  );
@@ -533,6 +552,7 @@ export function recordStoryInitState(): void {
533
552
  useStoryStore.setState((state) => {
534
553
  state.history[0]!.prng = prng;
535
554
  });
555
+ keepDrawsSoFar();
536
556
  }
537
557
 
538
558
  // ---------------------------------------------------------------------------
@@ -656,6 +676,24 @@ function switchToLoadedPlaythrough(ifid: string, id: string): void {
656
676
  switchToPlaythrough(id, stored);
657
677
  }
658
678
 
679
+ /**
680
+ * Move the running game to the playthrough a save it wrote was stored in,
681
+ * when that is not the one it asked for: another tab deleted the game's
682
+ * playthrough, and the save took the story's current one (#527). `requested`
683
+ * is the playthrough the save was issued with (see resolvePlaythroughId). A
684
+ * game that has switched since (a restart, a load) stays where it is.
685
+ */
686
+ export async function followSavedPlaythrough(
687
+ requested: string | PromiseLike<string>,
688
+ saved: { meta: { playthroughId: string } } | undefined,
689
+ ): Promise<void> {
690
+ const id = saved?.meta.playthroughId;
691
+ const asked = await requested;
692
+ if (id && id !== asked && knownPlaythroughId() === asked) {
693
+ switchToPlaythrough(id, Promise.resolve());
694
+ }
695
+ }
696
+
659
697
  // ---------------------------------------------------------------------------
660
698
  // Superseded loads
661
699
  // ---------------------------------------------------------------------------
@@ -814,7 +852,7 @@ function keepHookWrites(
814
852
  keys.add(pathKey(path));
815
853
  const value = getByPath(after, path);
816
854
  if (deepEqual(getByPath(moment.variables, path), value)) continue;
817
- changes.push({ path, deleted: false, value });
855
+ changes.push({ path, deleted: false, value, absolute: true });
818
856
  }
819
857
  if (changes.length === 0) return;
820
858
  // A copy of its own, so the writes keep the snapshot's references (which
@@ -833,7 +871,8 @@ function keepHookWrites(
833
871
  * value of it is written. Into an array, elements removed from the end are
834
872
  * removed at the same indices and elements added are appended; changes at
835
873
  * indices the array lacks are dropped (it was resized, so its indices do not
836
- * line up with the live ones).
874
+ * line up with the live ones). The hooks' explicit writes are not diffs: an
875
+ * array's length or an element they set is set to that value (#515).
837
876
  */
838
877
  function writeHookChange(
839
878
  work: Record<string, unknown>,
@@ -878,6 +917,11 @@ function writeKey(
878
917
  // After the holes it followed
879
918
  holder.length += change.gap ?? 0;
880
919
  holder.push(value);
920
+ } else if (change && 'absolute' in change) {
921
+ // A write the hooks made: the length or element they set, whatever
922
+ // the snapshot's array looks like
923
+ if (key === 'length') holder.length = value as number;
924
+ else holder[index] = value;
881
925
  } else if (key === 'length' && change) {
882
926
  // Holes added at the end
883
927
  holder.length += value as number;
@@ -1364,7 +1408,9 @@ export const useStoryStore = create<StoryState>()(
1364
1408
  }
1365
1409
 
1366
1410
  const previousPassage = get().currentPassage;
1367
- emit('beforenavigate', passageName);
1411
+ // A callback that restarted or loaded replaced the game this
1412
+ // navigation was requested in: it does not carry on into the new one
1413
+ if (replacesState(() => emit('beforenavigate', passageName))) return;
1368
1414
 
1369
1415
  // Compute variable delta before Immer set(). Read the variables after
1370
1416
  // beforenavigate so changes made by its handlers are recorded.
@@ -1413,8 +1459,16 @@ export const useStoryStore = create<StoryState>()(
1413
1459
  const deferred = deferredNavigations;
1414
1460
  deferredNavigations = [];
1415
1461
  finishEnteredMoment(get, set);
1462
+ // The draws so far are the entered moment's recorded position
1463
+ keepDrawsSoFar();
1416
1464
  persistSessionThen(get, () => {
1417
- emit('afternavigate', passageName, previousPassage);
1465
+ if (
1466
+ replacesState(() =>
1467
+ emit('afternavigate', passageName, previousPassage),
1468
+ )
1469
+ ) {
1470
+ return;
1471
+ }
1418
1472
  for (const next of deferred) get().navigate(next);
1419
1473
  });
1420
1474
  },
@@ -1541,7 +1595,14 @@ export const useStoryStore = create<StoryState>()(
1541
1595
  state.saveError = null;
1542
1596
  });
1543
1597
  // Queued now, in call order with other storage operations
1544
- await quickSave(storyData.ifid, playthrough, payload, slot, custom);
1598
+ const saved = await quickSave(
1599
+ storyData.ifid,
1600
+ playthrough,
1601
+ payload,
1602
+ slot,
1603
+ custom,
1604
+ );
1605
+ await followSavedPlaythrough(playthrough, saved);
1545
1606
  recordKnownSave(set, slot, true);
1546
1607
  }),
1547
1608
  'spindle: failed to save',
@@ -1740,10 +1801,18 @@ export const useStoryStore = create<StoryState>()(
1740
1801
 
1741
1802
  beginSave: () => {
1742
1803
  const before = get().variables;
1804
+ const replaced = latestStateApplied;
1743
1805
  const writes = new Map<string, string[]>();
1744
1806
  hookWrites = writes;
1745
1807
  return () => {
1746
1808
  if (hookWrites === writes) hookWrites = null;
1809
+ // A restart or load in a hook left the game the save was issued
1810
+ // for (its playthrough) for another: no save describes both
1811
+ if (latestStateApplied !== replaced) {
1812
+ throw new Error(
1813
+ 'spindle: a beforesave handler restarted or loaded the game, so the save was not made',
1814
+ );
1815
+ }
1747
1816
  const payload = get().getSavePayload();
1748
1817
  keepHookWrites(payload, before, get().variables, [...writes.values()]);
1749
1818
  return payload;
@@ -1776,6 +1845,10 @@ export const useStoryStore = create<StoryState>()(
1776
1845
  } finally {
1777
1846
  leavingPlaythrough = null;
1778
1847
  }
1848
+ // A restart or load its handlers issued replaced the game after this
1849
+ // load did: the later one wins, as one issued after the load returned
1850
+ // would (#517)
1851
+ if (latestStateApplied !== replacement) return;
1779
1852
 
1780
1853
  // Loading a save moves the game to the save's playthrough, after the
1781
1854
  // `beforeload` handlers (whose saves belong to the game being left).
@@ -1848,6 +1921,7 @@ export const useStoryStore = create<StoryState>()(
1848
1921
  // Replay the passage's random rolls from its entry PRNG state; saves
1849
1922
  // whose moments predate PRNG snapshots use the payload's.
1850
1923
  restorePRNGFrom(entry?.prng !== undefined ? entry.prng : payload.prng);
1924
+ keepDrawsSoFar();
1851
1925
 
1852
1926
  // Write the loaded game to the session so a refresh restores it.
1853
1927
  // Draws made by the handlers would shift the passage's replayed rolls
package/src/story-api.ts CHANGED
@@ -101,9 +101,11 @@ function ensureVariableChangedSubscription(): void {
101
101
  prefix: string,
102
102
  ) => {
103
103
  for (const key of changedNames(prev, next)) {
104
+ // As Story.get() hands values out: a retained value must not be a
105
+ // way to change live state or recorded history (#518)
104
106
  changed[prefix + key] = {
105
- from: ownValue(prev, key),
106
- to: ownValue(next, key),
107
+ from: readOnlyValue(ownValue(prev, key)),
108
+ to: readOnlyValue(ownValue(next, key)),
107
109
  };
108
110
  }
109
111
  };
@@ -447,6 +449,12 @@ function createStoryAPI(): StoryAPI {
447
449
  await new Promise<void>((resolve) => {
448
450
  requestAnimationFrame(() => requestAnimationFrame(() => resolve()));
449
451
  });
452
+ // Preact runs a component's effects a frame and a timer after it
453
+ // renders, and a store subscription made in one (useSyncExternalStore)
454
+ // only then sees an update made before it: the re-render it triggers is
455
+ // ahead of what the frames above wait for. A timer queued now runs after
456
+ // the one Preact queued in its frame.
457
+ await new Promise<void>((resolve) => setTimeout(resolve, 0));
450
458
  // A navigation can still be rendering: the passage display mounts the
451
459
  // new passage from an effect, after a fade-through's outgoing phase.
452
460
  // Its actions exist only once it is mounted, so wait for that. Compare
package/src/structural.ts CHANGED
@@ -681,6 +681,13 @@ export type PathChange =
681
681
  * holding equal content there still takes the write.
682
682
  */
683
683
  alias?: true;
684
+ /**
685
+ * Set for a write a caller made explicitly (a `Story.set` of a save
686
+ * hook), not found by a diff: the value is the one to hold at the
687
+ * path, also for an array's length and for an index past its end,
688
+ * which a diff's changes leave to the array they were found in.
689
+ */
690
+ absolute?: true;
684
691
  }
685
692
  | {
686
693
  path: string[];
package/src/tooling.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  } from './code-check';
22
22
  import {
23
23
  widgetDefinitions as readWidgetDefinitions,
24
+ effectiveWidgetDefinitions,
24
25
  type WidgetDefinition,
25
26
  } from './widgets/widget-def';
26
27
  import {
@@ -186,8 +187,8 @@ export function validateStoryMarkup(
186
187
  // The calls of widgets that declare what their arguments hold are checked
187
188
  const widgets = readWidgetDefinitions(list, parameterLookup(all));
188
189
  const blocks = new Set(
189
- widgets
190
- .filter((def) => def.block && def.closeStart !== undefined)
190
+ effectiveWidgetDefinitions(widgets)
191
+ .filter((def) => def.block)
191
192
  .map((def) => def.name.toLowerCase()),
192
193
  );
193
194
  const parametersOf = parameterLookup([
@@ -37,4 +37,8 @@ export class NameSet {
37
37
  delete(name: string): void {
38
38
  this.names.delete(name);
39
39
  }
40
+
41
+ clear(): void {
42
+ this.names.clear();
43
+ }
40
44
  }
@@ -115,10 +115,19 @@ export function withEntry(
115
115
  /** An empty namespace that cannot change. */
116
116
  export const EMPTY_NAMESPACE: Namespace = Object.freeze(createNamespace());
117
117
 
118
- /** The names whose own entries differ between `a` and `b`, `a`'s first. */
118
+ /**
119
+ * The names whose own entries differ between `a` and `b`, `a`'s first: an
120
+ * entry one holds and the other lacks (also one holding `undefined`), or
121
+ * values that are not the same by SameValue (#519): an unchanged NaN is no
122
+ * change, 0 and -0 differ.
123
+ */
119
124
  export function changedNames(a: object, b: object): string[] {
120
125
  const names = new Set([...Object.keys(a), ...Object.keys(b)]);
121
- return [...names].filter((name) => ownValue(a, name) !== ownValue(b, name));
126
+ return [...names].filter(
127
+ (name) =>
128
+ hasOwn(a, name) !== hasOwn(b, name) ||
129
+ !Object.is(ownValue(a, name), ownValue(b, name)),
130
+ );
122
131
  }
123
132
 
124
133
  /**
@@ -53,7 +53,9 @@ export function tokenTextContainsChildren(
53
53
  /**
54
54
  * Recursively scan an AST node array for a VariableNode
55
55
  * with scope 'local' and name 'children' (@children), in the content and in
56
- * the attributes and labels that render markup.
56
+ * the attributes and labels that render markup. A nested `{widget}` is not
57
+ * entered: its slot belongs to the innermost widget (as widgetDefinitions
58
+ * reads it), and a definition renders nothing of its own.
57
59
  */
58
60
  export function astContainsChildren(
59
61
  nodes: ASTNode[],
@@ -87,6 +89,7 @@ export function astContainsChildren(
87
89
  }
88
90
  }
89
91
  if (node.type === 'macro') {
92
+ if (node.name.toLowerCase() === 'widget') continue;
90
93
  const tag: Token = {
91
94
  isClose: false,
92
95
  nameStart: 0,
@@ -1,13 +1,13 @@
1
1
  import { registerWidget } from './widget-registry';
2
2
  import { astContainsChildren } from './ast-scanner';
3
- import { registerBlockMacro, type ASTNode } from '../markup/ast';
3
+ import type { ASTNode } from '../markup/ast';
4
4
  import { errorMessage } from '../utils/error-message';
5
5
  import { checkWidgetHolds, parseWidgetDef, type WidgetDef } from './widget-def';
6
6
 
7
7
  /**
8
8
  * Register the widget a definition declares, with its body. Widgets whose
9
9
  * body renders {@children} take a closing tag, so they are registered as
10
- * block macros too: passages parsed later nest their content. A parameter
10
+ * block macros too (see registerWidget). A parameter
11
11
  * that no namespace can hold or declares what it holds wrongly throws (see
12
12
  * registerWidget and checkWidgetHolds), registering nothing.
13
13
  */
@@ -16,7 +16,6 @@ export function registerWidgetDef(def: WidgetDef, body: ASTNode[]): void {
16
16
  const { name, params, holds } = def;
17
17
  const isBlock = astContainsChildren(body);
18
18
  registerWidget(name, body, params, isBlock, holds);
19
- if (isBlock) registerBlockMacro(name);
20
19
  }
21
20
 
22
21
  /**
@@ -7,6 +7,7 @@ import { STRING_HOLDS, type MacroArgs, type StringHolds } from '../registry';
7
7
  import { tokenizeMarkupTolerant } from '../markup/parse';
8
8
  import type { MacroToken } from '../markup/tokens';
9
9
  import type { ParametersOf } from '../code-check';
10
+ import { NameMap } from '../utils/macro-names';
10
11
  import { registeredParameters, tokenTextContainsChildren } from './ast-scanner';
11
12
 
12
13
  /** A {widget} definition's name, then its `@` parameters. */
@@ -182,16 +183,45 @@ export function widgetDefinitions(
182
183
  }
183
184
 
184
185
  /**
185
- * The names of the block widgets (those whose body renders `{@children}`)
186
- * that StoryInit and the passages tagged `widget` define, closed. They must
187
- * be known as block macros before any passage is parsed, so that passages
188
- * invoking them nest their content whatever the passage order.
186
+ * The definitions the runtime ends up with, one per widget name: the closed
187
+ * ones, the latest winning as registration replaces a widget. The widget
188
+ * passages register before StoryInit runs, so StoryInit's definitions come
189
+ * last whatever the passage order. Read with the flat scanner, so a nested
190
+ * definition owns its own `{@children}`.
189
191
  */
192
+ export function effectiveWidgetDefinitions(
193
+ definitions: readonly WidgetDefinition[],
194
+ ): WidgetDefinition[] {
195
+ const inInit = (def: WidgetDefinition) => def.passage === 'StoryInit';
196
+ const effective = new NameMap<WidgetDefinition>();
197
+ for (const def of [
198
+ ...definitions.filter((def) => !inInit(def)),
199
+ ...definitions.filter(inInit),
200
+ ]) {
201
+ if (def.closeStart !== undefined) effective.set(def.name, def);
202
+ }
203
+ return [...effective.values()];
204
+ }
205
+
206
+ /**
207
+ * The widgets that StoryInit and the passages tagged `widget` define, as the
208
+ * runtime ends up with them (see effectiveWidgetDefinitions). Whether each
209
+ * takes a body must be known before any passage is parsed, so that passages
210
+ * invoking them nest their content (or don't) whatever the passage order.
211
+ */
212
+ export function effectiveWidgets(
213
+ passages: Iterable<WidgetPassage>,
214
+ parametersOf: ParametersOf = registeredParameters,
215
+ ): WidgetDefinition[] {
216
+ return effectiveWidgetDefinitions(widgetDefinitions(passages, parametersOf));
217
+ }
218
+
219
+ /** The names of the block widgets among the effectiveWidgets. */
190
220
  export function blockWidgetNames(
191
221
  passages: Iterable<WidgetPassage>,
192
222
  parametersOf: ParametersOf = registeredParameters,
193
223
  ): string[] {
194
- return widgetDefinitions(passages, parametersOf)
195
- .filter((def) => def.block && def.closeStart !== undefined)
224
+ return effectiveWidgets(passages, parametersOf)
225
+ .filter((def) => def.block)
196
226
  .map((def) => def.name);
197
227
  }
@@ -1,4 +1,4 @@
1
- import type { ASTNode } from '../markup/ast';
1
+ import { clearBlockWidgets, setBlockWidget, type ASTNode } from '../markup/ast';
2
2
  import { checkVariableName } from '../utils/namespace';
3
3
  import { NameMap } from '../utils/macro-names';
4
4
  import type { StringHolds } from '../registry';
@@ -15,7 +15,9 @@ interface WidgetEntry {
15
15
  const widgets = new NameMap<WidgetEntry>();
16
16
 
17
17
  /**
18
- * Register a widget. Its `@` parameters become locals of its body, so one
18
+ * Register a widget. A widget whose body renders {@children} takes a closing
19
+ * tag, so it is a block macro to the parser too, for the passages parsed
20
+ * later; the latest definition decides. Its `@` parameters become locals of its body, so one
19
21
  * that no namespace can hold (`@__proto__`) throws a TypeError and the
20
22
  * widget is not registered.
21
23
  */
@@ -36,6 +38,7 @@ export function registerWidget(
36
38
  holds,
37
39
  isBlock,
38
40
  });
41
+ setBlockWidget(name, isBlock);
39
42
  }
40
43
 
41
44
  export function getWidget(name: string): WidgetEntry | undefined {
@@ -56,4 +59,5 @@ export function isBlockWidget(name: string): boolean {
56
59
 
57
60
  export function clearWidgets(): void {
58
61
  widgets.clear();
62
+ clearBlockWidgets();
59
63
  }