@rohal12/spindle 0.64.19 → 0.64.21

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.
@@ -9253,6 +9253,7 @@ var VALID_EVENTS = /* @__PURE__ */ new Set([
9253
9253
  "beforerestart",
9254
9254
  "actionsChanged",
9255
9255
  "variableChanged",
9256
+ "settingchanged",
9256
9257
  "beforesave",
9257
9258
  "aftersave",
9258
9259
  "beforeload",
@@ -19268,7 +19269,7 @@ function executeStoryInit() {
19268
19269
  container.style.display = "none";
19269
19270
  document.body.appendChild(container);
19270
19271
  storyInitContainer = container;
19271
- render(h(ActionsDisabledContext.Provider, { value: true }, h(() => renderNodes(ast), null)), container);
19272
+ settingUpStart(() => render(h(ActionsDisabledContext.Provider, { value: true }, h(() => renderNodes(ast), null)), container));
19272
19273
  recordStoryInitState();
19273
19274
  }
19274
19275
  const saveTitlePassage = state.storyData.passages.get("SaveTitle");
@@ -19288,9 +19289,13 @@ function initializeStory(session) {
19288
19289
  console.warn(`spindle: discarding the saved session: the story no longer has the passage "${missing}"`);
19289
19290
  session = void 0;
19290
19291
  }
19291
- if (session) useStoryStore.getState().loadFromPayload(session);
19292
- emit("storyinit");
19293
- if (!session) recordStoryInitState();
19292
+ if (session) {
19293
+ useStoryStore.getState().loadFromPayload(session);
19294
+ emit("storyinit");
19295
+ } else {
19296
+ settingUpStart(() => emit("storyinit"));
19297
+ recordStoryInitState();
19298
+ }
19294
19299
  }
19295
19300
  // src/passage-roles.ts
19296
19301
  /** Runtime-owned passage roles, shared with stateless authoring tools. */
@@ -19625,6 +19630,22 @@ function moveInHistory(get, set, step) {
19625
19630
  keepDrawsSoFar();
19626
19631
  persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage, kind));
19627
19632
  }
19633
+ /** How many runs of settingUpStart() are under way. */
19634
+ var startSetups = 0;
19635
+ /**
19636
+ * Run `fn`, which sets up the start moment of a new game: the StoryInit
19637
+ * passage, or the `storyinit` handlers at boot (unless a session was
19638
+ * restored) and on restart. recordStoryInitState() records what it leaves
19639
+ * behind, so recordMoment() has nothing to do meanwhile (see there).
19640
+ */
19641
+ function settingUpStart(fn) {
19642
+ startSetups++;
19643
+ try {
19644
+ return fn();
19645
+ } finally {
19646
+ startSetups--;
19647
+ }
19648
+ }
19628
19649
  /**
19629
19650
  * Record the state StoryInit left behind as the start moment: its variable
19630
19651
  * snapshot (the history base) and PRNG state. Called by executeStoryInit()
@@ -19645,6 +19666,32 @@ function recordStoryInitState() {
19645
19666
  keepDrawsSoFar();
19646
19667
  }
19647
19668
  /**
19669
+ * Record the live variables as the state of the current moment (see
19670
+ * StoryState.recordMoment): what a navigation does for the moment it
19671
+ * enters, without the navigation.
19672
+ */
19673
+ function recordCurrentMoment(get, set) {
19674
+ const { storyData, history, historyIndex, variables } = get();
19675
+ if (!storyData || historyIndex < 0) return;
19676
+ if (startSetups > 0 && history.length === 1) return;
19677
+ if (navigationTriggerPhase && enteredMoment?.navigationId === get().navigationId) return;
19678
+ const recorded = variables === lastNavigationVars || deepEqualStrict(reconstructVarsAt(historyIndex), variables);
19679
+ if (!recorded) {
19680
+ const entry = historyIndex > 0 ? computeVarPatches(reconstructVarsAt(historyIndex - 1), variables) : null;
19681
+ patchEntries.length = historyIndex;
19682
+ if (entry) patchEntries[historyIndex - 1] = entry;
19683
+ else variableBase = variables;
19684
+ if (sessionMoments.length > historyIndex) sessionMoments.length = historyIndex;
19685
+ lastNavigationVars = variables;
19686
+ if (historyIndex < history.length - 1) set((state) => {
19687
+ state.history = state.history.slice(0, historyIndex + 1);
19688
+ });
19689
+ clearReplayWatchers();
19690
+ }
19691
+ for (const capture of hookCaptures) capture.before = variables;
19692
+ if (!recorded) persistSessionThen(get);
19693
+ }
19694
+ /**
19648
19695
  * Settles once the latest playthrough switch (init's lookup or creation, a
19649
19696
  * restart's creation, the replacement of a deleted current playthrough, a
19650
19697
  * load making the loaded save's playthrough current) is stored, with the
@@ -19848,11 +19895,10 @@ function loadedEntryMoment(payload) {
19848
19895
  if (typeof moment.variables !== "object" || moment.variables === null) return;
19849
19896
  return moment;
19850
19897
  }
19851
- /** The variable paths `Story.set` writes while a save's hooks run. */
19852
- var hookWrites = /* @__PURE__ */ new Set();
19898
+ var hookCaptures = /* @__PURE__ */ new Set();
19853
19899
  /** Note that `path` of the variables was written (see keepHookWrites). */
