@rohal12/spindle 0.62.5 → 0.62.6

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.
@@ -7,6 +7,7 @@ import {
7
7
  escapeOffsets,
8
8
  parameterLookup,
9
9
  executesRawBody,
10
+ usesBuiltinSemantics,
10
11
  type PieceBase,
11
12
  } from './code-check';
12
13
  import { macroArgumentSpans } from './components/macros/macro-args';
@@ -19,9 +20,22 @@ import {
19
20
  } from './js-lexer';
20
21
  import type { ToolingMacro } from './tooling';
21
22
 
23
+ /** Enclosing text containers, in order from the passage to the cursor. */
24
+ export type CompletionContainer =
25
+ | { kind: 'string'; quote: '"' | "'"; escapes: 'quotes' | 'javascript' }
26
+ | { kind: 'attribute'; name: string; quote: '"' | "'" | null; code: boolean }
27
+ | { kind: 'link-label' };
28
+
22
29
  export type CompletionContext =
23
30
  | { kind: 'literal' }
24
- | (PieceBase & { kind: 'code'; code: string; goal: JsGoal; cursor: number });
31
+ | (PieceBase & {
32
+ kind: 'code';
33
+ code: string;
34
+ goal: JsGoal;
35
+ cursor: number;
36
+ /** Encode replacement text through these containers, innermost first. */
37
+ containers?: readonly CompletionContainer[];
38
+ });
25
39
 
26
40
  const LITERAL = { kind: 'literal' } as const;
27
41
 
