@rohal12/spindle 0.62.4 → 0.62.5

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.
@@ -4328,6 +4328,7 @@ function branchParents(name, macros) {
4328
4328
  function getMacroParameters(name) {
4329
4329
  return metadataRegistry.get(name)?.parameters;
4330
4330
  }
4331
+ getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
4331
4332
  function getMacroRegistry() {
4332
4333
  return Array.from(metadataRegistry.values());
4333
4334
  }
@@ -4446,6 +4447,8 @@ function pairMarkup(tokens, options = {}) {
4446
4447
  };
4447
4448
  const root = [];
4448
4449
  const stack = [];
4450
+ const openPositions = /* @__PURE__ */ new Map();
4451
+ const tagKey = (tag) => `${tag.type}:${lowerName(tag)}`;
4449
4452
  const add = (node) => (last$1(stack)?.into ?? root).push(node);
4450
4453
  /**
4451
4454
  * End the element on top of the stack, with `close` if it has one: its
@@ -4454,6 +4457,10 @@ function pairMarkup(tokens, options = {}) {
4454
4457
  const end = (ending, close, owns = ending === "closed") => {
4455
4458
  const { node, body } = stack.pop();
4456
4459
  const open = node.token;
4460
+ const key = tagKey(open);
4461
+ const positions = openPositions.get(key);
4462
+ positions.pop();
4463
+ if (positions.length === 0) openPositions.delete(key);
4457
4464
  const noticedAt = close ? close.end : noticedAtEnd;
4458
4465
  for (const { tag } of body.branches) if (open.type !== "macro" || !parentsOf(tag.name).includes(lowerName(open))) misplaced(tag, open, noticedAt);
4459
4466
  if (ending === "unclosed") report("unclosed-block", open, `Unclosed ${tagLabel(open)}: no ${closerOf(open)} closes it`, noticedAt, { name: nameOf(open) });
@@ -4472,8 +4479,7 @@ function pairMarkup(tokens, options = {}) {
4472
4479
  if (!top) report("stray-closer", token, `${tagLabel(token)} closes nothing: no ${token.type === "html" ? `<${token.tag}>` : `{${token.name}}`} is open here`, token.start, { name: nameOf(token) });
4473
4480
  else if (closes(top.node.token, token)) end("closed", token);
4474
4481
  else {
4475
- let outer = stack.length - 1;
4476
- while (outer >= 0 && !closes(stack[outer].node.token, token)) outer--;
4482
+ const outer = last$1(openPositions.get(tagKey(token)) ?? []) ?? -1;
4477
4483
  end("mismatch", token, outer === -1);
4478
4484
  if (outer !== -1) {
4479
4485
  while (stack.length > outer + 1) end("cut", token);
@@ -4517,6 +4523,10 @@ function pairMarkup(tokens, options = {}) {
4517
4523
  branches: []
4518
4524
  };
4519
4525
  node.body = body;
4526
+ const key = tagKey(token);
4527
+ const positions = openPositions.get(key) ?? [];
4528
+ positions.push(stack.length);
4529
+ openPositions.set(key, positions);
4520
4530
  stack.push({
4521
4531
  node,
4522
4532
  body,
@@ -10747,6 +10757,40 @@ function jsCodeEnd(onOpenEnd) {
10747
10757
  }
10748
10758
  /** The JavaScript reader Spindle uses today: js-lexer, then a lenient scan. */
10749
10759
  var defaultCodeEnd = jsCodeEnd();
10760
+ /**
10761
+ * Index possible brace ends for repeated recovery attempts in one template.
10762
+ * Within plain code, nested braces must close first. At a quote, slash or
10763
+ * escape we stop making lexical assumptions, but the remaining raw `}`s
10764
+ * still bound how many pending braces could close. Indexing visits each
10765
+ * opener once, so unmatched plain-code openers can skip suffix scans.
10766
+ */
10767
+ function indexCodeEnds(input) {
10768
+ const possible = /* @__PURE__ */ new Set();
10769
+ const pending = [];
10770
+ let remaining = 0;
10771
+ let lastBrace = -1;
10772
+ for (let i = 0; i < input.length; i++) if (input[i] === "}") {
10773
+ remaining++;
10774
+ lastBrace = i;
10775
+ }
10776
+ const uncertain = () => {
10777
+ for (let i = Math.max(0, pending.length - remaining); i < pending.length; i++) possible.add(pending[i]);
10778
+ pending.length = 0;
10779
+ };
10780
+ for (let i = 0; i < input.length; i++) {
10781
+ const c = input[i];
10782
+ if (c === "{") pending.push(i);
10783
+ else if (c === "}") {
10784
+ remaining--;
10785
+ const open = pending.pop();
10786
+ if (open !== void 0) possible.add(open);
10787
+ } else if (/['"`/\\]/.test(c)) uncertain();
10788
+ }
10789
+ return (start) => {
10790
+ if (start > lastBrace) return -1;
10791
+ return possible.has(start - 1) ? defaultCodeEnd.closeBrace(input, start, start) : parsedCodeEnd(input, start, "expression");
10792
+ };
10793
+ }
10750
10794
  //#endregion
10751
10795
  //#region src/markup/code-attributes.ts
10752
10796
  /**
@@ -10772,6 +10816,7 @@ function splitSigilTemplate(template, incomplete = false) {
10772
10816
  const parts = [];
10773
10817
  let text = "";
10774
10818
  let i = 0;
10819
+ const closeBrace = indexCodeEnds(template);
10775
10820
  while (i < template.length) {
10776
10821
  const brace = template.indexOf("{", i);
10777
10822
  if (brace === -1) {
@@ -10780,7 +10825,7 @@ function splitSigilTemplate(template, incomplete = false) {
10780
10825
  }
10781
10826
  text += template.slice(i, brace);
10782
10827
  i = brace + 1;
10783
- let end = isSigil(template[i]) ? defaultCodeEnd.closeBrace(template, i, i) : -1;
10828
+ let end = isSigil(template[i]) ? closeBrace(i) : -1;
10784
10829
  if (end === -1 && incomplete && isSigil(template[i])) end = template.length;
10785
10830
  if (end === -1) {
10786
10831
  text += "{";
@@ -11822,6 +11867,10 @@ function widgetParameters(params, holds = {}) {
11822
11867
  ...hasOwn(holds, name) ? { holds: holds[name] } : {}
11823
11868
  }));
11824
11869
  }
11870
+ /** A raw body is executable only while the builtin implementation owns it. */
11871
+ function executesRawBody(name, parametersOf) {
11872
+ return isRawMacro(name, parametersOf.widget?.(name) !== void 0) && parametersOf.source?.(name) !== "user";
11873
+ }
11825
11874
  /**
11826
11875
  * `params` with each `string` and `text` parameter (options too) saying
11827
11876
  * what it holds: what it declares, else `holds`.
@@ -11849,7 +11898,9 @@ function withHolds(params, holds) {
11849
11898
  function parameterLookup(macros) {
11850
11899
  const parameters = new NameMap();
11851
11900
  const widgets = new NameMap();
11852
- for (const { name, parameters: params, interpolate, widget } of macros) {
11901
+ const sources = new NameMap();
11902
+ for (const { name, parameters: params, interpolate, widget, source } of macros) {
11903
+ sources.set(name, source ?? "user");
11853
11904
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11854
11905
  if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11855
11906
  }
@@ -11863,6 +11914,7 @@ function parameterLookup(macros) {
11863
11914
  return params;
11864
11915
  };
11865
11916
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
11917
+ lookup.source = (name) => sources.get(name);
11866
11918
  return lookup;
11867
11919
  }
11868
11920
  /** What a `string` or `text` argument holds when its parameter doesn't say. */
@@ -11928,7 +11980,7 @@ function* codeAndText(src, tokens, parametersOf) {
11928
11980
  else if (token.type === "macro" && !token.isClose) {
11929
11981
  const name = token.name.toLowerCase();
11930
11982
  const widget = parametersOf.widget?.(name);
11931
- if (name === "do" && !widget) {
11983
+ if (executesRawBody(name, parametersOf)) {
11932
11984
  const close = closeOfTextBody(t, name);
11933
11985
  if (close < 0) continue;
11934
11986
  yield {
@@ -12289,6 +12341,7 @@ function locate(text, part, from) {
12289
12341
  //#region src/widgets/ast-scanner.ts
12290
12342
  /** The declared parameters of the macros registered so far. */
12291
12343
  var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
12344
+ registeredParameters.source = getMacroParameters.source;
12292
12345
  /**
12293
12346
  * Whether the text of an attribute value or macro label renders a
12294
12347
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -13144,7 +13197,6 @@ var TextEvaluator = class {
13144
13197
  }, depth + 1);
13145
13198
  }
13146
13199
  macro(node, scope, depth) {
13147
- if (isSubMacro(node.name)) return "";
13148
13200
  const widget = getWidget(node.name);
13149
13201
  if (widget) {
13150
13202
  let locals = scope.locals;
@@ -13167,6 +13219,7 @@ var TextEvaluator = class {
13167
13219
  widgetChildren: widgetChildrenOf(node.children, scope.widgetChildren)
13168
13220
  });
13169
13221
  }
13222
+ if (isSubMacro(node.name)) return "";
13170
13223
  const text = getMacroText(node.name);
13171
13224
  if (!text) {
13172
13225
  const message = getMacro(node.name) ? `{${node.name}} has no text form, so it can't be used in an attribute value or label` : `unknown macro {${node.name}}`;
@@ -14377,7 +14430,6 @@ function nodeKey(node) {
14377
14430
  return key;
14378
14431
  }
14379
14432
  function renderMacro(node, key) {
14380
- if (isSubMacro(node.name)) return null;
14381
14433
  const invocation = {
14382
14434
  rawArgs: node.rawArgs,
14383
14435
  className: node.className,
@@ -14390,6 +14442,7 @@ function renderMacro(node, key) {
14390
14442
  params: widget.params,
14391
14443
  invocationChildren: node.children
14392
14444
  }, key);
14445
+ if (isSubMacro(node.name)) return null;
14393
14446
  const Component = getMacro(node.name);
14394
14447
  if (Component) return /* @__PURE__ */ jsx(Component, {
14395
14448
  ...invocation,
@@ -18334,8 +18387,14 @@ function establishPlaythrough(ifid) {
18334
18387
  function saveWithHooks(slot, custom, beginCapture, write) {
18335
18388
  try {
18336
18389
  const capture = beginCapture();
18337
- withoutDraws(() => emit("beforesave", slot, custom));
18338
- return write(capture()).then((result) => {
18390
+ let payload;
18391
+ try {
18392
+ withoutDraws(() => emit("beforesave", slot, custom));
18393
+ payload = capture();
18394
+ } finally {
18395
+ capture.dispose();
18396
+ }
18397
+ return write(payload).then((result) => {
18339
18398
  withoutDraws(() => emit("aftersave", slot));
18340
18399
  return result;
18341
18400
  });
@@ -19255,6 +19314,7 @@ function freshTransients(defaults) {
19255
19314
  function enterStart(state, passage, variables, transientDefaults) {
19256
19315
  state.currentPassage = passage;
19257
19316
  state.navigationId++;
19317
+ state.replacementNavigationId = state.navigationId;
19258
19318
  state.variables = variables;
19259
19319
  state.transient = freshTransients(transientDefaults);
19260
19320
  state.temporary = createNamespace();
@@ -19527,10 +19587,10 @@ function loadedEntryMoment(payload) {
19527
19587
  return moment;
19528
19588
  }
19529
19589
  /** The variable paths `Story.set` writes while a save's hooks run. */
19530
- var hookWrites = null;
19590
+ var hookWrites = /* @__PURE__ */ new Set();
19531
19591
  /** Note that `path` of the variables was written (see keepHookWrites). */
19532
19592
  function recordHookWrite(path) {
19533
- hookWrites?.set(pathKey(path), path);
19593
+ for (const writes of hookWrites) writes.set(pathKey(path), path);
19534
19594
  }
19535
19595
  /**
19536
19596
  * Write the changes between `before` and `after` (the live variables around
@@ -19773,6 +19833,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
19773
19833
  storyData: null,
19774
19834
  currentPassage: "",
19775
19835
  navigationId: 0,
19836
+ replacementNavigationId: 0,
19776
19837
  variables: createNamespace(),
19777
19838
  variableDefaults: {},
19778
19839
  transient: createNamespace(),
@@ -20088,14 +20149,17 @@ var useStoryStore = create()(storyStore((set, get) => ({
20088
20149
  const before = get().variables;
20089
20150
  const replaced = latestStateApplied;
20090
20151
  const writes = /* @__PURE__ */ new Map();
20091
- hookWrites = writes;
20092
- return () => {
20093
- if (hookWrites === writes) hookWrites = null;
20152
+ hookWrites.add(writes);
20153
+ const dispose = () => {
20154
+ hookWrites.delete(writes);
20155
+ };
20156
+ return Object.assign(() => {
20157
+ dispose();
20094
20158
  if (latestStateApplied !== replaced) throw new Error("spindle: a beforesave handler restarted or loaded the game, so the save was not made");
20095
20159
  const payload = get().getSavePayload();
20096
20160
  keepHookWrites(payload, before, get().variables, [...writes.values()]);
20097
20161
  return payload;
20098
- };
20162
+ }, { dispose });
20099
20163
  },
20100
20164
  loadFromPayload: (payload, slot, playthroughId, issued) => {
20101
20165
  const applying = slotLoadApplying ?? issued;
@@ -20139,6 +20203,7 @@ var useStoryStore = create()(storyStore((set, get) => ({
20139
20203
  set((state) => {
20140
20204
  state.currentPassage = payload.passage;
20141
20205
  state.navigationId++;
20206
+ state.replacementNavigationId = state.navigationId;
20142
20207
  state.variables = createNamespace(deepClone(entry?.variables ?? payload.variables));
20143
20208
  state.history = retained.map((m) => ({
20144
20209
  passage: m.passage,
@@ -23136,7 +23201,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
23136
23201
  });
23137
23202
  } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
23138
23203
  }
23139
- if (token.name.toLowerCase() === "do" && !parametersOf.widget?.(token.name)) {
23204
+ if (executesRawBody(token.name, parametersOf)) {
23140
23205
  let close = t + 1;
23141
23206
  while (close < tokens.length) {
23142
23207
  const c = tokens[close];
@@ -23887,7 +23952,6 @@ defineMacro({
23887
23952
  id: navigationId
23888
23953
  });
23889
23954
  const resolvedTypeRef = useRef("fade");
23890
- const prevHistoryLenRef = useRef(0);
23891
23955
  const displayedId = displayed.id;
23892
23956
  const isOutgoing = useCallback((state) => state.navigationId !== displayedId, [displayedId]);
23893
23957
  const hasLeft = useCallback(() => isOutgoing(useStoryStore.getState()), [isOutgoing]);
@@ -23911,12 +23975,9 @@ defineMacro({
23911
23975
  }, [cancelTransition]);
23912
23976
  useEffect(() => {
23913
23977
  const store = useStoryStore.getState();
23914
- const { history, historyIndex, transitionConfig } = store;
23915
- const prevLen = prevHistoryLenRef.current;
23916
- prevHistoryLenRef.current = history.length;
23978
+ const { replacementNavigationId, transitionConfig } = store;
23917
23979
  const isFirstLoad = !displayedPassage;
23918
- const isRestart = history.length === 1 && historyIndex === 0 && prevLen > 1;
23919
- const isLoad = history.length > 1 && historyIndex === history.length - 1 && prevLen > 1 && Math.abs(history.length - prevLen) > 1;
23980
+ const isReplacement = navigationId === replacementNavigationId;
23920
23981
  if (navigationId === displayed.id) return;
23921
23982
  const next = store.consumeNextTransition();
23922
23983
  cancelTransition();
@@ -23926,7 +23987,7 @@ defineMacro({
23926
23987
  setDisplayedPassage(currentPassage);
23927
23988
  return;
23928
23989
  }
23929
- if (isFirstLoad || isRestart || isLoad) {
23990
+ if (isFirstLoad || isReplacement) {
23930
23991
  resolvedTypeRef.current = "fade";
23931
23992
  setDisplayedPassage(currentPassage);
23932
23993
  return;
@@ -3825,6 +3825,11 @@ function branchParents(name, macros) {
3825
3825
  if (!macros) return [...companionParents.get(name) ?? []].filter((parent) => parent !== "listbox");
3826
3826
  return macros.filter((macro) => macro.name.toLowerCase() !== "listbox" && macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase())).map((macro) => macro.name.toLowerCase());
3827
3827
  }
3828
+ /** The declared parameters of the macro `name`, if it declares any. */
3829
+ function getMacroParameters(name) {
3830
+ return metadataRegistry.get(name)?.parameters;
3831
+ }
3832
+ getMacroParameters.source = (name) => metadataRegistry.get(name)?.source;
3828
3833
  function getMacroRegistry() {
3829
3834
  return Array.from(metadataRegistry.values());
3830
3835
  }
@@ -3943,6 +3948,8 @@ function pairMarkup(tokens, options = {}) {
3943
3948
  };
3944
3949
  const root = [];
3945
3950
  const stack = [];
3951
+ const openPositions = /* @__PURE__ */ new Map();
3952
+ const tagKey = (tag) => `${tag.type}:${lowerName(tag)}`;
3946
3953
  const add = (node) => (last$1(stack)?.into ?? root).push(node);
3947
3954
  /**
3948
3955
  * End the element on top of the stack, with `close` if it has one: its
@@ -3951,6 +3958,10 @@ function pairMarkup(tokens, options = {}) {
3951
3958
  const end = (ending, close, owns = ending === "closed") => {
3952
3959
  const { node, body } = stack.pop();
3953
3960
  const open = node.token;
3961
+ const key = tagKey(open);
3962
+ const positions = openPositions.get(key);
3963
+ positions.pop();
3964
+ if (positions.length === 0) openPositions.delete(key);
3954
3965
  const noticedAt = close ? close.end : noticedAtEnd;
3955
3966
  for (const { tag } of body.branches) if (open.type !== "macro" || !parentsOf(tag.name).includes(lowerName(open))) misplaced(tag, open, noticedAt);
3956
3967
  if (ending === "unclosed") report("unclosed-block", open, `Unclosed ${tagLabel(open)}: no ${closerOf(open)} closes it`, noticedAt, { name: nameOf(open) });
@@ -3969,8 +3980,7 @@ function pairMarkup(tokens, options = {}) {
3969
3980
  if (!top) report("stray-closer", token, `${tagLabel(token)} closes nothing: no ${token.type === "html" ? `<${token.tag}>` : `{${token.name}}`} is open here`, token.start, { name: nameOf(token) });
3970
3981
  else if (closes(top.node.token, token)) end("closed", token);
3971
3982
  else {
3972
- let outer = stack.length - 1;
3973
- while (outer >= 0 && !closes(stack[outer].node.token, token)) outer--;
3983
+ const outer = last$1(openPositions.get(tagKey(token)) ?? []) ?? -1;
3974
3984
  end("mismatch", token, outer === -1);
3975
3985
  if (outer !== -1) {
3976
3986
  while (stack.length > outer + 1) end("cut", token);
@@ -4014,6 +4024,10 @@ function pairMarkup(tokens, options = {}) {
4014
4024
  branches: []
4015
4025
  };
4016
4026
  node.body = body;
4027
+ const key = tagKey(token);
4028
+ const positions = openPositions.get(key) ?? [];
4029
+ positions.push(stack.length);
4030
+ openPositions.set(key, positions);
4017
4031
  stack.push({
4018
4032
  node,
4019
4033
  body,
@@ -10211,6 +10225,40 @@ function jsCodeEnd(onOpenEnd) {
10211
10225
  }
10212
10226
  /** The JavaScript reader Spindle uses today: js-lexer, then a lenient scan. */
10213
10227
  var defaultCodeEnd = jsCodeEnd();
10228
+ /**
10229
+ * Index possible brace ends for repeated recovery attempts in one template.
10230
+ * Within plain code, nested braces must close first. At a quote, slash or
10231
+ * escape we stop making lexical assumptions, but the remaining raw `}`s
10232
+ * still bound how many pending braces could close. Indexing visits each
10233
+ * opener once, so unmatched plain-code openers can skip suffix scans.
10234
+ */
10235
+ function indexCodeEnds(input) {
10236
+ const possible = /* @__PURE__ */ new Set();
10237
+ const pending = [];
10238
+ let remaining = 0;
10239
+ let lastBrace = -1;
10240
+ for (let i = 0; i < input.length; i++) if (input[i] === "}") {
10241
+ remaining++;
10242
+ lastBrace = i;
10243
+ }
10244
+ const uncertain = () => {
10245
+ for (let i = Math.max(0, pending.length - remaining); i < pending.length; i++) possible.add(pending[i]);
10246
+ pending.length = 0;
10247
+ };
10248
+ for (let i = 0; i < input.length; i++) {
10249
+ const c = input[i];
10250
+ if (c === "{") pending.push(i);
10251
+ else if (c === "}") {
10252
+ remaining--;
10253
+ const open = pending.pop();
10254
+ if (open !== void 0) possible.add(open);
10255
+ } else if (/['"`/\\]/.test(c)) uncertain();
10256
+ }
10257
+ return (start) => {
10258
+ if (start > lastBrace) return -1;
10259
+ return possible.has(start - 1) ? defaultCodeEnd.closeBrace(input, start, start) : parsedCodeEnd(input, start, "expression");
10260
+ };
10261
+ }
10214
10262
  //#endregion
10215
10263
  //#region src/markup/code-attributes.ts
10216
10264
  /**
@@ -10236,6 +10284,7 @@ function splitSigilTemplate(template, incomplete = false) {
10236
10284
  const parts = [];
10237
10285
  let text = "";
10238
10286
  let i = 0;
10287
+ const closeBrace = indexCodeEnds(template);
10239
10288
  while (i < template.length) {
10240
10289
  const brace = template.indexOf("{", i);
10241
10290
  if (brace === -1) {
@@ -10244,7 +10293,7 @@ function splitSigilTemplate(template, incomplete = false) {
10244
10293
  }
10245
10294
  text += template.slice(i, brace);
10246
10295
  i = brace + 1;
10247
- let end = isSigil(template[i]) ? defaultCodeEnd.closeBrace(template, i, i) : -1;
10296
+ let end = isSigil(template[i]) ? closeBrace(i) : -1;
10248
10297
  if (end === -1 && incomplete && isSigil(template[i])) end = template.length;
10249
10298
  if (end === -1) {
10250
10299
  text += "{";
@@ -11155,6 +11204,10 @@ function widgetParameters(params, holds = {}) {
11155
11204
  ...hasOwn(holds, name) ? { holds: holds[name] } : {}
11156
11205
  }));
11157
11206
  }
11207
+ /** A raw body is executable only while the builtin implementation owns it. */
11208
+ function executesRawBody(name, parametersOf) {
11209
+ return isRawMacro(name, parametersOf.widget?.(name) !== void 0) && parametersOf.source?.(name) !== "user";
11210
+ }
11158
11211
  /**
11159
11212
  * `params` with each `string` and `text` parameter (options too) saying
11160
11213
  * what it holds: what it declares, else `holds`.
@@ -11182,7 +11235,9 @@ function withHolds(params, holds) {
11182
11235
  function parameterLookup(macros) {
11183
11236
  const parameters = new NameMap();
11184
11237
  const widgets = new NameMap();
11185
- for (const { name, parameters: params, interpolate, widget } of macros) {
11238
+ const sources = new NameMap();
11239
+ for (const { name, parameters: params, interpolate, widget, source } of macros) {
11240
+ sources.set(name, source ?? "user");
11186
11241
  if (params) parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
11187
11242
  if (widget) widgets.set(name, widgetParameters(widget.params, widget.holds) ?? []);
11188
11243
  }
@@ -11196,6 +11251,7 @@ function parameterLookup(macros) {
11196
11251
  return params;
11197
11252
  };
11198
11253
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
11254
+ lookup.source = (name) => sources.get(name);
11199
11255
  return lookup;
11200
11256
  }
11201
11257
  /** What a `string` or `text` argument holds when its parameter doesn't say. */
@@ -11261,7 +11317,7 @@ function* codeAndText(src, tokens, parametersOf) {
11261
11317
  else if (token.type === "macro" && !token.isClose) {
11262
11318
  const name = token.name.toLowerCase();
11263
11319
  const widget = parametersOf.widget?.(name);
11264
- if (name === "do" && !widget) {
11320
+ if (executesRawBody(name, parametersOf)) {
11265
11321
  const close = closeOfTextBody(t, name);
11266
11322
  if (close < 0) continue;
11267
11323
  yield {
@@ -11701,7 +11757,7 @@ function completionContext(source, cursor, macros = []) {
11701
11757
  } else if (token.type === "link" && token.displayEnd === src.length) return nested(token.display, token.displayStart);
11702
11758
  else if (token.type === "text" && !token.comment) {
11703
11759
  const opener = tokens[tokens.length - 2];
11704
- if (opener?.type === "macro" && !opener.isClose && isRawMacro(opener.name, parametersOf.widget?.(opener.name) !== void 0)) return codeAt(token.value, token.start, "statements");
11760
+ if (opener?.type === "macro" && !opener.isClose && executesRawBody(opener.name, parametersOf)) return codeAt(token.value, token.start, "statements");
11705
11761
  } else if (token.type === "macro" && !token.isClose && token.argsEnd === src.length) {
11706
11762
  const name = token.name.toLowerCase();
11707
11763
  const args = token.rawArgs;
@@ -11757,6 +11813,7 @@ function completionContext(source, cursor, macros = []) {
11757
11813
  //#region src/widgets/ast-scanner.ts
11758
11814
  /** The declared parameters of the macros registered so far. */
11759
11815
  var registeredParameters = (name) => parameterLookup(getMacroRegistry())(name);
11816
+ registeredParameters.source = getMacroParameters.source;
11760
11817
  /**
11761
11818
  * Whether the text of an attribute value or macro label renders a
11762
11819
  * `{@children}`: it is markup, parsed as the renderer parses it.
@@ -13031,7 +13088,7 @@ function collectTokenRefs(content, tokens, at, emit, options) {
13031
13088
  });
13032
13089
  } else if (!/^["'`]/.test(first)) scanCode(first, (i) => at(token.argsStart + lead + i), emit);
13033
13090
  }
13034
- if (token.name.toLowerCase() === "do" && !parametersOf.widget?.(token.name)) {
13091
+ if (executesRawBody(token.name, parametersOf)) {
13035
13092
  let close = t + 1;
13036
13093
  while (close < tokens.length) {
13037
13094
  const c = tokens[close];
@@ -13195,6 +13252,11 @@ var Bindings = class {
13195
13252
  readGroups() {
13196
13253
  const { code, groups } = this;
13197
13254
  const stack = [];
13255
+ const active = {
13256
+ "{": [],
13257
+ "(": [],
13258
+ "[": []
13259
+ };
13198
13260
  for (let i = 0; i < code.length; i++) {
13199
13261
  const c = code.charAt(i);
13200
13262
  if (c === "{" || c === "(" || c === "[") {
@@ -13205,15 +13267,16 @@ var Bindings = class {
13205
13267
  parent: stack[stack.length - 1]
13206
13268
  };
13207
13269
  groups.push(group);
13270
+ active[c].push(stack.length);
13208
13271
  stack.push(group);
13209
13272
  this.byOpen.set(i, group);
13210
13273
  } else if (CLOSERS[c]) {
13211
- let k = stack.length - 1;
13212
- while (k >= 0 && stack[k].kind !== CLOSERS[c]) k--;
13213
- if (k >= 0) {
13274
+ const positions = active[CLOSERS[c]];
13275
+ const k = positions[positions.length - 1];
13276
+ if (k !== void 0) {
13214
13277
  stack[k].close = i;
13215
13278
  this.byClose.set(i, stack[k]);
13216
- stack.length = k;
13279
+ while (stack.length > k) active[stack.pop().kind].pop();
13217
13280
  }
13218
13281
  }
13219
13282
  }
@@ -25211,8 +25274,8 @@ async function formatLf(text, options) {
25211
25274
  output = output.replace(/\n*$/, "\n");
25212
25275
  return replaceAll(output.split("\n").map((line) => literalLines.get(line.trim()) ?? line).join("\n"), sentinel, "\n");
25213
25276
  }
25214
- /** HTML whose whitespace renders as written: a `<pre>` or `<textarea>`, or a `white-space` style. */
25215
- var WHITESPACE_AS_WRITTEN = /<(?:pre|textarea)[\s>]|white-space\s*:/i;
25277
+ /** Literal HTML and opaque SVG, whose text can inherit significant whitespace. */
25278
+ var WHITESPACE_AS_WRITTEN = /<(?:pre|textarea|svg)[\s>]|white-space\s*:/i;
25216
25279
  /** Preserve whole literal elements, including openers beside nested tags. */
25217
25280
  function whitespaceSensitiveLines(source, isBlock) {
25218
25281
  const lines = /* @__PURE__ */ new Set();
@@ -25222,7 +25285,11 @@ function whitespaceSensitiveLines(source, isBlock) {
25222
25285
  function visit(nodes) {
25223
25286
  for (const node of nodes) {
25224
25287
  const { token, body } = node;
25225
- if (token.type === "html" && (["pre", "textarea"].includes(token.tag.toLowerCase()) || Object.entries(token.attributes).some(([name, value]) => name.toLowerCase() === "style" && /white-space\s*:/i.test(value)))) {
25288
+ if (token.type === "html" && ([
25289
+ "pre",
25290
+ "textarea",
25291
+ "svg"
25292
+ ].includes(token.tag.toLowerCase()) || Object.entries(token.attributes).some(([name, value]) => name.toLowerCase() === "style" && /white-space\s*:/i.test(value)))) {
25226
25293
  const first = lineAt(node.start);
25227
25294
  const last = lineAt(node.end - 1);
25228
25295
  for (let line = first; line <= last; line++) lines.add(line);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.62.4",
3
+ "version": "0.62.5",
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
@@ -229,11 +229,25 @@ export interface ParametersOf {
229
229
  * commas or spaces (see splitArgs), not by parseMacroArgs.
230
230
  */
231
231
  widget?(name: string): readonly WidgetParameter[] | undefined;
232
+ /** Effective registration origin; absent metadata retains builtin defaults. */
233
+ source?(name: string): 'builtin' | 'user' | undefined;
234
+ }
235
+
236
+ /** A raw body is executable only while the builtin implementation owns it. */
237
+ export function executesRawBody(
238
+ name: string,
239
+ parametersOf: ParametersOf,
240
+ ): boolean {
241
+ return (
242
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined) &&
243
+ parametersOf.source?.(name) !== 'user'
244
+ );
232
245
  }
233
246
 
234
247
  /** What the argument check needs to know of a macro (see MacroMetadata). */
235
248
  export interface MacroParameters {
236
249
  name: string;
250
+ source?: 'builtin' | 'user';
237
251
  parameters?: readonly ParameterDef[];
238
252
  interpolate?: boolean;
239
253
  /** For a widget: its `@` parameters and what some declare to hold. */
@@ -273,7 +287,15 @@ export function parameterLookup(
273
287
  ): ParametersOf {
274
288
  const parameters = new NameMap<readonly ParameterDef[]>();
275
289
  const widgets = new NameMap<readonly WidgetParameter[]>();
276
- for (const { name, parameters: params, interpolate, widget } of macros) {
290
+ const sources = new NameMap<'builtin' | 'user'>();
291
+ for (const {
292
+ name,
293
+ parameters: params,
294
+ interpolate,
295
+ widget,
296
+ source,
297
+ } of macros) {
298
+ sources.set(name, source ?? 'user');
277
299
  if (params)
278
300
  parameters.set(name, withHolds(params, holdsByDefault(interpolate)));
279
301
  if (widget)
@@ -289,6 +311,7 @@ export function parameterLookup(
289
311
  return params;
290
312
  };
291
313
  if (widgets.size > 0) lookup.widget = (name) => widgets.get(name);
314
+ lookup.source = (name) => sources.get(name);
292
315
  return lookup;
293
316
  }
294
317
 
@@ -396,7 +419,7 @@ export function* codeAndText(
396
419
  } else if (token.type === 'macro' && !token.isClose) {
397
420
  const name = token.name.toLowerCase();
398
421
  const widget = parametersOf.widget?.(name);
399
- if (name === 'do' && !widget) {
422
+ if (executesRawBody(name, parametersOf)) {
400
423
  const close = closeOfTextBody(t, name);
401
424
  if (close < 0) continue;
402
425
  const body = src.slice(token.end, tokens[close]!.start);
@@ -6,6 +6,7 @@ import {
6
6
  attributeValues,
7
7
  escapeOffsets,
8
8
  parameterLookup,
9
+ executesRawBody,
9
10
  type PieceBase,
10
11
  } from './code-check';
11
12
  import { macroArgumentSpans } from './components/macros/macro-args';
@@ -141,10 +142,7 @@ export function completionContext(
141
142
  if (
142
143
  opener?.type === 'macro' &&
143
144
  !opener.isClose &&
144
- isRawMacro(
145
- opener.name,
146
- parametersOf.widget?.(opener.name) !== undefined,
147
- )
145
+ executesRawBody(opener.name, parametersOf)
148
146
  ) {
149
147
  return codeAt(token.value, token.start, 'statements');
150
148
  }
@@ -789,9 +789,6 @@ defineMacro({
789
789
  // Track the resolved transition type for the data-transition prop
790
790
  const resolvedTypeRef = useRef<string>('fade');
791
791
 
792
- // Track previous history length to detect restart/load
793
- const prevHistoryLenRef = useRef(0);
794
-
795
792
  const displayedId = displayed.id;
796
793
  const isOutgoing = useCallback(
797
794
  (state: StoryState) => state.navigationId !== displayedId,
@@ -834,20 +831,10 @@ defineMacro({
834
831
  // State machine effect — triggers on every navigation
835
832
  useEffect(() => {
836
833
  const store = useStoryStore.getState();
837
- const { history, historyIndex, transitionConfig } = store;
838
-
839
- // Determine if this is a first load, restart, or save-load
840
- const prevLen = prevHistoryLenRef.current;
841
- prevHistoryLenRef.current = history.length;
834
+ const { replacementNavigationId, transitionConfig } = store;
842
835
 
843
836
  const isFirstLoad = !displayedPassage;
844
- const isRestart =
845
- history.length === 1 && historyIndex === 0 && prevLen > 1;
846
- const isLoad =
847
- history.length > 1 &&
848
- historyIndex === history.length - 1 &&
849
- prevLen > 1 &&
850
- Math.abs(history.length - prevLen) > 1;
837
+ const isReplacement = navigationId === replacementNavigationId;
851
838
 
852
839
  // Already showing this navigation (initial render)
853
840
  if (navigationId === displayed.id) {
@@ -871,7 +858,7 @@ defineMacro({
871
858
  }
872
859
 
873
860
  // First load, restart, or load → use simple fade (no outgoing phase)
874
- if (isFirstLoad || isRestart || isLoad) {
861
+ if (isFirstLoad || isReplacement) {
875
862
  resolvedTypeRef.current = 'fade';
876
863
  setDisplayedPassage(currentPassage);
877
864
  return;
@@ -375,8 +375,8 @@ async function formatLf(
375
375
  );
376
376
  }
377
377
 
378
- /** HTML whose whitespace renders as written: a `<pre>` or `<textarea>`, or a `white-space` style. */
379
- const WHITESPACE_AS_WRITTEN = /<(?:pre|textarea)[\s>]|white-space\s*:/i;
378
+ /** Literal HTML and opaque SVG, whose text can inherit significant whitespace. */
379
+ const WHITESPACE_AS_WRITTEN = /<(?:pre|textarea|svg)[\s>]|white-space\s*:/i;
380
380
 
381
381
  /** Preserve whole literal elements, including openers beside nested tags. */
382
382
  function whitespaceSensitiveLines(
@@ -392,7 +392,7 @@ function whitespaceSensitiveLines(
392
392
  const { token, body } = node;
393
393
  if (
394
394
  token.type === 'html' &&
395
- (['pre', 'textarea'].includes(token.tag.toLowerCase()) ||
395
+ (['pre', 'textarea', 'svg'].includes(token.tag.toLowerCase()) ||
396
396
  Object.entries(token.attributes).some(
397
397
  ([name, value]) =>
398
398
  name.toLowerCase() === 'style' && /white-space\s*:/i.test(value),