@rohal12/spindle 0.62.5 → 0.62.7

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.
@@ -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,6 +1,8 @@
1
+ import { NameMap } from './utils/macro-names';
1
2
  export {
2
3
  completionContext,
3
4
  type CompletionContext,
5
+ type CompletionContainer,
4
6
  } from './completion-context';
5
7
  import { branchParents } from './registry';
6
8
  /**
@@ -15,7 +17,12 @@ import {
15
17
  type MarkupPassage,
16
18
  } from './markup/validate';
17
19
  import { isBlockMacro, isRawMacro } from './markup/ast';
18
- import { tokenizeMarkupTolerant } from './markup/parse';
20
+ import {
21
+ tokenizeMarkup as tokenizeRawMarkup,
22
+ tokenizeMarkupTolerant as tokenizeRawMarkupTolerant,
23
+ type ParseMarkupOptions as RuntimeParseMarkupOptions,
24
+ type TolerantTokens,
25
+ } from './markup/parse';
19
26
  import {
20
27
  parameterLookup,
21
28
  passagePiecesOf,
@@ -82,13 +89,8 @@ export type {
82
89
  JsLexHandlers,
83
90
  Sigil,
84
91
  } from './js-lexer';
85
- export {
86
- MarkupError,
87
- parseSelectors,
88
- tokenizeMarkup,
89
- tokenizeMarkupTolerant,
90
- } from './markup/parse';
91
- export type { ParseMarkupOptions, TolerantTokens } from './markup/parse';
92
+ export { MarkupError, parseSelectors } from './markup/parse';
93
+ export type { TolerantTokens } from './markup/parse';
92
94
  export { SIGIL_SCOPES, isSigil } from './markup/tokens';
93
95
  export type {
94
96
  AttributeSpan,
@@ -132,11 +134,13 @@ export {
132
134
  export { splitIncludeFlag } from './components/macros/include-args';
133
135
  export {
134
136
  macroArgumentSpans,
137
+ parseBoundVariable,
135
138
  evaluatePassageName,
136
139
  passageTarget,
137
140
  } from './components/macros/macro-args';
138
141
  export type {
139
142
  MacroArgumentSpan,
143
+ BoundVariable,
140
144
  PassageTarget,
141
145
  } from './components/macros/macro-args';
142
146
  export { transform } from './transform';
@@ -198,6 +202,46 @@ export interface ToolingMacro {
198
202
  storeVar?: boolean;
199
203
  }
200
204
 
205
+ /** Public tokenization can use the same effective metadata as validation. */
206
+ export interface ParseMarkupOptions extends RuntimeParseMarkupOptions {
207
+ /** Macro and widget metadata; widgets override builtin raw-body behavior. */
208
+ macros?: Iterable<ToolingMacro>;
209
+ }
210
+
211
+ function tokenizationOptions(
212
+ options: ParseMarkupOptions,
213
+ ): RuntimeParseMarkupOptions {
214
+ if (!options.macros) return options;
215
+ const macros = [...options.macros];
216
+ const parametersOf = parameterLookup(macros);
217
+ return {
218
+ ...options,
219
+ hooks: {
220
+ isRaw: (name) =>
221
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
222
+ isBlock: blockLookup(macros),
223
+ branchParents: (name) => branchParents(name, macros),
224
+ ...options.hooks,
225
+ },
226
+ };
227
+ }
228
+
229
+ /** Flat tokens with optional effective macro/widget metadata. */
230
+ export function tokenizeMarkup(
231
+ source: string,
232
+ options: ParseMarkupOptions = {},
233
+ ): Token[] {
234
+ return tokenizeRawMarkup(source, tokenizationOptions(options));
235
+ }
236
+
237
+ /** Metadata-aware flat tokens and recovery errors, in original source offsets. */
238
+ export function tokenizeMarkupTolerant(
239
+ source: string,
240
+ options: ParseMarkupOptions = {},
241
+ ): TolerantTokens {
242
+ return tokenizeRawMarkupTolerant(source, tokenizationOptions(options));
243
+ }
244
+
201
245
  /**
202
246
  * Validate the markup of a story's passages as Spindle does when the story
203
247
  * starts, against the given macros (built-in and user-defined): malformed
@@ -343,13 +387,17 @@ function referenceOptions(
343
387
  passages: readonly MarkupPassage[] = [],
344
388
  ) {
345
389
  const list = [...macros];
390
+ const effective = new NameMap<ToolingMacro>();
391
+ for (const macro of list) effective.set(macro.name, macro);
346
392
  const widgets = effectiveWidgetDefinitions(
347
393
  readWidgetDefinitions(passages, parameterLookup(list)),
348
394
  );
349
395
  return {
350
396
  all,
351
397
  storeVarMacros: new Set(
352
- list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase()),
398
+ [...effective.values()]
399
+ .filter((m) => m.storeVar)
400
+ .map((m) => m.name.toLowerCase()),
353
401
  ),
354
402
  parametersOf: parameterLookup([...list, ...definedWidgetMacros(widgets)]),
355
403
  tolerant: true,
@@ -361,13 +409,15 @@ function referenceOptions(
361
409
  * in source order, with the dotted path of fields accessed and where each is
362
410
  * written (offsets into `source`, UTF-16): `{$var}` displays, code in
363
411
  * expressions, conditions, `{do}` bodies and macro arguments, quoted names
364
- * bound by input macros, and the markup in labels and HTML attributes. Prose
412
+ * bound by input macros, and the markup in labels and HTML attributes. Input
413
+ * bindings include decoded root/path names and editable `binding` spans. Prose
365
414
  * is literal text. Malformed tags are skipped, so it reads half-typed markup.
366
415
  * The macros are those the markup may use, built-in and user-defined.
367
416
  *
368
417
  * These are the references the story start checks. With `all: true`, the
369
418
  * list is complete (the checked ones are among it, in source order): it also
370
- * has the variable a macro names in a `variable` parameter, such as the
419
+ * has sigilless input bindings (`{textbox "name"}`), the variable a macro
420
+ * names in a `variable` parameter, such as the
371
421
  * target of `{unset}` and `{computed}`, and the `{$name}` in the selectors of
372
422
  * a link, display or expression (`[[.c{$name} Go->T]]`). A rename or a find
373
423
  * 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,
@@ -1,3 +1,13 @@
1
+ /** The parent in the rendered tree, including slots and shadow hosts. */
2
+ export function composedParent(el: Element): Element | null {
3
+ return (
4
+ el.assignedSlot ??
5
+ el.parentElement ??
6
+ (el.getRootNode() as ShadowRoot).host ??
7
+ null
8
+ );
9
+ }
10
+
1
11
  /** Elements whose content is never text the reader reads. */
