@rohal12/spindle 0.60.0 → 0.60.2

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.
@@ -3366,6 +3366,8 @@ var BLOCK_MACROS = new NameSet([
3366
3366
  * definition is, whereas the macros in BLOCK_MACROS stay blocks.
3367
3367
  */
3368
3368
  var BLOCK_WIDGETS = new NameSet();
3369
+ /** Classification owned by defineMacro, independent of explicit registrations. */
3370
+ var DEFINED_BLOCK_MACROS = new NameSet();
3369
3371
  /** Macros whose body is JavaScript source, kept verbatim. */
3370
3372
  var RAW_BODY_MACROS = /* @__PURE__ */ new Set(["do"]);
3371
3373
  /** Whether a macro's body is JavaScript, kept verbatim (`{do}`). */
@@ -3374,7 +3376,7 @@ function isRawMacro(name) {
3374
3376
  }
3375
3377
  /** Whether a macro takes a body closed by `{/name}`. */
3376
3378
  function isBlockMacro(name) {
3377
- return BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
3379
+ return BLOCK_MACROS.has(name) || DEFINED_BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
3378
3380
  }
3379
3381
  /** Macros whose branches render as one: the node holds one per branch. */
3380
3382
  var BRANCHING = /* @__PURE__ */ new Set([
@@ -10090,9 +10092,13 @@ function parseDelay(str) {
10090
10092
  * Error its string form (e.g. "Error").
10091
10093
  */
10092
10094
  function errorMessage(err, fallback) {
10093
- if (err instanceof Error) return err.message || fallback || String(err);
10094
- if (typeof err === "string" && err !== "") return err;
10095
- return fallback ?? String(err);
10095
+ try {
10096
+ if (err instanceof Error) return err.message || fallback || String(err);
10097
+ if (typeof err === "string" && err !== "") return err;
10098
+ return fallback ?? String(err);
10099
+ } catch {
10100
+ return fallback ?? "Unprintable error";
10101
+ }
10096
10102
  }
10097
10103
  //#endregion
10098
10104
  //#region src/utils/listeners.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rohal12/spindle",
3
- "version": "0.60.0",
3
+ "version": "0.60.2",
4
4
  "type": "module",
5
5
  "description": "A Preact-based story format for Twine 2.",
6
6
  "license": "Unlicense",
@@ -234,7 +234,7 @@ function classData(value: object): unknown {
234
234
  return ['Date', Date.prototype.getTime.call(value), extra()];
235
235
  }
236
236
  if (value instanceof RegExp) {
237
- return ['RegExp', [...regExpParts(value), value.lastIndex], extra()];
237
+ return ['RegExp', savedRegExp(value), extra()];
238
238
  }
239
239
  return savedData(ownData(value));
240
240
  }
@@ -299,8 +299,7 @@ function reducers(): Record<string, (value: unknown) => unknown> {
299
299
  return key !== undefined && [key];
300
300
  };
301
301
  out[REGEXP_TAG] = (v) =>
302
- v instanceof RegExp &&
303
- v.lastIndex !== 0 && [...regExpParts(v), v.lastIndex];
302
+ v instanceof RegExp && !Object.is(v.lastIndex, 0) && savedRegExp(v);
304
303
  if (GUARD_V8_KEYS) {
305
304
  out[KEYS_TAG] = (v) => {
306
305
  return isPlainData(v) && keyEntries(v);
@@ -309,6 +308,20 @@ function reducers(): Record<string, (value: unknown) => unknown> {
309
308
  return out;
310
309
  }
311
310
 
311
+ /** RegExp cursors are primitive data; object coercion cannot be replayed safely. */
312
+ function isRegExpCursor(value: unknown): boolean {
313
+ return (
314
+ value === null || (typeof value !== 'object' && typeof value !== 'function')
315
+ );
316
+ }
317
+
318
+ function savedRegExp(re: RegExp): unknown[] {
319
+ if (!isRegExpCursor(re.lastIndex)) {
320
+ throw new TypeError('spindle: Cannot save an object-valued RegExp cursor');
321
+ }
322
+ return [...regExpParts(re), re.lastIndex];
323
+ }
324
+
312
325
  /**
313
326
  * The RegExp of a `[source, flags, lastIndex]` list (an `R` entry, or the
314
327
  * contents of a RegExp subclass), or undefined if the list is malformed.
@@ -318,7 +331,8 @@ function newRegExp(data: unknown): RegExp | undefined {
318
331
  !Array.isArray(data) ||
319
332
  typeof data[0] !== 'string' ||
320
333
  typeof data[1] !== 'string' ||
321
- !Number.isSafeInteger(data[2])
334
+ data.length !== 3 ||
335
+ !isRegExpCursor(data[2])
322
336
  ) {
323
337
  return undefined;
324
338
  }
@@ -11,6 +11,7 @@ import {
11
11
  renderNodes,
12
12
  NobrContext,
13
13
  ViewScopeContext,
14
+ InterfaceContext,
14
15
  useViewScope,
15
16
  } from '../markup/render';
16
17
  import { useStoryFields } from '../hooks/use-story-fields';
@@ -138,20 +139,22 @@ export function Passage({
138
139
  const viewScope = useViewScope();
139
140
 
140
141
  const inner = (
141
- <ViewScopeContext.Provider value={viewScope}>
142
- <div
143
- ref={elRef}
144
- class="passage"
145
- data-passage={passage.name}
146
- data-tags={passage.tags.join(' ')}
147
- data-transition={dataTransition}
148
- >
149
- {headerContent && <div class="passage-header">{headerContent}</div>}
150
- {content}
151
- {footerContent && <div class="passage-footer">{footerContent}</div>}
152
- {doneContent && <div hidden>{doneContent}</div>}
153
- </div>
154
- </ViewScopeContext.Provider>
142
+ <InterfaceContext.Provider value={false}>
143
+ <ViewScopeContext.Provider value={viewScope}>
144
+ <div
145
+ ref={elRef}
146
+ class="passage"
147
+ data-passage={passage.name}
148
+ data-tags={passage.tags.join(' ')}
149
+ data-transition={dataTransition}
150
+ >
151
+ {headerContent && <div class="passage-header">{headerContent}</div>}
152
+ {content}
153
+ {footerContent && <div class="passage-footer">{footerContent}</div>}
154
+ {doneContent && <div hidden>{doneContent}</div>}
155
+ </div>
156
+ </ViewScopeContext.Provider>
157
+ </InterfaceContext.Provider>
155
158
  );
156
159
 
157
160
  return nobr ? (
@@ -10,6 +10,7 @@ import {
10
10
  renderNodes,
11
11
  NobrContext,
12
12
  ViewScopeContext,
13
+ InterfaceContext,
13
14
  useViewScope,
14
15
  } from '../markup/render';
15
16
  import { useStoryFields } from '../hooks/use-story-fields';
@@ -128,35 +129,37 @@ export function PassageDialog({
128
129
  const cls = panelClass ? `dialog-panel ${panelClass}` : 'dialog-panel';
129
130
 
130
131
  return (
131
- <DialogCloseContext.Provider value={stableOnClose}>
132
- <div
133
- class="dialog-overlay"
134
- onClick={handleBackdrop}
135
- >
132
+ <InterfaceContext.Provider value={false}>
133
+ <DialogCloseContext.Provider value={stableOnClose}>
136
134
  <div
137
- ref={panelRef}
138
- class={cls}
139
- role="dialog"
140
- data-dialog-passage={passageName}
141
- aria-modal="true"
142
- aria-label={label ?? passageName}
143
- tabIndex={-1}
135
+ class="dialog-overlay"
136
+ onClick={handleBackdrop}
144
137
  >
145
- {showCloseButton && (
146
- <DialogCloseButton
147
- dialogName={passageName ?? label ?? 'dialog'}
148
- passageName={passageName}
149
- onClose={stableOnClose}
150
- />
151
- )}
152
- <div class="dialog-body">
153
- <ViewScopeContext.Provider value={viewScope}>
154
- {content}
155
- </ViewScopeContext.Provider>
138
+ <div
139
+ ref={panelRef}
140
+ class={cls}
141
+ role="dialog"
142
+ data-dialog-passage={passageName}
143
+ aria-modal="true"
144
+ aria-label={label ?? passageName}
145
+ tabIndex={-1}
146
+ >
147
+ {showCloseButton && (
148
+ <DialogCloseButton
149
+ dialogName={passageName ?? label ?? 'dialog'}
150
+ passageName={passageName}
151
+ onClose={stableOnClose}
152
+ />
153
+ )}
154
+ <div class="dialog-body">
155
+ <ViewScopeContext.Provider value={viewScope}>
156
+ {content}
157
+ </ViewScopeContext.Provider>
158
+ </div>
156
159
  </div>
157
160
  </div>
158
- </div>
159
- </DialogCloseContext.Provider>
161
+ </DialogCloseContext.Provider>
162
+ </InterfaceContext.Provider>
160
163
  );
161
164
  }
162
165
 
@@ -1,4 +1,7 @@
1
- import { evaluate } from '../../expression';
1
+ import { evaluateDisplay } from '../../expression';
2
+ import { DisplayOnlyContext } from '../../display-only';
3
+ import { useContext } from 'preact/hooks';
4
+ import { MacroError } from './MacroError';
2
5
  import { useInterpolate } from '../../hooks/use-interpolate';
3
6
  import { useMergedLocals } from '../../hooks/use-merged-locals';
4
7
  import { display, wrapContent } from './display';
@@ -7,6 +10,7 @@ import type { ExpressionNode } from '../../markup/ast';
7
10
  /** An expression display: `{$hp + 1}`. */
8
11
  export function ExprDisplay({ node }: { node: ExpressionNode }) {
9
12
  const { expression } = node;
13
+ const displayOnly = useContext(DisplayOnlyContext);
10
14
  const resolve = useInterpolate();
11
15
  const className = resolve(node.className);
12
16
  const id = resolve(node.id);
@@ -15,10 +19,21 @@ export function ExprDisplay({ node }: { node: ExpressionNode }) {
15
19
  let text: string;
16
20
  try {
17
21
  text = display(
18
- evaluate(expression, variables, temporary, localsValues, transient),
22
+ evaluateDisplay(
23
+ expression,
24
+ [variables, temporary, localsValues, transient],
25
+ displayOnly,
26
+ ),
27
+ );
28
+ } catch (error) {
29
+ return wrapContent(
30
+ className,
31
+ id,
32
+ <MacroError
33
+ macro={expression}
34
+ error={error}
35
+ />,
19
36
  );
20
- } catch {
21
- text = `{error: ${expression}}`;
22
37
  }
23
38
  return wrapContent(className, id, text);
24
39
  }
@@ -1,3 +1,4 @@
1
+ import { DisplayOnlyContext } from '../../display-only';
1
2
  import { useStoryStore } from '../../store';
2
3
  import { useStoryFields } from '../../hooks/use-story-fields';
3
4
  import { parseMarkup } from '../../markup/parse';
@@ -13,6 +14,7 @@ defineMacro({
13
14
  merged: true,
14
15
  parameters: INCLUDE_PARAMETERS,
15
16
  render(_props, ctx) {
17
+ const displayOnly = ctx.hooks.useContext(DisplayOnlyContext);
16
18
  const { storyData } = useStoryFields('storyData');
17
19
 
18
20
  const { inline } = ctx.args;
@@ -42,8 +44,10 @@ defineMacro({
42
44
  // not on every render (an unrelated variable update re-renders it)
43
45
  const included = !failure && !!passage;
44
46
  ctx.hooks.useEffect(() => {
45
- if (included) useStoryStore.getState().trackRender(passageName);
46
- }, [included, passageName]);
47
+ if (included && !displayOnly) {
48
+ useStoryStore.getState().trackRender(passageName);
49
+ }
50
+ }, [included, passageName, displayOnly]);
47
51
 
48
52
  if (!storyData) return null;
49
53
  if (failure) {
@@ -12,7 +12,7 @@ export function MacroError({
12
12
  return (
13
13
  <span
14
14
  class="error"
15
- title={String(error)}
15
+ title={errorMessage(error)}
16
16
  >
17
17
  {`{${macro} error${currentSourceLocation()}: ${errorMessage(error)}}`}
18
18
  </span>
@@ -162,6 +162,25 @@ function createSnapshot(
162
162
  copyLiveState(passageEl, clone);
163
163
  pendingScrolls.set(clone, scrollOffsets(passageEl, clone));
164
164
 
165
+ // A cloned browsing context would reload and execute scripts on insertion.
166
+ // Keep its authored size/style as a passive placeholder instead.
167
+ const originals = passageEl.querySelectorAll('iframe, object, embed');
168
+ const copies = clone.querySelectorAll('iframe, object, embed');
169
+ copies.forEach((embedded, i) => {
170
+ const placeholder = document.createElement('div');
171
+ for (const name of ['class', 'style', 'width', 'height']) {
172
+ const value = embedded.getAttribute(name);
173
+ if (value !== null) placeholder.setAttribute(name, value);
174
+ }
175
+ const original = originals[i];
176
+ if (original) {
177
+ const rect = original.getBoundingClientRect();
178
+ placeholder.style.width = `${rect.width}px`;
179
+ placeholder.style.height = `${rect.height}px`;
180
+ }
181
+ embedded.replaceWith(placeholder);
182
+ });
183
+
165
184
  // Strip id attributes to avoid duplicates
166
185
  clone.removeAttribute('id');
167
186
  const idEls = clone.querySelectorAll('[id]');
@@ -4,6 +4,7 @@ import { useInterpolate } from '../../hooks/use-interpolate';
4
4
  import { ownValue, variableNameError } from '../../utils/namespace';
5
5
  import { SCOPE_SIGILS } from '../../markup/tokens';
6
6
  import type { VariableNode } from '../../markup/ast';
7
+ import { MacroError } from './MacroError';
7
8
  import { display, wrapContent } from './display';
8
9
 
9
10
  const STORE_NAMESPACES = {
@@ -32,23 +33,34 @@ export function VarDisplay({ node }: { node: VariableNode }) {
32
33
  return <span class="error">{`{${sigil}${name} error: ${nameError}}`}</span>;
33
34
  }
34
35
 
35
- let value: unknown;
36
- if (scope === 'local') {
37
- value = ownValue(localsValues, root);
38
- } else {
39
- value = storeValue;
40
- }
36
+ try {
37
+ let value: unknown;
38
+ if (scope === 'local') {
39
+ value = ownValue(localsValues, root);
40
+ } else {
41
+ value = storeValue;
42
+ }
41
43
 
42
- // Resolve dot path (e.g. "character.name" → character['name']). Primitives
43
- // box on access, so built-ins like "name.length" resolve too.
44
- for (let i = 1; i < parts.length; i++) {
45
- if (value == null) {
46
- value = undefined;
47
- break;
44
+ // Resolve dot path (e.g. "character.name" → character['name']). Primitives
45
+ // box on access, so built-ins like "name.length" resolve too.
46
+ for (let i = 1; i < parts.length; i++) {
47
+ if (value == null) {
48
+ value = undefined;
49
+ break;
50
+ }
51
+ const part = parts[i] as string;
52
+ value = (value as Record<string, unknown>)[part];
48
53
  }
49
- const part = parts[i] as string;
50
- value = (value as Record<string, unknown>)[part];
51
- }
52
54
 
53
- return wrapContent(className, id, display(value));
55
+ return wrapContent(className, id, display(value));
56
+ } catch (error) {
57
+ return wrapContent(
58
+ className,
59
+ id,
60
+ <MacroError
61
+ macro={sigil + name}
62
+ error={error}
63
+ />,
64
+ );
65
+ }
54
66
  }
@@ -1,3 +1,4 @@
1
+ import { WATCH_PARAMETERS } from '../../watch-parameters';
1
2
  import { defineMacro } from '../../define-macro';
2
3
  import { FrozenStateContext } from '../../hooks/use-story-fields';
3
4
  import { useStoryStore } from '../../store';
@@ -13,26 +14,7 @@ import {
13
14
  defineMacro({
14
15
  name: 'watch',
15
16
  // {watch "condition" goto "X" dialog "X" run "X" name "X" priority N once}
16
- parameters: [
17
- {
18
- name: 'condition',
19
- type: 'string',
20
- holds: 'expression',
21
- required: true,
22
- },
23
- {
24
- name: 'options',
25
- type: 'options',
26
- parameters: [
27
- { name: 'goto', type: 'string', holds: 'passage' },
28
- { name: 'dialog', type: 'string', holds: 'passage' },
29
- { name: 'run', type: 'string', holds: 'statements' },
30
- { name: 'name', type: 'string', holds: 'text' },
31
- { name: 'priority', type: 'number' },
32
- { name: 'once', type: 'flag' },
33
- ],
34
- },
35
- ],
17
+ parameters: WATCH_PARAMETERS,
36
18
  render(_props, ctx) {
37
19
  const { hooks } = ctx;
38
20
 
@@ -1,7 +1,8 @@
1
1
  import { useContext, useMemo } from 'preact/hooks';
2
2
  import { WidgetChildrenContext, renderNodes } from '../../markup/render';
3
3
  import { useMergedLocals } from '../../hooks/use-merged-locals';
4
- import { evaluate } from '../../expression';
4
+ import { evaluateDisplay } from '../../expression';
5
+ import { DisplayOnlyContext } from '../../display-only';
5
6
  import type { ASTNode } from '../../markup/ast';
6
7
  import { splitArgs } from './arg-utils';
7
8
  import { createNamespace } from '../../utils/namespace';
@@ -39,6 +40,7 @@ function WidgetContent({
39
40
  rawArgs,
40
41
  invocationChildren,
41
42
  }: WidgetInvocationProps) {
43
+ const displayOnly = useContext(DisplayOnlyContext);
42
44
  const [mergedVars, mergedTemps, mergedLocals, mergedTrans] =
43
45
  useMergedLocals();
44
46
 
@@ -59,12 +61,10 @@ function WidgetContent({
59
61
  let value: unknown;
60
62
  if (expr !== undefined) {
61
63
  try {
62
- value = evaluate(
64
+ value = evaluateDisplay(
63
65
  expr,
64
- mergedVars,
65
- mergedTemps,
66
- mergedLocals,
67
- mergedTrans,
66
+ [mergedVars, mergedTemps, mergedLocals, mergedTrans],
67
+ displayOnly,
68
68
  );
69
69
  } catch {
70
70
  value = undefined;
@@ -24,7 +24,7 @@ import {
24
24
  } from './markup/render';
25
25
  import type { ASTNode } from './markup/ast';
26
26
  import { executeMutation, mutateState, readState } from './execute-mutation';
27
- import { evaluate } from './expression';
27
+ import { evaluateDisplay } from './expression';
28
28
  import { useStoryStore } from './store';
29
29
  import { getByPath, setByPath } from './utils/object-path';
30
30
  import { RESERVED_NAME } from './utils/namespace';
@@ -59,7 +59,7 @@ import type {
59
59
  MacroTextContext,
60
60
  ParameterDef,
61
61
  } from './registry';
62
- import { registerBlockMacro } from './markup/ast';
62
+ import { setDefinedBlockMacro } from './markup/ast';
63
63
 
64
64
  export type { MacroArgs, MacroTextContext, ParameterDef };
65
65
 
@@ -234,7 +234,7 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
234
234
  ctx.merged = useMergedLocals();
235
235
  const merged = ctx.merged;
236
236
  ctx.evaluate = (expr: string) =>
237
- evaluate(expr, merged[0], merged[1], merged[2], merged[3]);
237
+ evaluateDisplay(expr, [...merged], displayOnly);
238
238
  }
239
239
 
240
240
  if (config.storeVar) {
@@ -326,7 +326,5 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
326
326
  if (config.subMacros) {
327
327
  for (const sub of config.subMacros) registerSubMacro(sub);
328
328
  }
329
- if (isBlock) {
330
- registerBlockMacro(config.name);
331
- }
329
+ setDefinedBlockMacro(config.name, isBlock);
332
330
  }
@@ -12,6 +12,8 @@ export const ACTING_MACROS: readonly string[] = [
12
12
  'computed',
13
13
  'goto',
14
14
  'watch',
15
+ 'unwatch',
16
+ 'widget',
15
17
  ];
16
18
 
17
19
  /**
package/src/expression.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import type { StoryState } from './store';
2
2
  import { useStoryStore } from './store';
3
3
  import type { Passage } from './parser';
4
- import { random, randomInt } from './prng';
4
+ import { random, randomInt, withoutDraws } from './prng';
5
5
  import {
6
6
  BINDINGS,
7
7
  FNS_BINDING,
@@ -211,6 +211,16 @@ export function evaluate(expr: string, ...namespaces: Namespaces): unknown {
211
211
  return run(getOrCompile(expr, 'expression'), ...namespaces);
212
212
  }
213
213
 
214
+ /** Evaluate display-only content without consuming gameplay randomness. */
215
+ export function evaluateDisplay(
216
+ expr: string,
217
+ namespaces: Namespaces,
218
+ displayOnly = false,
219
+ ): unknown {
220
+ const read = () => evaluate(expr, ...namespaces);
221
+ return displayOnly ? withoutDraws(read) : read();
222
+ }
223
+
214
224
  /**
215
225
  * Execute statements (no return value).
216
226
  * e.g. execute("$health = 100; $name = 'Hero'", variables, temporary)
@@ -6,6 +6,7 @@ import {
6
6
  interpolateText,
7
7
  type TextScope,
8
8
  } from '../interpolation';
9
+ import { DisplayOnlyContext } from '../display-only';
9
10
  import { errorMessage } from '../utils/error-message';
10
11
 
11
12
  /**
@@ -15,10 +16,18 @@ import { errorMessage } from '../utils/error-message';
15
16
  */
16
17
  export function useTextScope(): TextScope {
17
18
  const [variables, temporary, locals, transient] = useMergedLocals();
19
+ const displayOnly = useContext(DisplayOnlyContext);
18
20
  const widgetChildren = useContext(WidgetChildrenContext);
19
21
  return useMemo(
20
- () => ({ variables, temporary, locals, transient, widgetChildren }),
21
- [variables, temporary, locals, transient, widgetChildren],
22
+ () => ({
23
+ variables,
24
+ temporary,
25
+ locals,
26
+ transient,
27
+ widgetChildren,
28
+ displayOnly,
29
+ }),
30
+ [variables, temporary, locals, transient, widgetChildren, displayOnly],
22
31
  );
23
32
  }
24
33
 
@@ -481,7 +481,7 @@ export function useModalFocus(
481
481
  root.addEventListener(
482
482
  'load',
483
483
  (e) => {
484
- if (e.target instanceof Node && isFrame(e.target as Element)) {
484
+ if (e.target && isFrame(e.target as Element)) {
485
485
  attachFrame(e.target as HTMLIFrameElement);
486
486
  }
487
487
  },
@@ -13,7 +13,7 @@
13
13
  * one without a text form (inputs, links, {set}, …) has nothing to put in a
14
14
  * string, so it is reported instead of being run or shown as source.
15
15
  */
16
- import { evaluate } from './expression';
16
+ import { evaluateDisplay } from './expression';
17
17
  import {
18
18
  SCOPE_SIGILS,
19
19
  SIGIL_SCOPES,
@@ -61,6 +61,7 @@ export function widgetChildrenOf(
61
61
 
62
62
  /** The scope text-only markup is evaluated in. */
63
63
  export interface TextScope {
64
+ displayOnly?: boolean;
64
65
  variables: Record<string, unknown>;
65
66
  temporary: Record<string, unknown>;
66
67
  locals: Record<string, unknown>;
@@ -171,12 +172,10 @@ function resolveVariable(
171
172
 
172
173
  /** Evaluate an expression in `scope`. */
173
174
  function evaluateIn(expr: string, scope: TextScope): unknown {
174
- return evaluate(
175
+ return evaluateDisplay(
175
176
  expr,
176
- scope.variables,
177
- scope.temporary,
178
- scope.locals,
179
- scope.transient,
177
+ [scope.variables, scope.temporary, scope.locals, scope.transient],
178
+ scope.displayOnly,
180
179
  );
181
180
  }
182
181
 
package/src/markup/ast.ts CHANGED
@@ -72,6 +72,19 @@ const BLOCK_MACROS = new NameSet([
72
72
  */
73
73
  const BLOCK_WIDGETS = new NameSet();
74
74
 
75
+ /** Classification owned by defineMacro, independent of explicit registrations. */
76
+ const DEFINED_BLOCK_MACROS = new NameSet();
77
+
78
+ export function setDefinedBlockMacro(name: string, isBlock: boolean): void {
79
+ setClassification(DEFINED_BLOCK_MACROS, name, isBlock);
80
+ }
81
+
82
+ /** Update the classification owned by one registration source. */
83
+ function setClassification(names: NameSet, name: string, block: boolean): void {
84
+ if (block) names.add(name);
85
+ else names.delete(name);
86
+ }
87
+
75
88
  /** Macros whose body is JavaScript source, kept verbatim. */
76
89
  const RAW_BODY_MACROS = new Set(['do']);
77
90
 
@@ -82,7 +95,11 @@ export function isRawMacro(name: string): boolean {
82
95
 
83
96
  /** Whether a macro takes a body closed by `{/name}`. */
84
97
  export function isBlockMacro(name: string): boolean {
85
- return BLOCK_MACROS.has(name) || BLOCK_WIDGETS.has(name);
98
+ return (
99
+ BLOCK_MACROS.has(name) ||
100
+ DEFINED_BLOCK_MACROS.has(name) ||
101
+ BLOCK_WIDGETS.has(name)
102
+ );
86
103
  }
87
104
 
88
105
  /** Register a custom macro as a block macro so the parser nests children. */
@@ -95,8 +112,7 @@ export function registerBlockMacro(name: string): void {
95
112
  * does. A block macro registered under the same name stays a block.
96
113
  */
97
114
  export function setBlockWidget(name: string, isBlock: boolean): void {
98
- if (isBlock) BLOCK_WIDGETS.add(name);
99
- else BLOCK_WIDGETS.delete(name);
115
+ setClassification(BLOCK_WIDGETS, name, isBlock);
100
116
  }
101
117
 
102
118
  /** Forget which widgets take a body (see clearWidgets). */
@@ -107,6 +123,7 @@ export function clearBlockWidgets(): void {
107
123
  /** Unregister a custom block macro (for test cleanup). */
108
124
  export function unregisterBlockMacro(name: string): void {
109
125
  BLOCK_MACROS.delete(name);
126
+ DEFINED_BLOCK_MACROS.delete(name);
110
127
  }
111
128
 
112
129
  /** Macros whose branches render as one: the node holds one per branch. */