@rohal12/spindle 0.64.17 → 0.64.18

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.
@@ -19605,7 +19605,8 @@ function moveInHistory(get, set, step) {
19605
19605
  const previousPassage = get().currentPassage;
19606
19606
  const targetPassage = history[target].passage;
19607
19607
  const navigation = get().navigationId;
19608
- emit("beforenavigate", targetPassage);
19608
+ const kind = step < 0 ? "back" : "forward";
19609
+ emit("beforenavigate", targetPassage, kind);
19609
19610
  if (get().navigationId !== navigation) return;
19610
19611
  target = get().historyIndex + step;
19611
19612
  if (target < 0 || target >= get().history.length) return;
@@ -19621,7 +19622,7 @@ function moveInHistory(get, set, step) {
19621
19622
  lastNavigationVars = get().variables;
19622
19623
  restorePRNGFromMoment(get().history[get().historyIndex]);
19623
19624
  keepDrawsSoFar();
19624
- persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage));
19625
+ persistSessionThen(get, () => emit("afternavigate", targetPassage, previousPassage, kind));
19625
19626
  }
19626
19627
  /**
19627
19628
  * Record the state StoryInit left behind as the start moment: its variable
@@ -20180,7 +20181,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20180
20181
  }
20181
20182
  const previousPassage = get().currentPassage;
20182
20183
  const navigation = get().navigationId;
20183
- if (replacesState(() => emit("beforenavigate", passageName)) || get().navigationId !== navigation) return;
20184
+ if (replacesState(() => emit("beforenavigate", passageName, "navigate")) || get().navigationId !== navigation) return;
20184
20185
  const patchEntry = computeVarPatches(lastNavigationVars, get().variables);
20185
20186
  set((state) => {
20186
20187
  state.temporary = createNamespace();
@@ -20215,7 +20216,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20215
20216
  finishEnteredMoment(get, set);
20216
20217
  keepDrawsSoFar();
20217
20218
  persistSessionThen(get, () => {
20218
- if (replacesState(() => emit("afternavigate", passageName, previousPassage))) return;
20219
+ if (replacesState(() => emit("afternavigate", passageName, previousPassage, "navigate"))) return;
20219
20220
  for (const next of deferred) get().navigate(next);
20220
20221
  });
20221
20222
  },
@@ -22096,6 +22097,19 @@ function setOne(draft, name, value) {
22096
22097
  const { isTransient, key } = parseName(name);
22097
22098
  setByPath(isTransient ? draft.transient : draft.variables, key.split("."), value);
22098
22099
  }
22100
+ /**
22101
+ * The history index `index` names (the current moment's when left out), or
22102
+ * a RangeError naming the moments the history holds.
22103
+ */
22104
+ function momentIndex(index) {
22105
+ const { history, historyIndex } = useStoryStore.getState();
22106
+ const at = index ?? historyIndex;
22107
+ if (!Number.isInteger(at) || at < 0 || at >= history.length) {
22108
+ const held = history.length === 0 ? "no moments yet" : `moments 0 to ${history.length - 1}`;
22109
+ throw new RangeError(`spindle: History index ${String(at)} is out of range: the history holds ${held}.`);
22110
+ }
22111
+ return at;
22112
+ }
22099
22113
  /** A method calling the store action `name`, as the store holds it then. */