19854
19900
  function recordHookWrite(path) {
19855
- for (const writes of hookWrites) writes.set(pathKey(path), path);
19901
+ for (const { writes } of hookCaptures) writes.set(pathKey(path), path);
19856
19902
  }
19857
19903
  /**
19858
19904
  * Write the changes between `before` and `after` (the live variables around
@@ -19987,6 +20033,7 @@ var PROGRAM_ORDER_ACTIONS = [
19987
20033
  "navigate",
19988
20034
  "goBack",
19989
20035
  "goForward",
20036
+ "recordMoment",
19990
20037
  "restart",
19991
20038
  "save",
19992
20039
  "load",
@@ -20223,6 +20270,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20223
20270
  },
20224
20271
  goBack: () => moveInHistory(get, set, -1),
20225
20272
  goForward: () => moveInHistory(get, set, 1),
20273
+ recordMoment: () => recordCurrentMoment(get, set),
20226
20274
  setVariable: (name, value) => {
20227
20275
  set((state) => {
20228
20276
  checkVariableName(name, `$${name}`);
@@ -20295,7 +20343,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20295
20343
  enterRuntimePhase();
20296
20344
  executeStoryInit();
20297
20345
  clearSession(storyData.ifid);
20298
- emit("storyinit");
20346
+ settingUpStart(() => emit("storyinit"));
20299
20347
  recordStoryInitState();
20300
20348
  },
20301
20349
  save: (slot, custom) => {
@@ -20408,18 +20456,20 @@ var useStoryStore = create()(storyStore((set, get) => ({
20408
20456
  };
20409
20457
  },
20410
20458
  beginSave: () => {
20411
- const before = get().variables;
20459
+ const capture = {
20460
+ before: get().variables,
20461
+ writes: /* @__PURE__ */ new Map()
20462
+ };
20412
20463
  const replaced = latestStateApplied;
20413
- const writes = /* @__PURE__ */ new Map();
20414
- hookWrites.add(writes);
20464
+ hookCaptures.add(capture);
20415
20465
  const dispose = () => {
20416
- hookWrites.delete(writes);
20466
+ hookCaptures.delete(capture);
20417
20467
  };
20418
20468
  return Object.assign(() => {
20419
20469
  dispose();
20420
20470
  if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
20421
20471
  const payload = get().getSavePayload();
20422
- keepHookWrites(payload, before, get().variables, [...writes.values()]);
20472
+ keepHookWrites(payload, capture.before, get().variables, [...capture.writes.values()]);
20423
20473
  return payload;
20424
20474
  }, { dispose });
20425
20475
  },
