@rohal12/spindle 0.63.0 → 0.64.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -10,7 +10,7 @@
10
10
  * runtime reads it, or, when it matches one further out, closes that one and
11
11
  * what was open inside it stays unclosed.
12
12
  */
13
- import { branchParents } from '../registry';
13
+ import { branchParents, getMacroParameters } from '../registry';
14
14
  import { sourcePositions } from './line-column';
15
15
  import { isBlockMacro, isRawMacro } from './ast';
16
16
  import type { HtmlToken, MacroToken, Span, Token } from './tokens';
@@ -153,13 +153,15 @@ export function pairMarkup(
153
153
  const isBlock = options.isBlock ?? isBlockMacro;
154
154
  const isRaw = options.isRaw ?? isRawMacro;
155
155
  const parentsOf = (name: string): readonly string[] => {
156
+ if (options.branchParents) return options.branchParents(name);
157
+ const registered = branchParents(name);
156
158
  const lower = name.toLowerCase();
157
159
  const builtin = Object.prototype.hasOwnProperty.call(BRANCH_PARENT, lower)
158
160
  ? BRANCH_PARENT[lower]
159
161
  : undefined;
160
- return builtin
161
- ? [builtin]
162
- : (options.branchParents?.(name) ?? branchParents(name));
162
+ return builtin && getMacroParameters.source(builtin) === undefined
163
+ ? [...registered, builtin]
164
+ : registered;
163
165
  };
164
166
  const errors: PairingError[] = [];
165
167
  const noticedAtEnd = (tokens[tokens.length - 1]?.end ?? 0) + 1;
@@ -226,7 +226,7 @@ function PlaceholderAttributes({
226
226
  const ref = useDirectAttributes(direct);
227
227
  return withAttributeErrors(
228
228
  errors,
229
- h(tag, ref ? { ...props, ref } : props, ...children),
229
+ h(tag, ref ? { ...props, ref } : props, children),
230
230
  );
231
231
  }
232
232
 
@@ -243,7 +243,7 @@ function DirectAttributes({
243
243
  children: preact.ComponentChildren[];
244
244
  }) {
245
245
  const ref = useDirectAttributes(direct);
246
- return h(tag, { ...props, ref }, ...children);
246
+ return h(tag, { ...props, ref }, children);
247
247
  }
248
248
 
249
249
  /** An error met while evaluating the named attribute. */
@@ -306,16 +306,20 @@ function htmlToPreact(
306
306
  unwrapParagraphs = false,
307
307
  ): preact.ComponentChildren {
308
308
  const content = parseHtmlInert(html.trim());
309
- if (unwrapParagraphs) {
310
- for (const child of Array.from(content.childNodes)) {
311
- if (child.nodeType === Node.ELEMENT_NODE && child.nodeName === 'P') {
312
- (child as Element).replaceWith(...Array.from(child.childNodes));
309
+ const children: preact.ComponentChildren[] = [];
310
+ for (const child of Array.from(content.childNodes)) {
311
+ if (
312
+ unwrapParagraphs &&
313
+ child.nodeType === Node.ELEMENT_NODE &&
314
+ child.nodeName === 'P'
315
+ ) {
316
+ for (const node of Array.from(child.childNodes)) {
317
+ children.push(convertDomNode(node, children.length, ph));
313
318
  }
319
+ } else {
320
+ children.push(convertDomNode(child, children.length, ph));
314
321
  }
315
322
  }
316
- const children = Array.from(content.childNodes).map((child, i) =>
317
- convertDomNode(child, i, ph),
318
- );
319
323
  return <>{children}</>;
320
324
  }
321
325
 
@@ -392,7 +396,7 @@ function convertDomNode(
392
396
  />
393
397
  );
394
398
  }
395
- return h(tag, { ...props, key }, ...children);
399
+ return h(tag, { ...props, key }, children);
396
400
  }
397
401
  return null;
398
402
  }
@@ -1047,7 +1051,7 @@ function buildPlainTextVnodes(
1047
1051
  const children = expandPlaceholderText(trimLineEdges(core), ph).filter(
1048
1052
  (part) => part !== '',
1049
1053
  );
1050
- return unwrapParagraphs ? <>{children}</> : h('p', null, ...children);
1054
+ return unwrapParagraphs ? <>{children}</> : h('p', null, children);
1051
1055
  }
1052
1056
 
1053
1057
  /**
@@ -1111,20 +1115,24 @@ export function renderNodes(
1111
1115
  components,
1112
1116
  nodes: [],
1113
1117
  };
1114
- let combined = '';
1118
+ const chunks: string[] = [];
1119
+ let trailingBackslash = false;
1115
1120
 
1116
1121
  for (let i = 0; i < nodes.length; i++) {
1117
1122
  const node = nodes[i]!;
1118
1123
  if (node.type === 'text') {
1119
- combined += node.value;
1124
+ chunks.push(node.value);
1125
+ if (node.value) trailingBackslash = node.value.endsWith('\\');
1120
1126
  continue;
1121
1127
  }
1122
1128
  const phIdx = components.length;
1123
1129
  components.push(renderSingleNode(node));
1124
1130
  ph.nodes.push(node);
1125
- if (combined.endsWith('\\')) combined += ESCAPE_GUARD;
1126
- combined += placeholderHtml(ph.nonce, phIdx);
1131
+ if (trailingBackslash) chunks.push(ESCAPE_GUARD);
1132
+ chunks.push(placeholderHtml(ph.nonce, phIdx));
1133
+ trailingBackslash = false;
1127
1134
  }
1135
+ const combined = chunks.join('');
1128
1136
 
1129
1137
  // Fast path: skip micromark + innerHTML when text has no markdown syntax.
1130
1138
  // This eliminates ~655 innerHTML calls on plain UI text like "ALMA",
package/src/registry.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { ComponentType } from 'preact';
2
2
  import type { ASTNode, Branch } from './markup/ast';
3
+ import { consumesOptionClauses } from './components/macros/option-clauses';
3
4
  import {
4
5
  effectiveNamedDefinitions,
5
6
  NameMap,
@@ -247,10 +248,19 @@ export function registerMacroMetadata(
247
248
  }
248
249
  }
249
250
  metadataRegistry.set(name, metadata);
250
- for (const sub of metadata.subMacros) {
251
- const parents = companionParents.get(sub) ?? new Set<string>();
252
- parents.add(metadata.name.toLowerCase());
253
- companionParents.set(sub, parents);
251
+ indexCompanionParents(companionParents, metadata);
252
+ }
253
+
254
+ /** Share index construction between live registrations and stateless tooling. */
255
+ function indexCompanionParents(
256
+ index: NameMap<Set<string>>,
257
+ macro: Pick<MacroMetadata, 'name' | 'subMacros'>,
258
+ ): void {
259
+ const name = macro.name.toLowerCase();
260
+ for (const sub of macro.subMacros) {
261
+ const parents = index.get(sub) ?? new Set<string>();
262
+ parents.add(name);
263
+ index.set(sub, parents);
254
264
  }
255
265
  }
256
266
 
@@ -261,17 +271,27 @@ export function branchParents(
261
271
  ): string[] {
262
272
  if (!macros) {
263
273
  return [...(companionParents.get(name) ?? [])].filter(
264
- (parent) => parent !== 'listbox' && parent !== 'cycle',
274
+ (parent) => !consumesOptionClauses(metadataRegistry.get(parent)!),
265
275
  );
266
276
  }
267
- return effectiveNamedDefinitions(macros)
268
- .filter(
269
- (macro) =>
270
- macro.name.toLowerCase() !== 'listbox' &&
271
- macro.name.toLowerCase() !== 'cycle' &&
272
- macro.subMacros.some((sub) => sub.toLowerCase() === name.toLowerCase()),
273
- )
274
- .map((macro) => macro.name.toLowerCase());
277
+ return [...branchParentLookup(macros)(name)];
278
+ }
279
+
280
+ /** Build once per effective metadata snapshot, then look up each token. */
281
+ export function branchParentLookup(
282
+ macros: readonly (Pick<MacroMetadata, 'name' | 'subMacros'> & {
283
+ source?: 'builtin' | 'user';
284
+ widget?: unknown;
285
+ })[],
286
+ ): (name: string) => readonly string[] {
287
+ const parents = new NameMap<Set<string>>();
288
+ for (const macro of effectiveNamedDefinitions(macros)) {
289
+ if (consumesOptionClauses(macro)) continue;
290
+ indexCompanionParents(parents, macro);
291
+ }
292
+ const index = new NameMap<readonly string[]>();
293
+ for (const [sub, names] of parents) index.set(sub, [...names]);
294
+ return (name) => index.get(name) ?? [];
275
295
  }
276
296
 
277
297
  /** The declared parameters of the macro `name`, if it declares any. */
@@ -25,6 +25,7 @@ import {
25
25
  widgetPieces,
26
26
  withParseCache,
27
27
  executesRawBody,
28
+ macroArgumentLookup,
28
29
  type ParametersOf,
29
30
  type Piece,
30
31
  } from './code-check';
@@ -802,6 +803,7 @@ function collectTokenRefs(
802
803
  options: ReferenceOptions,
803
804
  ): void {
804
805
  const { storeVarMacros, parametersOf } = options;
806
+ const argumentRole = macroArgumentLookup(tokens, parametersOf);
805
807
  for (let t = 0; t < tokens.length; t++) {
806
808
  const token = tokens[t]!;
807
809
  if (
@@ -845,29 +847,38 @@ function collectTokenRefs(
845
847
  else scanInterpolations(value, valueIn, emit, options);
846
848
  }
847
849
  } else if (token.type === 'macro' && !token.isClose) {
850
+ const role = argumentRole(token);
848
851
  const binding =
852
+ role === 'invocation' &&
849
853
  storeVarMacros.has(token.name.toLowerCase()) &&
850
854
  !parametersOf.widget?.(token.name)
851
855
  ? boundReference(token, at, options.all)
852
856
  : undefined;
853
- scanArgs(
854
- token,
855
- parametersOf,
856
- at,
857
- (ref) => {
858
- // A parameterless custom storeVar macro also scans its arguments
859
- // as code. Keep the binding's decoded path and span just once.
860
- if (!binding || ref.start < binding.start || ref.start >= binding.end)
861
- emit(ref);
862
- },
863
- options,
864
- );
857
+ if (role === 'condition') {
858
+ scanCode(token.rawArgs, (i) => at(token.argsStart + i), emit);
859
+ } else if (role === 'invocation')
860
+ scanArgs(
861
+ token,
862
+ parametersOf,
863
+ at,
864
+ (ref) => {
865
+ // A parameterless custom storeVar macro also scans its arguments
866
+ // as code. Keep the binding's decoded path and span just once.
867
+ if (
868
+ !binding ||
869
+ ref.start < binding.start ||
870
+ ref.start >= binding.end
871
+ )
872
+ emit(ref);
873
+ },
874
+ options,
875
+ );
865
876
  // Selectors (`{.{$cls} button}`) are interpolated when rendered
866
877
  scanSelectors(content, token, at, emit, options);
867
878
 
868
879
  if (binding) emit(binding);
869
880
 
870
- if (executesRawBody(token.name, parametersOf)) {
881
+ if (role === 'invocation' && executesRawBody(token.name, parametersOf)) {
871
882
  // A {do} body is JavaScript: scan its source text as code, however
872
883
  // the markup tokens split it up.
873
884
  let close = t + 1;
package/src/tooling.ts CHANGED
@@ -4,7 +4,12 @@ export {
4
4
  type CompletionContext,
5
5
  type CompletionContainer,
6
6
  } from './completion-context';
7
- import { branchParents } from './registry';
7
+ import { branchParentLookup } from './registry';
8
+ import {
9
+ consumesOptionClauses,
10
+ isOptionClause,
11
+ } from './components/macros/option-clauses';
12
+ import { pairMarkup, type PairedNode } from './markup/pair';
8
13
  /**
9
14
  * What the tooling entry point (`@rohal12/spindle/tooling`) bundles as
10
15
  * dist/pkg/story-variables.js: the StoryVariables parser and the markup
@@ -16,7 +21,12 @@ import {
16
21
  type MarkupDiagnostic,
17
22
  type MarkupPassage,
18
23
  } from './markup/validate';
19
- import { isBlockMacro, isRawMacro, isRegisteredBlockMacro } from './markup/ast';
24
+ import {
25
+ isBlockMacro,
26
+ isBuiltinBlockMacro,
27
+ isRawMacro,
28
+ isRegisteredBlockMacro,
29
+ } from './markup/ast';
20
30
  import {
21
31
  tokenizeMarkup as tokenizeRawMarkup,
22
32
  tokenizeMarkupTolerant as tokenizeRawMarkupTolerant,
@@ -44,7 +54,7 @@ import {
44
54
  type VariableReference,
45
55
  } from './story-variables';
46
56
  import type { ParameterDef } from './registry';
47
- import type { Token } from './markup/tokens';
57
+ import type { MacroToken, Token } from './markup/tokens';
48
58
  import type { WidgetDef } from './widgets/widget-def';
49
59
 
50
60
  export { parseDeclarations, parseStoryVariables } from './story-variables';
@@ -232,7 +242,7 @@ function tokenizationOptions(
232
242
  isRaw: (name) =>
233
243
  isRawMacro(name, parametersOf.widget?.(name) !== undefined),
234
244
  isBlock: blockLookup(macros),
235
- branchParents: (name) => branchParents(name, macros),
245
+ branchParents: branchParentLookup(macros),
236
246
  ...options.hooks,
237
247
  },
238
248
  };
@@ -272,6 +282,15 @@ export function validateStoryMarkup(
272
282
  const widgets = effectiveWidgetDefinitions(
273
283
  readWidgetDefinitions(list, parameterLookup(all)),
274
284
  );
285
+ const effective = effectiveToolingMacros([
286
+ ...all,
287
+ ...widgets.map((widget) => ({
288
+ name: widget.name,
289
+ block: widget.block,
290
+ subMacros: [],
291
+ widget,
292
+ })),
293
+ ]);
275
294
  const parametersOf = parameterLookup([
276
295
  ...all,
277
296
  ...definedWidgetMacros(widgets),
@@ -282,19 +301,11 @@ export function validateStoryMarkup(
282
301
  for (const sub of macro.subMacros) known.add(sub.toLowerCase());
283
302
  }
284
303
  return validateMarkup(list, {
285
- branchParents: (name) => branchParents(name, all),
304
+ branchParents: branchParentLookup(effective),
286
305
  isKnownMacro: (name) => known.has(name),
287
306
  macroNames: known,
288
307
  parametersOf,
289
- isBlockMacro: blockLookup([
290
- ...all,
291
- ...widgets.map((w) => ({
292
- name: w.name,
293
- block: w.block,
294
- subMacros: [],
295
- widget: w,
296
- })),
297
- ]),
308
+ isBlockMacro: blockLookup(effective),
298
309
  checkPassageNames: options.checkPassageNames,
299
310
  tolerant: options.tolerant,
300
311
  });
@@ -306,14 +317,100 @@ function definedWidgetMacros(widgets: readonly WidgetDefinition[]) {
306
317
  }
307
318
 
308
319
  /** Whether a macro takes a body, among `macros` and the built-in ones. */
309
- function blockLookup(macros: readonly ToolingMacro[]) {
320
+ function blockLookup(macros: readonly ToolingMacro[], includeRuntime = true) {
310
321
  const definitions = new NameMap<boolean>();
311
322
  for (const macro of effectiveToolingMacros(macros)) {
312
323
  definitions.set(macro.name, macro.block);
313
324
  }
314
325
  return (name: string) =>
315
- isRegisteredBlockMacro(name) ||
316
- (definitions.get(name) ?? isBlockMacro(name));
326
+ (includeRuntime && isRegisteredBlockMacro(name)) ||
327
+ (definitions.get(name) ??
328
+ (includeRuntime ? isBlockMacro(name) : isBuiltinBlockMacro(name)));
329
+ }
330
+
331
+ /** A macro head's contextual role, with original UTF-16 token spans. */
332
+ export interface MacroCall {
333
+ token: MacroToken;
334
+ kind: 'invocation' | 'branch' | 'value';
335
+ /** The opening head consuming this clause; absent for invocations. */
336
+ owner?: MacroToken;
337
+ }
338
+
339
+ /**
340
+ * Classify heads against explicit effective metadata, without running code.
341
+ * Labels and attributes are separate markup scopes and never inherit a
342
+ * surrounding control's clause ownership. This describes dispatch, not
343
+ * whether a conditional body will execute.
344
+ */
345
+ export function macroCalls(
346
+ source: string,
347
+ macros: Iterable<ToolingMacro> = [],
348
+ ): MacroCall[] {
349
+ const all = effectiveToolingMacros(macros);
350
+ const definitions = new NameMap(all.map((macro) => [macro.name, macro]));
351
+ const parametersOf = parameterLookup(all);
352
+ const options = tokenizationOptions({
353
+ macros: all,
354
+ hooks: { isBlock: blockLookup(all, false) },
355
+ });
356
+ const hooks = options.hooks!;
357
+ const tokens = tokenizeRawMarkupTolerant(source, options).tokens;
358
+ const calls: MacroCall[] = [];
359
+ const classify = (tokens: readonly Token[]) => {
360
+ const found = new Map<MacroToken, MacroCall>();
361
+ const pending: { node: PairedNode; parent?: MacroToken }[] = pairMarkup(
362
+ tokens,
363
+ hooks,
364
+ ).nodes.map((node) => ({ node }));
365
+ while (pending.length) {
366
+ const { node, parent } = pending.pop()!;
367
+ const token = node.token;
368
+ if (token.type === 'macro') {
369
+ const definition = parent && definitions.get(parent.name);
370
+ const value =
371
+ definition &&
372
+ consumesOptionClauses(definition) &&
373
+ isOptionClause(token.name);
374
+ found.set(token, {
375
+ token,
376
+ kind: value ? 'value' : 'invocation',
377
+ ...(value && { owner: parent }),
378
+ });
379
+ }
380
+ if (!node.body) continue;
381
+ const owner = token.type === 'macro' ? token : undefined;
382
+ for (const child of node.body.children)
383
+ pending.push({ node: child, parent: owner });
384
+ for (const branch of node.body.branches) {
385
+ found.set(branch.tag, { token: branch.tag, kind: 'branch', owner });
386
+ for (const child of branch.children)
387
+ pending.push({ node: child, parent: owner });
388
+ }
389
+ }
390
+ for (const token of tokens) {
391
+ if (token.type !== 'macro' || token.isClose) continue;
392
+ const call = found.get(token) ?? { token, kind: 'branch' as const };
393
+ calls.push(call);
394
+ }
395
+ };
396
+ classify(tokens);
397
+ for (const piece of passagePiecesOf(source, tokens, parametersOf, {
398
+ isBlock: hooks.isBlock,
399
+ })) {
400
+ if (piece.kind !== 'text' || !piece.tokens.length) continue;
401
+ classify(piece.tokens);
402
+ }
403
+ // Consumed arguments are literal even if a same-named widget would
404
+ // normally evaluate them as markup. Drop heads inside those arguments.
405
+ let literalEnd = -1;
406
+ return calls
407
+ .sort((a, b) => a.token.start - b.token.start)
408
+ .filter((call) => {
409
+ if (call.token.start < literalEnd) return false;
410
+ if (call.kind === 'value' || call.kind === 'branch')
411
+ literalEnd = call.token.argsEnd;
412
+ return true;
413
+ });
317
414
  }
318
415
 
319
416
  /**
@@ -982,6 +982,26 @@ export interface PairingError {
982
982
  data: Record<string, string>;
983
983
  }
984
984
 
985
+ /** A macro head’s contextual dispatch role. */
986
+ export interface MacroCall {
987
+ /** Opening macro head, with UTF-16 spans in the original source. */
988
+ token: MacroToken;
989
+ kind: 'invocation' | 'branch' | 'value';
990
+ /** Opening head consuming this clause; absent for invocations or stray branches. */
991
+ owner?: MacroToken;
992
+ }
993
+
994
+ /**
995
+ * Classify macro heads using explicit effective macro/widget metadata.
996
+ * Includes independently evaluated labels and attributes, with original
997
+ * source spans. Tolerates malformed markup. Describes dispatch, not whether
998
+ * a conditional body executes. Pass builtinMacros to enable builtin rules.
999
+ */
1000
+ export function macroCalls(
1001
+ source: string,
1002
+ macros?: Iterable<ToolingMacro>,
1003
+ ): MacroCall[];
1004
+
985
1005
  /** A branch (`{else}`, `{case}`, …) of a macro, with what follows it. */
986
1006
  export interface PairedBranch {
987
1007
  tag: MacroToken;