@rohal12/spindle 0.17.0 → 0.19.0

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/story-init.ts CHANGED
@@ -1,63 +1,30 @@
1
+ import { h, render } from 'preact';
1
2
  import { useStoryStore } from './store';
2
3
  import { tokenize } from './markup/tokenizer';
3
4
  import { buildAST } from './markup/ast';
4
- import { execute } from './expression';
5
- import type { ASTNode } from './markup/ast';
5
+ import { renderNodes } from './markup/render';
6
6
  import { setSaveTitlePassage } from './saves/save-manager';
7
- import { deepClone } from './class-registry';
8
7
 
9
8
  /**
10
- * Walk AST nodes from StoryInit and execute {set} and {do} imperatively
11
- * (no Preact rendering needed for initialization).
12
- */
13
- function walkAndExecute(
14
- nodes: ASTNode[],
15
- vars: Record<string, unknown>,
16
- temps: Record<string, unknown>,
17
- ) {
18
- for (const node of nodes) {
19
- if (node.type !== 'macro') continue;
20
-
21
- if (node.name === 'set') {
22
- execute(node.rawArgs, vars, temps);
23
- } else if (node.name === 'do') {
24
- const code = node.children
25
- .map((n) => (n.type === 'text' ? n.value : ''))
26
- .join('');
27
- execute(code, vars, temps);
28
- }
29
- }
30
- }
31
-
32
- /**
33
- * Execute the StoryInit passage: tokenize, parse, and run all {set}/{do} macros.
34
- * Called during boot and after restart() to ensure variables are initialized.
9
+ * Execute the StoryInit passage: tokenize, parse, and render all macros
10
+ * into a detached DOM node so their side effects fire through the normal
11
+ * Preact pipeline. This is macro-agnostic — any macro works in StoryInit.
35
12
  */
