@rohal12/spindle 0.64.10 → 0.64.12

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.
@@ -26,6 +26,7 @@ import { HTML_TEXT_ELEMENTS, RAW_TEXT_ELEMENTS } from './html-elements';
26
26
  import { isCodeAttribute } from './code-attributes';
27
27
  import { errorMessage } from '../utils/error-message';
28
28
  import { EMPTY_NAMESPACE } from '../utils/namespace';
29
+ import { authorElement, isHtmlEncoding } from './html-integration';
29
30
 
30
31
  export interface LocalsUpdater {
31
32
  update: (key: string, value: unknown) => void;
@@ -61,7 +62,7 @@ export const InlineContext = createContext(false);
61
62
  */
62
63
  export const StructuralContext = createContext(false);
63
64
  /**
64
- * True while rendering inside an element whose content is not markdown: SVG
65
+ * True while rendering inside an element whose content is not markdown: SVG/MathML
65
66
  * (whose namespace `<p>` wrappers would break) and the preformatted `<pre>`
66
67
  * `<textarea>`, `<style>` and `<script>`, whose text is literal.
67
68
  * Macro and widget bodies read it so their content stays literal too.
@@ -85,12 +86,14 @@ export function useViewScope(): string {
85
86
  }
86
87
 
87
88
  /**
88
- * True inside an `<svg>` element. SVG attributes are case-sensitive and have
89
- * no live form properties, so they are set as written (see splitAttributes).
89
+ * The foreign namespace containing author elements. SVG and MathML attributes
90
+ * are case-sensitive and have no live HTML form properties.
90
91
  */
91
- const SvgContext = createContext(false);
92
+ const ForeignContext = createContext<'svg' | 'math' | undefined>(undefined);
92
93
 
93
94
  const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';
95
+ const MATH_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';
96
+ const MATH_TEXT_ELEMENTS = new Set(['mi', 'mo', 'mn', 'ms', 'mtext']);
94
97
 
95
98
  /**
96
99
  * Elements whose children must be elements of particular types: markdown
@@ -205,13 +208,15 @@ function PlaceholderAttributes({
205
208
  tag,
206
209
  attributes,
207
210
  placeholders,
208
- svg,
211
+ foreign,
212
+ math,
209
213
  children,
210
214
  }: {
211
215
  tag: string;
212
216
  attributes: Attribute[];
213
217
  placeholders: Record<string, ASTNode[]>;
214
- svg: boolean;
218
+ foreign: boolean;
219
+ math: boolean;
215
220
  children: preact.ComponentChildren[];
216
221
  }) {
217
222
  const scope = useTextScope();
@@ -223,11 +228,11 @@ function PlaceholderAttributes({
223
228
  for (const error of result.errors) errors.push([name, error]);
224
229
  return [name, result.text, written, true];
225
230
  });
226
- const { props, direct } = splitAttributes(resolved, svg, tag);
231
+ const { props, direct } = splitAttributes(resolved, foreign, tag);
227
232
  const ref = useDirectAttributes(direct);
228
233
  return withAttributeErrors(
229
234
  errors,
230
- h(tag, ref ? { ...props, ref } : props, children),
235
+ authorElement(tag, ref ? { ...props, ref } : props, children, math),
231
236
  );
232
237
  }
233
238
 
@@ -236,15 +241,17 @@ function DirectAttributes({
236
241
  tag,
237
242
  props,
238
243
  direct,
244
+ math,
239
245
  children,
240
246
  }: {
241
247
  tag: string;
242
248
  props: Record<string, unknown>;
243
249
  direct: [string, string][];
250
+ math: boolean;
244
251
  children: preact.ComponentChildren[];
245
252
  }) {
246
253
  const ref = useDirectAttributes(direct);
247
- return h(tag, { ...props, ref }, children);
254
+ return authorElement(tag, { ...props, ref }, children, math);
248
255
  }
249
256
 
250
257
  /** An error met while evaluating the named attribute. */
@@ -353,7 +360,8 @@ function convertDomNode(
353
360
 
354
361
  // Convert attributes, as author HTML's (see splitAttributes): markdown
355
362
  // output holds raw HTML from text nodes (a custom macro's, or comments)
356
- const svg = el.namespaceURI === SVG_NAMESPACE;
363
+ const foreign =
364
+ el.namespaceURI === SVG_NAMESPACE || el.namespaceURI === MATH_NAMESPACE;
357
365
  const attributes: Attribute[] = [];
358
366
  let placeholders: Record<string, ASTNode[]> | undefined;
359
367
  for (const { name, value } of Array.from(el.attributes)) {
@@ -380,12 +388,13 @@ function convertDomNode(
380
388
  tag={tag}
381
389
  attributes={attributes}
382
390
  placeholders={placeholders}
383
- svg={svg}
391
+ foreign={foreign}
392
+ math={el.namespaceURI === MATH_NAMESPACE}
384
393
  children={children}
385
394
  />
386
395
  );
387
396
  }
388
- const { props, direct } = splitAttributes(attributes, svg, tag);
397
+ const { props, direct } = splitAttributes(attributes, foreign, tag);
389
398
  if (direct.length > 0) {
390
399
  return (
391
400
  <DirectAttributes
@@ -393,11 +402,17 @@ function convertDomNode(
393
402
  tag={tag}
394
403
  props={props}
395
404
  direct={direct}
405
+ math={el.namespaceURI === MATH_NAMESPACE}
396
406
  children={children}
397
407
  />
398
408
  );
399
409
  }
400
- return h(tag, { ...props, key }, children);
410
+ return authorElement(
411
+ tag,
412
+ { ...props, key },
413
+ children,
414
+ el.namespaceURI === MATH_NAMESPACE,
415
+ );
401
416
  }
402
417
  return null;
403
418
  }
@@ -513,7 +528,7 @@ const PREACT_RESERVED = new Set([
513
528
  ]);
514
529
 
515
530
  /** Names set directly on SVG elements (see splitAttributes). */
516
- const SVG_DIRECT = new Set([...PREACT_RESERVED, 'class', 'className']);
531
+ const FOREIGN_DIRECT = new Set([...PREACT_RESERVED, 'class', 'className']);
517
532
 
518
533
  /** Attribute names setAttribute accepts (`@click` is parsed, not settable). */
519
534
  const SETTABLE_NAME = /^[A-Za-z_:][\w:.-]*$/;
@@ -564,7 +579,7 @@ function isNativeDefault(tag: string, name: string): boolean {
564
579
  */
565
580
  function splitAttributes(
566
581
  attributes: Attribute[],
567
- svg: boolean,
582
+ foreign: boolean,
568
583
  tag: string,
569
584
  ): { props: Record<string, unknown>; direct: [string, string][] } {
570
585
  const props: Record<string, unknown> = {};
@@ -576,7 +591,7 @@ function splitAttributes(
576
591
  const lower = name.toLowerCase();
577
592
  if (BOOLEAN_ATTRIBUTES.has(lower) && written !== '' && value === '') {
578
593
  continue;
579
- } else if (!svg && LIVE_PROPERTIES.has(lower)) {
594
+ } else if (!foreign && LIVE_PROPERTIES.has(lower)) {
580
595
  if (!bound && isNativeDefault(tag, lower)) {
581
596
  defaults.push([name.toUpperCase(), lower === 'value' ? value : '']);
582
597
  } else {
@@ -586,11 +601,11 @@ function splitAttributes(
586
601
  !SETTABLE_NAME.test(name) ||
587
602
  lower.startsWith('on') ||
588
603
  lower === 'translate' ||
589
- (svg && (SVG_DIRECT.has(name) || name === '__proto__'))
604
+ (foreign && (FOREIGN_DIRECT.has(name) || name === '__proto__'))
590
605
  ) {
591
606
  direct.push([name, value]);
592
607
  } else {
593
- props[svg ? name : name.toUpperCase()] = value;
608
+ props[foreign ? name : name.toUpperCase()] = value;
594
609
  }
595
610
  }
596
611
  for (const [name, value] of defaults) props[name] = value;
@@ -752,13 +767,9 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
752
767
  inline: parentInline,
753
768
  structural: parentStructural,
754
769
  } = useRenderOptions();
755
- const inSvg = useContext(SvgContext);
770
+ const parentNamespace = useContext(ForeignContext);
756
771
  const tag = node.tag.toLowerCase();
757
- const isSvgRoot = tag === 'svg';
758
- // The content of a foreignObject is HTML again (see below)
759
- const isHtmlRoot = inSvg && tag === 'foreignobject';
760
- const rawContent = inRaw && !isHtmlRoot;
761
- const isRawRoot = !inRaw && (isSvgRoot || PREFORMATTED_ELEMENTS.has(tag));
772
+ const namespace = tag === 'svg' || tag === 'math' ? tag : parentNamespace;
762
773
  const errors: AttributeError[] = [];
763
774
  const resolved = Object.entries(node.attributes).map(([k, v]): Attribute => [
764
775
  k,
@@ -766,7 +777,24 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
766
777
  v,
767
778
  hasInterpolation(v),
768
779
  ]);
769
- const { props, direct } = splitAttributes(resolved, inSvg || isSvgRoot, tag);
780
+ const htmlAnnotation =
781
+ namespace === 'math' &&
782
+ tag === 'annotation-xml' &&
783
+ isHtmlEncoding(resolved.find(([name]) => name === 'encoding')?.[1]);
784
+ // MathML token elements keep literal text, but their element children use
785
+ // HTML attributes (Preact also switches their DOM namespace to HTML).
786
+ const mathText = namespace === 'math' && MATH_TEXT_ELEMENTS.has(tag);
787
+ const isHtmlRoot =
788
+ (namespace === 'svg' && tag === 'foreignobject') || htmlAnnotation;
789
+ const childNamespace = isHtmlRoot || mathText ? undefined : namespace;
790
+ const rawContent = inRaw && !isHtmlRoot;
791
+ const isRawRoot =
792
+ !inRaw && (namespace !== undefined || PREFORMATTED_ELEMENTS.has(tag));
793
+ const { props, direct } = splitAttributes(
794
+ resolved,
795
+ namespace !== undefined,
796
+ tag,
797
+ );
770
798
  const ref = useDirectAttributes(direct);
771
799
  if (ref) props.ref = ref;
772
800
  const isInline = INLINE_ELEMENTS.has(tag);
@@ -830,17 +858,26 @@ function HtmlNodeRenderer({ node }: { node: HtmlNode }) {
830
858
  // markdown, for the content of macros and widgets in it too (#477)
831
859
  if (isHtmlRoot && children) {
832
860
  children = (
833
- <SvgContext.Provider value={false}>
861
+ <ForeignContext.Provider value={undefined}>
834
862
  <RawTextContext.Provider value={false}>
835
863
  {children}
836
864
  </RawTextContext.Provider>
837
- </SvgContext.Provider>
865
+ </ForeignContext.Provider>
838
866
  );
839
867
  }
840
- let element = h(node.tag, props, children);
841
- if (isSvgRoot && !inSvg) {
842
- element = <SvgContext.Provider value={true}>{element}</SvgContext.Provider>;
868
+ if (childNamespace !== parentNamespace) {
869
+ children = (
870
+ <ForeignContext.Provider value={childNamespace}>
871
+ {children}
872
+ </ForeignContext.Provider>
873
+ );
843
874
  }
875
+ const element = authorElement(
876
+ node.tag,
877
+ props,
878
+ children,
879
+ namespace === 'math',
880
+ );
844
881
  return withAttributeErrors(
845
882
  errors,
846
883
  isRawRoot ? (
@@ -188,7 +188,15 @@ export function openPlaySessionWith(
188
188
  reject(new Error(CLOSED_MESSAGE));
189
189
  return;
190
190
  }
191
- queue.push({ op, args, resolve: resolve as Job['resolve'], reject });
191
+ // Match postMessage's call-time snapshot even while another request
192
+ // is active. A clone error rejects just this promise before enqueueing.
193
+ const snapshot: unknown[] = structuredClone(args);
194
+ queue.push({
195
+ op,
196
+ args: snapshot,
197
+ resolve: resolve as Job['resolve'],
198
+ reject,
199
+ });
192
200
  pump();
193
201
  });
194
202
 
package/src/tooling.ts CHANGED
@@ -1,6 +1,9 @@
1
+ import { completionScopes } from './completion-context';
1
2
  import { effectiveNamedDefinitions, NameMap } from './utils/macro-names';
2
3
  export {
3
4
  completionContext,
5
+ completionTarget,
6
+ type CompletionTarget,
4
7
  type CompletionContext,
5
8
  type CompletionContainer,
6
9
  } from './completion-context';
@@ -32,6 +35,7 @@ import {
32
35
  tokenizeMarkupTolerant as tokenizeRawMarkupTolerant,
33
36
  type ParseMarkupOptions as RuntimeParseMarkupOptions,
34
37
  type TolerantTokens,
38
+ mapOffsets,
35
39
  } from './markup/parse';
36
40
  import {
37
41
  parameterLookup,
@@ -97,6 +101,7 @@ export type {
97
101
  FindCodeEndOptions,
98
102
  JsGoal,
99
103
  JsLexHandlers,
104
+ CompletionIdentifier,
100
105
  Sigil,
101
106
  } from './js-lexer';
102
107
  export { MarkupError, parseSelectors } from './markup/parse';
@@ -347,7 +352,6 @@ export function macroCalls(
347
352
  macros: Iterable<ToolingMacro> = [],
348
353
  ): MacroCall[] {
349
354
  const all = effectiveToolingMacros(macros);
350
- const definitions = new NameMap(all.map((macro) => [macro.name, macro]));
351
355
  const parametersOf = parameterLookup(all);
352
356
  const options = tokenizationOptions({
353
357
  macros: all,
@@ -356,7 +360,39 @@ export function macroCalls(
356
360
  const hooks = options.hooks!;
357
361
  const tokens = tokenizeRawMarkupTolerant(source, options).tokens;
358
362
  const calls: MacroCall[] = [];
363
+ const classifier = macroClassifier(all);
359
364
  const classify = (tokens: readonly Token[]) => {
365
+ for (const call of classifier(tokens)) calls.push(call);
366
+ };
367
+ classify(tokens);
368
+ for (const piece of passagePiecesOf(source, tokens, parametersOf, {
369
+ isBlock: hooks.isBlock,
370
+ })) {
371
+ if (piece.kind !== 'text' || !piece.tokens.length) continue;
372
+ classify(piece.tokens);
373
+ }
374
+ // Consumed arguments are literal even if a same-named widget would
375
+ // normally evaluate them as markup. Drop heads inside those arguments.
376
+ let literalEnd = -1;
377
+ return calls
378
+ .sort((a, b) => a.token.start - b.token.start)
379
+ .filter((call) => {
380
+ if (call.token.start < literalEnd) return false;
381
+ if (call.kind === 'value' || call.kind === 'branch')
382
+ literalEnd = call.token.argsEnd;
383
+ return true;
384
+ });
385
+ }
386
+
387
+ /** Shared contextual dispatch for complete and unfinished grammar tokens. */
388
+ function macroClassifier(all: readonly ToolingMacro[]) {
389
+ const definitions = new NameMap(all.map((macro) => [macro.name, macro]));
390
+ const hooks = tokenizationOptions({
391
+ macros: all,
392
+ hooks: { isBlock: blockLookup(all, false) },
393
+ }).hooks!;
394
+ return (tokens: readonly Token[]) => {
395
+ const calls: MacroCall[] = [];
360
396
  const found = new Map<MacroToken, MacroCall>();
361
397
  const pending: { node: PairedNode; parent?: MacroToken }[] = pairMarkup(
362
398
  tokens,
@@ -392,25 +428,33 @@ export function macroCalls(
392
428
  const call = found.get(token) ?? { token, kind: 'branch' as const };
393
429
  calls.push(call);
394
430
  }
431
+ return calls;
395
432
  };
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
- });
433
+ }
434
+
435
+ /** The opening macro head containing a cursor, including unfinished heads. */
436
+ export function macroCallAt(
437
+ source: string,
438
+ cursor: number,
439
+ macros: Iterable<ToolingMacro> = [],
440
+ ): MacroCall | undefined {
441
+ const all = effectiveToolingMacros(macros);
442
+ const classify = macroClassifier(all);
443
+ let selected: MacroCall | undefined;
444
+ completionScopes(source, cursor, all, (tokens, map) => {
445
+ const call = classify(tokens).find(
446
+ ({ token }) => map(token.start) < cursor && cursor <= map(token.end),
447
+ );
448
+ if (call)
449
+ selected = {
450
+ ...call,
451
+ token: mapOffsets(call.token, map),
452
+ ...(call.owner && { owner: mapOffsets(call.owner, map) }),
453
+ };
454
+ // A control-owned argument is literal, even for a markup-holding widget.
455
+ return !call || call.kind === 'invocation';
456
+ });
457
+ return selected;
414
458
  }
415
459
 
416
460
  /**
@@ -276,27 +276,26 @@ function openComment(tokens: readonly Token[]): number {
276
276
  /** `<name` or `</name`, where a tag may start. */
277
277
  const TAG_START = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)/g;
278
278
 
279
- /**
280
- * Whether the text from `at` is a tag that a `>` on the next line would
281
- * close (on the same line, `<a@b>` would be an email autolink).
282
- */
283
- function closesWithGt(text: string, at: number): boolean {
284
- const rest = `${text.slice(at)}\n>`;
285
- const [first] = tokenizeMarkupTolerant(rest).tokens;
286
- return first?.type === 'html' && first.end === rest.length;
287
- }
288
-
289
279
  /**
290
280
  * Where a tag starts that is text only for want of its `>`, or -1: `</b`,
291
281
  * or `<b_r x=` (no error: `<b` is no tag before `_`), which a `>` on a later
292
282
  * line makes a tag. In a text-only element only its end tag counts.
293
283
  */
294
284
  function openTag(text: string, tokens: readonly Token[]): number {
285
+ let closed: number | undefined;
295
286
  for (const { token, element } of markupText(tokens)) {
296
287
  for (const m of text.slice(token.start, token.end).matchAll(TAG_START)) {
297
288
  const at = token.start + m.index;
298
289
  if (element && !(m[1] && m[2]!.toLowerCase() === element)) continue;
299
- if (closesWithGt(text, at)) return at;
290
+ // Only a tag ending at the appended > can have been left open.
291
+ // Probe once for all candidates: re-tokenizing every suffix makes
292
+ // plain text such as repeated `</x ` quadratic (#709). The newline
293
+ // also keeps `<a@b` from becoming an email autolink.
294
+ closed ??=
295
+ tokenizeMarkupTolerant(`${text}\n>`).tokens.find(
296
+ (t) => t.type === 'html' && t.end === text.length + 2,
297
+ )?.start ?? -1;
298
+ if (closed === at) return at;
300
299
  }
301
300
  }
302
301
  return -1;
@@ -1002,6 +1002,17 @@ export function macroCalls(
1002
1002
  macros?: Iterable<ToolingMacro>,
1003
1003
  ): MacroCall[];
1004
1004
 
1005
+ /** Opening macro head containing cursor, including unfinished heads. Uses
1006
+ * the same contextual ownership as macroCalls, including independently
1007
+ * evaluated labels/attributes. Returns undefined outside a head. UTF-16
1008
+ * offsets are in source; invalid cursors throw RangeError.
1009
+ */
1010
+ export declare function macroCallAt(
1011
+ source: string,
1012
+ cursor: number,
1013
+ macros?: Iterable<ToolingMacro>,
1014
+ ): MacroCall | undefined;
1015
+
1005
1016
  /** A branch (`{else}`, `{case}`, …) of a macro, with what follows it. */
1006
1017
  export interface PairedBranch {
1007
1018
  tag: MacroToken;
@@ -1340,3 +1351,34 @@ export declare function completionContext(
1340
1351
  cursor: number,
1341
1352
  macros?: Iterable<ToolingMacro>,
1342
1353
  ): CompletionContext;
1354
+
1355
+ /** Identifier replacement boundaries in decoded code (UTF-16). */
1356
+ export interface CompletionIdentifier {
1357
+ kind: 'root' | 'member';
1358
+ /** Decoded name, excluding a root's sigil. */
1359
+ name: string;
1360
+ /** Includes the sigil for roots and the complete escaped identifier suffix. */
1361
+ start: number;
1362
+ end: number;
1363
+ /** Start of the preceding dot, for bracket-access edits. */
1364
+ dotStart?: number;
1365
+ }
1366
+
1367
+ /** Full code and identifier boundaries for an edit at the cursor. */
1368
+ export type CompletionTarget =
1369
+ | { kind: 'literal' }
1370
+ | (Extract<CompletionContext, { kind: 'code' }> & {
1371
+ identifier?: CompletionIdentifier;
1372
+ });
1373
+
1374
+ /** Like completionContext, with full code including the suffix after cursor.
1375
+ * identifier supplies root/member replacement boundaries in code; use
1376
+ * pieceOffset(target, boundary) for original source positions and encode
1377
+ * inserted text through containers from innermost to outermost. Accepts
1378
+ * unfinished enclosing markup; invalid cursors throw RangeError.
1379
+ */
1380
+ export declare function completionTarget(
1381
+ source: string,
1382
+ cursor: number,
1383
+ macros?: Iterable<ToolingMacro>,
1384
+ ): CompletionTarget;