@rohal12/spindle 0.62.6 → 0.62.8

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.
@@ -19,7 +19,12 @@ import type { Span as SourceSpan } from '../../markup/tokens';
19
19
  import type { MacroArgs, ParameterDef } from '../../registry';
20
20
  import type { StoryState } from '../../store';
21
21
  import { noPassageError } from '../../runtime-errors';
22
- import { stringLiteralValue } from '../../js-lexer';
22
+ import {
23
+ parseMemberIdentifier,
24
+ parseReferencePath,
25
+ stringLiteralValue,
26
+ } from '../../js-lexer';
27
+ import { RESERVED_NAME } from '../../utils/namespace';
23
28
  import {
24
29
  endsWithOperator,
25
30
  isWhitespace,
@@ -451,6 +456,84 @@ export function readBoundVariable(rawArgs: string): string {
451
456
  return first ? slice(src, first) : '';
452
457
  }
453
458
 
459
+ /** A runtime input binding, with UTF-16 spans into the raw arguments. */
460
+ export interface BoundVariable extends SourceSpan {
461
+ /** Decoded story-variable root and dot members. */
462
+ name: string;
463
+ path: string[];
464
+ /** Whether the author wrote the optional literal `$` sigil. */
465
+ explicitSigil: boolean;
466
+ /** Editable root spelling, excluding quotes, sigil and dot members. */
467
+ nameStart: number;
468
+ nameEnd: number;
469
+ }
470
+
471
+ /**
472
+ * Read the first term as the runtime's story-variable binding. Quotes are
473
+ * stripped, but this is an identifier path, not a JavaScript string literal:
474
+ * only identifier escapes are decoded. Returns null for a missing binding;
475
+ * throws for rejected namespaces, invalid escapes and reserved path names.
476
+ * The full span excludes quotes and includes the sigil when written.
477
+ */
478
+ export function parseBoundVariable(rawArgs: string): BoundVariable | null {
479
+ const term = readBoundVariable(rawArgs);
480
+ if (!term) return null;
481
+ const lead = rawArgs.length - rawArgs.trimStart().length;
482
+ const offsets: number[] = [];
483
+ for (let i = 0; i < term.length; i++) {
484
+ if (term[i] !== '"' && term[i] !== "'") offsets.push(lead + i);
485
+ }
486
+ const firstToken = term.replace(/["']/g, '');
487
+ const unbindable: Record<string, string> = {
488
+ '%': 'transient variables',
489
+ _: 'temporary variables',
490
+ '@': 'locals',
491
+ };
492
+ const kind = unbindable[firstToken.charAt(0)];
493
+ if (kind) {
494
+ throw new Error(`${kind} (${firstToken}) cannot be bound to input macros`);
495
+ }
496
+ const explicitSigil = firstToken.startsWith('$');
497
+ if (!explicitSigil && firstToken.split('.')[0]!.includes('\\')) {
498
+ throw new Error(
499
+ 'Escaped binding identifiers require a literal $ story-variable sigil',
500
+ );
501
+ }
502
+ const segments = firstToken
503
+ .replace(/^\$/, '')
504
+ .split('.')
505
+ .map((segment, index) => {
506
+ if (!segment.includes('\\')) return segment;
507
+ if (index > 0) {
508
+ const name = parseMemberIdentifier(segment);
509
+ if (name === null) throw new Error('Invalid bound identifier');
510
+ return name;
511
+ }
512
+ const reference = parseReferencePath(`$${segment}`);
513
+ if (!reference || reference.nested)
514
+ throw new Error('Invalid bound identifier');
515
+ return reference.name;
516
+ });
517
+ if (segments.includes(RESERVED_NAME)) {
518
+ throw new Error(
519
+ `"$${segments.join('.')}" cannot be bound: ${RESERVED_NAME} is reserved`,
520
+ );
521
+ }
522
+ const rootStart = explicitSigil ? 1 : 0;
523
+ const rootEnd = firstToken.indexOf('.', rootStart);
524
+ const nameEnd = rootEnd < 0 ? firstToken.length : rootEnd;
525
+ return {
526
+ name: segments[0]!,
527
+ path: segments.slice(1),
528
+ explicitSigil,
529
+ start: offsets[0] ?? lead,
530
+ end: offsets.length ? offsets[offsets.length - 1]! + 1 : lead,
531
+ nameStart: offsets[rootStart] ?? lead + rootStart,
532
+ nameEnd:
533
+ offsets[nameEnd - 1] === undefined ? lead : offsets[nameEnd - 1]! + 1,
534
+ };
535
+ }
536
+
454
537
  /** A consumed argument and its declared parameter, with UTF-16 source offsets. */
455
538
  export interface MacroArgumentSpan extends SourceSpan {
456
539
  /** The original parameter object, including for nested keyword options. */
@@ -29,8 +29,6 @@ import { executeMutation, mutateState, readState } from './execute-mutation';
29
29
  import { evaluateDisplay } from './expression';
30
30
  import { useStoryFields } from './hooks/use-story-fields';
31
31
  import { getByPath, setByPath } from './utils/object-path';
32
- import { RESERVED_NAME } from './utils/namespace';
33
- import { parseMemberIdentifier, parseReferencePath } from './js-lexer';
34
32
  import { useAction } from './hooks/use-action';
35
33
  import type { UseActionOptions } from './hooks/use-action';
36
34
  import { collectText } from './utils/extract-text';
@@ -40,7 +38,7 @@ import { wrapContent } from './components/macros/display';
40
38
  import {
41
39
  MacroArgumentError,
42
40
  parseMacroArgs,
43
- readBoundVariable,
41
+ parseBoundVariable,
44
42
  } from './components/macros/macro-args';
45
43
  import { MacroError } from './components/macros/MacroError';
46
44
  import {
@@ -241,66 +239,14 @@ export function defineMacro<const P extends readonly ParameterDef[] = []>(
241
239
  }
242
240
 
243
241
  if (config.storeVar) {
244
- const firstToken = readBoundVariable(props.rawArgs).replace(/["']/g, '');
245
-
246
- // Only story variables ($name) can be bound: another sigil would be
247
- // read as a story key spelled with it (#414)
248
- const unbindable: Record<string, string> = {
249
- '%': 'transient variables',
250
- _: 'temporary variables',
251
- '@': 'locals',
252
- };
253
- const kind = unbindable[firstToken.charAt(0)];
254
- if (kind) {
255
- return h(
256
- 'span',
257
- { class: 'error' },
258
- `{${config.name}}: ${kind} (${firstToken}) cannot be bound to input macros`,
259
- );
260
- }
261
-
262
- if (
263
- !firstToken.startsWith('$') &&
264
- firstToken.split('.')[0]!.includes('\\')
265
- ) {
266
- return h(MacroError, {
267
- macro: config.name,
268
- error: new Error(
269
- 'Escaped binding identifiers require a literal $ story-variable sigil',
270
- ),
271
- });
272
- }
273
-
274
242
  let segments: string[];
275
243
  try {
276
- segments = firstToken
277
- .replace(/^\$/, '')
278
- .split('.')
279
- .map((segment, index) => {
280
- if (!segment.includes('\\')) return segment;
281
- // Members follow JavaScript's identifier grammar, which accepts
282
- // more names than story-variable roots (for example $foo and é).
283
- if (index > 0) {
284
- const name = parseMemberIdentifier(segment);
285
- if (name === null) throw new Error('Invalid bound identifier');
286
- return name;
287
- }
288
- const reference = parseReferencePath(`$${segment}`);
289
- if (!reference || reference.nested)
290
- throw new Error('Invalid bound identifier');
291
- return reference.name;
292
- });
244
+ const binding = parseBoundVariable(props.rawArgs);
245
+ segments = binding ? [binding.name, ...binding.path] : [''];
293
246
  } catch (error) {
294
247
  return h(MacroError, { macro: config.name, error });
295
248
  }
296
249
  const varExpr = segments.join('.');
297
- if (segments.includes(RESERVED_NAME)) {
298
- return h(
299
- 'span',
300
- { class: 'error' },
301
- `{${config.name}}: "$${varExpr}" cannot be bound: ${RESERVED_NAME} is reserved`,
302
- );
303
- }
304
250
  ctx.varName = varExpr;
305
251
  ctx.value = getByPath(useStoryFields('variables').variables, segments);
306
252
  // In program order, also when mutation code performs the input
package/src/headless.ts CHANGED
@@ -8,6 +8,7 @@
8
8
  * same boot sequence directly.
9
9
  */
10
10
  import { boot } from './index';
11
+ import { readOnlyValue } from './execute-mutation';
11
12
  import { isSpecialPassage, useStoryStore } from './store';
12
13
  import { noPassageError, specialPassageError } from './runtime-errors';
13
14
  import type { StoryAPI } from './story-api';
@@ -87,11 +88,11 @@ export function bootStory(options: BootStoryOptions): Promise<StoryAPI> {
87
88
  }
88
89
 
89
90
  /**
90
- * The story's `$` variables: a shallow copy of the current values, keyed by
91
- * name without the `$`. Values are the store's own (frozen) objects.
91
+ * The story's `$` variables, keyed by name without the `$`. Mutable values
92
+ * are copied together, preserving aliases without exposing live state.
92
93
  */
93
94
  export function storyVariables(): Record<string, unknown> {
94
- return { ...useStoryStore.getState().variables };
95
+ return { ...readOnlyValue(useStoryStore.getState().variables) };
95
96
  }
96
97
 
97
98
  /**
@@ -1,4 +1,9 @@
1
- import { composedParent, isRendered } from '../utils/element-visibility';
1
+ import {
2
+ composedChildren,
3
+ composedElements,
4
+ composedParent,
5
+ isRendered,
6
+ } from '../utils/element-visibility';
2
7
  import { useLayoutEffect } from 'preact/hooks';
3
8
  import type { RefObject } from 'preact';
4
9
 
@@ -17,24 +22,6 @@ const FOCUSABLE = [
17
22
  '[tabindex]',
18
23
  ].join(',');
19
24
 
20
- function composedChildren(root: ParentNode): Element[] {
21
- if ((root as Element).localName === 'slot') {
22
- const assigned = (root as HTMLSlotElement).assignedNodes({
23
- flatten: true,
24
- });
25
- return assigned.filter((node): node is Element => node.nodeType === 1);
26
- }
27
- return Array.from(root.children);
28
- }
29
-
30
- /** Authored elements in rendered order; unassigned light DOM is not rendered. */
31
- function* composedElements(root: ParentNode): Generator<HTMLElement> {
32
- for (const el of composedChildren(root)) {
33
- yield el as HTMLElement;
34
- yield* composedElements(el.shadowRoot ?? el);
35
- }
36
- }
37
-
38
25
  /**
39
26
  * Whether `el` can be focused at all: shown, rendered, enabled (also by its
40
27
  * fieldset) and not inert.
package/src/markup/ast.ts CHANGED
@@ -5,6 +5,7 @@
5
5
  import { withSelectors, type Selectors, type VariableScope } from './tokens';
6
6
  import type { PairedBranch, PairedNode } from './pair';
7
7
  import { NameSet } from '../utils/macro-names';
8
+ import { getMacroParameters } from '../registry';
8
9
 
9
10
  export interface TextNode {
10
11
  type: 'text';
@@ -184,7 +185,10 @@ function astNode({ token, body }: PairedNode): ASTNode {
184
185
  };
185
186
  if (!body) return withSelectors(node, token);
186
187
  const children = buildAst(body.children);
187
- const branching = BRANCHING.has(name) && !WIDGETS.has(name);
188
+ const branching =
189
+ BRANCHING.has(name) &&
190
+ !WIDGETS.has(name) &&
191
+ getMacroParameters.source(name) !== 'user';
188
192
  if (!branching && body.branches.length === 0) {
189
193
  node.children = children;
190
194
  return withSelectors(node, token);
@@ -1,5 +1,6 @@
1
1
  import { isSigil } from './tokens';
2
2
  import { indexCodeEnds } from './code-end';
3
+ import { lexJs } from '../js-lexer';
3
4
 
4
5
  /**
5
6
  * Attributes whose value is code with braces of its own, not text: event
@@ -23,7 +24,7 @@ export type SigilPart =
23
24
  * Split a code attribute value into literal text and its `{…}` blocks that
24
25
  * start with a sigil. Braces inside strings don't close a block; an
25
26
  * unclosed block, any other brace and backslashes are text. A block whose
26
- * sigil is not followed by a word character (`{$(…)}`) is code, kept
27
+ * sigil is not followed by an identifier (`{$(…)}`) is code, kept
27
28
  * verbatim: not resolved, and not decoded like text.
28
29
  */
29
30
  export function splitSigilTemplate(
@@ -52,9 +53,16 @@ export function splitSigilTemplate(
52
53
  if (text) parts.push({ text });
53
54
  text = '';
54
55
  const block = template.slice(i, end);
56
+ let reference = /^.\w/.test(block);
57
+ if (!reference && block[1] === '\\') {
58
+ lexJs(block, {
59
+ variable(_sigil, _name, start) {
60
+ if (start === 0) reference = true;
61
+ },
62
+ });
63
+ }
55
64
  parts.push(
56
- /^.\w/.test(block) ||
57
- (incomplete && block.length === 1 && end === template.length)
65
+ reference || (incomplete && block.length === 1 && end === template.length)
58
66
  ? { expr: block }
59
67
  : { verbatim: `{${block}}` },
60
68
  );
@@ -1,3 +1,5 @@
1
+ import { upperBound } from '../utils/sorted';
2
+
1
3
  /** 1-based line and column of `offset` in `text`. */
2
4
  export function lineColumn(
3
5
  text: string,
@@ -20,14 +22,7 @@ export function sourcePositions(text: string) {
20
22
  if (text[i] === '\n') starts.push(i + 1);
21
23
  }
22
24
  return (offset: number) => {
23
- let low = 0;
24
- let high = starts.length;
25
- while (low < high) {
26
- const mid = (low + high) >>> 1;
27
- if (starts[mid]! <= offset) low = mid + 1;
28
- else high = mid;
29
- }
30
- const line = Math.max(1, low);
25
+ const line = Math.max(1, upperBound(starts, offset));
31
26
  return { line, column: offset - starts[line - 1]! + 1 };
32
27
  };
33
28
  }
@@ -15,6 +15,7 @@ import type { Selectors, Token } from './tokens';
15
15
  import { isCodeAttribute } from './code-attributes';
16
16
  import { defaultCodeEnd, indexCodeEnds, type CodeEnd } from './code-end';
17
17
  import { lineColumn, sourcePositions } from './line-column';
18
+ import { upperBound } from '../utils/sorted';
18
19
 
19
20
  export { lineColumn };
20
21
 
@@ -163,8 +164,18 @@ export function analyzeMarkup(
163
164
  // A malformed tag is noticed where it starts, an unpaired tag where its
164
165
  // problem shows (see PairingError.noticedAt). Within a malformed tag the
165
166
  // markup is no markup: what the recovery pairs there is dropped.
166
- const inDamage = (start: number) =>
167
- errors.some((e, i) => start >= damage[i]! && start <= e.offset);
167
+ // Damage starts increase during recovery, but intervals can overlap. A
168
+ // prefix maximum keeps even nested damage searchable in logarithmic time.
169
+ const damageEnds: number[] = [];
170
+ for (const e of errors) {
171
+ damageEnds.push(
172
+ Math.max(damageEnds[damageEnds.length - 1] ?? -1, e.offset),
173
+ );
174
+ }
175
+ const inDamage = (start: number) => {
176
+ const index = upperBound(damage, start) - 1;
177
+ return index >= 0 && start <= damageEnds[index]!;
178
+ };
168
179
  const noticed: [number, MarkupError][] = errors.map((e, i) => [
169
180
  damage[i]! + 0.5,
170
181
  e,
@@ -651,7 +651,7 @@ function decodeText(text: string): string {
651
651
  }
652
652
 
653
653
  /** A `{` and a sigil starting a reference, in a code attribute. */
654
- const SIGIL_REFERENCE = /\{[$_@%]\w/;
654
+ const SIGIL_REFERENCE = /\{[$_@%][\w\\]/;
655
655
 
656
656
  const attributeNodes = new Map<string, ParsedText>();
657
657
  const ATTRIBUTE_CACHE_LIMIT = 2000;
@@ -1,4 +1,10 @@
1
- import { isHidden, isRendered } from '../utils/element-visibility';
1
+ import {
2
+ composedChildNodes,
3
+ composedElements,
4
+ composedParent,
5
+ isHidden,
6
+ isRendered,
7
+ } from '../utils/element-visibility';
2
8
  import { getAction } from '../action-registry';
3
9
 
4
10
  /** Elements that start and end a line. */
@@ -81,8 +87,11 @@ export function observableText(
81
87
 
82
88
  const walk = (node: Node, inPre: boolean) => {
83
89
  if (node.nodeType === 3) {
84
- if (node.parentElement && !isRendered(node.parentElement, visibilityRoot))
85
- return;
90
+ const parent =
91
+ (node as Text).assignedSlot ??
92
+ node.parentElement ??
93
+ (node.getRootNode() as ShadowRoot).host;
94
+ if (parent && !isRendered(parent, visibilityRoot)) return;
86
95
  const data = node.textContent ?? '';
87
96
  if (inPre) out += data;
88
97
  else {
@@ -114,9 +123,10 @@ export function observableText(
114
123
  if (block) endLine();
115
124
  const closedDetails =
116
125
  child.tagName === 'DETAILS' && !child.hasAttribute('open');
126
+ const rendered = composedChildNodes(child);
117
127
  const children = closedDetails
118
- ? Array.from(child.children).filter((c) => !isHidden(c))
119
- : Array.from(child.childNodes);
128
+ ? rendered.filter((c) => c.nodeType === 1 && !isHidden(c as Element))
129
+ : rendered;
120
130
  for (const c of children) {
121
131
  walk(c, inPre || child.tagName === 'PRE');
122
132
  }
@@ -148,14 +158,16 @@ export function observableErrors(
148
158
  visibilityRoot?: Element,
149
159
  ): string[] {
150
160
  const left = (e: Element) => {
151
- for (let at: Element | null = e; at; at = at.parentElement) {
161
+ for (let at: Element | null = e; at; at = composedParent(at)) {
152
162
  if (isHidden(at)) return true;
153
163
  if (at === el) return false;
154
164
  if (skip && at.matches(skip)) return true;
155
165
  }
156
166
  return false;
157
167
  };
158
- return Array.from(el.querySelectorAll('.error'))
159
- .filter((e) => !left(e) && isRendered(e, visibilityRoot))
168
+ return [...composedElements(el)]
169
+ .filter(
170
+ (e) => e.matches('.error') && !left(e) && isRendered(e, visibilityRoot),
171
+ )
160
172
  .map((e) => observableText(e, skip, visibilityRoot).trim());
161
173
  }
package/src/registry.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { ComponentType } from 'preact';
2
2
  import type { ASTNode, Branch } from './markup/ast';
3
- import { NameMap, NameSet } from './utils/macro-names';
3
+ import {
4
+ effectiveNamedDefinitions,
5
+ NameMap,
6
+ NameSet,
7
+ } from './utils/macro-names';
4
8
 
5
9
  export interface MacroProps {
6
10
  rawArgs: string;
@@ -260,7 +264,7 @@ export function branchParents(
260
264
  (parent) => parent !== 'listbox',
261
265
  );
262
266
  }
263
- return macros
267
+ return effectiveNamedDefinitions(macros)
264
268
  .filter(
265
269
  (macro) =>
266
270
  macro.name.toLowerCase() !== 'listbox' &&
@@ -29,8 +29,10 @@ import {
29
29
  import { getMacroParameters, type ParameterDef } from './registry';
30
30
  import {
31
31
  MacroArgumentError,
32
+ parseBoundVariable,
32
33
  parseMacroArgs,
33
34
  type ArgSpans,
35
+ type BoundVariable,
34
36
  } from './components/macros/macro-args';
35
37
  import { NOT_MARKUP } from './markup/validate';
36
38
  import {
@@ -88,8 +90,6 @@ function declarationRegex(sigil: string): RegExp {
88
90
  }
89
91
  /** A `$name` or `%name` reference with its dot path, at a sigil the lexer found. */
90
92
  const VAR_PATH_RE = /([$%])(\w+(?:\.\w+)*)/y;
91
- /** Quoted first argument of an input macro naming a story variable. */
92
- const QUOTED_VAR_ARG_RE = /^["']\$(\w+(?:\.\w+)*)["']?$/;
93
93
 
94
94
  const VALID_VAR_TYPES = new Set<string>(['number', 'string', 'boolean']);
95
95
 
@@ -376,6 +376,12 @@ export interface VariableReference {
376
376
  /** Where `$a.b.c` is written in the markup, as `[start, end)` UTF-16 offsets. */
377
377
  start: number;
378
378
  end: number;
379
+ /**
380
+ * For an input binding, its decoded identity and editable root span.
381
+ * Offsets are into the markup, including inside escaped labels. The sigil
382
+ * is semantically `$` even when `binding.explicitSigil` is false.
383
+ */
384
+ binding?: BoundVariable;
379
385
  }
380
386
 
381
387
  /** What a check of a variable reference found wrong with it. */
@@ -753,6 +759,38 @@ function scanSelectors(
753
759
  );
754
760
  }
755
761
 
762
+ /** Read a runtime binding and map its editable spans into the passage. */
763
+ function boundReference(
764
+ token: Extract<Token, { type: 'macro' }>,
765
+ at: At,
766
+ all: boolean | undefined,
767
+ ): VariableReference | undefined {
768
+ try {
769
+ const binding = parseBoundVariable(token.rawArgs);
770
+ // Sigilless bindings are part of the complete editor list, but do not
771
+ // change which references story startup checks.
772
+ if (!binding || (!all && !binding.explicitSigil)) return undefined;
773
+ const mapped = {
774
+ ...binding,
775
+ start: at(token.argsStart + binding.start),
776
+ end: at(token.argsStart + binding.end),
777
+ nameStart: at(token.argsStart + binding.nameStart),
778
+ nameEnd: at(token.argsStart + binding.nameEnd),
779
+ };
780
+ return {
781
+ sigil: '$',
782
+ name: binding.name,
783
+ path: binding.path,
784
+ start: mapped.start,
785
+ end: mapped.end,
786
+ binding: mapped,
787
+ };
788
+ } catch {
789
+ // Tolerant tooling skips bindings the runtime rejects.
790
+ return undefined;
791
+ }
792
+ }
793
+
756
794
  /** Report the `$var` references in the tokens of `content`. */
757
795
  function collectTokenRefs(
758
796
  content: string,
@@ -805,33 +843,27 @@ function collectTokenRefs(
805
843
  else scanInterpolations(value, valueIn, emit, options);
806
844
  }
807
845
  } else if (token.type === 'macro' && !token.isClose) {
808
- scanArgs(token, parametersOf, at, emit, options);
846
+ const binding =
847
+ storeVarMacros.has(token.name.toLowerCase()) &&
848
+ !parametersOf.widget?.(token.name)
849
+ ? boundReference(token, at, options.all)
850
+ : undefined;
851
+ scanArgs(
852
+ token,
853
+ parametersOf,
854
+ at,
855
+ (ref) => {
856
+ // A parameterless custom storeVar macro also scans its arguments
857
+ // as code. Keep the binding's decoded path and span just once.
858
+ if (!binding || ref.start < binding.start || ref.start >= binding.end)
859
+ emit(ref);
860
+ },
861
+ options,
862
+ );
809
863
  // Selectors (`{.{$cls} button}`) are interpolated when rendered
810
864
  scanSelectors(content, token, at, emit, options);
811
865
 
812
- if (
813
- storeVarMacros.has(token.name.toLowerCase()) &&
814
- !parametersOf.widget?.(token.name)
815
- ) {
816
- const lead = token.rawArgs.length - token.rawArgs.trimStart().length;
817
- const first = token.rawArgs.trim().split(/\s+/)[0] ?? '';
818
- const quoted = QUOTED_VAR_ARG_RE.exec(first);
819
- if (quoted) {
820
- const [name, ...path] = quoted[1]!.split('.');
821
- const start = token.argsStart + lead + 1;
822
- emit({
823
- sigil: '$',
824
- name: name!,
825
- path,
826
- start: at(start),
827
- end: at(start + 1 + quoted[1]!.length),
828
- });
829
- }
830
- // Unquoted, the variable is an argument of no declared role
831
- else if (!/^["'`]/.test(first)) {
832
- scanCode(first, (i) => at(token.argsStart + lead + i), emit);
833
- }
834
- }
866
+ if (binding) emit(binding);
835
867
 
836
868
  if (executesRawBody(token.name, parametersOf)) {
837
869
  // A {do} body is JavaScript: scan its source text as code, however
package/src/tooling.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { NameMap } from './utils/macro-names';
1
+ import { effectiveNamedDefinitions, NameMap } from './utils/macro-names';
2
2
  export {
3
3
  completionContext,
4
4
  type CompletionContext,
@@ -134,11 +134,13 @@ export {
134
134
  export { splitIncludeFlag } from './components/macros/include-args';
135
135
  export {
136
136
  macroArgumentSpans,
137
+ parseBoundVariable,
137
138
  evaluatePassageName,
138
139
  passageTarget,
139
140
  } from './components/macros/macro-args';
140
141
  export type {
141
142
  MacroArgumentSpan,
143
+ BoundVariable,
142
144
  PassageTarget,
143
145
  } from './components/macros/macro-args';
144
146
  export { transform } from './transform';
@@ -206,11 +208,22 @@ export interface ParseMarkupOptions extends RuntimeParseMarkupOptions {
206
208
  macros?: Iterable<ToolingMacro>;
207
209
  }
208
210
 
211
+ /** Widgets take precedence over macros regardless of metadata input order. */
212
+ function effectiveToolingMacros(
213
+ macros: Iterable<ToolingMacro>,
214
+ ): ToolingMacro[] {
215
+ const list = [...macros];
216
+ return effectiveNamedDefinitions([
217
+ ...list.filter((m) => !m.widget),
218
+ ...list.filter((m) => m.widget),
219
+ ]);
220
+ }
221
+
209
222
  function tokenizationOptions(
210
223
  options: ParseMarkupOptions,
211
224
  ): RuntimeParseMarkupOptions {
212
225
  if (!options.macros) return options;
213
- const macros = [...options.macros];
226
+ const macros = effectiveToolingMacros(options.macros);
214
227
  const parametersOf = parameterLookup(macros);
215
228
  return {
216
229
  ...options,
@@ -252,7 +265,7 @@ export function validateStoryMarkup(
252
265
  options: ValidateMarkupOptions = {},
253
266
  ): MarkupDiagnostic[] {
254
267
  const list = [...passages];
255
- const all = [...macros];
268
+ const all = effectiveToolingMacros(macros);
256
269
  const known = new Set<string>();
257
270
  // The calls of widgets that declare what their arguments hold are checked
258
271
  const widgets = effectiveWidgetDefinitions(
@@ -311,7 +324,7 @@ export function passagePieces(
311
324
  source: string,
312
325
  macros: Iterable<ToolingMacro> = [],
313
326
  ): Piece[] {
314
- const all = [...macros];
327
+ const all = effectiveToolingMacros(macros);
315
328
  const parametersOf = parameterLookup(all);
316
329
  return passagePiecesOfTokens(
317
330
  source,
@@ -335,7 +348,7 @@ export function passagePiecesOfTokens(
335
348
  macros: Iterable<ToolingMacro>,
336
349
  tokens: readonly Token[],
337
350
  ): Piece[] {
338
- const all = [...macros];
351
+ const all = effectiveToolingMacros(macros);
339
352
  return [
340
353
  ...passagePiecesOf(source, tokens, parameterLookup(all), {
341
354
  isBlock: blockLookup(all),
@@ -407,13 +420,15 @@ function referenceOptions(
407
420
  * in source order, with the dotted path of fields accessed and where each is
408
421
  * written (offsets into `source`, UTF-16): `{$var}` displays, code in
409
422
  * expressions, conditions, `{do}` bodies and macro arguments, quoted names
410
- * bound by input macros, and the markup in labels and HTML attributes. Prose
423
+ * bound by input macros, and the markup in labels and HTML attributes. Input
424
+ * bindings include decoded root/path names and editable `binding` spans. Prose
411
425
  * is literal text. Malformed tags are skipped, so it reads half-typed markup.
412
426
  * The macros are those the markup may use, built-in and user-defined.
413
427
  *
414
428
  * These are the references the story start checks. With `all: true`, the
415
429
  * list is complete (the checked ones are among it, in source order): it also
416
- * has the variable a macro names in a `variable` parameter, such as the
430
+ * has sigilless input bindings (`{textbox "name"}`), the variable a macro
431
+ * names in a `variable` parameter, such as the
417
432
  * target of `{unset}` and `{computed}`, and the `{$name}` in the selectors of
418
433
  * a link, display or expression (`[[.c{$name} Go->T]]`). A rename or a find
419
434
  * of references needs these too.
@@ -96,6 +96,15 @@ type SameShape<A, B> = Same<A, B> extends true ? Same<keyof A, keyof B> : false;
96
96
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
97
97
  type AssertTrue<T extends readonly true[]> = T;
98
98
  type ToolingChecks = [
99
+ Same<
100
+ typeof SourceTooling.parseBoundVariable,
101
+ typeof PublishedTooling.parseBoundVariable
102
+ >,
103
+ SameShape<SourceTooling.BoundVariable, PublishedTooling.BoundVariable>,
104
+ SameShape<
105
+ SourceTooling.VariableReference,
106
+ PublishedTooling.VariableReference
107
+ >,
99
108
  Same<typeof SourceTooling.parseCode, typeof PublishedTooling.parseCode>,
100
109
  Same<
101
110
  typeof SourceTooling.macroArgumentSpans,