@rohal12/spindle 0.62.2 → 0.62.4
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/dist/pkg/format.js +1 -1
- package/dist/pkg/headless.js +464 -272
- package/dist/pkg/play-worker.js +95 -7
- package/dist/pkg/play.js +3 -3
- package/dist/pkg/story-variables.js +590 -386
- package/dist/pkg/tooling.js +1 -0
- package/package.json +1 -1
- package/src/code-check.ts +1 -1
- package/src/completion-context.ts +226 -0
- package/src/components/Passage.tsx +28 -3
- package/src/define-macro.ts +6 -1
- package/src/hooks/use-render-options.ts +4 -0
- package/src/macro-discovery.ts +27 -15
- package/src/markup/code-attributes.ts +10 -3
- package/src/markup/parse.ts +19 -4
- package/src/markup/render.tsx +6 -4
- package/src/markup/spindle.d.peggy.ts +2 -0
- package/src/markup/spindle.peggy +22 -13
- package/src/passage-render-state.ts +7 -0
- package/src/play/session.ts +3 -3
- package/src/play/window-events.ts +63 -0
- package/src/play/worker.ts +62 -9
- package/src/saves/format.ts +4 -0
- package/src/saves/types.ts +6 -6
- package/src/static-literal.ts +24 -22
- package/src/store.ts +42 -16
- package/src/tooling.ts +4 -0
- package/src/triggers.ts +107 -0
- package/src/twine-editor/references.ts +9 -11
- package/src/widgets/ast-scanner.ts +40 -44
- package/src/widgets/widget-def.ts +74 -45
- package/types/play.d.ts +6 -5
- package/types/tooling.d.ts +17 -0
package/src/play/session.ts
CHANGED
|
@@ -72,9 +72,9 @@ export function workerExecArgv(execArgv: readonly string[]): string[] {
|
|
|
72
72
|
}
|
|
73
73
|
|
|
74
74
|
/**
|
|
75
|
-
* Opens a session that runs the story in a worker
|
|
76
|
-
*
|
|
77
|
-
*
|
|
75
|
+
* Opens a session that runs the story in a worker with happy-dom's DOM.
|
|
76
|
+
* `window` is `globalThis`: properties authored on it are bare globals too.
|
|
77
|
+
* Idle callbacks use a timer-backed scheduler.
|
|
78
78
|
* Requires `trusted: true`: story code has unrestricted host Node access.
|
|
79
79
|
*/
|
|
80
80
|
export function openPlaySession(
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import type { Window } from 'happy-dom';
|
|
2
|
+
|
|
3
|
+
/** Expose the story's global window at the DOM event boundary. */
|
|
4
|
+
export function installWindowEvents(window: Window): void {
|
|
5
|
+
const storyWindow = globalThis as unknown as Window;
|
|
6
|
+
type Listener = Parameters<Window['addEventListener']>[1];
|
|
7
|
+
const wrapped = new WeakMap<object, Listener>();
|
|
8
|
+
const originals = new WeakMap<object, Listener>();
|
|
9
|
+
const wrap = (listener: Listener): Listener => {
|
|
10
|
+
// EventListener objects keep their own handleEvent receiver.
|
|
11
|
+
if (typeof listener !== 'function') return listener;
|
|
12
|
+
let callback = wrapped.get(listener);
|
|
13
|
+
if (!callback) {
|
|
14
|
+
callback = listener.bind(storyWindow);
|
|
15
|
+
wrapped.set(listener, callback);
|
|
16
|
+
originals.set(callback, listener);
|
|
17
|
+
}
|
|
18
|
+
return callback;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
const { addEventListener, removeEventListener } = window;
|
|
22
|
+
window.addEventListener = (type, listener, options) =>
|
|
23
|
+
addEventListener(type, wrap(listener), options);
|
|
24
|
+
// happy-dom also removes already-wrapped listeners for once and abort.
|
|
25
|
+
window.removeEventListener = (type, listener) =>
|
|
26
|
+
removeEventListener(type, wrapped.get(listener) ?? listener);
|
|
27
|
+
|
|
28
|
+
for (const name of Object.getOwnPropertyNames(window)) {
|
|
29
|
+
const descriptor = Object.getOwnPropertyDescriptor(window, name)!;
|
|
30
|
+
if (!name.startsWith('on') || !descriptor.get || !descriptor.set) continue;
|
|
31
|
+
Object.defineProperty(window, name, {
|
|
32
|
+
...descriptor,
|
|
33
|
+
get() {
|
|
34
|
+
const listener = descriptor.get!.call(window);
|
|
35
|
+
return originals.get(listener) ?? listener;
|
|
36
|
+
},
|
|
37
|
+
set(listener: Listener) {
|
|
38
|
+
descriptor.set!.call(window, wrap(listener));
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// Translate references on the real event, retaining its identity, methods,
|
|
44
|
+
// cancellation and element targets. Subclasses share this Event prototype.
|
|
45
|
+
const exposeWindow = (target: unknown) =>
|
|
46
|
+
target === window ? storyWindow : target;
|
|
47
|
+
const prototype = window.Event.prototype;
|
|
48
|
+
for (const name of ['target', 'currentTarget']) {
|
|
49
|
+
const descriptor = Object.getOwnPropertyDescriptor(prototype, name)!;
|
|
50
|
+
Object.defineProperty(prototype, name, {
|
|
51
|
+
...descriptor,
|
|
52
|
+
get() {
|
|
53
|
+
return exposeWindow(descriptor.get!.call(this));
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
const { composedPath } = prototype;
|
|
58
|
+
prototype.composedPath = function () {
|
|
59
|
+
return composedPath
|
|
60
|
+
.call(this)
|
|
61
|
+
.map((target) => (target === window ? storyWindow : target));
|
|
62
|
+
};
|
|
63
|
+
}
|
package/src/play/worker.ts
CHANGED
|
@@ -8,6 +8,7 @@ import type * as HappyDom from 'happy-dom';
|
|
|
8
8
|
import type * as Headless from '../headless';
|
|
9
9
|
import { errorMessage } from '../utils/error-message';
|
|
10
10
|
import { loadOptional } from './optional';
|
|
11
|
+
import { installWindowEvents } from './window-events';
|
|
11
12
|
import type { Op, Ready, Reply, Request, WorkerData } from './protocol';
|
|
12
13
|
|
|
13
14
|
type HeadlessModule = typeof Headless;
|
|
@@ -23,20 +24,28 @@ Object.defineProperty(process, 'stdout', {
|
|
|
23
24
|
const port = parentPort!;
|
|
24
25
|
const data = workerData as WorkerData;
|
|
25
26
|
|
|
26
|
-
/**
|
|
27
|
+
/** Install happy-dom's DOM in the global environment Spindle runs in. */
|
|
27
28
|
async function installDom(): Promise<void> {
|
|
28
29
|
const { Window } = await loadOptional<typeof HappyDom>(
|
|
29
30
|
'happy-dom',
|
|
30
31
|
'play sessions',
|
|
31
32
|
);
|
|
32
33
|
const window = new Window({ url: 'http://localhost/' });
|
|
34
|
+
installWindowEvents(window);
|
|
33
35
|
const global = globalThis as Record<string, unknown>;
|
|
34
36
|
const source = window as unknown as Record<string, unknown>;
|
|
35
|
-
global.window = window;
|
|
36
37
|
global.document = window.document;
|
|
37
38
|
// Node's own globals (fetch, URL, ...) stay as they are,
|
|
38
39
|
for (const name of Object.getOwnPropertyNames(window)) {
|
|
39
|
-
if (!(name in globalThis))
|
|
40
|
+
if (!(name in globalThis)) {
|
|
41
|
+
// happy-dom binds its accessors to the DOM window. Keep them live:
|
|
42
|
+
// copying values disconnects onresize setters and snapshots dimensions.
|
|
43
|
+
Object.defineProperty(
|
|
44
|
+
globalThis,
|
|
45
|
+
name,
|
|
46
|
+
Object.getOwnPropertyDescriptor(window, name)!,
|
|
47
|
+
);
|
|
48
|
+
}
|
|
40
49
|
}
|
|
41
50
|
// except those the story must get from happy-dom.
|
|
42
51
|
for (const name of HAPPY_DOM_GLOBALS) {
|
|
@@ -46,6 +55,26 @@ async function installDom(): Promise<void> {
|
|
|
46
55
|
value: source[name],
|
|
47
56
|
});
|
|
48
57
|
}
|
|
58
|
+
// Story JavaScript and expressions run through Function in this realm.
|
|
59
|
+
// Use that realm's global object for browser aliases too, so assignments,
|
|
60
|
+
// property descriptors and deletions on window have browser semantics.
|
|
61
|
+
for (const name of ['window', 'self', 'parent', 'top', 'frames']) {
|
|
62
|
+
Object.defineProperty(globalThis, name, {
|
|
63
|
+
configurable: true,
|
|
64
|
+
writable: true,
|
|
65
|
+
value: globalThis,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
// DOM event callbacks and document.defaultView still use the backing
|
|
69
|
+
// window. Preserve their access to the API now installed on globalThis.
|
|
70
|
+
Object.defineProperty(window, 'Story', {
|
|
71
|
+
configurable: true,
|
|
72
|
+
get: () => global.Story,
|
|
73
|
+
set: (value: unknown) => {
|
|
74
|
+
global.Story = value;
|
|
75
|
+
},
|
|
76
|
+
});
|
|
77
|
+
installIdleCallbacks();
|
|
49
78
|
// Node's BroadcastChannel reaches every worker thread in the process, so
|
|
50
79
|
// sessions would hear each other's save-slot notices. Spindle works without
|
|
51
80
|
// one (it falls back when the constructor is missing).
|
|
@@ -54,12 +83,36 @@ async function installDom(): Promise<void> {
|
|
|
54
83
|
writable: true,
|
|
55
84
|
value: undefined,
|
|
56
85
|
});
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** happy-dom has no idle scheduler; yield to a timer with a 50 ms budget. */
|
|
89
|
+
function installIdleCallbacks(): void {
|
|
90
|
+
const timers = new Map<number, ReturnType<typeof setTimeout>>();
|
|
91
|
+
let nextHandle = 0;
|
|
92
|
+
globalThis.requestIdleCallback = (callback, options) => {
|
|
93
|
+
const handle = ++nextHandle;
|
|
94
|
+
const requested = performance.now();
|
|
95
|
+
timers.set(
|
|
96
|
+
handle,
|
|
97
|
+
setTimeout(() => {
|
|
98
|
+
timers.delete(handle);
|
|
99
|
+
const started = performance.now();
|
|
100
|
+
const didTimeout =
|
|
101
|
+
options?.timeout !== undefined &&
|
|
102
|
+
started - requested >= options.timeout;
|
|
103
|
+
callback({
|
|
104
|
+
didTimeout,
|
|
105
|
+
timeRemaining: () =>
|
|
106
|
+
didTimeout ? 0 : Math.max(0, 50 - (performance.now() - started)),
|
|
107
|
+
});
|
|
108
|
+
}, 1),
|
|
109
|
+
);
|
|
110
|
+
return handle;
|
|
111
|
+
};
|
|
112
|
+
globalThis.cancelIdleCallback = (handle) => {
|
|
113
|
+
clearTimeout(timers.get(handle));
|
|
114
|
+
timers.delete(handle);
|
|
115
|
+
};
|
|
63
116
|
}
|
|
64
117
|
|
|
65
118
|
/**
|
package/src/saves/format.ts
CHANGED
|
@@ -193,6 +193,7 @@ function isPayload(value: unknown): value is Record<string, unknown> {
|
|
|
193
193
|
isCountsMap(value.renderCounts) &&
|
|
194
194
|
isOptionalPRNGSnapshot(value.prng) &&
|
|
195
195
|
isWatchers(value.watchers) &&
|
|
196
|
+
isWatchers(value.replayWatchers) &&
|
|
196
197
|
(value.interfaceWatchers === undefined ||
|
|
197
198
|
typeof value.interfaceWatchers === 'boolean')
|
|
198
199
|
);
|
|
@@ -220,6 +221,9 @@ export function decodePayload(encoded: unknown): SavePayload {
|
|
|
220
221
|
assertTrustedWatchers(
|
|
221
222
|
(body.watchers ?? []) as NonNullable<SavePayload['watchers']>,
|
|
222
223
|
);
|
|
224
|
+
assertTrustedWatchers(
|
|
225
|
+
(body.replayWatchers ?? []) as NonNullable<SavePayload['replayWatchers']>,
|
|
226
|
+
);
|
|
223
227
|
const payload = {
|
|
224
228
|
...body,
|
|
225
229
|
visitCounts: mapToCounts(body.visitCounts),
|
package/src/saves/types.ts
CHANGED
|
@@ -28,6 +28,8 @@ export interface SavePayload {
|
|
|
28
28
|
prng?: PRNGSnapshot | null;
|
|
29
29
|
/** The {watch} macro watchers registered (absent in older saves). */
|
|
30
30
|
watchers?: SavedWatcher[];
|
|
31
|
+
/** Watchers needed to replay entry-render effects, including consumed ones. */
|
|
32
|
+
replayWatchers?: SavedWatcher[];
|
|
31
33
|
/**
|
|
32
34
|
* Whether the story interface had mounted when the save was made, so that
|
|
33
35
|
* `watchers` includes its {watch} macros (absent in older saves).
|
|
@@ -66,13 +68,11 @@ export interface PlaythroughRecord {
|
|
|
66
68
|
}
|
|
67
69
|
|
|
68
70
|
/** Public-facing save metadata for the Story API. */
|
|
69
|
-
export interface SaveInfo
|
|
71
|
+
export interface SaveInfo extends Pick<
|
|
72
|
+
SaveMeta,
|
|
73
|
+
'title' | 'passage' | 'createdAt' | 'updatedAt' | 'custom'
|
|
74
|
+
> {
|
|
70
75
|
slot: string;
|
|
71
|
-
title: string;
|
|
72
|
-
passage: string;
|
|
73
|
-
createdAt: string;
|
|
74
|
-
updatedAt: string;
|
|
75
|
-
custom: Record<string, unknown>;
|
|
76
76
|
}
|
|
77
77
|
|
|
78
78
|
export interface SaveExport {
|
package/src/static-literal.ts
CHANGED
|
@@ -471,18 +471,33 @@ export class Reader {
|
|
|
471
471
|
|
|
472
472
|
/** Skip an array literal (or any bracketed group) at the cursor. */
|
|
473
473
|
protected skipBalanced(): boolean {
|
|
474
|
+
const close = { '[': ']', '{': '}', '(': ')' }[this.src.charAt(this.i)];
|
|
475
|
+
return close ? this.skipNested(close) : false;
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** Skip groups and template interpolations with an explicit stack. */
|
|
479
|
+
private skipNested(close: string): boolean {
|
|
474
480
|
const { src } = this;
|
|
475
|
-
const
|
|
476
|
-
if (!close) return false;
|
|
481
|
+
const stack = [close];
|
|
477
482
|
this.i++;
|
|
478
|
-
while (this.i < src.length) {
|
|
479
|
-
|
|
483
|
+
while (this.i < src.length && stack.length) {
|
|
484
|
+
const c = src.charAt(this.i);
|
|
485
|
+
const top = stack[stack.length - 1];
|
|
486
|
+
if (c === top) {
|
|
487
|
+
stack.pop();
|
|
480
488
|
this.i++;
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
489
|
+
} else if (top === '`') {
|
|
490
|
+
if (c === '\\') this.i += 2;
|
|
491
|
+
else if (c === '$' && src.charAt(this.i + 1) === '{') {
|
|
492
|
+
stack.push('}');
|
|
493
|
+
this.i += 2;
|
|
494
|
+
} else this.i++;
|
|
495
|
+
} else if (c === '`' || c === '[' || c === '{' || c === '(') {
|
|
496
|
+
stack.push(c === '`' ? '`' : { '[': ']', '{': '}', '(': ')' }[c]!);
|
|
497
|
+
this.i++;
|
|
498
|
+
} else if (!this.skipOne()) return false;
|
|
484
499
|
}
|
|
485
|
-
return
|
|
500
|
+
return stack.length === 0;
|
|
486
501
|
}
|
|
487
502
|
|
|
488
503
|
/** Skip one character, or one string, template, comment or group. */
|
|
@@ -512,19 +527,6 @@ export class Reader {
|
|
|
512
527
|
|
|
513
528
|
/** Skip a template literal, with the expressions in it. */
|
|
514
529
|
protected skipTemplate(): boolean {
|
|
515
|
-
|
|
516
|
-
this.i++;
|
|
517
|
-
while (this.i < src.length) {
|
|
518
|
-
const c = src.charAt(this.i);
|
|
519
|
-
if (c === '\\') this.i += 2;
|
|
520
|
-
else if (c === '`') {
|
|
521
|
-
this.i++;
|
|
522
|
-
return true;
|
|
523
|
-
} else if (c === '$' && src.charAt(this.i + 1) === '{') {
|
|
524
|
-
this.i++;
|
|
525
|
-
if (!this.skipBalanced()) return false;
|
|
526
|
-
} else this.i++;
|
|
527
|
-
}
|
|
528
|
-
return false;
|
|
530
|
+
return this.skipNested('`');
|
|
529
531
|
}
|
|
530
532
|
}
|
package/src/store.ts
CHANGED
|
@@ -26,6 +26,8 @@ import {
|
|
|
26
26
|
assertTrustedWatchers,
|
|
27
27
|
interfaceMounted,
|
|
28
28
|
savedMacroWatchers,
|
|
29
|
+
savedReplayWatchers,
|
|
30
|
+
clearReplayWatchers,
|
|
29
31
|
reinitTriggerState,
|
|
30
32
|
} from './triggers';
|
|
31
33
|
import {
|
|
@@ -206,6 +208,7 @@ function applyVarPatches(
|
|
|
206
208
|
vars: Record<string, unknown>,
|
|
207
209
|
changes: readonly VarChange[],
|
|
208
210
|
): Record<string, unknown> {
|
|
211
|
+
if (changes.length === 0) return vars;
|
|
209
212
|
const next = Object.create(
|
|
210
213
|
Object.getPrototypeOf(vars) as object | null,
|
|
211
214
|
) as Record<string, unknown>;
|
|
@@ -324,6 +327,7 @@ function persistSession(get: () => StoryState): { error: unknown } | undefined {
|
|
|
324
327
|
renderCounts,
|
|
325
328
|
prng: snapshotPRNG(),
|
|
326
329
|
watchers: savedMacroWatchers(),
|
|
330
|
+
replayWatchers: savedReplayWatchers(),
|
|
327
331
|
interfaceWatchers: interfaceMounted(),
|
|
328
332
|
});
|
|
329
333
|
}
|
|
@@ -422,6 +426,9 @@ function finishEnteredMoment(get: StoreGet, set: StoreSet): void {
|
|
|
422
426
|
const moment = enteredMoment;
|
|
423
427
|
enteredMoment = null;
|
|
424
428
|
if (!moment || get().navigationId !== moment.navigationId) return;
|
|
429
|
+
// Navigation can run inside a macro's render. Its watcher effects are
|
|
430
|
+
// recorded below, so they must not also be replayed as passage effects.
|
|
431
|
+
clearReplayWatchers();
|
|
425
432
|
if (get().variables !== moment.variables) {
|
|
426
433
|
rerecordNewestMoment(get().variables);
|
|
427
434
|
}
|
|
@@ -558,6 +565,7 @@ export function recordStoryInitState(): void {
|
|
|
558
565
|
if (history.length !== 1 || historyIndex !== 0) return;
|
|
559
566
|
|
|
560
567
|
resetModuleState(variables);
|
|
568
|
+
clearReplayWatchers();
|
|
561
569
|
|
|
562
570
|
const prng = snapshotPRNG();
|
|
563
571
|
useStoryStore.setState((state) => {
|
|
@@ -1817,6 +1825,7 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1817
1825
|
renderCounts: { ...renderCounts },
|
|
1818
1826
|
prng: snapshotPRNG(),
|
|
1819
1827
|
watchers: savedMacroWatchers(),
|
|
1828
|
+
replayWatchers: savedReplayWatchers(),
|
|
1820
1829
|
interfaceWatchers: interfaceMounted(),
|
|
1821
1830
|
};
|
|
1822
1831
|
},
|
|
@@ -1860,6 +1869,7 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1860
1869
|
// running game as it is
|
|
1861
1870
|
assertPassagesExist(get().storyData, payload);
|
|
1862
1871
|
assertTrustedWatchers(payload.watchers ?? []);
|
|
1872
|
+
assertTrustedWatchers(payload.replayWatchers ?? []);
|
|
1863
1873
|
applyReplacement(replacement);
|
|
1864
1874
|
|
|
1865
1875
|
leavingPlaythrough = leaving;
|
|
@@ -1893,18 +1903,36 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1893
1903
|
// Convert full snapshots to patch entries. They are copied in one
|
|
1894
1904
|
// piece, so values the moments share stay shared, and a transition's
|
|
1895
1905
|
// patches hold only the variables that changed.
|
|
1896
|
-
const
|
|
1897
|
-
|
|
1906
|
+
const index = Math.max(
|
|
1907
|
+
0,
|
|
1908
|
+
Math.min(payload.historyIndex, payload.history.length - 1),
|
|
1909
|
+
);
|
|
1910
|
+
const start = Math.min(
|
|
1911
|
+
index,
|
|
1912
|
+
Math.max(0, payload.history.length - get().maxHistory),
|
|
1913
|
+
);
|
|
1914
|
+
const retained = payload.history.slice(start, start + get().maxHistory);
|
|
1915
|
+
const namespaces = new Map<Record<string, unknown>, Namespace>();
|
|
1916
|
+
const snapshots = deepClone(retained.map((m) => m.variables)).map(
|
|
1917
|
+
(vars) => {
|
|
1918
|
+
let normalized = namespaces.get(vars);
|
|
1919
|
+
if (!normalized) {
|
|
1920
|
+
normalized = createNamespace(vars);
|
|
1921
|
+
namespaces.set(vars, normalized);
|
|
1922
|
+
}
|
|
1923
|
+
return normalized;
|
|
1924
|
+
},
|
|
1898
1925
|
);
|
|
1899
1926
|
variableBase = deepClone(snapshots[0]!);
|
|
1900
1927
|
patchEntries = snapshots
|
|
1901
1928
|
.slice(1)
|
|
1902
|
-
.map((curr, i) =>
|
|
1903
|
-
|
|
1904
|
-
|
|
1905
|
-
|
|
1906
|
-
|
|
1907
|
-
|
|
1929
|
+
.map((curr, i) =>
|
|
1930
|
+
curr === snapshots[i]
|
|
1931
|
+
? { forward: [] }
|
|
1932
|
+
: computeVarPatches(snapshots[i]!, curr),
|
|
1933
|
+
);
|
|
1934
|
+
// Seed only retained moments; repeated namespaces stay shared.
|
|
1935
|
+
sessionMoments = retained.map((m, i) => savedMoment(m, snapshots[i]!));
|
|
1908
1936
|
|
|
1909
1937
|
set((state) => {
|
|
1910
1938
|
state.currentPassage = payload.passage;
|
|
@@ -1912,17 +1940,12 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1912
1940
|
state.variables = createNamespace(
|
|
1913
1941
|
deepClone(entry?.variables ?? payload.variables),
|
|
1914
1942
|
);
|
|
1915
|
-
state.history =
|
|
1943
|
+
state.history = retained.map((m) => ({
|
|
1916
1944
|
passage: m.passage,
|
|
1917
1945
|
timestamp: m.timestamp,
|
|
1918
1946
|
prng: m.prng,
|
|
1919
1947
|
}));
|
|
1920
|
-
state.historyIndex =
|
|
1921
|
-
0,
|
|
1922
|
-
Math.min(payload.historyIndex, state.history.length - 1),
|
|
1923
|
-
);
|
|
1924
|
-
// A save made under a higher limit keeps no more than the limit
|
|
1925
|
-
trimHistory(state);
|
|
1948
|
+
state.historyIndex = index - start;
|
|
1926
1949
|
state.visitCounts = createCounts(payload.visitCounts);
|
|
1927
1950
|
state.renderCounts = createCounts(payload.renderCounts);
|
|
1928
1951
|
state.temporary = createNamespace();
|
|
@@ -1933,7 +1956,10 @@ export const useStoryStore = create<StoryState>()(
|
|
|
1933
1956
|
// older version, leaves the registered ones), then: loaded state is
|
|
1934
1957
|
// not a change watchers react to
|
|
1935
1958
|
if (payload.watchers) {
|
|
1936
|
-
restoreMacroWatchers(
|
|
1959
|
+
restoreMacroWatchers(
|
|
1960
|
+
payload.replayWatchers ?? payload.watchers,
|
|
1961
|
+
payload.interfaceWatchers,
|
|
1962
|
+
);
|
|
1937
1963
|
}
|
|
1938
1964
|
reinitTriggerState();
|
|
1939
1965
|
|
package/src/tooling.ts
CHANGED
package/src/triggers.ts
CHANGED
|
@@ -5,6 +5,7 @@ import type { StoryData } from './parser';
|
|
|
5
5
|
import { evaluate } from './expression';
|
|
6
6
|
import { executeMutation, readState } from './execute-mutation';
|
|
7
7
|
import { useStoryStore } from './store';
|
|
8
|
+
import { getRenderedNavigationId } from './passage-render-state';
|
|
8
9
|
import { createListeners } from './utils/listeners';
|
|
9
10
|
|
|
10
11
|
export interface WatchOptions {
|
|
@@ -23,7 +24,10 @@ export interface QueuedDialog {
|
|
|
23
24
|
dismissible?: boolean;
|
|
24
25
|
}
|
|
25
26
|
|
|
27
|
+
let registrations = 0;
|
|
28
|
+
|
|
26
29
|
interface Trigger {
|
|
30
|
+
order: number;
|
|
27
31
|
name?: string;
|
|
28
32
|
condition: string;
|
|
29
33
|
callback?: () => void;
|
|
@@ -75,6 +79,7 @@ function registerTrigger(
|
|
|
75
79
|
const callback = isCallback ? callbackOrOptions : undefined;
|
|
76
80
|
|
|
77
81
|
const trigger: Trigger = {
|
|
82
|
+
order: registrations++,
|
|
78
83
|
name: options?.name,
|
|
79
84
|
condition,
|
|
80
85
|
callback,
|
|
@@ -125,6 +130,97 @@ export interface SavedWatcher {
|
|
|
125
130
|
options: WatchOptions;
|
|
126
131
|
}
|
|
127
132
|
|
|
133
|
+
// A passage replays its entry variables on load. Watchers removed by its
|
|
134
|
+
// initial render must replay too; removals after player actions stay removed.
|
|
135
|
+
let macroRenderDepth = 0;
|
|
136
|
+
let entryRenderDepth = 0;
|
|
137
|
+
let replayNavigation = -1;
|
|
138
|
+
const replayRemoved = new Map<
|
|
139
|
+
string,
|
|
140
|
+
{ watcher: SavedWatcher; order: number }
|
|
141
|
+
>();
|
|
142
|
+
|
|
143
|
+
/** Entry lifecycle callbacks and deferred initial passage subtrees replay on load. */
|
|
144
|
+
export function duringEntryRender<T>(render: () => T): T {
|
|
145
|
+
entryRenderDepth++;
|
|
146
|
+
try {
|
|
147
|
+
return render();
|
|
148
|
+
} finally {
|
|
149
|
+
entryRenderDepth--;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
function isEntryRender(): boolean {
|
|
154
|
+
return (
|
|
155
|
+
entryRenderDepth > 0 ||
|
|
156
|
+
(macroRenderDepth > 0 &&
|
|
157
|
+
getRenderedNavigationId() !== useStoryStore.getState().navigationId)
|
|
158
|
+
);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function duringMacroRender<T>(render: () => T): T {
|
|
162
|
+
macroRenderDepth++;
|
|
163
|
+
try {
|
|
164
|
+
return render();
|
|
165
|
+
} finally {
|
|
166
|
+
macroRenderDepth--;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Forget replay removals whose effects have become part of a recorded entry. */
|
|
171
|
+
export function clearReplayWatchers(): void {
|
|
172
|
+
replayRemoved.clear();
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function replayRemovals() {
|
|
176
|
+
const navigation = useStoryStore.getState().navigationId;
|
|
177
|
+
if (navigation !== replayNavigation) {
|
|
178
|
+
replayRemoved.clear();
|
|
179
|
+
replayNavigation = navigation;
|
|
180
|
+
}
|
|
181
|
+
return replayRemoved;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function rememberRemoval(trigger: Trigger): void {
|
|
185
|
+
const removed = replayRemovals();
|
|
186
|
+
if (!trigger.macroKey || !trigger.options) return;
|
|
187
|
+
if (isEntryRender()) {
|
|
188
|
+
// A once watcher may be re-declared and consumed again in this entry.
|
|
189
|
+
// Replay begins with its first registration, before surviving peers.
|
|
190
|
+
if (removed.has(trigger.macroKey)) return;
|
|
191
|
+
removed.set(trigger.macroKey, {
|
|
192
|
+
watcher: {
|
|
193
|
+
condition: trigger.condition,
|
|
194
|
+
options: { ...trigger.options },
|
|
195
|
+
},
|
|
196
|
+
order: trigger.order,
|
|
197
|
+
});
|
|
198
|
+
} else {
|
|
199
|
+
removed.delete(trigger.macroKey);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Entry-render removals plus still active watchers, absent when none need replay. */
|
|
204
|
+
export function savedReplayWatchers(): SavedWatcher[] | undefined {
|
|
205
|
+
const removed = replayRemovals();
|
|
206
|
+
if (!removed.size) return undefined;
|
|
207
|
+
const all = new Map(removed);
|
|
208
|
+
for (const trigger of triggers) {
|
|
209
|
+
if (!trigger.macroKey || !trigger.options || all.has(trigger.macroKey))
|
|
210
|
+
continue;
|
|
211
|
+
all.set(trigger.macroKey, {
|
|
212
|
+
watcher: {
|
|
213
|
+
condition: trigger.condition,
|
|
214
|
+
options: { ...trigger.options },
|
|
215
|
+
},
|
|
216
|
+
order: trigger.order,
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
return [...all.values()]
|
|
220
|
+
.sort((a, b) => a.order - b.order)
|
|
221
|
+
.map(({ watcher }) => watcher);
|
|
222
|
+
}
|
|
223
|
+
|
|
128
224
|
/** Canonical identity includes every option, so an imported action cannot change it. */
|
|
129
225
|
function watcherKey(condition: string, options: WatchOptions): string {
|
|
130
226
|
const sorted = Object.fromEntries(
|
|
@@ -251,6 +347,15 @@ export function restoreMacroWatchers(
|
|
|
251
347
|
}
|
|
252
348
|
|
|
253
349
|
export function removeTrigger(name: string): void {
|
|
350
|
+
for (const trigger of triggers) {
|
|
351
|
+
if (trigger.name === name) rememberRemoval(trigger);
|
|
352
|
+
}
|
|
353
|
+
// An explicit later unwatch also removes a consumed entry watcher.
|
|
354
|
+
if (!isEntryRender()) {
|
|
355
|
+
for (const [key, { watcher }] of replayRemovals()) {
|
|
356
|
+
if (watcher.options.name === name) replayRemoved.delete(key);
|
|
357
|
+
}
|
|
358
|
+
}
|
|
254
359
|
triggers = triggers.filter((t) => t.name !== name);
|
|
255
360
|
}
|
|
256
361
|
|
|
@@ -310,6 +415,7 @@ function runCheckLoop(): void {
|
|
|
310
415
|
anyFired = true;
|
|
311
416
|
|
|
312
417
|
if (trigger.options?.once) {
|
|
418
|
+
rememberRemoval(trigger);
|
|
313
419
|
triggers = triggers.filter((t) => t !== trigger);
|
|
314
420
|
}
|
|
315
421
|
|
|
@@ -406,6 +512,7 @@ export function reinitTriggerState(): void {
|
|
|
406
512
|
*/
|
|
407
513
|
export function resetTriggers(): void {
|
|
408
514
|
triggers = [];
|
|
515
|
+
replayRemoved.clear();
|
|
409
516
|
resets++;
|
|
410
517
|
closeAllOpenDialogs();
|
|
411
518
|
resetListeners.notify();
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { passagePiecesOfTokens } from '../tooling';
|
|
2
2
|
import { tokenizeMarkupTolerant } from '../markup/parse';
|
|
3
3
|
import { builtinMacros } from './builtin-macros';
|
|
4
4
|
|
|
@@ -13,19 +13,17 @@ export function parsePassageText(text: string): string[] {
|
|
|
13
13
|
try {
|
|
14
14
|
// Both `[[…]]` and `{link}` report `macro: 'link'`; only the link token
|
|
15
15
|
// tells them apart.
|
|
16
|
-
const
|
|
17
|
-
|
|
16
|
+
const tokens = tokenizeMarkupTolerant(text).tokens;
|
|
17
|
+
const bracketTargets = new Set(
|
|
18
|
+
tokens
|
|
19
|
+
.filter((token) => token.type === 'link')
|
|
20
|
+
.map((link) => link.targetStart),
|
|
18
21
|
);
|
|
19
22
|
const names = new Set<string>();
|
|
20
|
-
for (const
|
|
21
|
-
if (
|
|
22
|
-
if (
|
|
23
|
-
links.some(
|
|
24
|
-
(link) => ref.start >= link.targetStart && ref.start < link.targetEnd,
|
|
25
|
-
)
|
|
26
|
-
)
|
|
23
|
+
for (const piece of passagePiecesOfTokens(text, builtinMacros, tokens)) {
|
|
24
|
+
if (piece.kind !== 'passage' || bracketTargets.has(piece.offset))
|
|
27
25
|
continue;
|
|
28
|
-
names.add(
|
|
26
|
+
names.add(piece.name);
|
|
29
27
|
}
|
|
30
28
|
return [...names];
|
|
31
29
|
} catch {
|