@rohal12/spindle 0.64.19 → 0.64.20

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.
@@ -19268,7 +19268,7 @@ function executeStoryInit() {
19268
19268
  container.style.display = "none";
19269
19269
  document.body.appendChild(container);
19270
19270
  storyInitContainer = container;
19271
- render(h(ActionsDisabledContext.Provider, { value: true }, h(() => renderNodes(ast), null)), container);
19271
+ settingUpStart(() => render(h(ActionsDisabledContext.Provider, { value: true }, h(() => renderNodes(ast), null)), container));
19272
19272
  recordStoryInitState();
19273
19273
  }
19274
19274
  const saveTitlePassage = state.storyData.passages.get("SaveTitle");
@@ -19288,9 +19288,13 @@ function initializeStory(session) {
19288
19288
  console.warn(`spindle: discarding the saved session: the story no longer has the passage "${missing}"`);
19289
19289
  session = void 0;
19290
19290
  }
19291
- if (session) useStoryStore.getState().loadFromPayload(session);
19292
- emit("storyinit");
19293
- if (!session) recordStoryInitState();
19291
+ if (session) {
19292
+ useStoryStore.getState().loadFromPayload(session);
19293
+ emit("storyinit");
19294
+ } else {
19295
+ settingUpStart(() => emit("storyinit"));
19296
+ recordStoryInitState();
19297
+ }
19294
19298
  }
19295
19299
  // src/passage-roles.ts
19296
19300
  /** Runtime-owned passage roles, shared with stateless authoring tools. */
@@ -19625,6 +19629,22 @@ function moveInHistory(get, set, step) {
19625
19629
  keepDrawsSoFar();
19626
19630
  persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage, kind));
19627
19631
  }
19632
+ /** How many runs of settingUpStart() are under way. */
19633
+ var startSetups = 0;
19634
+ /**
19635
+ * Run `fn`, which sets up the start moment of a new game: the StoryInit
19636
+ * passage, or the `storyinit` handlers at boot (unless a session was
19637
+ * restored) and on restart. recordStoryInitState() records what it leaves
19638
+ * behind, so recordMoment() has nothing to do meanwhile (see there).
19639
+ */
19640
+ function settingUpStart(fn) {
19641
+ startSetups++;
19642
+ try {
19643
+ return fn();
19644
+ } finally {
19645
+ startSetups--;
19646
+ }
19647
+ }
19628
19648
  /**
19629
19649
  * Record the state StoryInit left behind as the start moment: its variable
19630
19650
  * snapshot (the history base) and PRNG state. Called by executeStoryInit()
@@ -19645,6 +19665,32 @@ function recordStoryInitState() {
19645
19665
  keepDrawsSoFar();
19646
19666
  }
19647
19667
  /**
19668
+ * Record the live variables as the state of the current moment (see
19669
+ * StoryState.recordMoment): what a navigation does for the moment it
19670
+ * enters, without the navigation.
19671
+ */
19672
+ function recordCurrentMoment(get, set) {
19673
+ const { storyData, history, historyIndex, variables } = get();
19674
+ if (!storyData || historyIndex < 0) return;
19675
+ if (startSetups > 0 && history.length === 1) return;
19676
+ if (navigationTriggerPhase && enteredMoment?.navigationId === get().navigationId) return;
19677
+ const recorded = variables === lastNavigationVars || deepEqualStrict(reconstructVarsAt(historyIndex), variables);
19678
+ if (!recorded) {
19679
+ const entry = historyIndex > 0 ? computeVarPatches(reconstructVarsAt(historyIndex - 1), variables) : null;
19680
+ patchEntries.length = historyIndex;
19681
+ if (entry) patchEntries[historyIndex - 1] = entry;
19682
+ else variableBase = variables;
19683
+ if (sessionMoments.length > historyIndex) sessionMoments.length = historyIndex;
19684
+ lastNavigationVars = variables;
19685
+ if (historyIndex < history.length - 1) set((state) => {
19686
+ state.history = state.history.slice(0, historyIndex + 1);
19687
+ });
19688
+ clearReplayWatchers();
19689
+ }
19690
+ for (const capture of hookCaptures) capture.before = variables;
19691
+ if (!recorded) persistSessionThen(get);
19692
+ }
19693
+ /**
19648
19694
  * Settles once the latest playthrough switch (init's lookup or creation, a
19649
19695
  * restart's creation, the replacement of a deleted current playthrough, a
19650
19696
  * load making the loaded save's playthrough current) is stored, with the
@@ -19848,11 +19894,10 @@ function loadedEntryMoment(payload) {
19848
19894
  if (typeof moment.variables !== "object" || moment.variables === null) return;
19849
19895
  return moment;
19850
19896
  }
19851
- /** The variable paths `Story.set` writes while a save's hooks run. */
19852
- var hookWrites = /* @__PURE__ */ new Set();
19897
+ var hookCaptures = /* @__PURE__ */ new Set();
19853
19898
  /** Note that `path` of the variables was written (see keepHookWrites). */