@@ -21445,10 +21495,18 @@ var settings = {
21445
21495
  getRange(name) {
21446
21496
  return valueOf(name, 0);
21447
21497
  },
21498
+ /**
21499
+ * Store a value, notify the settings controls, then emit `settingchanged`.
21500
+ * Setting the value a setting already has changes nothing and emits
21501
+ * nothing.
21502
+ */
21448
21503
  set(name, value) {
21504
+ const unchanged = hasOwn(values, name) && (values[name] === value || values[name] !== values[name] && value !== value);
21449
21505
  values[name] = value;
21450
21506
  persist();
21507
+ if (unchanged) return;
21451
21508
  for (const listener of [...listeners]) listener();
21509
+ emit("settingchanged", name, value);
21452
21510
  },
21453
21511
  getAll() {
21454
21512
  return { ...values };
@@ -22190,6 +22248,7 @@ function createStoryAPI() {
22190
22248
  goto: storeAction("navigate"),
22191
22249
  back: storeAction("goBack"),
22192
22250
  forward: storeAction("goForward"),
22251
+ recordMoment: storeAction("recordMoment"),
22193
22252
  restart: storeAction("restart"),
22194
22253
  save: storeAction("save"),
22195
22254
  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.21",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -12,6 +12,7 @@ type EventMap = {
12
12
  variableChanged: (
13
13
  changed: Record<string, { from: unknown; to: unknown }>,
14
14
  ) => void;
15
+ settingchanged: (name: string, value: unknown) => void;
15
16
  beforesave: (
16
17
  slot: string | undefined,
17
18
  custom: Record<string, unknown> | undefined,
@@ -34,6 +35,7 @@ const VALID_EVENTS = new Set<string>([
34
35
  'beforerestart',
35
36
  'actionsChanged',
36
37
  'variableChanged',
38
+ 'settingchanged',
37
39
  'beforesave',
38
40
  'aftersave',
39
41
  'beforeload',
package/src/settings.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { emit } from './event-emitter';
1
2
  import { useStoryStore } from './store';
2
3
  import { createNamespace, hasOwn, ownValue } from './utils/namespace';
3
4
 
@@ -130,10 +131,21 @@ export const settings = {
130
131
  return valueOf(name, 0);
131
132
  },
132
133
 
134
+ /**
135
+ * Store a value, notify the settings controls, then emit `settingchanged`.
136
+ * Setting the value a setting already has changes nothing and emits
137
+ * nothing.
138
+ */
133
139
  set(name: string, value: unknown): void {
140
+ const unchanged =
141
+ hasOwn(values, name) &&
142
+ (values[name] === value ||
143
+ (values[name] !== values[name] && value !== value));
134
144
  values[name] = value;
135
145
  persist();
146
+ if (unchanged) return;
136
147
  for (const listener of [...listeners]) listener();
148
+ emit('settingchanged', name, value);
137
149
  },
138
150
 
139
151
  getAll(): Record<string, unknown> {
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
@@ -139,6 +139,15 @@ export interface StoryEventMap {
139
139
  variableChanged: (
140
140
  changed: Record<string, { from: unknown; to: unknown }>,
141
141
  ) => void;
142
+ /**
143
+ * A setting's value changed through the settings controls or
144
+ * `Story.settings.set()`, and has been stored. `name` is the setting's name
145
+ * and `value` the new value. Does not fire when a setting is registered,
146
+ * when persisted values are applied at startup (read those with
147
+ * `Story.settings.get()` from `storyinit` on), or when a value is set to
148
+ * what it already is.
149
+ */
150
+ settingchanged: (name: string, value: unknown) => void;
142
151
  beforesave: (
143
152
  slot: string | undefined,
144
153
  custom: Record<string, unknown> | undefined,
@@ -751,6 +760,21 @@ export interface StoryAPI {
751
760
  /** Go forward one step in history. Throws like `goto()`. */
752
761
  forward(): void;
753
762
 
763
+ /**
764
+ * Record the story variables as they are now as the state of the current
765
+ * moment, without navigating. From then on a page refresh, a save made on
766
+ * this passage and loaded, and moving back to this moment restore them,
767
+ * not the state on entering the passage. Use it for a change the player
768
+ * makes on a passage without leaving it (in a dialog, say).
769
+ *
770
+ * Writes the session, and throws like `goto()` once the moment is
771
+ * recorded. If the player had gone back, the moments after the current
772
+ * one are dropped. No events fire, the passage is not rendered again and
773
+ * the moment keeps the PRNG state it was entered with. Does nothing when
774
+ * the variables are as recorded already.
775
+ */
776
+ recordMoment(): void;
777
+
754
778
  /** Restart the story from the beginning. */
755
779
  restart(): void;
756
780