@rohal12/spindle 0.62.1 → 0.62.3

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/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 { collectStoryPassageReferences } from '../tooling';
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 links = tokenizeMarkupTolerant(text).tokens.filter(
17
- (token) => token.type === 'link',
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 ref of collectStoryPassageReferences(text, builtinMacros)) {
21
- if (ref.target.kind !== 'name') continue;
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(ref.target.name);
26
+ names.add(piece.name);
29
27
  }
30
28
  return [...names];
31
29
  } catch {
@@ -1,7 +1,7 @@
1
1
  import type { ASTNode } from '../markup/ast';
2
2
  import type { Token } from '../markup/tokens';
3
3
  import { codeAndText, parameterLookup, type ParametersOf } from '../code-check';
4
- import { parseMarkup } from '../markup/parse';
4
+ import { parseMarkup, type MarkupHooks } from '../markup/parse';
5
5
  import { getMacroRegistry } from '../registry';
6
6
 
7
7
  /** The declared parameters of the macros registered so far. */
@@ -15,16 +15,17 @@ export const registeredParameters: ParametersOf = (name) =>
15
15
  function textContainsChildren(
16
16
  text: string,
17
17
  parametersOf: ParametersOf,
18
+ hooks?: Partial<MarkupHooks>,
18
19
  ): boolean {
19
20
  if (!text.includes('{')) return false;
20
21
  let nodes: ASTNode[];
21
22
  try {
22
- nodes = parseMarkup(text, { text: true });
23
+ nodes = parseMarkup(text, { text: true, hooks });
23
24
  } catch {
24
25
  // The renderer reports the markup that does not parse
25
26
  return false;
26
27
  }
27
- return astContainsChildren(nodes, parametersOf);
28
+ return astContainsChildren(nodes, parametersOf, hooks);
28
29
  }
29
30
 
30
31
  /**
@@ -32,17 +33,19 @@ function textContainsChildren(
32
33
  * argument that holds markup (`<span title="{@children}">`,
33
34
  * `{button "{@children}"}`). Literal arguments and code are not markup.
34
35
  * `src` is the text a flat token's offsets index into (its attribute values
35
- * are read from it); a token made from an AST has none.
36
+ * are read from it); a token made from an AST has none. Discovery hooks
37
+ * also apply inside these texts, before widgets have been registered.
36
38
  */
37
39
  export function tokenTextContainsChildren(
38
40
  token: Token,
39
41
  parametersOf: ParametersOf = registeredParameters,
40
42
  src = '',
43
+ hooks?: Partial<MarkupHooks>,
41
44
  ): boolean {
42
45
  for (const piece of codeAndText(src, [token], parametersOf)) {
43
46
  if (
44
47
  piece.kind === 'text' &&
45
- textContainsChildren(piece.text, parametersOf)
48
+ textContainsChildren(piece.text, parametersOf, hooks)
46
49
  ) {
47
50
  return true;
48
51
  }
@@ -60,6 +63,7 @@ export function tokenTextContainsChildren(
60
63
  export function astContainsChildren(
61
64
  nodes: ASTNode[],
62
65
  parametersOf: ParametersOf = registeredParameters,
66
+ hooks?: Partial<MarkupHooks>,
63
67
  ): boolean {
64
68
  for (const node of nodes) {
65
69
  if (
@@ -69,46 +73,38 @@ export function astContainsChildren(
69
73
  ) {
70
74
  return true;
71
75
  }
72
- if (node.type === 'html') {
73
- // A token in name only: the scan reads its attribute values
74
- const tag: Token = {
75
- isClose: false,
76
- isSelfClose: false,
77
- tagNameStart: 0,
78
- tagNameEnd: 0,
79
- attributeSpans: [],
80
- ...node,
81
- start: 0,
82
- end: 0,
83
- };
84
- if (
85
- tokenTextContainsChildren(tag, parametersOf) ||
86
- astContainsChildren(node.children, parametersOf)
87
- ) {
88
- return true;
89
- }
76
+ if (node.type !== 'html' && node.type !== 'macro') continue;
77
+ if (node.type === 'macro' && node.name.toLowerCase() === 'widget') continue;
78
+ // A token in name only: the scan reads its label or attribute values.
79
+ const span = { isClose: false, start: 0, end: 0 };
80
+ const tag: Token =
81
+ node.type === 'html'
82
+ ? {
83
+ ...node,
84
+ ...span,
85
+ isSelfClose: false,
86
+ tagNameStart: 0,
87
+ tagNameEnd: 0,
88
+ attributeSpans: [],
89
+ }
90
+ : {
91
+ ...node,
92
+ ...span,
93
+ nameStart: 0,
94
+ nameEnd: 0,
95
+ argsStart: 0,
96
+ argsEnd: 0,
97
+ };
98
+ if (
99
+ tokenTextContainsChildren(tag, parametersOf, '', hooks) ||
100
+ astContainsChildren(node.children, parametersOf, hooks)
101
+ ) {
102
+ return true;
90
103
  }
91
- if (node.type === 'macro') {
92
- if (node.name.toLowerCase() === 'widget') continue;
93
- const tag: Token = {
94
- isClose: false,
95
- nameStart: 0,
96
- nameEnd: 0,
97
- argsStart: 0,
98
- argsEnd: 0,
99
- ...node,
100
- start: 0,
101
- end: 0,
102
- };
103
- if (
104
- tokenTextContainsChildren(tag, parametersOf) ||
105
- astContainsChildren(node.children, parametersOf)
106
- ) {
107
- return true;
108
- }
109
- if (node.branches) {
110
- for (const branch of node.branches) {
111
- if (astContainsChildren(branch.children, parametersOf)) return true;
104
+ if (node.type === 'macro' && node.branches) {
105
+ for (const branch of node.branches) {
106
+ if (astContainsChildren(branch.children, parametersOf, hooks)) {
107
+ return true;
112
108
  }
113
109
  }
114
110
  }
@@ -5,6 +5,7 @@
5
5
  import { parseMacroArgs, type ArgSpans } from '../components/macros/macro-args';
6
6
  import { STRING_HOLDS, type MacroArgs, type StringHolds } from '../registry';
7
7
  import { tokenizeMarkupTolerant } from '../markup/parse';
8
+ import { isRawMacro } from '../markup/ast';
8
9
  import type { MacroToken } from '../markup/tokens';
9
10
  import type { ParametersOf } from '../code-check';
10
11
  import { NameMap } from '../utils/macro-names';
@@ -131,55 +132,83 @@ export function widgetDefinitions(
131
132
  passages: Iterable<WidgetPassage>,
132
133
  parametersOf: ParametersOf = registeredParameters,
133
134
  ): WidgetDefinition[] {
134
- const found: WidgetDefinition[] = [];
135
- for (const passage of passages) {
136
- if (passage.name !== 'StoryInit' && !passage.tags?.includes('widget')) {
137
- continue;
138
- }
139
- // The open definitions: their tags, and whether a slot was seen
140
- const open: { token: MacroToken; isBlock: boolean; closeStart?: number }[] =
141
- [];
142
- const done: typeof open = [];
143
- for (const token of tokenizeMarkupTolerant(passage.content).tokens) {
144
- if (token.type === 'macro' && token.name.toLowerCase() === 'widget') {
145
- if (!token.isClose) {
146
- open.push({ token, isBlock: false });
147
- } else {
148
- const def = open.pop();
149
- if (def) done.push({ ...def, closeStart: token.start });
135
+ const list = [...passages];
136
+ const scan = (replacesDo: boolean): WidgetDefinition[] => {
137
+ const found: WidgetDefinition[] = [];
138
+ const hooks = {
139
+ isRaw: (name: string) =>
140
+ isRawMacro(
141
+ name,
142
+ replacesDo || parametersOf.widget?.(name) !== undefined,
143
+ ),
144
+ };
145
+ for (const passage of list) {
146
+ if (passage.name !== 'StoryInit' && !passage.tags?.includes('widget')) {
147
+ continue;
148
+ }
149
+ // The open definitions: their tags, and whether a slot was seen
150
+ const open: {
151
+ token: MacroToken;
152
+ isBlock: boolean;
153
+ closeStart?: number;
154
+ }[] = [];
155
+ const done: typeof open = [];
156
+ for (const token of tokenizeMarkupTolerant(passage.content, { hooks })
157
+ .tokens) {
158
+ if (token.type === 'macro' && token.name.toLowerCase() === 'widget') {
159
+ if (!token.isClose) {
160
+ open.push({ token, isBlock: false });
161
+ } else {
162
+ const def = open.pop();
163
+ if (def) done.push({ ...def, closeStart: token.start });
164
+ }
165
+ } else if (
166
+ open.length > 0 &&
167
+ ((token.type === 'variable' &&
168
+ token.scope === 'local' &&
169
+ token.name === 'children') ||
170
+ tokenTextContainsChildren(
171
+ token,
172
+ parametersOf,
173
+ passage.content,
174
+ hooks,
175
+ ))
176
+ ) {
177
+ open[open.length - 1]!.isBlock = true;
150
178
  }
151
- } else if (
152
- open.length > 0 &&
153
- ((token.type === 'variable' &&
154
- token.scope === 'local' &&
155
- token.name === 'children') ||
156
- tokenTextContainsChildren(token, parametersOf, passage.content))
157
- ) {
158
- open[open.length - 1]!.isBlock = true;
159
179
  }
160
- }
161
- done.push(...open);
162
- const defs: WidgetDefinition[] = [];
163
- for (const { token, isBlock, closeStart } of done) {
164
- try {
165
- const [from, to] = nameSpan(token.rawArgs);
166
- defs.push({
167
- ...parseWidgetDef(token.rawArgs),
168
- block: isBlock,
169
- passage: passage.name,
170
- start: token.start,
171
- end: token.end,
172
- nameStart: token.argsStart + from,
173
- nameEnd: token.argsStart + to,
174
- ...(closeStart === undefined ? {} : { closeStart }),
175
- });
176
- } catch {
177
- // The {widget} macro reports a definition it cannot read
180
+ done.push(...open);
181
+ const defs: WidgetDefinition[] = [];
182
+ for (const { token, isBlock, closeStart } of done) {
183
+ try {
184
+ const [from, to] = nameSpan(token.rawArgs);
185
+ defs.push({
186
+ ...parseWidgetDef(token.rawArgs),
187
+ block: isBlock,
188
+ passage: passage.name,
189
+ start: token.start,
190
+ end: token.end,
191
+ nameStart: token.argsStart + from,
192
+ nameEnd: token.argsStart + to,
193
+ ...(closeStart === undefined ? {} : { closeStart }),
194
+ });
195
+ } catch {
196
+ // The {widget} macro reports a definition it cannot read
197
+ }
178
198
  }
199
+ found.push(...defs.sort((a, b) => a.start - b.start));
179
200
  }
180
- found.push(...defs.sort((a, b) => a.start - b.start));
181
- }
182
- return found;
201
+ return found;
202
+ };
203
+ const initial = scan(false);
204
+ // Discover definitions with real raw bodies first, so JavaScript strings
205
+ // that merely mention a widget cannot replace the built-in do. Once a
206
+ // closed do widget is known, its body and its callers are markup.
207
+ return effectiveWidgetDefinitions(initial).some(
208
+ (def) => def.name.toLowerCase() === 'do',
209
+ )
210
+ ? scan(true)
211
+ : initial;
183
212
  }
184
213
 
185
214
  /**
@@ -1241,3 +1241,20 @@ export declare function macroArgumentSpans(
1241
1241
  rawArgs: string,
1242
1242
  parameters: readonly ParameterDef[],
1243
1243
  ): MacroArgumentSpan[];
1244
+
1245
+ /** Executable code at a cursor, or prose/literal text that suppresses completion. */
1246
+ export type CompletionContext =
1247
+ | { kind: 'literal' }
1248
+ | (PieceBase & { kind: 'code'; code: string; goal: JsGoal; cursor: number });
1249
+
1250
+ /** Inspect only the prefix before cursor (UTF-16), accepting unfinished markup.
1251
+ * Strings, comments, regexes and template text are literal; template
1252
+ * interpolations are code. Code offsets map to source with pieceOffset.
1253
+ * Uses macro parameter metadata for nested labels, attributes and held code.
1254
+ * Throws RangeError for an invalid cursor; never executes story code.
1255
+ */
1256
+ export declare function completionContext(
1257
+ source: string,
1258
+ cursor: number,
1259
+ macros?: Iterable<ToolingMacro>,
1260
+ ): CompletionContext;