22100
22114
  function storeAction(name) {
22101
22115
  return ((...args) => useStoryStore.getState()[name](...args));
@@ -22146,6 +22160,22 @@ function createStoryAPI() {
22146
22160
  get passage() {
22147
22161
  return useStoryStore.getState().currentPassage;
22148
22162
  },
22163
+ history: {
22164
+ get length() {
22165
+ return useStoryStore.getState().history.length;
22166
+ },
22167
+ get index() {
22168
+ return useStoryStore.getState().historyIndex;
22169
+ },
22170
+ passage(index) {
22171
+ const at = momentIndex(index);
22172
+ return useStoryStore.getState().history[at].passage;
22173
+ },
22174
+ variables(index) {
22175
+ const at = momentIndex(index);
22176
+ return freeze(useStoryStore.getState().getHistoryVariables(at), true);
22177
+ }
22178
+ },
22149
22179
  settings,
22150
22180
  registerClass(name, ctor) {
22151
22181
  registerClass(name, ctor);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.64.17",
3
+ "version": "0.64.18",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -1,3 +1,10 @@
1
+ /**
2
+ * How the story moved: `'navigate'` recorded a new history moment (a link,
3
+ * `{goto}`, `Story.goto()`, a watcher's goto); `'back'` and `'forward'`
4
+ * moved through the moments already recorded.
5
+ */
6
+ export type NavigationKind = 'navigate' | 'back' | 'forward';
7
+
1
8
  type EventMap = {
2
9
  storyinit: () => void;
3
10
  beforerestart: () => void;
@@ -12,8 +19,8 @@ type EventMap = {
12
19
  aftersave: (slot: string | undefined) => void;
13
20
  beforeload: (slot: string | undefined) => void;
14
21
  afterload: (slot: string | undefined) => void;
15
- beforenavigate: (passageName: string) => void;
16
- afternavigate: (to: string, from: string) => void;
22
+ beforenavigate: (passageName: string, kind: NavigationKind) => void;
23
+ afternavigate: (to: string, from: string, kind: NavigationKind) => void;
17
24
  passagerender: (passage: string, element: HTMLElement) => void;
18
25
  dialogrender: (passage: string, element: HTMLElement) => void;
19
26
  };
package/src/store.ts CHANGED
@@ -18,7 +18,7 @@ import type {
18
18
  SaveExport,
19
19
  } from './saves/types';
20
20
  import { executeStoryInit } from './story-init';
21
- import { emit } from './event-emitter';
21
+ import { emit, type NavigationKind } from './event-emitter';
22
22
  import {
23
23
  resetTriggers,
24
24
  checkTriggersOnNavigation,
@@ -520,7 +520,8 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
520
520
  // the game on, and this traversal is dropped rather than applied to a
521
521
  // history that is no longer the one it was computed from (#516)
522
522
  const navigation = get().navigationId;
523
- emit('beforenavigate', targetPassage);
523
+ const kind: NavigationKind = step < 0 ? 'back' : 'forward';
524
+ emit('beforenavigate', targetPassage, kind);
524
525
  if (get().navigationId !== navigation) return;
525
526
 
526
527
  // Lowering maxHistory in the callback can trim either end without a new
@@ -544,7 +545,7 @@ function moveInHistory(get: StoreGet, set: StoreSet, step: -1 | 1): void {
544
545
  restorePRNGFromMoment(get().history[get().historyIndex]);
545
546
  keepDrawsSoFar();
546
547
  persistSessionThen(get, () =>
547
- emit('afternavigate', targetPassage, previousPassage),
548
+ emit('afternavigate', targetPassage, previousPassage, kind),
548
549
  );
549
550
  }
550
551
 
@@ -1436,7 +1437,7 @@ export const useStoryStore = create<StoryState>()(
1436
1437
  // traversal, this navigation must then give way to the callback's.
1437
1438
  const navigation = get().navigationId;
1438
1439
  if (
1439
- replacesState(() => emit('beforenavigate', passageName)) ||
1440
+ replacesState(() => emit('beforenavigate', passageName, 'navigate')) ||
1440
1441
  get().navigationId !== navigation
1441
1442
  )
1442
1443
  return;
@@ -1493,7 +1494,7 @@ export const useStoryStore = create<StoryState>()(
1493
1494
  persistSessionThen(get, () => {
1494
1495
  if (
1495
1496
  replacesState(() =>
1496
- emit('afternavigate', passageName, previousPassage),
1497
+ emit('afternavigate', passageName, previousPassage, 'navigate'),
1497
1498
  )
1498
1499
  ) {
1499
1500
  return;
package/src/story-api.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import { useStoryStore, trackRuntimeUnsub, recordHookWrite } from './store';
2
2
  import type { StoryState, VariableNamespaces } from './store';
3
+ import { freeze } from 'immer';
3
4
  import {
4
5
  on as emitterOn,
5
6
  emit,
7
+ type NavigationKind,
6
8
  type StoryEvent,
7
9
  type StoryEventCallback,
8
10
  } from './event-emitter';
@@ -70,6 +72,7 @@ import type { TransitionConfig } from './transition';
70
72
 
71
73
  export type { StoryAction };
72
74
  export type { MacroMetadata };
75
+ export type { NavigationKind };
73
76
 
74
77
  // Deferred-render promise lifecycle.
75
78
  // deferRender() creates a promise; ready() resolves it. A deferRender() while
@@ -154,6 +157,12 @@ export interface StoryAPI {
154
157
  previousPassage(): Passage | undefined;
155
158
  readonly title: string;
156
159
  readonly passage: string;
160
+ readonly history: {
161
+ readonly length: number;
162
+ readonly index: number;
163
+ passage(index?: number): string;
164
+ variables(index?: number): Record<string, unknown>;
165
+ };
157
166
  readonly settings: typeof settings;
158
167
  registerClass(name: string, ctor: new (...args: any[]) => any): void;
159
168
  defineMacro(config: MacroDefinition): void;
@@ -280,6 +289,25 @@ function setOne(draft: VariableNamespaces, name: string, value: unknown): void {
280
289
  setByPath(namespace, key.split('.'), value);
281
290
  }
282
291
 
292
+ /**
293
+ * The history index `index` names (the current moment's when left out), or
294
+ * a RangeError naming the moments the history holds.
295
+ */
296
+ function momentIndex(index: number | undefined): number {
297
+ const { history, historyIndex } = useStoryStore.getState();
298
+ const at = index ?? historyIndex;
299
+ if (!Number.isInteger(at) || at < 0 || at >= history.length) {
300
+ const held =
301
+ history.length === 0
302
+ ? 'no moments yet'
303
+ : `moments 0 to ${history.length - 1}`;
304
+ throw new RangeError(
305
+ `spindle: History index ${String(at)} is out of range: the history holds ${held}.`,
306
+ );
307
+ }
308
+ return at;
309
+ }
310
+
283
311
  /** A method calling the store action `name`, as the store holds it then. */
284
312
  function storeAction<K extends keyof StoryState>(name: K): StoryState[K] {
285
313
  return ((...args: unknown[]) =>
@@ -364,6 +392,26 @@ function createStoryAPI(): StoryAPI {
364
392
  return useStoryStore.getState().currentPassage;
365
393
  },
366
394
 
395
+ history: {
396
+ get length(): number {
397
+ return useStoryStore.getState().history.length;
398
+ },
399
+ get index(): number {
400
+ return useStoryStore.getState().historyIndex;
401
+ },
402
+ passage(index?: number): string {
403
+ const at = momentIndex(index);
404
+ return useStoryStore.getState().history[at]!.passage;
405
+ },
406
+ variables(index?: number): Record<string, unknown> {
407
+ const at = momentIndex(index);
408
+ // The copy Back and Forward would restore, frozen like the values
409
+ // Story.get() hands out: it is the caller's own, and a write to it
410
+ // fails instead of seeming to change the recorded moment
411
+ return freeze(useStoryStore.getState().getHistoryVariables(at), true);
412
+ },
413
+ },
414
+
367
415
  settings,
368
416
 
369
417
  registerClass(name: string, ctor: new (...args: any[]) => any): void {
@@ -5,7 +5,14 @@
5
5
  *
6
6
  * Run: npx tsc --noEmit
7
7
  */
8
- import type { StoryAPI as SourceAPI } from './story-api';
8
+ import type {
9
+ NavigationKind as SourceNavigationKind,
10
+ StoryAPI as SourceAPI,
11
+ } from './story-api';
12
+ import type {
13
+ StoryEvent as SourceStoryEvent,
14
+ StoryEventCallback as SourceStoryEventCallback,
15
+ } from './event-emitter';
9
16
  import type { parseStoryVariables as SourceParse } from './story-variables';
10
17
  import type {
11
18
  MacroContext as SourceMacroContext,
@@ -16,6 +23,9 @@ import type { ASTNode as SourceASTNode } from './markup/ast';
16
23
  import type { bootStory as SourceBootStory } from './headless';
17
24
  import type {
18
25
  StoryAPI as PublishedAPI,
26
+ NavigationKind as PublishedNavigationKind,
27
+ StoryEvent as PublishedStoryEvent,
28
+ StoryEventCallback as PublishedStoryEventCallback,
19
29
  MacroContext as PublishedMacroContext,
20
30
  MacroDefinition as PublishedMacroDefinition,
21
31
  MacroProps as PublishedMacroProps,
@@ -165,6 +175,19 @@ type ToolingChecks = [
165
175
  ];
166
176
  type _toolingTypes = AssertTrue<ToolingChecks>;
167
177
 
178
+ // The story events and what each passes to its callbacks. The `on()` of the
179
+ // two StoryAPI types above stay assignable to each other when a callback
180
+ // gains or loses an argument, so the arguments are compared here.
181
+ type EventChecks = [
182
+ Same<SourceStoryEvent, PublishedStoryEvent>,
183
+ Same<
184
+ { [E in SourceStoryEvent]: Parameters<SourceStoryEventCallback<E>> },
185
+ { [E in PublishedStoryEvent]: Parameters<PublishedStoryEventCallback<E>> }
186
+ >,
187
+ Same<SourceNavigationKind, PublishedNavigationKind>,
188
+ ];
189
+ type _eventTypes = AssertTrue<EventChecks>;
190
+
168
191
  // A typical custom macro written against the published types must type-check,
169
192
  // and misuse of the hooks must not (no `any` leaking through).
170
193
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
package/types/index.d.ts CHANGED
@@ -118,6 +118,16 @@ export interface Passage {
118
118
  content: string;
119
119
  }
120
120
 
121
+ /**
122
+ * How the story moved, as the navigation events report it: `'navigate'`
123
+ * recorded a new history moment (a link, `{goto}`, `Story.goto()`, a
124
+ * watcher's goto); `'back'` and `'forward'` moved through the moments already
125
+ * recorded (`Story.back()`, `Story.forward()`, the `{back}` and `{forward}`
126
+ * buttons).
127
+ * @see {@link ../../src/event-emitter.ts} for the implementation.
128
+ */
129
+ export type NavigationKind = 'navigate' | 'back' | 'forward';
130
+
121
131
  /**
122
132
  * Map of story event names to their callback signatures.
123
133
  * @see {@link ../../src/event-emitter.ts} for the implementation.
@@ -136,8 +146,16 @@ export interface StoryEventMap {
136
146
  aftersave: (slot: string | undefined) => void;
137
147
  beforeload: (slot: string | undefined) => void;
138
148
  afterload: (slot: string | undefined) => void;
139
- beforenavigate: (passageName: string) => void;
140
- afternavigate: (to: string, from: string) => void;
149
+ /**
150
+ * The story is about to move to `passageName`. `Story.passage` and
151
+ * `Story.history` still describe the moment being left.
152
+ */
153
+ beforenavigate: (passageName: string, kind: NavigationKind) => void;
154
+ /**
155
+ * The story moved from passage `from` to passage `to`. `Story.passage` and
156
+ * `Story.history` describe the moment arrived at.
157
+ */
158
+ afternavigate: (to: string, from: string, kind: NavigationKind) => void;
141
159
  /**
142
160
  * A passage's `.passage` element was committed to the DOM (first render,
143
161
  * navigation, back/forward, restart, load). Fires after the transition
@@ -812,6 +830,29 @@ export interface StoryAPI {
812
830
  /** The current passage name. */
813
831
  readonly passage: string;
814
832
 
833
+ /**
834
+ * The history: the moments Back and Forward move through, oldest first.
835
+ * Read-only. `Story.config.maxHistory` limits how many are kept.
836
+ */
837
+ readonly history: {
838
+ /** The number of moments kept. */
839
+ readonly length: number;
840
+ /** The index of the current moment (0 is the oldest kept). */
841
+ readonly index: number;
842
+ /**
843
+ * The passage name of the moment at `index` (the current moment when
844
+ * left out). Throws a `RangeError` if the history has no such moment.
845
+ */
846
+ passage(index?: number): string;
847
+ /**
848
+ * The story variables recorded for the moment at `index` (the current
849
+ * moment when left out): the state on entering it, which Back and
850
+ * Forward restore. A frozen copy, keyed by name without the `$`. Throws a
851
+ * `RangeError` if the history has no such moment.
852
+ */
853
+ variables(index?: number): Record<string, unknown>;
854
+ };
855
+
815
856
  /** The settings API. */
816
857
  readonly settings: SettingsAPI;
817
858