19854
19899
  function recordHookWrite(path) {
19855
- for (const writes of hookWrites) writes.set(pathKey(path), path);
19900
+ for (const { writes } of hookCaptures) writes.set(pathKey(path), path);
19856
19901
  }
19857
19902
  /**
19858
19903
  * Write the changes between `before` and `after` (the live variables around
@@ -19987,6 +20032,7 @@ var PROGRAM_ORDER_ACTIONS = [
19987
20032
  "navigate",
19988
20033
  "goBack",
19989
20034
  "goForward",
20035
+ "recordMoment",
19990
20036
  "restart",
19991
20037
  "save",
19992
20038
  "load",
@@ -20223,6 +20269,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20223
20269
  },
20224
20270
  goBack: () => moveInHistory(get, set, -1),
20225
20271
  goForward: () => moveInHistory(get, set, 1),
20272
+ recordMoment: () => recordCurrentMoment(get, set),
20226
20273
  setVariable: (name, value) => {
20227
20274
  set((state) => {
20228
20275
  checkVariableName(name, `$${name}`);
@@ -20295,7 +20342,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20295
20342
  enterRuntimePhase();
20296
20343
  executeStoryInit();
20297
20344
  clearSession(storyData.ifid);
20298
- emit("storyinit");
20345
+ settingUpStart(() => emit("storyinit"));
20299
20346
  recordStoryInitState();
20300
20347
  },
20301
20348
  save: (slot, custom) => {
@@ -20408,18 +20455,20 @@ var useStoryStore = create()(storyStore((set, get) => ({
20408
20455
  };
20409
20456
  },
20410
20457
  beginSave: () => {
20411
- const before = get().variables;
20458
+ const capture = {
20459
+ before: get().variables,
20460
+ writes: /* @__PURE__ */ new Map()
20461
+ };
20412
20462
  const replaced = latestStateApplied;
20413
- const writes = /* @__PURE__ */ new Map();
20414
- hookWrites.add(writes);
20463
+ hookCaptures.add(capture);
20415
20464
  const dispose = () => {
20416
- hookWrites.delete(writes);
20465
+ hookCaptures.delete(capture);
20417
20466
  };
20418
20467
  return Object.assign(() => {
20419
20468
  dispose();
20420
20469
  if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
20421
20470
  const payload = get().getSavePayload();
20422
- keepHookWrites(payload, before, get().variables, [...writes.values()]);
20471
+ keepHookWrites(payload, capture.before, get().variables, [...capture.writes.values()]);
20423
20472
  return payload;
20424
20473
  }, { dispose });
20425
20474
  },