@@ -45,6 +59,7 @@ export function completionContext(
45
59
  code: string,
46
60
  goal: JsGoal,
47
61
  map: Mapping,
62
+ containers: readonly CompletionContainer[],
48
63
  ): CompletionContext => {
49
64
  // A following identifier probes the lexer's state at EOF. It cannot
50
65
  // close a string, regex, comment or template, and needs no guessed
@@ -72,6 +87,7 @@ export function completionContext(
72
87
  goal,
73
88
  offset,
74
89
  cursor: code.length,
90
+ ...(containers.length ? { containers } : {}),
75
91
  ...(offsets.some((at, i) => at !== offset + i)
76
92
  ? { sourceOffsets: offsets }
77
93
  : {}),
@@ -84,6 +100,7 @@ export function completionContext(
84
100
  text = false,
85
101
  depth = 0,
86
102
  sigilsOnly = false,
103
+ containers: readonly CompletionContainer[] = [],
87
104
  ): CompletionContext => {
88
105
  if (depth >= 64) return LITERAL;
89
106
  if (sigilsOnly) {
@@ -91,7 +108,12 @@ export function completionContext(
91
108
  for (const part of splitSigilTemplate(src, true)) {
92
109
  if ('expr' in part) {
93
110
  if (at + 1 + part.expr.length === src.length) {
94
- return codeContext(part.expr, 'expression', (i) => map(at + 1 + i));
111
+ return codeContext(
112
+ part.expr,
113
+ 'expression',
114
+ (i) => map(at + 1 + i),
115
+ containers,
116
+ );
95
117
  }
96
118
  at += part.expr.length + 2;
97
119
  } else at += ('text' in part ? part.text : part.verbatim).length;
@@ -108,12 +130,13 @@ export function completionContext(
108
130
  const token = tokens[tokens.length - 1];
109
131
  if (!token || token.end !== src.length) return LITERAL;
110
132
  const codeAt = (code: string, at: number, goal: JsGoal = 'expression') =>
111
- codeContext(code, goal, (i) => map(at + i));
133
+ codeContext(code, goal, (i) => map(at + i), containers);
112
134
  const nested = (
113
135
  value: string,
114
136
  at: number,
115
137
  offsets?: readonly number[],
116
138
  onlySigils = false,
139
+ container?: CompletionContainer,
117
140
  ) =>
118
141
  read(
119
142
  value,
@@ -121,6 +144,7 @@ export function completionContext(
121
144
  true,
122
145
  depth + 1,
123
146
  onlySigils,
147
+ container ? [...containers, container] : containers,
124
148
  );
125
149
 
126
150
  if (token.type === 'variable' && token.nameEnd === src.length) {
@@ -132,11 +156,21 @@ export function completionContext(
132
156
  if (token.type === 'html') {
133
157
  for (const { name, value, at } of attributeValues(src, token)) {
134
158
  if (at + value.length === src.length) {
135
- return nested(value, at, undefined, isCodeAttribute(name));
159
+ const span = token.attributeSpans.find(
160
+ (span) => span.valueStart === at,
161
+ );
162
+ return nested(value, at, undefined, isCodeAttribute(name), {
163
+ kind: 'attribute',
164
+ name,
165
+ quote: span?.quote ?? null,
166
+ code: isCodeAttribute(name),
167
+ });
136
168
  }
137
169
  }
138
170
  } else if (token.type === 'link' && token.displayEnd === src.length) {
139
- return nested(token.display, token.displayStart);
171
+ return nested(token.display, token.displayStart, undefined, false, {
172
+ kind: 'link-label',
173
+ });
140
174
  } else if (token.type === 'text' && !token.comment) {
141
175
  const opener = tokens[tokens.length - 2];
142
176
  if (
@@ -154,7 +188,10 @@ export function completionContext(
154
188
  const name = token.name.toLowerCase();
155
189
  const args = token.rawArgs;
156
190
  const widget = parametersOf.widget?.(name);
157
- if (!widget && ['if', 'elseif', 'case'].includes(name)) {
191
+ if (
192
+ usesBuiltinSemantics(name, parametersOf) &&
193
+ ['if', 'elseif', 'case'].includes(name)
194
+ ) {
158
195
  return codeAt(args, token.argsStart);
159
196
  }
160
197
  const stringContext = (
@@ -176,13 +213,23 @@ export function completionContext(
176
213
  ? stringLiteralValue(raw + raw[0])
177
214
  : quoted.value;
178
215
  if (value == null) return LITERAL;
216
+ const container: CompletionContainer = {
217
+ kind: 'string',
218
+ quote: raw[0] as '"' | "'",
219
+ escapes,
220
+ };
179
221
  const offsets = escapeOffsets(raw.slice(1), at + 1, value, escapes);
180
222
  if (holds === 'expression' || holds === 'statements') {
181
- return codeContext(value, holds, (i) =>
182
- map(offsets?.[i] ?? at + 1 + i),
223
+ return codeContext(
224
+ value,
225
+ holds,
226
+ (i) => map(offsets?.[i] ?? at + 1 + i),
227
+ [...containers, container],
183
228
  );
184
229
  }
185
- return holds === 'markup' ? nested(value, at + 1, offsets) : LITERAL;
230
+ return holds === 'markup'
231
+ ? nested(value, at + 1, offsets, false, container)
232
+ : LITERAL;
186
233
  };
187
234
  if (widget) {
188
235
  const spans = splitArgSpans(args);
@@ -1,3 +1,5 @@
1
+ import { getMacroParameters } from '../../registry';
2
+ import { getWidget } from '../../widgets/widget-registry';
1
3
  import { render } from 'preact';
2
4
  import { useContext, useEffect, useRef } from 'preact/hooks';
3
5
  import {
@@ -52,11 +54,16 @@ function settlesAfterRender(nodes: ASTNode[]): boolean {
52
54
  case 'macro':
53
55
  return (
54
56
  SETTLING_MACROS.has(n.name) &&
57
+ !getWidget(n.name) &&
58
+ getMacroParameters.source(n.name) === 'builtin' &&
55
59
  settlesAfterRender(n.children) &&
56
60
  (n.branches ?? []).every((b) => settlesAfterRender(b.children))
57
61
  );
58
62
  case 'html':
59
63
  return settlesAfterRender(n.children);
64
+ case 'variable':
65
+ // A forwarded slot may render timers or author-defined macros.
66
+ return n.scope !== 'local' || n.name !== 'children';
60
67
  default:
61
68
  return true;
62
69
  }
@@ -1,4 +1,4 @@
1
- import { isRendered } from '../utils/element-visibility';
1
+ import { composedParent, isRendered } from '../utils/element-visibility';
2
2
  import { useLayoutEffect } from 'preact/hooks';
3
3
  import type { RefObject } from 'preact';
4
4
 
@@ -17,16 +17,6 @@ const FOCUSABLE = [
17
17
  '[tabindex]',
18
18
  ].join(',');
19
19
 
20
- /** The parent in the rendered tree, including slots and shadow hosts. */
21
- function composedParent(el: Element): Element | null {
22
- return (
23
- el.assignedSlot ??
24
- el.parentElement ??
25
- (el.getRootNode() as ShadowRoot).host ??
26
- null
27
- );
28
- }
29
-
30
20
  function composedChildren(root: ParentNode): Element[] {
31
21
  if ((root as Element).localName === 'slot') {
32
22
  const assigned = (root as HTMLSlotElement).assignedNodes({
@@ -183,7 +183,9 @@ export const defaultCodeEnd: CodeEnd = jsCodeEnd();
183
183
  * still bound how many pending braces could close. Indexing visits each
184
184
  * opener once, so unmatched plain-code openers can skip suffix scans.
185
185
  */
186
- export function indexCodeEnds(input: string): (start: number) => number {
186
+ export function indexCodeEnds(
187
+ input: string,
188
+ ): (start: number, codeStart?: number, limit?: number) => number {
187
189
  const possible = new Set<number>();
188
190
  const pending: number[] = [];
189
191
  let remaining = 0;
@@ -213,12 +215,30 @@ export function indexCodeEnds(input: string): (start: number) => number {
213
215
  if (open !== undefined) possible.add(open);
214
216
  } else if (/['"`/\\]/.test(c)) uncertain();
215
217
  }
216
- return (start) => {
217
- if (start > lastBrace) return -1;
218
+ return (start, codeStart = start, limit = input.length) => {
219
+ if (start > lastBrace || codeStart >= limit) return -1;
220
+ const source = limit === input.length ? input : input.slice(0, limit);
218
221
  // A syntax error may end the parser's recovery at an inner `}`, even
219
222
  // when neither the token reader nor the lenient reader can close here.
220
- return possible.has(start - 1)
221
- ? defaultCodeEnd.closeBrace(input, start, start)
222
- : parsedCodeEnd(input, start, 'expression');
223
+ // Selectors can put lenientStart after something other than the opener.
224
+ // Macro names can themselves contain braces, which the strict reader
225
+ // skips before reading arguments; the index must not count those.
226
+ if (
227
+ input[start - 1] !== '{' ||
228
+ possible.has(start - 1) ||
229
+ input.slice(start, codeStart).includes('{')
230
+ ) {
231
+ return defaultCodeEnd.closeBrace(source, codeStart, start);
232
+ }
233
+ // Acorn locates its starting line and syntax errors by scanning the
234
+ // prefix. Recovery must not hand it the whole passage for every opener.
235
+ // Keep one preceding character so a leading #! cannot become a hashbang.
236
+ const base = Math.max(0, codeStart - 1);
237
+ const end = parsedCodeEnd(
238
+ source.slice(base),
239
+ codeStart - base,
240
+ 'expression',
241
+ );
242
+ return end < 0 ? -1 : base + end;
223
243
  };
224
244
  }
@@ -13,7 +13,7 @@ import {
13
13
  } from './pair';
14
14
  import type { Selectors, Token } from './tokens';
15
15
  import { isCodeAttribute } from './code-attributes';
16
- import { defaultCodeEnd, type CodeEnd } from './code-end';
16
+ import { defaultCodeEnd, indexCodeEnds, type CodeEnd } from './code-end';
17
17
  import { lineColumn, sourcePositions } from './line-column';
18
18
 
19
19
  export { lineColumn };
@@ -93,9 +93,12 @@ function run(
93
93
  options: ParseMarkupOptions,
94
94
  completion = false,
95
95
  ): unknown {
96
- const hooks = options.hooks
97
- ? { ...defaultHooks, ...options.hooks }
98
- : defaultHooks;
96
+ const hooks = { ...defaultHooks, ...options.hooks };
97
+ if (!options.hooks?.closeBrace) {
98
+ const codeEnd = indexCodeEnds(source);
99
+ hooks.closeBrace = (_input, codeStart, lenientStart) =>
100
+ codeEnd(lenientStart, codeStart);
101
+ }
99
102
  try {
100
103
  return pegParse(source, {
101
104
  startRule,
@@ -272,19 +275,26 @@ export function scanMarkupTolerant(
272
275
  const errors: MarkupError[] = [];
273
276
  const damage: number[] = [];
274
277
  let position: ReturnType<typeof sourcePositions> | undefined;
275
- // The code of a tag ends at a }: with none after it, the tag is unclosed
276
- // without reading its code to the end of the source, which every
277
- // unclosed tag would do again (#265).
278
+ // Share the index across recovery attempts, whose inputs are suffixes or
279
+ // truncated prefixes. Re-indexing each attempt would itself be quadratic.
280
+ const codeEnd = indexCodeEnds(source);
281
+ const customCloseBrace = options.hooks?.closeBrace;
278
282
  const lastBrace = source.lastIndexOf('}');
279
- const { closeBrace } = { ...defaultHooks, ...options.hooks };
280
283
  /** `text` shifted by `base`, tokenized: the tokens or the error. */
281
284
  const attempt = (text: string, base: number): Token[] | MarkupError => {
282
285
  const hooks: Partial<MarkupHooks> = {
283
286
  ...options.hooks,
284
- closeBrace: (input, codeStart, lenientStart) =>
285
- base + Math.min(codeStart, lenientStart) > lastBrace
286
- ? -1
287
- : closeBrace(input, codeStart, lenientStart),
287
+ closeBrace: (input, codeStart, lenientStart) => {
288
+ if (base + Math.min(codeStart, lenientStart) > lastBrace) return -1;
289
+ if (customCloseBrace)
290
+ return customCloseBrace(input, codeStart, lenientStart);
291
+ const end = codeEnd(
292
+ base + lenientStart,
293
+ base + codeStart,
294
+ base + text.length,
295
+ );
296
+ return end < 0 ? -1 : end - base;
297
+ },
288
298
  };
289
299
  try {
290
300
  return (
@@ -990,7 +990,7 @@ export function renderInlineNodes(nodes: ASTNode[]): preact.ComponentChildren {
990
990
  * it as micromark does.
991
991
  */
992
992
  const MARKDOWN_SYNTAX_RE =
993
- /[*_`#|~\[>\\\-+=\r]|!\[|\d+[.)]|&#?[a-zA-Z0-9]+;| {2}\n|<[!?]/;
993
+ /[*_`#|~\[>\\\-+=\r]|!\[|\d{1,9}[.)]|&#?[a-zA-Z0-9]+;| {2}\n|<[!?]/;
994
994
  /** Two line endings (LF, CRLF or CR) with only whitespace between them. */
995
995
  const BLANK_LINE_RE = /(?:\r\n|\r(?!\n)|\n)\s*[\r\n]/;
996
996
  const PLACEHOLDER_STRIP_RE = /<span data-tw=[0-9a-z]+:\d+><\/span>/g;
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,
@@ -198,6 +200,46 @@ export interface ToolingMacro {
198
200
  storeVar?: boolean;
199
201
  }
200
202
 
203
+ /** Public tokenization can use the same effective metadata as validation. */
204
+ export interface ParseMarkupOptions extends RuntimeParseMarkupOptions {
205
+ /** Macro and widget metadata; widgets override builtin raw-body behavior. */
206
+ macros?: Iterable<ToolingMacro>;
207
+ }
208
+
209
+ function tokenizationOptions(
210
+ options: ParseMarkupOptions,
211
+ ): RuntimeParseMarkupOptions {
212
+ if (!options.macros) return options;
213
+ const macros = [...options.macros];
214
+ const parametersOf = parameterLookup(macros);
215
+ return {
216
+ ...options,
217
+ hooks: {
218
+ isRaw: (name) =>
219
+ isRawMacro(name, parametersOf.widget?.(name) !== undefined),
220
+ isBlock: blockLookup(macros),
221
+ branchParents: (name) => branchParents(name, macros),
222
+ ...options.hooks,
223
+ },
224
+ };
225
+ }
226
+
227
+ /** Flat tokens with optional effective macro/widget metadata. */
228
+ export function tokenizeMarkup(
229
+ source: string,
230
+ options: ParseMarkupOptions = {},
231
+ ): Token[] {
232
+ return tokenizeRawMarkup(source, tokenizationOptions(options));
233
+ }
234
+
235
+ /** Metadata-aware flat tokens and recovery errors, in original source offsets. */
236
+ export function tokenizeMarkupTolerant(
237
+ source: string,
238
+ options: ParseMarkupOptions = {},
239
+ ): TolerantTokens {
240
+ return tokenizeRawMarkupTolerant(source, tokenizationOptions(options));
241
+ }
242
+
201
243
  /**
202
244
  * Validate the markup of a story's passages as Spindle does when the story
203
245
  * starts, against the given macros (built-in and user-defined): malformed
@@ -343,13 +385,17 @@ function referenceOptions(
343
385
  passages: readonly MarkupPassage[] = [],
344
386
  ) {
345
387
  const list = [...macros];
388
+ const effective = new NameMap<ToolingMacro>();
389
+ for (const macro of list) effective.set(macro.name, macro);
346
390
  const widgets = effectiveWidgetDefinitions(
347
391
  readWidgetDefinitions(passages, parameterLookup(list)),
348
392
  );
349
393
  return {
350
394
  all,
351
395
  storeVarMacros: new Set(
352
- list.filter((m) => m.storeVar).map((m) => m.name.toLowerCase()),
396
+ [...effective.values()]
397
+ .filter((m) => m.storeVar)
398
+ .map((m) => m.name.toLowerCase()),
353
399
  ),
354
400
  parametersOf: parameterLookup([...list, ...definedWidgetMacros(widgets)]),
355
401
  tolerant: true,
@@ -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.
@@ -1245,9 +1247,22 @@ export declare function macroArgumentSpans(
1245
1247
  ): MacroArgumentSpan[];
1246
1248
 
1247
1249
  /** Executable code at a cursor, or prose/literal text that suppresses completion. */
1250
+ /** Enclosing text containers, in order from the passage to the cursor. */
1251
+ export type CompletionContainer =
1252
+ | { kind: 'string'; quote: '"' | "'"; escapes: 'quotes' | 'javascript' }
1253
+ | { kind: 'attribute'; name: string; quote: '"' | "'" | null; code: boolean }
1254
+ | { kind: 'link-label' };
1255
+
1248
1256
  export type CompletionContext =
1249
1257
  | { kind: 'literal' }
1250
- | (PieceBase & { kind: 'code'; code: string; goal: JsGoal; cursor: number });
1258
+ | (PieceBase & {
1259
+ kind: 'code';
1260
+ code: string;
1261
+ goal: JsGoal;
1262
+ cursor: number;
1263
+ /** Encode replacement text through these containers, innermost first. */
1264
+ containers?: readonly CompletionContainer[];
1265
+ });
1251
1266
 
1252
1267
  /** Inspect only the prefix before cursor (UTF-16), accepting unfinished markup.
1253
1268
  * Strings, comments, regexes and template text are literal; template