2
12
  const NOT_TEXT = new Set(['SCRIPT', 'STYLE', 'TEMPLATE', 'NOSCRIPT']);
3
13
 
@@ -26,13 +36,16 @@ export function isHidden(el: Element): boolean {
26
36
  * toggles it: the browser renders none of that content (#389).
27
37
  */
28
38
  function inClosedDetails(el: Element, root?: Element): boolean {
29
- const stop = root?.parentElement;
30
- for (let e = el.parentElement; e && e !== stop; e = e.parentElement) {
31
- if (e.localName !== 'details' || e.hasAttribute('open')) continue;
32
- const summary = Array.from(e.children).find(
33
- (c) => c.localName === 'summary',
34
- );
35
- if (!summary?.contains(el)) return true;
39
+ for (let child = el; child !== root;) {
40
+ const parent = composedParent(child);
41
+ if (!parent) break;
42
+ if (parent.localName === 'details' && !parent.hasAttribute('open')) {
43
+ const summary = Array.from(parent.children).find(
44
+ (c) => c.localName === 'summary',
45
+ );
46
+ if (child !== summary) return true;
47
+ }
48
+ child = parent;
36
49
  }
37
50
  return false;
38
51
  }
@@ -49,7 +62,7 @@ export function isRendered(el: Element, root?: Element): boolean {
49
62
  e.ownerDocument.defaultView?.getComputedStyle(e);
50
63
  const visibility = style(el)?.visibility;
51
64
  if (visibility === 'hidden' || visibility === 'collapse') return false;
52
- for (let e: Element | null = el; e; e = e.parentElement) {
65
+ for (let e: Element | null = el; e; e = composedParent(e)) {
53
66
  if (style(e)?.display === 'none') return false;
54
67
  if (e === root) break;
55
68
  }
@@ -59,7 +72,7 @@ export function isRendered(el: Element, root?: Element): boolean {
59
72
  /** Visibility shared by reader observations and native control handling. */
60
73
  export function isReaderVisible(el: Element): boolean {
61
74
  if (!el.isConnected || !isRendered(el)) return false;
62
- for (let at: Element | null = el; at; at = at.parentElement) {
75
+ for (let at: Element | null = el; at; at = composedParent(at)) {
63
76
  if (isHidden(at) || at.hasAttribute('inert')) return false;
64
77
  }
65
78
  return true;
@@ -496,6 +496,8 @@ export declare class MarkupError extends Error {
496
496
  }
497
497
 
498
498
  export interface ParseMarkupOptions {
499
+ /** Effective macro/widget metadata; a do widget has a markup body. */
500
+ macros?: Iterable<ToolingMacro>;
499
501
  /**
500
502
  * Text mode, for markup that becomes a string (HTML attribute values,
501
503
  * macro labels): only `{…}` markup and brace escapes are recognized.
@@ -710,6 +712,12 @@ export interface VariableReference {
710
712
  /** Where `$a.b.c` is written: `[start, end)` UTF-16 offsets into the markup. */
711
713
  start: number;
712
714
  end: number;
715
+ /**
716
+ * For an input binding, its decoded identity and editable root span.
717
+ * Offsets are into the markup, including inside escaped labels. The sigil
718
+ * is semantically `$` even when `binding.explicitSigil` is false.
719
+ */
720
+ binding?: BoundVariable;
713
721
  }
714
722
 
715
723
  /**
@@ -747,10 +755,12 @@ export interface VariableDiagnostic {
747
755
  * The variable references the markup of a passage evaluates, in source order,
748
756
  * with their positions. Malformed tags are skipped. The macros are those the
749
757
  * markup may use (`builtinMacros` and the user-defined ones).
758
+ * Input bindings include decoded root/path names and editable `binding` spans.
750
759
  *
751
760
  * These are the references the story start checks. With `all: true` the list
752
761
  * is complete (the checked ones are among it, in source order): it also has
753
- * the variable a macro names in a `variable` parameter, such as the target of
762
+ * sigilless input bindings (`{textbox "name"}`), the variable a macro names
763
+ * in a `variable` parameter, such as the target of
754
764
  * `{unset}` and `{computed}`, and the `{$name}` in the selectors of a link,
755
765
  * display or expression (`[[.c{$name} Go->T]]`).
756
766
  */
@@ -1225,6 +1235,32 @@ export interface ParsedCode {
1225
1235
  */
1226
1236
  export declare function parseCode(src: string, goal?: JsGoal): ParsedCode;
1227
1237
 
1238
+ /** A runtime input binding, with UTF-16 spans into the raw arguments. */
1239
+ export interface BoundVariable {
1240
+ /** Decoded story-variable root and dot members. */
1241
+ name: string;
1242
+ path: string[];
1243
+ /** Whether the author wrote the optional literal `$` sigil. */
1244
+ explicitSigil: boolean;
1245
+ /** The binding spelling, excluding quotes and including any sigil. */
1246
+ start: number;
1247
+ end: number;
1248
+ /** Editable root spelling, excluding quotes, sigil and dot members. */
1249
+ nameStart: number;
1250
+ nameEnd: number;
1251
+ }
1252
+
1253
+ /**
1254
+ * Read the first term as the runtime's story-variable binding. Quotes are
1255
+ * stripped, but this is an identifier path, not a JavaScript string literal:
1256
+ * only identifier escapes are decoded. Returns null for a missing binding;
1257
+ * throws for rejected namespaces, invalid escapes and reserved path names.
1258
+ * All offsets are UTF-16 offsets into rawArgs.
1259
+ */
1260
+ export declare function parseBoundVariable(
1261
+ rawArgs: string,
1262
+ ): BoundVariable | null;
1263
+
1228
1264
  /** A consumed argument and its original parameter (including option keywords). */
1229
1265
  export interface MacroArgumentSpan {
1230
1266
  parameter: ParameterDef;
@@ -1245,9 +1281,22 @@ export declare function macroArgumentSpans(
1245
1281
  ): MacroArgumentSpan[];
1246
1282
 
1247
1283
  /** Executable code at a cursor, or prose/literal text that suppresses completion. */
1284
+ /** Enclosing text containers, in order from the passage to the cursor. */
1285
+ export type CompletionContainer =
1286
+ | { kind: 'string'; quote: '"' | "'"; escapes: 'quotes' | 'javascript' }
1287
+ | { kind: 'attribute'; name: string; quote: '"' | "'" | null; code: boolean }
1288
+ | { kind: 'link-label' };
1289
+
1248
1290
  export type CompletionContext =
1249
1291
  | { kind: 'literal' }
1250
- | (PieceBase & { kind: 'code'; code: string; goal: JsGoal; cursor: number });
1292
+ | (PieceBase & {
1293
+ kind: 'code';
1294
+ code: string;
1295
+ goal: JsGoal;
1296
+ cursor: number;
1297
+ /** Encode replacement text through these containers, innermost first. */
1298
+ containers?: readonly CompletionContainer[];
1299
+ });
1251
1300
 
1252
1301
  /** Inspect only the prefix before cursor (UTF-16), accepting unfinished markup.
1253
1302
  * Strings, comments, regexes and template text are literal; template