@rohal12/spindle 0.61.5 → 0.61.6

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.
@@ -11752,8 +11752,14 @@ function stringHolds(param) {
11752
11752
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11753
11753
  */
11754
11754
  function* codeAndText(src, tokens, parametersOf) {
11755
- /** The index of the closing tag of the `name` macro opened at `t`. */
11756
- const closeOf = (t, name) => tokens.findIndex((c, k) => k > t && c.type === "macro" && c.isClose && c.name.toLowerCase() === name);
11755
+ const closeOfTextBody = (t, name) => {
11756
+ for (let k = t + 1; k < tokens.length; k++) {
11757
+ const c = tokens[k];
11758
+ if (c.type === "text") continue;
11759
+ return c.type === "macro" && c.isClose && c.name.toLowerCase() === name ? k : -1;
11760
+ }
11761
+ return -1;
11762
+ };
11757
11763
  for (let t = 0; t < tokens.length; t++) {
11758
11764
  const token = tokens[t];
11759
11765
  if (token.type === "link") {
@@ -11789,7 +11795,7 @@ function* codeAndText(src, tokens, parametersOf) {
11789
11795
  else if (token.type === "macro" && !token.isClose) {
11790
11796
  const name = token.name.toLowerCase();
11791
11797
  if (name === "do") {
11792
- const close = closeOf(t, name);
11798
+ const close = closeOfTextBody(t, name);
11793
11799
  if (close < 0) continue;
11794
11800
  yield {
11795
11801
  kind: "code",
@@ -11803,9 +11809,8 @@ function* codeAndText(src, tokens, parametersOf) {
11803
11809
  }
11804
11810
  const args = token.rawArgs;
11805
11811
  if (PASSAGE_BODIES.has(name)) {
11806
- const close = closeOf(t, name);
11807
- const body = tokens.slice(t + 1, close);
11808
- if (close > t + 1 && body.every((b) => b.type === "text")) {
11812
+ const close = closeOfTextBody(t, name);
11813
+ if (close > t + 1) {
11809
11814
  const text = src.slice(token.end, tokens[close].start);
11810
11815
  const written = text.trim();
11811
11816
  yield {
@@ -12389,6 +12394,12 @@ function registerWidgetDefinitions(nodes, passageName) {
12389
12394
  */
12390
12395
  var FrozenStateContext = createContext(null);
12391
12396
  /**
12397
+ * Whether a loop has yet to reconcile its rows with newer namespaces.
12398
+ * Queued row effects wait for that reconciliation. This differs from a
12399
+ * detached click body's permanent freeze: its initial effects still run.
12400
+ */
12401
+ var PendingIterationContext = createContext(null);
12402
+ /**
12392
12403
  * Tells a timer ({repeat}, {timed}) whether the passage it belongs to has
12393
12404
  * been left: it must not run a new body then, for that would write into the
12394
12405
  * destination's state until the outgoing tree unmounts (#410). Null outside
@@ -19221,14 +19232,24 @@ function applyReplacement(n) {
19221
19232
  * stop (#401).
19222
19233
  */
19223
19234
  var subscribeStateReplacement = replacementListeners.subscribe;
19224
- var runtimeUnsubs = [];
19235
+ var runtimeUnsubs = /* @__PURE__ */ new Set();
19225
19236
  var inRuntimePhase = false;
19226
19237
  /**
19227
19238
  * Track an unsubscribe function for automatic cleanup on restart.
19228
- * No-op if called during the startup phase (before enterRuntimePhase).
19239
+ * Return its manual cleanup, which also releases the tracked entry.
19240
+ * Startup subscriptions (before enterRuntimePhase) survive restart.
19229
19241
  */
19230
19242
  function trackRuntimeUnsub(unsub) {
19231
- if (inRuntimePhase) runtimeUnsubs.push(unsub);
19243
+ if (!inRuntimePhase) return unsub;
19244
+ let cleanup = unsub;
19245
+ const tracked = () => {
19246
+ const call = cleanup;
19247
+ cleanup = void 0;
19248
+ runtimeUnsubs.delete(tracked);
19249
+ call?.();
19250
+ };
19251
+ runtimeUnsubs.add(tracked);
19252
+ return tracked;
19232
19253
  }
19233
19254
  /** Mark the start of the runtime phase. Called before executeStoryInit(). */
19234
19255
  function enterRuntimePhase() {
@@ -19237,7 +19258,7 @@ function enterRuntimePhase() {
19237
19258
  /** Call all tracked unsubs and reset the runtime phase. */
19238
19259
  function cleanupRuntimeHandlers() {
19239
19260
  for (const unsub of runtimeUnsubs) unsub();
19240
- runtimeUnsubs = [];
19261
+ runtimeUnsubs.clear();
19241
19262
  inRuntimePhase = false;
19242
19263
  }
19243
19264
  /** A hotkey is a `KeyboardEvent.key` value; anything else disables it. */
@@ -19590,7 +19611,8 @@ var useStoryStore = create()(storyStore((set, get) => ({
19590
19611
  return;
19591
19612
  }
19592
19613
  const previousPassage = get().currentPassage;
19593
- if (replacesState(() => emit("beforenavigate", passageName))) return;
19614
+ const navigation = get().navigationId;
19615
+ if (replacesState(() => emit("beforenavigate", passageName)) || get().navigationId !== navigation) return;
19594
19616
  const patchEntry = computeVarPatches(lastNavigationVars, get().variables);
19595
19617
  set((state) => {
19596
19618
  state.temporary = createNamespace();
@@ -21591,9 +21613,7 @@ function createStoryAPI() {
21591
21613
  },
21592
21614
  on(event, callback) {
21593
21615
  if (event === "variableChanged") ensureVariableChangedSubscription();
21594
- const unsub = on(event, callback);
21595
- trackRuntimeUnsub(unsub);
21596
- return unsub;
21616
+ return trackRuntimeUnsub(on(event, callback));
21597
21617
  },
21598
21618
  async waitForActions() {
21599
21619
  await settleRunningActions();
@@ -23515,6 +23535,7 @@ defineMacro({
23515
23535
  const isTemp = target.startsWith("_");
23516
23536
  const name = target.slice(1);
23517
23537
  const localsUpdate = isLocal ? ctx.update : null;
23538
+ const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
23518
23539
  const prevOutput = ctx.hooks.useRef(UNSET);
23519
23540
  const lastNavigation = ctx.hooks.useRef(-1);
23520
23541
  const compute = () => computeAndApply(expr, name, isTemp, isLocal, ctx.getValues, rawArgs, prevOutput, lastNavigation, localsUpdate);
@@ -23523,7 +23544,9 @@ defineMacro({
23523
23544
  ran.current = true;
23524
23545
  compute();
23525
23546
  }
23526
- ctx.hooks.useLayoutEffect(compute, [ctx.merged]);
23547
+ ctx.hooks.useLayoutEffect(() => {
23548
+ if (!pendingIteration?.(useStoryStore.getState())) compute();
23549
+ }, [ctx.merged, pendingIteration]);
23527
23550
  return null;
23528
23551
  }
23529
23552
  });
@@ -23705,6 +23728,17 @@ defineMacro({
23705
23728
  }
23706
23729
  ],
23707
23730
  render({ rawArgs, children = [] }, ctx) {
23731
+ const enclosingFreeze = useContext(FrozenStateContext);
23732
+ const enclosingPending = useContext(PendingIterationContext);
23733
+ const [variables, temporary, , transient] = ctx.merged;
23734
+ const pending = useMemo(() => (state) => !!enclosingPending?.(state) || (state.variables !== variables || state.temporary !== temporary || state.transient !== transient) && !enclosingFreeze?.(state), [
23735
+ enclosingPending,
23736
+ enclosingFreeze,
23737
+ variables,
23738
+ temporary,
23739
+ transient
23740
+ ]);
23741
+ const freeze = useMemo(() => (state) => !!enclosingFreeze?.(state) || pending(state), [enclosingFreeze, pending]);
23708
23742
  const keys = ctx.hooks.useRef({
23709
23743
  contents: [],
23710
23744
  generations: [],
@@ -23744,9 +23778,15 @@ defineMacro({
23744
23778
  indexValue: i,
23745
23779
  children
23746
23780
  }, `${i}-${generations[i]}`));
23747
- return ctx.wrap(/* @__PURE__ */ jsx(ItemEditContext.Provider, {
23748
- value: true,
23749
- children: content
23781
+ return ctx.wrap(/* @__PURE__ */ jsx(FrozenStateContext.Provider, {
23782
+ value: freeze,
23783
+ children: /* @__PURE__ */ jsx(PendingIterationContext.Provider, {
23784
+ value: pending,
23785
+ children: /* @__PURE__ */ jsx(ItemEditContext.Provider, {
23786
+ value: true,
23787
+ children: content
23788
+ })
23789
+ })
23750
23790
  }));
23751
23791
  },
23752
23792
  text({ rawArgs, children = [] }, ctx) {
@@ -11073,8 +11073,14 @@ function stringHolds(param) {
11073
11073
  * `parametersOf` gives the declared parameters of a macro, if it has any.
11074
11074
  */
11075
11075
  function* codeAndText(src, tokens, parametersOf) {
11076
- /** The index of the closing tag of the `name` macro opened at `t`. */
11077
- const closeOf = (t, name) => tokens.findIndex((c, k) => k > t && c.type === "macro" && c.isClose && c.name.toLowerCase() === name);
11076
+ const closeOfTextBody = (t, name) => {
11077
+ for (let k = t + 1; k < tokens.length; k++) {
11078
+ const c = tokens[k];
11079
+ if (c.type === "text") continue;
11080
+ return c.type === "macro" && c.isClose && c.name.toLowerCase() === name ? k : -1;
11081
+ }
11082
+ return -1;
11083
+ };
11078
11084
  for (let t = 0; t < tokens.length; t++) {
11079
11085
  const token = tokens[t];
11080
11086
  if (token.type === "link") {
@@ -11110,7 +11116,7 @@ function* codeAndText(src, tokens, parametersOf) {
11110
11116
  else if (token.type === "macro" && !token.isClose) {
11111
11117
  const name = token.name.toLowerCase();
11112
11118
  if (name === "do") {
11113
- const close = closeOf(t, name);
11119
+ const close = closeOfTextBody(t, name);
11114
11120
  if (close < 0) continue;
11115
11121
  yield {
11116
11122
  kind: "code",
@@ -11124,9 +11130,8 @@ function* codeAndText(src, tokens, parametersOf) {
11124
11130
  }
11125
11131
  const args = token.rawArgs;
11126
11132
  if (PASSAGE_BODIES.has(name)) {
11127
- const close = closeOf(t, name);
11128
- const body = tokens.slice(t + 1, close);
11129
- if (close > t + 1 && body.every((b) => b.type === "text")) {
11133
+ const close = closeOfTextBody(t, name);
11134
+ if (close > t + 1) {
11130
11135
  const text = src.slice(token.end, tokens[close].start);
11131
11136
  const written = text.trim();
11132
11137
  yield {
@@ -24599,21 +24604,23 @@ function sameSpindleTokens(before, after) {
24599
24604
  return expected.length === found.length && expected.every((t, i) => t === found[i]);
24600
24605
  }
24601
24606
  /**
24602
- * Put each of `tokens` back in place of its placeholders (those that
24603
- * `placeholdersOf` gives for its index): the first of each.
24607
+ * Restore the first occurrence of each marker in the unchanged document.
24608
+ * Never search inserted source: literals may spell any other marker.
24604
24609
  */
24605
- function restorePlaceholders(text, tokens, placeholdersOf) {
24606
- let result = text;
24607
- tokens.forEach((token, index) => {
24608
- for (const placeholder of placeholdersOf(index)) result = result.replace(placeholder, () => token);
24610
+ function restorePlaceholders(text, groups) {
24611
+ const replacements = /* @__PURE__ */ new Map();
24612
+ for (const [tokens, placeholdersOf] of groups) tokens.forEach((token, index) => {
24613
+ for (const marker of placeholdersOf(index)) replacements.set(marker, token);
24614
+ });
24615
+ return text.replace(/<!--(?:SP|SVG):\d+-->|__SP\d+__/g, (marker) => {
24616
+ const token = replacements.get(marker);
24617
+ replacements.delete(marker);
24618
+ return token ?? marker;
24609
24619
  });
24610
- return result;
24611
24620
  }
24612
- /**
24613
- * Restore SVG blocks from placeholders.
24614
- */
24615
- function restoreSvgBlocks(text, tokens) {
24616
- return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
24621
+ /** Restore both families together, so neither can consume the other's source. */
24622
+ function restoreHtmlTokens(text, spindle, svg) {
24623
+ return restorePlaceholders(text, [[spindle, SPINDLE_PLACEHOLDERS], [svg, SVG_PLACEHOLDERS]]);
24617
24624
  }
24618
24625
  /**
24619
24626
  * Replace Spindle tokens with placeholders.
@@ -24691,12 +24698,6 @@ function replaceSpindleTokens(html) {
24691
24698
  tokens
24692
24699
  };
24693
24700
  }
24694
- /**
24695
- * Restore original Spindle tokens from placeholders.
24696
- */
24697
- function restoreSpindleTokens(text, tokens) {
24698
- return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
24699
- }
24700
24701
  //#endregion
24701
24702
  //#region src/format/format-passage.ts
24702
24703
  /** Default dedenting sub-macros. */
@@ -24858,13 +24859,17 @@ async function formatLf(text, options) {
24858
24859
  continue;
24859
24860
  }
24860
24861
  const { text: svgPlaceholdered, tokens: svgTokens } = replaceSvgBlocks(htmlText);
24862
+ if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
24863
+ lines.push(...region.lines);
24864
+ continue;
24865
+ }
24861
24866
  const { text: placeholdered, tokens } = replaceSpindleTokens(svgPlaceholdered);
24862
24867
  const formatted = await formatHTML(placeholdered, prettier, prettierOptions);
24863
24868
  if (formatted === void 0 || !placeholdersIntact(formatted, tokens, SPINDLE_PLACEHOLDERS) || !placeholdersIntact(formatted, svgTokens, SVG_PLACEHOLDERS)) {
24864
24869
  lines.push(...region.lines);
24865
24870
  continue;
24866
24871
  }
24867
- const restored = restoreSvgBlocks(restoreSpindleTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel))), svgTokens);
24872
+ const restored = restoreHtmlTokens(formatted.trim(), tokens.map((t) => replaceAll(t, "\n", sentinel)), svgTokens);
24868
24873
  for (const fLine of restored.split("\n")) lines.push(fLine);
24869
24874
  continue;
24870
24875
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.61.5",
3
+ "version": "0.61.6",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
package/src/code-check.ts CHANGED
@@ -334,15 +334,19 @@ export function* codeAndText(
334
334
  tokens: readonly Token[],
335
335
  parametersOf: ParametersOf,
336
336
  ): Generator<Piece> {
337
- /** The index of the closing tag of the `name` macro opened at `t`. */
338
- const closeOf = (t: number, name: string) =>
339
- tokens.findIndex(
340
- (c, k) =>
341
- k > t &&
342
- c.type === 'macro' &&
343
- c.isClose &&
344
- c.name.toLowerCase() === name,
345
- );
337
+ // Only a plain-text body is read here: raw JavaScript in {do}, or a
338
+ // passage name in {dialog}. Start at the opener and stop at any markup,
339
+ // including a nested opener, rather than rescanning the token prefix.
340
+ const closeOfTextBody = (t: number, name: string): number => {
341
+ for (let k = t + 1; k < tokens.length; k++) {
342
+ const c = tokens[k]!;
343
+ if (c.type === 'text') continue;
344
+ return c.type === 'macro' && c.isClose && c.name.toLowerCase() === name
345
+ ? k
346
+ : -1;
347
+ }
348
+ return -1;
349
+ };
346
350
  for (let t = 0; t < tokens.length; t++) {
347
351
  const token = tokens[t]!;
348
352
  if (token.type === 'link') {
@@ -393,7 +397,7 @@ export function* codeAndText(
393
397
  } else if (token.type === 'macro' && !token.isClose) {
394
398
  const name = token.name.toLowerCase();
395
399
  if (name === 'do') {
396
- const close = closeOf(t, name);
400
+ const close = closeOfTextBody(t, name);
397
401
  if (close < 0) continue;
398
402
  const body = src.slice(token.end, tokens[close]!.start);
399
403
  yield {
@@ -409,9 +413,8 @@ export function* codeAndText(
409
413
  const args = token.rawArgs;
410
414
  if (PASSAGE_BODIES.has(name)) {
411
415
  // The body names the passage when it is only text
412
- const close = closeOf(t, name);
413
- const body = tokens.slice(t + 1, close);
414
- if (close > t + 1 && body.every((b) => b.type === 'text')) {
416
+ const close = closeOfTextBody(t, name);
417
+ if (close > t + 1) {
415
418
  const text = src.slice(token.end, tokens[close]!.start);
416
419
  const written = text.trim();
417
420
  yield {
@@ -6,6 +6,7 @@ import { defineMacro } from '../../define-macro';
6
6
  import { MacroError, logMacroError } from './MacroError';
7
7
  import { currentSourceLocation } from '../../utils/source-location';
8
8
  import { checkVariableName, ownValue } from '../../utils/namespace';
9
+ import { PendingIterationContext } from '../../hooks/use-story-fields';
9
10
 
10
11
  /**
11
12
  * The previous output before the first successful evaluation. Distinct from
@@ -126,6 +127,7 @@ defineMacro({
126
127
  const isTemp = target.startsWith('_');
127
128
  const name = target.slice(1);
128
129
  const localsUpdate = isLocal ? ctx.update : null;
130
+ const pendingIteration = ctx.hooks.useContext(PendingIterationContext);
129
131
 
130
132
  const prevOutput = ctx.hooks.useRef<unknown>(UNSET);
131
133
  // The navigation the target was last checked in
@@ -153,7 +155,11 @@ defineMacro({
153
155
  // The merged values only decide when to recompute; computeAndApply reads
154
156
  // the current ones. The tuple is renewed with them and with the render
155
157
  // counts, which rendered() / hasRendered() read.
156
- ctx.hooks.useLayoutEffect(compute, [ctx.merged]);
158
+ ctx.hooks.useLayoutEffect(() => {
159
+ // A queued effect can outlive the loop state its locals belong to.
160
+ // Let the owner reconcile first, dropping any removed iterations.
161
+ if (!pendingIteration?.(useStoryStore.getState())) compute();
162
+ }, [ctx.merged, pendingIteration]);
157
163
 
158
164
  return null;
159
165
  },
@@ -1,4 +1,4 @@
1
- import { useMemo } from 'preact/hooks';
1
+ import { useContext, useMemo } from 'preact/hooks';
2
2
  import { defineMacro } from '../../define-macro';
3
3
  import { MacroError } from './MacroError';
4
4
  import { stableKey } from '../../utils/stable-key';
@@ -11,6 +11,11 @@ import type { ASTNode } from '../../markup/ast';
11
11
  import { checkVariableName } from '../../utils/namespace';
12
12
  import { readState } from '../../execute-mutation';
13
13
  import { LocalsScope } from './locals-scope';
14
+ import {
15
+ FrozenStateContext,
16
+ PendingIterationContext,
17
+ } from '../../hooks/use-story-fields';
18
+ import type { StoryState } from '../../store';
14
19
 
15
20
  /**
16
21
  * Check the arguments of "@item, @i of $list" or "@item of $list".
@@ -97,6 +102,26 @@ defineMacro({
97
102
  { name: 'list', type: 'expression', required: true },
98
103
  ],
99
104
  render({ rawArgs, children = [] }, ctx) {
105
+ const enclosingFreeze = useContext(FrozenStateContext);
106
+ const enclosingPending = useContext(PendingIterationContext);
107
+ const [variables, temporary, , transient] = ctx.merged!;
108
+ // Until this loop reconciles its rows, descendants still have the old
109
+ // @item/@i. Keep them from independently reacting to newer namespaces.
110
+ const pending = useMemo(
111
+ () => (state: StoryState) =>
112
+ !!enclosingPending?.(state) ||
113
+ // A detached owner keeps its snapshot permanently: there is no
114
+ // pending reconciliation for its initial effects to wait for.
115
+ ((state.variables !== variables ||
116
+ state.temporary !== temporary ||
117
+ state.transient !== transient) &&
118
+ !enclosingFreeze?.(state)),
119
+ [enclosingPending, enclosingFreeze, variables, temporary, transient],
120
+ );
121
+ const freeze = useMemo(
122
+ () => (state: StoryState) => !!enclosingFreeze?.(state) || pending(state),
123
+ [enclosingFreeze, pending],
124
+ );
100
125
  const keys = ctx.hooks.useRef<IterationKeys>({
101
126
  contents: [],
102
127
  generations: [],
@@ -158,9 +183,13 @@ defineMacro({
158
183
  ));
159
184
 
160
185
  return ctx.wrap(
161
- <ItemEditContext.Provider value={true}>
162
- {content}
163
- </ItemEditContext.Provider>,
186
+ <FrozenStateContext.Provider value={freeze}>
187
+ <PendingIterationContext.Provider value={pending}>
188
+ <ItemEditContext.Provider value={true}>
189
+ {content}
190
+ </ItemEditContext.Provider>
191
+ </PendingIterationContext.Provider>
192
+ </FrozenStateContext.Provider>,
164
193
  );
165
194
  },
166
195
  text({ rawArgs, children = [] }, ctx) {
@@ -14,9 +14,8 @@ import {
14
14
  import {
15
15
  multilineJsLiterals,
16
16
  replaceSpindleTokens,
17
- restoreSpindleTokens,
17
+ restoreHtmlTokens,
18
18
  replaceSvgBlocks,
19
- restoreSvgBlocks,
20
19
  placeholdersIntact,
21
20
  sameSpindleTokens,
22
21
  SPINDLE_PLACEHOLDERS,
@@ -299,6 +298,12 @@ async function formatLf(
299
298
  // HTML block — placeholder substitution + Prettier
300
299
  const { text: svgPlaceholdered, tokens: svgTokens } =
301
300
  replaceSvgBlocks(htmlText);
301
+ // A later whole-line Spindle token may hide an SVG marker. Check
302
+ // before that pass so a literal marker cannot stand in for it.
303
+ if (!placeholdersIntact(svgPlaceholdered, svgTokens, SVG_PLACEHOLDERS)) {
304
+ lines.push(...region.lines);
305
+ continue;
306
+ }
302
307
  const { text: placeholdered, tokens } =
303
308
  replaceSpindleTokens(svgPlaceholdered);
304
309
  const formatted = await formatHTMLPrettier(
@@ -318,11 +323,11 @@ async function formatLf(
318
323
  continue;
319
324
  }
320
325
  // A token's line breaks are its payload: keep them out of the line steps below
321
- const restoredSpindle = restoreSpindleTokens(
326
+ const restored = restoreHtmlTokens(
322
327
  formatted.trim(),
323
328
  tokens.map((t) => replaceAll(t, '\n', sentinel)),
329
+ svgTokens,
324
330
  );
325
- const restored = restoreSvgBlocks(restoredSpindle, svgTokens);
326
331
  for (const fLine of restored.split('\n')) {
327
332
  lines.push(fLine);
328
333
  }
@@ -198,29 +198,45 @@ export function sameSpindleTokens(before: string, after: string): boolean {
198
198
  }
199
199
 
200
200
  /**
201
- * Put each of `tokens` back in place of its placeholders (those that
202
- * `placeholdersOf` gives for its index): the first of each.
201
+ * Restore the first occurrence of each marker in the unchanged document.
202
+ * Never search inserted source: literals may spell any other marker.
203
203
  */
204
204
  function restorePlaceholders(
205
205
  text: string,
206
- tokens: string[],
207
- placeholdersOf: PlaceholdersOf,
206
+ groups: readonly (readonly [readonly string[], PlaceholdersOf])[],
208
207
  ): string {
209
- let result = text;
210
- tokens.forEach((token, index) => {
211
- for (const placeholder of placeholdersOf(index)) {
212
- // Callback form: a replacement string would expand `$&`, `$'`, etc.
213
- result = result.replace(placeholder, () => token);
214
- }
208
+ const replacements = new Map<string, string>();
209
+ for (const [tokens, placeholdersOf] of groups) {
210
+ tokens.forEach((token, index) => {
211
+ for (const marker of placeholdersOf(index))
212
+ replacements.set(marker, token);
213
+ });
214
+ }
215
+ return text.replace(/<!--(?:SP|SVG):\d+-->|__SP\d+__/g, (marker) => {
216
+ const token = replacements.get(marker);
217
+ replacements.delete(marker);
218
+ // Callback form also preserves literal `$&`, `$'`, etc.
219
+ return token ?? marker;
215
220
  });
216
- return result;
221
+ }
222
+
223
+ /** Restore both families together, so neither can consume the other's source. */
224
+ export function restoreHtmlTokens(
225
+ text: string,
226
+ spindle: string[],
227
+ svg: string[],
228
+ ): string {
229
+ return restorePlaceholders(text, [
230
+ [spindle, SPINDLE_PLACEHOLDERS],
231
+ [svg, SVG_PLACEHOLDERS],
232
+ ]);
217
233
  }
218
234
 
219
235
  /**
220
236
  * Restore SVG blocks from placeholders.
221
237
  */
222
238
  export function restoreSvgBlocks(text: string, tokens: string[]): string {
223
- return restorePlaceholders(text, tokens, SVG_PLACEHOLDERS);
239
+ return restorePlaceholders(text, [[tokens, SVG_PLACEHOLDERS]]);
224
240
  }
225
241
 
226
242
  /**
@@ -312,5 +328,5 @@ export function replaceSpindleTokens(html: string): PlaceholderResult {
312
328
  * Restore original Spindle tokens from placeholders.
313
329
  */
314
330
  export function restoreSpindleTokens(text: string, tokens: string[]): string {
315
- return restorePlaceholders(text, tokens, SPINDLE_PLACEHOLDERS);
331
+ return restorePlaceholders(text, [[tokens, SPINDLE_PLACEHOLDERS]]);
316
332
  }
@@ -15,6 +15,15 @@ export const FrozenStateContext = createContext<
15
15
  ((state: StoryState) => boolean) | null
16
16
  >(null);
17
17
 
18
+ /**
19
+ * Whether a loop has yet to reconcile its rows with newer namespaces.
20
+ * Queued row effects wait for that reconciliation. This differs from a
21
+ * detached click body's permanent freeze: its initial effects still run.
22
+ */
23
+ export const PendingIterationContext = createContext<
24
+ ((state: StoryState) => boolean) | null
25
+ >(null);
26
+
18
27
  /**
19
28
  * Tells a timer ({repeat}, {timed}) whether the passage it belongs to has
20
29
  * been left: it must not run a new body then, for that would write into the
package/src/store.ts CHANGED
@@ -765,17 +765,25 @@ export const subscribeStateReplacement = replacementListeners.subscribe;
765
765
  // Runtime handler cleanup (auto-unsub on restart)
766
766
  // ---------------------------------------------------------------------------
767
767
 
768
- let runtimeUnsubs: Array<() => void> = [];
768
+ let runtimeUnsubs = new Set<() => void>();
769
769
  let inRuntimePhase = false;
770
770
 
771
771
  /**
772
772
  * Track an unsubscribe function for automatic cleanup on restart.
773
- * No-op if called during the startup phase (before enterRuntimePhase).
773
+ * Return its manual cleanup, which also releases the tracked entry.
774
+ * Startup subscriptions (before enterRuntimePhase) survive restart.
774
775
  */
775
- export function trackRuntimeUnsub(unsub: () => void): void {
776
- if (inRuntimePhase) {
777
- runtimeUnsubs.push(unsub);
778
- }
776
+ export function trackRuntimeUnsub(unsub: () => void): () => void {
777
+ if (!inRuntimePhase) return unsub;
778
+ let cleanup: (() => void) | undefined = unsub;
779
+ const tracked = () => {
780
+ const call = cleanup;
781
+ cleanup = undefined;
782
+ runtimeUnsubs.delete(tracked);
783
+ call?.();
784
+ };
785
+ runtimeUnsubs.add(tracked);
786
+ return tracked;
779
787
  }
780
788
 
781
789
  /** Mark the start of the runtime phase. Called before executeStoryInit(). */
@@ -786,13 +794,13 @@ export function enterRuntimePhase(): void {
786
794
  /** Call all tracked unsubs and reset the runtime phase. */
787
795
  function cleanupRuntimeHandlers(): void {
788
796
  for (const unsub of runtimeUnsubs) unsub();
789
- runtimeUnsubs = [];
797
+ runtimeUnsubs.clear();
790
798
  inRuntimePhase = false;
791
799
  }
792
800
 
793
801
  /** Test-only: reset runtime phase state between tests. */
794
802
  export function _resetRuntimePhase(): void {
795
- runtimeUnsubs = [];
803
+ runtimeUnsubs = new Set();
796
804
  inRuntimePhase = false;
797
805
  }
798
806
 
@@ -1417,9 +1425,14 @@ export const useStoryStore = create<StoryState>()(
1417
1425
  }
1418
1426
 
1419
1427
  const previousPassage = get().currentPassage;
1420
- // A callback that restarted or loaded replaced the game this
1421
- // navigation was requested in: it does not carry on into the new one
1422
- if (replacesState(() => emit('beforenavigate', passageName))) return;
1428
+ // A callback may replace the game or move elsewhere. Like a history
1429
+ // traversal, this navigation must then give way to the callback's.
1430
+ const navigation = get().navigationId;
1431
+ if (
1432
+ replacesState(() => emit('beforenavigate', passageName)) ||
1433
+ get().navigationId !== navigation
1434
+ )
1435
+ return;
1423
1436
 
1424
1437
  // Compute variable delta before Immer set(). Read the variables after
1425
1438
  // beforenavigate so changes made by its handlers are recorded.
package/src/story-api.ts CHANGED
@@ -447,8 +447,7 @@ function createStoryAPI(): StoryAPI {
447
447
  ensureVariableChangedSubscription();
448
448
  }
449
449
  const unsub = emitterOn(event, callback);
450
- trackRuntimeUnsub(unsub);
451
- return unsub;
450
+ return trackRuntimeUnsub(unsub);
452
451
  },
453
452
 
454
453
  async waitForActions(): Promise<StoryAction[]> {