@sveltia/ui 0.80.1 → 0.80.2

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.
@@ -79,9 +79,11 @@ import {
79
79
  TRANSFORMER_MAP,
80
80
  } from './constants.js';
81
81
  import {
82
+ editorComponents,
82
83
  exportHtml,
83
84
  findUnsupportedNode,
84
85
  getCodeLanguage,
86
+ HTML_CODE_IMPORT_MAP,
85
87
  HTML_EXPORT_MAP,
86
88
  HTML_IMPORT_MAP,
87
89
  } from './html.js';
@@ -922,7 +924,10 @@ export const initEditor = ({
922
924
  // code blocks with their language. The export map also applies to copying
923
925
  html:
924
926
  format === 'html'
925
- ? { export: HTML_EXPORT_MAP, import: hasCodeBlock ? HTML_IMPORT_MAP : {} }
927
+ ? {
928
+ export: HTML_EXPORT_MAP,
929
+ import: { ...HTML_IMPORT_MAP, ...(hasCodeBlock ? HTML_CODE_IMPORT_MAP : {}) },
930
+ }
926
931
  : undefined,
927
932
  /**
928
933
  * Log an error like `createEditor` does by default, instead of throwing it.
@@ -950,6 +955,9 @@ export const initEditor = ({
950
955
 
951
956
  const editor = buildEditorFromExtensions(editorExtension);
952
957
 
958
+ // Let the HTML import tell the elements the components import
959
+ editorComponents.set(editor, components);
960
+
953
961
  // The order matters, as listeners with the same priority are called in the registration order
954
962
  const unregister = mergeUnregisters(
955
963
  registerRichText(editor),
@@ -6,13 +6,25 @@ export function getCodeLanguage(code: Element): string | undefined;
6
6
  * @type {DOMExportOutputMap}
7
7
  */
8
8
  export const HTML_EXPORT_MAP: DOMExportOutputMap;
9
+ /**
10
+ * Editor components of each editor, used to tell the elements they import, which come with their
11
+ * content, when HTML is imported.
12
+ * @type {WeakMap<LexicalEditor, TextEditorComponent[]>}
13
+ */
14
+ export const editorComponents: WeakMap<LexicalEditor, TextEditorComponent[]>;
9
15
  /**
10
16
  * Additional DOM conversions to import HTML. They take priority over Lexical’s own conversions.
11
17
  * @type {DOMConversionMap}
12
18
  */
13
19
  export const HTML_IMPORT_MAP: DOMConversionMap;
20
+ /**
21
+ * Additional DOM conversions to import HTML with code blocks.
22
+ * @type {DOMConversionMap}
23
+ */
24
+ export const HTML_CODE_IMPORT_MAP: DOMConversionMap;
14
25
  export function findUnsupportedNode(editor: LexicalEditor, dom: Document): Element | Comment | undefined;
15
26
  export function exportHtml(editor: LexicalEditor): string;
16
27
  import type { DOMExportOutputMap } from 'lexical';
17
- import type { DOMConversionMap } from 'lexical';
18
28
  import type { LexicalEditor } from 'lexical';
29
+ import type { TextEditorComponent } from '../../typedefs.js';
30
+ import type { DOMConversionMap } from 'lexical';
@@ -7,8 +7,11 @@ import { HeadingNode, QuoteNode } from '@lexical/rich-text';
7
7
  import { TableCellNode, TableNode } from '@lexical/table';
8
8
  import {
9
9
  $createTextNode as createTextNode,
10
+ $getEditor as getEditor,
10
11
  $isParagraphNode as isParagraphNode,
12
+ isDOMTextNode,
11
13
  isHTMLElement,
14
+ isInlineDomNode,
12
15
  ParagraphNode,
13
16
  TabNode,
14
17
  TextNode,
@@ -26,6 +29,7 @@ import { isPlainLanguage } from './shiki/facade.js';
26
29
  * LexicalEditor,
27
30
  * LexicalNode,
28
31
  * } from 'lexical';
32
+ * @import { TextEditorComponent } from '../../typedefs.js';
29
33
  */
30
34
 
31
35
  /**
@@ -345,11 +349,245 @@ const convertPreElement = (pre) => {
345
349
  };
346
350
  };
347
351
 
352
+ /**
353
+ * Editor components of each editor, used to tell the elements they import, which come with their
354
+ * content, when HTML is imported.
355
+ * @type {WeakMap<LexicalEditor, TextEditorComponent[]>}
356
+ */
357
+ export const editorComponents = new WeakMap();
358
+
359
+ /**
360
+ * Conversion maps of the editor component nodes, cached as each `importDOM()` call can create a new
361
+ * map.
362
+ * @type {WeakMap<any, DOMConversionMap>}
363
+ */
364
+ const componentConversionMaps = new WeakMap();
365
+
366
+ /**
367
+ * Get the conversion map of the given editor component node.
368
+ * @param {any} node Lexical node class.
369
+ * @returns {DOMConversionMap} Conversion map.
370
+ */
371
+ const getComponentConversionMap = (node) => {
372
+ let map = componentConversionMaps.get(node);
373
+
374
+ if (!map) {
375
+ map = node.importDOM?.() ?? {};
376
+ componentConversionMaps.set(node, /** @type {DOMConversionMap} */ (map));
377
+ }
378
+
379
+ return /** @type {DOMConversionMap} */ (map);
380
+ };
381
+
382
+ /**
383
+ * Editor component that imports each element, or `null` if none does, cached as the same element is
384
+ * checked many times during an import, and a conversion can run developer code. An element is only
385
+ * imported to one editor, as each import parses the HTML anew.
386
+ * @type {WeakMap<Element, TextEditorComponent | null>}
387
+ */
388
+ const elementComponents = new WeakMap();
389
+
390
+ /**
391
+ * Get the editor component that imports the given element, if any. The element’s content is then
392
+ * part of the component.
393
+ * @param {LexicalEditor} editor Editor instance.
394
+ * @param {Element} element Element.
395
+ * @returns {TextEditorComponent | undefined} Component.
396
+ */
397
+ const getElementComponent = (editor, element) => {
398
+ let component = elementComponents.get(element);
399
+
400
+ if (component === undefined) {
401
+ component =
402
+ editorComponents
403
+ .get(editor)
404
+ ?.find(
405
+ ({ node }) =>
406
+ !!getComponentConversionMap(node)[element.localName]?.(
407
+ /** @type {HTMLElement} */ (element),
408
+ ),
409
+ ) ?? null;
410
+ elementComponents.set(element, component);
411
+ }
412
+
413
+ return component ?? undefined;
414
+ };
415
+
416
+ /**
417
+ * Check if the given element is imported by an inline editor component, like an image, which is
418
+ * content in the line just like text.
419
+ * @param {Element} element Element.
420
+ * @returns {boolean} Result.
421
+ */
422
+ const isInlineComponentElement = (element) => {
423
+ const component = getElementComponent(getEditor(), element);
424
+
425
+ // The `node` is actually a node class
426
+ return !!component && !!(/** @type {any} */ (component.node).prototype.isInline?.());
427
+ };
428
+
429
+ /**
430
+ * Find the text or the inline editor component element next to the given text in the same line,
431
+ * like Lexical’s own `findTextInLine()` does for text only. Without the component, Lexical takes an
432
+ * element like an image for the end of the line, or skips it, and drops the space between it and
433
+ * the text, e.g. `a <img> b` becomes `a<img>b`.
434
+ * @param {Node} text Text node.
435
+ * @param {boolean} forward Whether to search forward.
436
+ * @returns {Text | Element | null} Text or element, or `null` if the line ends.
437
+ */
438
+ const findContentInLine = (text, forward) => {
439
+ let node = text;
440
+
441
+ for (;;) {
442
+ let sibling = forward ? node.nextSibling : node.previousSibling;
443
+
444
+ while (!sibling) {
445
+ const { parentElement } = node;
446
+
447
+ if (!parentElement) {
448
+ return null;
449
+ }
450
+
451
+ node = parentElement;
452
+ sibling = forward ? node.nextSibling : node.previousSibling;
453
+ }
454
+
455
+ node = sibling;
456
+
457
+ if (isHTMLElement(node)) {
458
+ if (isInlineComponentElement(node)) {
459
+ return node;
460
+ }
461
+
462
+ const { display } = node.style;
463
+
464
+ if (display ? !display.startsWith('inline') : !isInlineDomNode(node)) {
465
+ return null;
466
+ }
467
+ }
468
+
469
+ let descendant = forward ? node.firstChild : node.lastChild;
470
+
471
+ while (descendant) {
472
+ node = descendant;
473
+
474
+ if (isHTMLElement(node) && isInlineComponentElement(node)) {
475
+ return node;
476
+ }
477
+
478
+ descendant = forward ? node.firstChild : node.lastChild;
479
+ }
480
+
481
+ if (isDOMTextNode(node)) {
482
+ return node;
483
+ }
484
+
485
+ if (node.nodeName === 'BR') {
486
+ return null;
487
+ }
488
+ }
489
+ };
490
+
491
+ /**
492
+ * Check if the given node is within a `<pre>` element or an element with preformatted whitespace,
493
+ * whose text is imported by Lexical’s own conversion as is.
494
+ * @param {Node} node Node.
495
+ * @returns {boolean} Result.
496
+ */
497
+ const isPreformatted = (node) => {
498
+ for (let element = node.parentElement; element; element = element.parentElement) {
499
+ if (element.localName === 'pre' || element.style.whiteSpace.startsWith('pre')) {
500
+ return true;
501
+ }
502
+ }
503
+
504
+ return false;
505
+ };
506
+
507
+ /**
508
+ * Convert a text node, collapsing whitespace like Lexical’s own conversion does, except that an
509
+ * inline editor component element counts as content. See {@link findContentInLine}.
510
+ * @param {Text} domNode Text node.
511
+ * @returns {DOMConversionOutput} Conversion output.
512
+ */
513
+ const convertTextNode = (domNode) => {
514
+ let textContent = domNode.data.replace(/\r/g, '').replace(/[ \t\n]+/g, ' ');
515
+
516
+ if (textContent.startsWith(' ')) {
517
+ let previous = findContentInLine(domNode, false);
518
+ // Drop the space at the start of a line, or after another space
519
+ let drop = true;
520
+
521
+ for (; previous; previous = findContentInLine(previous, false)) {
522
+ if (!isDOMTextNode(previous)) {
523
+ drop = false;
524
+ break;
525
+ }
526
+
527
+ const previousText = previous.data;
528
+
529
+ // Skip empty text
530
+ if (previousText) {
531
+ drop = /[ \t\n]$/.test(previousText);
532
+ break;
533
+ }
534
+ }
535
+
536
+ if (drop) {
537
+ textContent = textContent.slice(1);
538
+ }
539
+ }
540
+
541
+ if (textContent.endsWith(' ')) {
542
+ let next = findContentInLine(domNode, true);
543
+ let isEndOfLine = true;
544
+
545
+ // Skip any text that only has whitespace, which is dropped as well
546
+ for (; next; next = findContentInLine(next, true)) {
547
+ if (!isDOMTextNode(next) || next.data.replace(/^[ \t\n]+/, '')) {
548
+ isEndOfLine = false;
549
+ break;
550
+ }
551
+ }
552
+
553
+ if (isEndOfLine) {
554
+ textContent = textContent.slice(0, -1);
555
+ }
556
+ }
557
+
558
+ return { node: textContent ? createTextNode(textContent) : null };
559
+ };
560
+
348
561
  /**
349
562
  * Additional DOM conversions to import HTML. They take priority over Lexical’s own conversions.
350
563
  * @type {DOMConversionMap}
351
564
  */
352
565
  export const HTML_IMPORT_MAP = {
566
+ /**
567
+ * Get the conversion for a text node, unless it’s preformatted, which Lexical’s own conversion
568
+ * handles.
569
+ * @param {Node} node Text node.
570
+ * @returns {DOMConversion | null} Conversion.
571
+ */
572
+ '#text': (node) =>
573
+ isPreformatted(node)
574
+ ? null
575
+ : {
576
+ /**
577
+ * Convert the text node.
578
+ * @param {Node} domNode Text node.
579
+ * @returns {DOMConversionOutput} Conversion output.
580
+ */
581
+ conversion: (domNode) => convertTextNode(/** @type {Text} */ (domNode)),
582
+ priority: 1,
583
+ },
584
+ };
585
+
586
+ /**
587
+ * Additional DOM conversions to import HTML with code blocks.
588
+ * @type {DOMConversionMap}
589
+ */
590
+ export const HTML_CODE_IMPORT_MAP = {
353
591
  /**
354
592
  * Get the conversion for a `<pre>` element.
355
593
  * @returns {DOMConversion} Conversion.
@@ -357,46 +595,103 @@ export const HTML_IMPORT_MAP = {
357
595
  pre: () => ({ conversion: convertPreElement, priority: 2 }),
358
596
  };
359
597
 
598
+ /**
599
+ * Get the names of the elements only editor components import, which no other node handles.
600
+ * @param {LexicalEditor} editor Editor instance.
601
+ * @returns {Set<string>} Tag names.
602
+ */
603
+ const getComponentOnlyTagNames = (editor) => {
604
+ const components = editorComponents.get(editor) ?? [];
605
+ // The `node` is actually a node class
606
+ const componentNodes = new Set(components.map(({ node }) => /** @type {any} */ (node)));
607
+
608
+ const otherTagNames = new Set(
609
+ [...editor._nodes.values()]
610
+ .filter(({ klass }) => !componentNodes.has(klass))
611
+ .flatMap(({ klass }) => Object.keys(klass.importDOM?.() ?? {})),
612
+ );
613
+
614
+ return new Set(
615
+ components
616
+ .flatMap(({ node }) => Object.keys(getComponentConversionMap(node)))
617
+ .filter((tagName) => !otherTagNames.has(tagName)),
618
+ );
619
+ };
620
+
360
621
  /**
361
622
  * Get the first node in the given document that the editor cannot import, which would be silently
362
623
  * dropped, possibly along with its content:
363
624
  *
364
625
  * - An element none of the registered nodes, including the ones of editor components, handle. This
365
- * includes an element the parser moves to `<head>`, like a `<script>` at the beginning.
626
+ * includes an element the parser moves to `<head>`, like a `<script>` at the beginning, and an
627
+ * element only editor components handle, but none of them imports, like a `<figure>` that isn’t an
628
+ * instance of a component for `<figure class="photo">`, which would be unwrapped.
366
629
  * - A comment, like `<!-- more -->`.
367
630
  *
368
- * The elements within a `<pre>` element are ignored, as its content is imported as plain text.
631
+ * The content of an element an editor component imports is part of the component, which is
632
+ * expected to drop the children, and the elements within a `<pre>` element are imported as plain
633
+ * text, so they’re ignored.
369
634
  * @param {LexicalEditor} editor Editor instance.
370
635
  * @param {Document} dom Parsed document.
371
636
  * @returns {Element | Comment | undefined} Unsupported node.
372
637
  */
373
638
  export const findUnsupportedNode = (editor, dom) => {
374
- const walker = dom.createTreeWalker(dom, NodeFilter.SHOW_ALL);
639
+ const componentOnlyTagNames = getComponentOnlyTagNames(editor);
375
640
 
376
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
377
- if (node.nodeType === Node.COMMENT_NODE) {
378
- return /** @type {Comment} */ (node);
379
- }
641
+ /**
642
+ * Find an unsupported node among the descendants of the given node.
643
+ * @param {Node} parent Parent node.
644
+ * @returns {Element | Comment | undefined} Unsupported node.
645
+ */
646
+ const findWithin = (parent) => {
647
+ /** @type {Element | Comment | undefined} */
648
+ let found;
649
+
650
+ [...parent.childNodes].some((node) => {
651
+ if (node.nodeType === Node.COMMENT_NODE) {
652
+ found = /** @type {Comment} */ (node);
653
+
654
+ return true;
655
+ }
656
+
657
+ if (node.nodeType !== Node.ELEMENT_NODE) {
658
+ return false;
659
+ }
380
660
 
381
- if (node.nodeType === Node.ELEMENT_NODE) {
382
661
  const element = /** @type {Element} */ (node);
383
662
  const tagName = element.localName;
384
663
 
664
+ if (getElementComponent(editor, element)) {
665
+ return false;
666
+ }
667
+
385
668
  // `_htmlConversions` holds the conversions of all the registered nodes, along with the ones
386
669
  // in the `html.import` editor config. A conversion may still skip an element on purpose,
387
670
  // like a `<br>` at the end of a paragraph, which browsers don’t render
388
671
  if (
389
672
  !DOCUMENT_TAGS.includes(tagName) &&
390
673
  !PASSTHROUGH_TAGS.includes(tagName) &&
391
- !element.parentElement?.closest('pre') &&
392
- !editor._htmlConversions.has(tagName)
674
+ (!editor._htmlConversions.has(tagName) || componentOnlyTagNames.has(tagName))
393
675
  ) {
394
- return element;
676
+ found = element;
677
+
678
+ return true;
395
679
  }
396
- }
397
- }
398
680
 
399
- return undefined;
681
+ found =
682
+ tagName === 'pre'
683
+ ? /** @type {Comment | undefined} */ (
684
+ dom.createTreeWalker(element, NodeFilter.SHOW_COMMENT).nextNode() ?? undefined
685
+ )
686
+ : findWithin(element);
687
+
688
+ return !!found;
689
+ });
690
+
691
+ return found;
692
+ };
693
+
694
+ return findWithin(dom);
400
695
  };
401
696
 
402
697
  /**
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.
3
3
  */
4
- export const UI_VERSION: "0.80.1";
4
+ export const UI_VERSION: "0.80.2";
@@ -3,4 +3,4 @@
3
3
  /**
4
4
  * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.
5
5
  */
6
- export const UI_VERSION = '0.80.1';
6
+ export const UI_VERSION = '0.80.2';
@@ -748,7 +748,11 @@ export type TextEditorComponent = {
748
748
  */
749
749
  trigger?: "button" | "menuitem" | undefined;
750
750
  /**
751
- * Lexical node class implementation.
751
+ * Lexical node class implementation. To support the HTML format, the
752
+ * class implements `importDOM` and `exportDOM`. An element the class imports is taken as a whole,
753
+ * and the editor doesn’t check its children for elements it cannot import. So the conversion should
754
+ * drop the children with `after: () => []`, and take priority over the editor’s own conversions
755
+ * for the same element type, like a link, with a `priority` of 4 or higher.
752
756
  */
753
757
  node: LexicalNode;
754
758
  /**
package/dist/typedefs.js CHANGED
@@ -318,7 +318,11 @@
318
318
  * @property {string} [icon] Material Symbols icon name.
319
319
  * @property {'menuitem' | 'button'} [trigger] Trigger UI of the component. Default: `menuitem`. A
320
320
  * menu item is placed under the Insert menu, while a button is placed directly on the toolbar.
321
- * @property {LexicalNode} node Lexical node class implementation.
321
+ * @property {LexicalNode} node Lexical node class implementation. To support the HTML format, the
322
+ * class implements `importDOM` and `exportDOM`. An element the class imports is taken as a whole,
323
+ * and the editor doesn’t check its children for elements it cannot import. So the conversion should
324
+ * drop the children with `after: () => []`, and take priority over the editor’s own conversions
325
+ * for the same element type, like a link, with a `priority` of 4 or higher.
322
326
  * @property {(props?: Record<string, any>) => LexicalNode} createNode Function to create a new node
323
327
  * instance.
324
328
  * @property {Transformer} transformer Node transformer.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sveltia/ui",
3
- "version": "0.80.1",
3
+ "version": "0.80.2",
4
4
  "description": "A collection of Svelte components and utilities for building user interfaces.",
5
5
  "repository": {
6
6
  "type": "git",
@@ -81,7 +81,7 @@
81
81
  "eslint-config-airbnb-extended": "^3.3.0",
82
82
  "eslint-config-prettier": "^10.1.8",
83
83
  "eslint-plugin-import": "^2.32.0",
84
- "eslint-plugin-jsdoc": "^65.1.0",
84
+ "eslint-plugin-jsdoc": "^65.2.0",
85
85
  "eslint-plugin-package-json": "^1.10.1",
86
86
  "eslint-plugin-svelte": "^3.23.0",
87
87
  "globals": "^17.13.0",