@@ -22190,6 +22239,7 @@ function createStoryAPI() {
22190
22239
  goto: storeAction("navigate"),
22191
22240
  back: storeAction("goBack"),
22192
22241
  forward: storeAction("goForward"),
22242
+ recordMoment: storeAction("recordMoment"),
22193
22243
  restart: storeAction("restart"),
22194
22244
  save: storeAction("save"),
22195
22245
  load: storeAction("load"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.19",
3
+ "version": "0.64.20",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/store.ts CHANGED
@@ -58,6 +58,7 @@ import {
58
58
  existingObjects,
59
59
  locateObjects,
60
60
  deepEqual,
61
+ deepEqualStrict,
61
62
  mergesWith,
62
63
  pathKey,
63
64
  shareEqual,
@@ -549,6 +550,24 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
549
550
  );
550
551
  }
551
552
 
553
+ /** How many runs of settingUpStart() are under way. */
554
+ let startSetups = 0;
555
+
556
+ /**
557
+ * Run `fn`, which sets up the start moment of a new game: the StoryInit
558
+ * passage, or the `storyinit` handlers at boot (unless a session was
559
+ * restored) and on restart. recordStoryInitState() records what it leaves
560
+ * behind, so recordMoment() has nothing to do meanwhile (see there).
561
+ */
562
+ export function settingUpStart<T>(fn: () => T): T {
563
+ startSetups++;
564
+ try {
565
+ return fn();
566
+ } finally {
567
+ startSetups--;
568
+ }
569
+ }
570
+
552
571
  /**
553
572
  * Record the state StoryInit left behind as the start moment: its variable
554
573
  * snapshot (the history base) and PRNG state. Called by executeStoryInit()
@@ -571,6 +590,70 @@ export function recordStoryInitState(): void {
571
590
  keepDrawsSoFar();
572
591
  }
573
592
 
593
+ /**
594
+ * Record the live variables as the state of the current moment (see
595
+ * StoryState.recordMoment): what a navigation does for the moment it
596
+ * enters, without the navigation.
597
+ */
598
+ function recordCurrentMoment(get: StoreGet, set: StoreSet): void {
599
+ const { storyData, history, historyIndex, variables } = get();
600
+ if (!storyData || historyIndex < 0) return;
601
+ // The start moment is recorded once StoryInit and the `storyinit` handlers
602
+ // have run (recordStoryInitState). A session written before that would
603
+ // hold it half set up, and a refresh would restore that over the StoryInit
604
+ // it runs again.
605
+ if (startSetups > 0 && history.length === 1) return;
606
+ // navigate() records the moment it entered, and writes the session, once
607
+ // the watchers reacting to it (this call is in one) have run
608
+ if (
609
+ navigationTriggerPhase &&
610
+ enteredMoment?.navigationId === get().navigationId
611
+ ) {
612
+ return;
613
+ }
614
+
615
+ // Nothing to record when the variables are as recorded (after a load the
616
+ // live ones are another object): the moments after this one stay
617
+ const recorded =
618
+ variables === lastNavigationVars ||
619
+ deepEqualStrict(reconstructVarsAt(historyIndex), variables);
620
+ if (!recorded) {
621
+ // The moment's patch is computed before anything changes: copying the
622
+ // values can throw (a getter), which must leave the history as it was
623
+ const entry =
624
+ historyIndex > 0
625
+ ? computeVarPatches(reconstructVarsAt(historyIndex - 1), variables)
626
+ : null;
627
+ // What changed is new play: as on a navigation from here, the moments
628
+ // after this one are dropped
629
+ patchEntries.length = historyIndex;
630
+ // patchEntries[i] leads from moment i to moment i + 1
631
+ if (entry) patchEntries[historyIndex - 1] = entry;
632
+ else variableBase = variables;
633
+ // The session takes the moment anew, with the variables as they are
634
+ if (sessionMoments.length > historyIndex) {
635
+ sessionMoments.length = historyIndex;
636
+ }
637
+ // The next navigate() diffs from this recorded snapshot
638
+ lastNavigationVars = variables;
639
+ if (historyIndex < history.length - 1) {
640
+ set((state) => {
641
+ state.history = state.history.slice(0, historyIndex + 1);
642
+ });
643
+ }
644
+ // What the watchers the passage's render consumed did is recorded now:
645
+ // a load must not bring them back to do it again
646
+ clearReplayWatchers();
647
+ }
648
+ // A save whose `beforesave` hooks are running (this call is in one) saves
649
+ // the moment as recorded here: only what the hooks change from now on is
650
+ // still to be written into its snapshot (see keepHookWrites)
651
+ for (const capture of hookCaptures) capture.before = variables;
652
+ // The moment keeps the PRNG state it was entered with: a load renders the
653
+ // passage again, and its rolls replay from there
654
+ if (!recorded) persistSessionThen(get);
655
+ }
656
+
574
657
  // ---------------------------------------------------------------------------
575
658
  // Playthrough setup
576
659
  // ---------------------------------------------------------------------------
@@ -837,12 +920,20 @@ function loadedEntryMoment(
837
920
  return moment;
838
921
  }
839
922
 
840
- /** The variable paths `Story.set` writes while a save's hooks run. */
841
- const hookWrites = new Set<Map<string, string[]>>();
923
+ /**
924
+ * A save whose `beforesave` hooks are running: the variables the hooks
925
+ * started from, and the variable paths `Story.set` has written since.
926
+ */
927
+ interface HookCapture {
928
+ before: Record<string, unknown>;
929
+ writes: Map<string, string[]>;
930
+ }
931
+
932
+ const hookCaptures = new Set<HookCapture>();
842
933
 
843
934
  /** Note that `path` of the variables was written (see keepHookWrites). */
844
935
  export function recordHookWrite(path: string[]): void {
845
- for (const writes of hookWrites) writes.set(pathKey(path), path);
936
+ for (const { writes } of hookCaptures) writes.set(pathKey(path), path);
846
937
  }
847
938
 
848
939
  /**
@@ -1034,6 +1125,15 @@ export interface StoryState {
1034
1125
  navigate: (passageName: string) => void;
1035
1126
  goBack: () => void;
1036
1127
  goForward: () => void;
1128
+ /**
1129
+ * Record the story variables as they are now as the current moment's
1130
+ * recorded state, without navigating: a page refresh, a save made here
1131
+ * and loaded, and moving back to the moment then restore them, not the
1132
+ * state on entering the passage. Writes the session. Moments after the
1133
+ * current one are dropped, as a navigation from it drops them. Does
1134
+ * nothing when the variables are as recorded.
1135
+ */
1136
+ recordMoment: () => void;
1037
1137
  setVariable: (name: string, value: unknown) => void;
1038
1138
  setTemporary: (name: string, value: unknown) => void;
1039
1139
  deleteVariable: (name: string) => void;
@@ -1159,6 +1259,7 @@ const PROGRAM_ORDER_ACTIONS = [
1159
1259
  'navigate',
1160
1260
  'goBack',
1161
1261
  'goForward',
1262
+ 'recordMoment',
1162
1263
  'restart',
1163
1264
  'save',
1164
1265
  'load',
@@ -1507,6 +1608,8 @@ export const useStoryStore = create<StoryState>()(
1507
1608
 
1508
1609
  goForward: () => moveInHistory(get, set, 1),
1509
1610
 
1611
+ recordMoment: () => recordCurrentMoment(get, set),
1612
+
1510
1613
  setVariable: (name: string, value: unknown) => {
1511
1614
  set((state) => {
1512
1615
  checkVariableName(name, `$${name}`);
@@ -1608,7 +1711,7 @@ export const useStoryStore = create<StoryState>()(
1608
1711
 
1609
1712
  executeStoryInit();
1610
1713
  clearSession(storyData.ifid);
1611
- emit('storyinit');
1714
+ settingUpStart(() => emit('storyinit'));
1612
1715
  // The storyinit handlers' changes belong to the start moment too
1613
1716
  recordStoryInitState();
1614
1717
  },
@@ -1831,12 +1934,14 @@ export const useStoryStore = create<StoryState>()(
1831
1934
  },
1832
1935
 
1833
1936
  beginSave: () => {
1834
- const before = get().variables;
1937
+ const capture: HookCapture = {
1938
+ before: get().variables,
1939
+ writes: new Map(),
1940
+ };
1835
1941
  const replaced = latestStateApplied;
1836
- const writes = new Map<string, string[]>();
1837
- hookWrites.add(writes);
1942
+ hookCaptures.add(capture);
1838
1943
  const dispose = () => {
1839
- hookWrites.delete(writes);
1944
+ hookCaptures.delete(capture);
1840
1945
  };
1841
1946
  return Object.assign(
1842
1947
  () => {
@@ -1849,8 +1954,8 @@ export const useStoryStore = create<StoryState>()(
1849
1954
  );
1850
1955
  }
1851
1956
  const payload = get().getSavePayload();
1852
- keepHookWrites(payload, before, get().variables, [
1853
- ...writes.values(),
1957
+ keepHookWrites(payload, capture.before, get().variables, [
1958
+ ...capture.writes.values(),
1854
1959
  ]);
1855
1960
  return payload;
1856
1961
  },
package/src/story-api.ts CHANGED
@@ -136,6 +136,7 @@ export interface StoryAPI {
136
136
  goto(passageName: string): void;
137
137
  back(): void;
138
138
  forward(): void;
139
+ recordMoment(): void;
139
140
  restart(): void;
140
141
  save(slot?: string, custom?: Record<string, unknown>): Promise<void>;
141
142
  load(slot?: string): Promise<void>;
@@ -369,6 +370,7 @@ function createStoryAPI(): StoryAPI {
369
370
  goto: storeAction('navigate'),
370
371
  back: storeAction('goBack'),
371
372
  forward: storeAction('goForward'),
373
+ recordMoment: storeAction('recordMoment'),
372
374
  restart: storeAction('restart'),
373
375
  save: storeAction('save'),
374
376
  load: storeAction('load'),
package/src/story-init.ts CHANGED
@@ -1,6 +1,11 @@
1
1
  import { ActionsDisabledContext } from './hooks/use-action';
2
2
  import { h, render } from 'preact';
3
- import { useStoryStore, recordStoryInitState, missingPassage } from './store';
3
+ import {
4
+ useStoryStore,
5
+ recordStoryInitState,
6
+ settingUpStart,
7
+ missingPassage,
8
+ } from './store';
4
9
  import { parseMarkup } from './markup/parse';
5
10
  import { registerWidgetDefinitions } from './widgets/register-widget-def';
6
11
  import { renderNodes } from './markup/render';
@@ -49,13 +54,15 @@ export function executeStoryInit() {
49
54
  container.style.display = 'none';
50
55
  document.body.appendChild(container);
51
56
  storyInitContainer = container;
52
- render(
53
- h(
54
- ActionsDisabledContext.Provider,
55
- { value: true },
56
- h(() => renderNodes(ast), null),
57
+ settingUpStart(() =>
58
+ render(
59
+ h(
60
+ ActionsDisabledContext.Provider,
61
+ { value: true },
62
+ h(() => renderNodes(ast), null),
63
+ ),
64
+ container,
57
65
  ),
58
- container,
59
66
  );
60
67
 
61
68
  // The start moment was recorded before StoryInit ran; its synchronous
@@ -94,11 +101,9 @@ export function initializeStory(session?: SavePayload): void {
94
101
 
95
102
  if (session) {
96
103
  useStoryStore.getState().loadFromPayload(session);
97
- }
98
-
99
- emit('storyinit');
100
-
101
- if (!session) {
104
+ emit('storyinit');
105
+ } else {
106
+ settingUpStart(() => emit('storyinit'));
102
107
  recordStoryInitState();
103
108
  }
104
109
  }
package/types/index.d.ts CHANGED
@@ -751,6 +751,21 @@ export interface StoryAPI {
751
751
  /** Go forward one step in history. Throws like `goto()`. */
752
752
  forward(): void;
753
753
 
754
+ /**
755
+ * Record the story variables as they are now as the state of the current
756
+ * moment, without navigating. From then on a page refresh, a save made on
757
+ * this passage and loaded, and moving back to this moment restore them,
758
+ * not the state on entering the passage. Use it for a change the player
759
+ * makes on a passage without leaving it (in a dialog, say).
760
+ *
761
+ * Writes the session, and throws like `goto()` once the moment is
762
+ * recorded. If the player had gone back, the moments after the current
763
+ * one are dropped. No events fire, the passage is not rendered again and
764
+ * the moment keeps the PRNG state it was entered with. Does nothing when
765
+ * the variables are as recorded already.
766
+ */
767
+ recordMoment(): void;
768
+
754
769
  /** Restart the story from the beginning. */
755
770
  restart(): void;
756
771