36
13
  export function executeStoryInit() {
37
14
  const state = useStoryStore.getState();
38
15
  if (!state.storyData) return;
39
16
 
40
17
  const storyInit = state.storyData.passages.get('StoryInit');
41
- if (!storyInit) return;
42
-
43
- const tokens = tokenize(storyInit.content);
44
- const ast = buildAST(tokens);
45
-
46
- const vars = deepClone(state.variables);
47
- const temps = deepClone(state.temporary);
48
-
49
- walkAndExecute(ast, vars, temps);
50
-
51
- // Apply all changes to the store
52
- for (const key of Object.keys(vars)) {
53
- if (vars[key] !== state.variables[key]) {
54
- state.setVariable(key, vars[key]);
55
- }
56
- }
57
- for (const key of Object.keys(temps)) {
58
- if (temps[key] !== state.temporary[key]) {
59
- state.setTemporary(key, temps[key]);
60
- }
18
+ if (storyInit) {
19
+ const tokens = tokenize(storyInit.content);
20
+ const ast = buildAST(tokens);
21
+
22
+ const container = document.createElement('div');
23
+ render(
24
+ h(() => renderNodes(ast) as any, null),
25
+ container,
26
+ );
27
+ render(null, container);
61
28
  }
62
29
 
63
30
  // Register SaveTitle passage if it exists
@@ -0,0 +1,161 @@
1
+ import { evaluate, execute } from './expression';
2
+ import { useStoryStore } from './store';
3
+
4
+ export interface WatchOptions {
5
+ goto?: string;
6
+ dialog?: string;
7
+ run?: string;
8
+ once?: boolean;
9
+ name?: string;
10
+ priority?: number;
11
+ }
12
+
13
+ interface Trigger {
14
+ id: number;
15
+ name?: string;
16
+ condition: string;
17
+ callback?: () => void;
18
+ options?: WatchOptions;
19
+ lastResult: boolean;
20
+ priority: number;
21
+ }
22
+
23
+ let nextId = 0;
24
+ let triggers: Trigger[] = [];
25
+ let checking = false;
26
+
27
+ type DialogCallback = () => void;
28
+ let dialogQueue: string[] = [];
29
+ let dialogNotify: DialogCallback | null = null;
30
+
31
+ function evalCondition(condition: string): boolean {
32
+ const state = useStoryStore.getState();
33
+ try {
34
+ return !!evaluate(condition, state.variables, state.temporary);
35
+ } catch {
36
+ return false;
37
+ }
38
+ }
39
+
40
+ export function addTrigger(
41
+ condition: string,
42
+ callbackOrOptions: (() => void) | WatchOptions,
43
+ ): () => void {
44
+ const id = nextId++;
45
+ const isCallback = typeof callbackOrOptions === 'function';
46
+ const options = isCallback ? undefined : callbackOrOptions;
47
+ const callback = isCallback ? callbackOrOptions : undefined;
48
+
49
+ const trigger: Trigger = {
50
+ id,
51
+ name: options?.name,
52
+ condition,
53
+ callback,
54
+ options,
55
+ lastResult: evalCondition(condition),
56
+ priority: options?.priority ?? 0,
57
+ };
58
+
59
+ triggers.push(trigger);
60
+ triggers.sort((a, b) => b.priority - a.priority);
61
+
62
+ return () => {
63
+ triggers = triggers.filter((t) => t.id !== id);
64
+ };
65
+ }
66
+
67
+ export function removeTrigger(name: string): void {
68
+ triggers = triggers.filter((t) => t.name !== name);
69
+ }
70
+
71
+ function fireTrigger(trigger: Trigger): void {
72
+ const { callback, options } = trigger;
73
+
74
+ if (callback) {
75
+ callback();
76
+ return;
77
+ }
78
+
79
+ if (!options) return;
80
+
81
+ if (options.run) {
82
+ const state = useStoryStore.getState();
83
+ execute(options.run, state.variables, state.temporary);
84
+ }
85
+
86
+ if (options.dialog) {
87
+ dialogQueue.push(options.dialog);
88
+ dialogNotify?.();
89
+ }
90
+
91
+ if (options.goto) {
92
+ useStoryStore.getState().navigate(options.goto);
93
+ }
94
+ }
95
+
96
+ const MAX_RECHECK_DEPTH = 10;
97
+
98
+ export function checkTriggers(): void {
99
+ if (checking) return;
100
+ checking = true;
101
+
102
+ try {
103
+ for (let depth = 0; depth < MAX_RECHECK_DEPTH; depth++) {
104
+ let anyFired = false;
105
+
106
+ // Snapshot triggers list — firing may remove `once` triggers
107
+ const current = [...triggers];
108
+ for (const trigger of current) {
109
+ // Skip if removed during this cycle
110
+ if (!triggers.includes(trigger)) continue;
111
+
112
+ const result = evalCondition(trigger.condition);
113
+ const wasFalse = !trigger.lastResult;
114
+ trigger.lastResult = result;
115
+
116
+ if (result && wasFalse) {
117
+ anyFired = true;
118
+
119
+ if (trigger.options?.once) {
120
+ triggers = triggers.filter((t) => t.id !== trigger.id);
121
+ }
122
+
123
+ fireTrigger(trigger);
124
+ }
125
+ }
126
+
127
+ if (!anyFired) break;
128
+ }
129
+ } finally {
130
+ checking = false;
131
+ }
132
+ }
133
+
134
+ export function reinitTriggerState(): void {
135
+ for (const trigger of triggers) {
136
+ trigger.lastResult = evalCondition(trigger.condition);
137
+ }
138
+ }
139
+
140
+ export function resetTriggers(): void {
141
+ triggers = [];
142
+ dialogQueue = [];
143
+ nextId = 0;
144
+ }
145
+
146
+ export function subscribeTriggerDialogs(cb: () => void): () => void {
147
+ dialogNotify = cb;
148
+ // Flush any queued dialogs
149
+ if (dialogQueue.length > 0) cb();
150
+ return () => {
151
+ if (dialogNotify === cb) dialogNotify = null;
152
+ };
153
+ }
154
+
155
+ export function shiftDialogQueue(): string | undefined {
156
+ return dialogQueue.shift();
157
+ }
158
+
159
+ export function dialogQueueLength(): number {
160
+ return dialogQueue.length;
161
+ }