@sveltia/ui 0.79.4 → 0.80.1

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.
Files changed (51) hide show
  1. package/dist/components/emoji/position.d.ts +2 -1
  2. package/dist/components/emoji/position.js +11 -3
  3. package/dist/components/text-editor/constants.d.ts +9 -1
  4. package/dist/components/text-editor/constants.js +10 -1
  5. package/dist/components/text-editor/core.d.ts +4 -2
  6. package/dist/components/text-editor/core.js +168 -35
  7. package/dist/components/text-editor/floating-link-editor.svelte +685 -0
  8. package/dist/components/text-editor/floating-link-editor.svelte.d.ts +17 -0
  9. package/dist/components/text-editor/html.d.ts +18 -0
  10. package/dist/components/text-editor/html.js +407 -0
  11. package/dist/components/text-editor/shiki/version.d.ts +1 -1
  12. package/dist/components/text-editor/shiki/version.js +1 -1
  13. package/dist/components/text-editor/store.svelte.js +12 -13
  14. package/dist/components/text-editor/text-editor.svelte +43 -17
  15. package/dist/components/text-editor/text-editor.svelte.d.ts +23 -6
  16. package/dist/components/text-editor/toolbar/insert-link-button.svelte +14 -71
  17. package/dist/components/text-editor/toolbar/text-editor-toolbar.svelte +12 -5
  18. package/dist/locales/ar.yaml +5 -1
  19. package/dist/locales/bg.yaml +5 -1
  20. package/dist/locales/ca.yaml +5 -1
  21. package/dist/locales/cs.yaml +5 -1
  22. package/dist/locales/da.yaml +5 -1
  23. package/dist/locales/de.yaml +5 -1
  24. package/dist/locales/el.yaml +5 -1
  25. package/dist/locales/en-CA.yaml +5 -1
  26. package/dist/locales/en-GB.yaml +5 -1
  27. package/dist/locales/en-US.yaml +5 -1
  28. package/dist/locales/es-CO.yaml +5 -1
  29. package/dist/locales/fa.yaml +5 -1
  30. package/dist/locales/fi.yaml +5 -1
  31. package/dist/locales/fr.yaml +5 -1
  32. package/dist/locales/he.yaml +5 -1
  33. package/dist/locales/hr.yaml +5 -1
  34. package/dist/locales/it.yaml +5 -1
  35. package/dist/locales/ja.yaml +5 -1
  36. package/dist/locales/ko.yaml +5 -1
  37. package/dist/locales/nl.yaml +5 -1
  38. package/dist/locales/pl.yaml +5 -1
  39. package/dist/locales/pt-BR.yaml +5 -1
  40. package/dist/locales/pt-PT.yaml +5 -1
  41. package/dist/locales/ru.yaml +5 -1
  42. package/dist/locales/sk.yaml +5 -1
  43. package/dist/locales/sv.yaml +5 -1
  44. package/dist/locales/tr.yaml +5 -1
  45. package/dist/locales/uk.yaml +5 -1
  46. package/dist/locales/vi.yaml +5 -1
  47. package/dist/locales/zh-CN.yaml +5 -1
  48. package/dist/locales/zh-TW.yaml +5 -1
  49. package/dist/typedefs.d.ts +13 -7
  50. package/dist/typedefs.js +12 -6
  51. package/package.json +5 -4
@@ -14,7 +14,7 @@ export const LIST_WIDTH: 280;
14
14
  */
15
15
  export const LIST_OFFSET: 4;
16
16
  export const VIEWPORT_MARGIN: 8;
17
- export function getSuggestionListPosition({ anchorRect, listMaxHeight, viewport, rtl }: {
17
+ export function getSuggestionListPosition({ anchorRect, listMaxHeight, viewport, rtl, listWidth, }: {
18
18
  anchorRect: EmojiAnchorRect;
19
19
  listMaxHeight: number;
20
20
  viewport: {
@@ -22,6 +22,7 @@ export function getSuggestionListPosition({ anchorRect, listMaxHeight, viewport,
22
22
  height: number;
23
23
  };
24
24
  rtl: boolean;
25
+ listWidth?: number | undefined;
25
26
  }): SuggestionListPosition;
26
27
  export type SuggestionListPosition = {
27
28
  /**
@@ -38,20 +38,28 @@ export const VIEWPORT_MARGIN = 8;
38
38
  * @param {number} options.listMaxHeight The height the list would like to have, in pixels.
39
39
  * @param {{ width: number, height: number }} options.viewport Size of the viewport in pixels.
40
40
  * @param {boolean} options.rtl Whether the layout is right-to-left.
41
+ * @param {number} [options.listWidth] Width of the dropdown in pixels, for another popup placed
42
+ * the same way.
41
43
  * @returns {SuggestionListPosition} Position.
42
44
  */
43
- export const getSuggestionListPosition = ({ anchorRect, listMaxHeight, viewport, rtl }) => {
45
+ export const getSuggestionListPosition = ({
46
+ anchorRect,
47
+ listMaxHeight,
48
+ viewport,
49
+ rtl,
50
+ listWidth = LIST_WIDTH,
51
+ }) => {
44
52
  const { width: innerWidth, height: innerHeight } = viewport;
45
53
  const spaceBelow = innerHeight - anchorRect.bottom;
46
54
  const spaceAbove = anchorRect.top;
47
55
  const flipped = spaceBelow < listMaxHeight + VIEWPORT_MARGIN && spaceAbove > spaceBelow;
48
- const anchorLeft = rtl ? anchorRect.right - LIST_WIDTH : anchorRect.left;
56
+ const anchorLeft = rtl ? anchorRect.right - listWidth : anchorRect.left;
49
57
 
50
58
  return {
51
59
  top: flipped ? undefined : `${Math.round(anchorRect.bottom + LIST_OFFSET)}px`,
52
60
  bottom: flipped ? `${Math.round(innerHeight - anchorRect.top + LIST_OFFSET)}px` : undefined,
53
61
  left: `${Math.round(
54
- Math.max(VIEWPORT_MARGIN, Math.min(anchorLeft, innerWidth - LIST_WIDTH - VIEWPORT_MARGIN)),
62
+ Math.max(VIEWPORT_MARGIN, Math.min(anchorLeft, innerWidth - listWidth - VIEWPORT_MARGIN)),
55
63
  )}px`,
56
64
  maxHeight: `${Math.round(
57
65
  Math.min(listMaxHeight, (flipped ? spaceAbove : spaceBelow) - LIST_OFFSET - VIEWPORT_MARGIN),
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @import { EditorThemeClasses } from 'lexical';
2
+ * @import { EditorThemeClasses, LexicalCommand } from 'lexical';
3
3
  * @import { Transformer } from '@lexical/markdown';
4
4
  * @import {
5
5
  * TextEditorBlockType,
@@ -61,9 +61,17 @@ export const DISABLED_MARKDOWN_TAGS: string[];
61
61
  * change made by the user.
62
62
  */
63
63
  export const IMPORT_UPDATE_TAG: "sui-import";
64
+ /**
65
+ * Command to show the floating link editor for the link at the selection, or for the selected text
66
+ * to be linked. A listener returns `false` when there is no link or text to edit, in which case the
67
+ * Link button falls back to the dialog.
68
+ * @type {LexicalCommand<void>}
69
+ */
70
+ export const OPEN_LINK_EDITOR_COMMAND: LexicalCommand<void>;
64
71
  import type { EditorThemeClasses } from 'lexical';
65
72
  import type { TextEditorFormatType } from '../../typedefs.js';
66
73
  import type { TextEditorInlineType } from '../../typedefs.js';
67
74
  import type { TextEditorBlockType } from '../../typedefs.js';
68
75
  import type { TextEditorNodeType } from '../../typedefs.js';
69
76
  import type { Transformer } from '@lexical/markdown';
77
+ import type { LexicalCommand } from 'lexical';
@@ -18,9 +18,10 @@ import {
18
18
  UNORDERED_LIST,
19
19
  } from '@lexical/markdown';
20
20
  import { HeadingNode, QuoteNode } from '@lexical/rich-text';
21
+ import { createCommand } from 'lexical';
21
22
 
22
23
  /**
23
- * @import { EditorThemeClasses } from 'lexical';
24
+ * @import { EditorThemeClasses, LexicalCommand } from 'lexical';
24
25
  * @import { Transformer } from '@lexical/markdown';
25
26
  * @import {
26
27
  * TextEditorBlockType,
@@ -237,3 +238,11 @@ export const DISABLED_MARKDOWN_TAGS = ['*', '__', '***', '___'];
237
238
  * change made by the user.
238
239
  */
239
240
  export const IMPORT_UPDATE_TAG = 'sui-import';
241
+
242
+ /**
243
+ * Command to show the floating link editor for the link at the selection, or for the selected text
244
+ * to be linked. A listener returns `false` when there is no link or text to edit, in which case the
245
+ * Link button falls back to the dialog.
246
+ * @type {LexicalCommand<void>}
247
+ */
248
+ export const OPEN_LINK_EDITOR_COMMAND = createCommand('OPEN_LINK_EDITOR_COMMAND');
@@ -3,11 +3,12 @@ export function handleEditorMouseDown(editor: LexicalEditor, event: MouseEvent):
3
3
  export function isSafeLinkURL(url: string): boolean;
4
4
  export function getSelectionTypes(): TextEditorSelectionState;
5
5
  export function exportMarkdown(enabledTransformers: Transformer[]): string;
6
- export function onEditorUpdate(editor: LexicalEditor, enabledTransformers: Transformer[], cachedValue?: string): string;
6
+ export function onEditorUpdate(editor: LexicalEditor, enabledTransformers: Transformer[], cachedValue?: string, format?: TextEditorValueFormat): string;
7
7
  export function getComponentMarkdown({ node, createNode, transformer, createMarkdown }: TextEditorComponent): string;
8
- export function initEditor({ enabledButtons, components, useMarkdownShortcuts, isCodeEditor, defaultLanguage, }: TextEditorConfig): InitEditorResult;
8
+ export function initEditor({ enabledButtons, components, useMarkdownShortcuts, isCodeEditor, defaultLanguage, format, }: TextEditorConfig): InitEditorResult;
9
9
  export function loadCodeHighlighter(lang: string): Promise<void>;
10
10
  export function convertMarkdownToLexical(editor: LexicalEditor, value: string, enabledTransformers: Transformer[]): Promise<string | undefined>;
11
+ export function convertHtmlToLexical(editor: LexicalEditor, value: string): Promise<string | undefined>;
11
12
  export function focusEditor(editor: LexicalEditor): Promise<void>;
12
13
  export type InitEditorResult = {
13
14
  /**
@@ -26,5 +27,6 @@ export type InitEditorResult = {
26
27
  import type { LexicalEditor } from 'lexical';
27
28
  import type { TextEditorSelectionState } from '../../typedefs.js';
28
29
  import type { Transformer } from '@lexical/markdown';
30
+ import type { TextEditorValueFormat } from '../../typedefs.js';
29
31
  import type { TextEditorComponent } from '../../typedefs.js';
30
32
  import type { TextEditorConfig } from '../../typedefs.js';
@@ -9,8 +9,10 @@ import {
9
9
  import { registerDragonSupport } from '@lexical/dragon';
10
10
  import { buildEditorFromExtensions, HorizontalRuleNode } from '@lexical/extension';
11
11
  import { createEmptyHistoryState, registerHistory } from '@lexical/history';
12
+ import { $generateNodesFromDOM as generateNodesFromDOM } from '@lexical/html';
12
13
  import {
13
14
  $isLinkNode as isLinkNode,
15
+ LinkNode,
14
16
  TOGGLE_LINK_COMMAND,
15
17
  $toggleLink as toggleLink,
16
18
  } from '@lexical/link';
@@ -35,7 +37,11 @@ import {
35
37
  registerRichText,
36
38
  } from '@lexical/rich-text';
37
39
  import { TableCellNode, TableNode, TableRowNode } from '@lexical/table';
38
- import { $getNearestNodeOfType as getNearestNodeOfType, objectKlassEquals } from '@lexical/utils';
40
+ import {
41
+ $getNearestNodeOfType as getNearestNodeOfType,
42
+ objectKlassEquals,
43
+ $unwrapNode as unwrapNode,
44
+ } from '@lexical/utils';
39
45
  import { sleep } from '@sveltia/utils/misc';
40
46
  import { isURL } from '@sveltia/utils/string';
41
47
  import {
@@ -72,6 +78,13 @@ import {
72
78
  TEXT_FORMAT_BUTTON_TYPES,
73
79
  TRANSFORMER_MAP,
74
80
  } from './constants.js';
81
+ import {
82
+ exportHtml,
83
+ findUnsupportedNode,
84
+ getCodeLanguage,
85
+ HTML_EXPORT_MAP,
86
+ HTML_IMPORT_MAP,
87
+ } from './html.js';
75
88
  import {
76
89
  increaseListIndentation,
77
90
  padBlankBlockquoteLines,
@@ -101,6 +114,7 @@ import { TABLE } from './transformers/table.js';
101
114
  * TextEditorConfig,
102
115
  * TextEditorInlineType,
103
116
  * TextEditorNodeType,
117
+ * TextEditorValueFormat,
104
118
  * TextEditorSelectionState,
105
119
  * } from '../../typedefs.js';
106
120
  */
@@ -487,12 +501,14 @@ export const exportMarkdown = (enabledTransformers) => {
487
501
  * @internal
488
502
  * @param {LexicalEditor} editor Editor instance.
489
503
  * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.
490
- * @param {string} [cachedValue] Markdown value from a previous call, to be reused instead of
491
- * converting the whole document again when only the selection has changed.
492
- * @returns {string} Markdown value.
504
+ * @param {string} [cachedValue] Value from a previous call, to be reused instead of converting the
505
+ * whole document again when only the selection has changed.
506
+ * @param {TextEditorValueFormat} [format] Value format.
507
+ * @returns {string} Markdown or HTML value.
493
508
  */
494
- export const onEditorUpdate = (editor, enabledTransformers, cachedValue) => {
495
- const value = cachedValue ?? exportMarkdown(enabledTransformers);
509
+ export const onEditorUpdate = (editor, enabledTransformers, cachedValue, format = 'markdown') => {
510
+ const value =
511
+ cachedValue ?? (format === 'html' ? exportHtml(editor) : exportMarkdown(enabledTransformers));
496
512
 
497
513
  editor.getRootElement()?.dispatchEvent(
498
514
  new CustomEvent('Update', {
@@ -646,13 +662,22 @@ const registerCodeEditorCommands = (editor, defaultLanguage) =>
646
662
  );
647
663
 
648
664
  /**
649
- * Register the link command, and the paste handler that turns a pasted URL into a link.
665
+ * Register the link command, the paste handler that turns a pasted URL into a link, and the
666
+ * transform that removes a link with an unsafe URL.
650
667
  * @param {LexicalEditor} editor Editor instance.
651
668
  * @returns {() => void} Cleanup handler.
652
669
  * @see https://github.com/facebook/lexical/blob/main/packages/lexical-link/src/LexicalLinkExtension.ts
653
670
  */
654
671
  const registerLinkCommands = (editor) =>
655
672
  mergeUnregisters(
673
+ // A link can also be created by importing the value or pasting rich text, which bypass the
674
+ // command below. Unwrap a link with an unsafe URL, keeping its text, so the URL never reaches
675
+ // the Markdown or HTML value
676
+ editor.registerNodeTransform(LinkNode, (node) => {
677
+ if (!isSafeLinkURL(node.getURL())) {
678
+ unwrapNode(node);
679
+ }
680
+ }),
656
681
  editor.registerCommand(
657
682
  TOGGLE_LINK_COMMAND,
658
683
  (payload) => {
@@ -750,13 +775,14 @@ const registerListCommands = (editor, enabledButtons = []) => {
750
775
  };
751
776
 
752
777
  /**
753
- * Register an update listener that triggers the Update event with the Markdown value, debounced so
754
- * only the latest update in a burst triggers it.
778
+ * Register an update listener that triggers the Update event with the Markdown or HTML value,
779
+ * debounced so only the latest update in a burst triggers it.
755
780
  * @param {LexicalEditor} editor Editor instance.
756
781
  * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.
782
+ * @param {TextEditorValueFormat} format Value format.
757
783
  * @returns {() => void} Cleanup handler.
758
784
  */
759
- const registerUpdateEvent = (editor, enabledTransformers) => {
785
+ const registerUpdateEvent = (editor, enabledTransformers, format) => {
760
786
  /** Incremented on every update, so only the latest one in a burst triggers the Update event. */
761
787
  let updateCount = 0;
762
788
  /** Whether the content has changed since the Update event was last triggered. */
@@ -796,6 +822,7 @@ const registerUpdateEvent = (editor, enabledTransformers) => {
796
822
  editor,
797
823
  enabledTransformers,
798
824
  contentChanged ? undefined : lastValue,
825
+ format,
799
826
  );
800
827
  contentChanged = false;
801
828
  });
@@ -863,6 +890,7 @@ export const initEditor = ({
863
890
  useMarkdownShortcuts,
864
891
  isCodeEditor = false,
865
892
  defaultLanguage = 'plain',
893
+ format = 'markdown',
866
894
  }) => {
867
895
  const hasCodeBlock = enabledButtons.includes('code-block') || isCodeEditor;
868
896
 
@@ -890,6 +918,12 @@ export const initEditor = ({
890
918
  [HorizontalRuleNode, TableNode, TableCellNode, TableRowNode]),
891
919
  ],
892
920
  theme: EDITOR_THEME,
921
+ // Export clean HTML without the attributes and elements only meant for the editor, and import
922
+ // code blocks with their language. The export map also applies to copying
923
+ html:
924
+ format === 'html'
925
+ ? { export: HTML_EXPORT_MAP, import: hasCodeBlock ? HTML_IMPORT_MAP : {} }
926
+ : undefined,
893
927
  /**
894
928
  * Log an error like `createEditor` does by default, instead of throwing it.
895
929
  * @param {Error} error Error.
@@ -941,7 +975,7 @@ export const initEditor = ({
941
975
  hasCodeBlock ? observeCodeTheme(editor) : undefined,
942
976
  enabledButtons.includes('link') ? registerLinkCommands(editor) : undefined,
943
977
  registerListCommands(editor, enabledButtons),
944
- registerUpdateEvent(editor, enabledTransformers),
978
+ registerUpdateEvent(editor, enabledTransformers, format),
945
979
  registerTabIndentation(editor),
946
980
  );
947
981
 
@@ -977,22 +1011,26 @@ export const loadCodeHighlighter = async (lang) => {
977
1011
  };
978
1012
 
979
1013
  /**
980
- * Number of the latest Markdown import started for each editor.
1014
+ * Number of the latest import started for each editor.
981
1015
  * @type {WeakMap<LexicalEditor, number>}
982
1016
  */
983
1017
  const latestImports = new WeakMap();
984
1018
 
985
1019
  /**
986
- * Convert Markdown to Lexical nodes.
1020
+ * Import a value to the editor, replacing the current content.
987
1021
  * @param {LexicalEditor} editor Editor instance.
988
- * @param {string} value Current Markdown value.
989
- * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1022
+ * @param {object} args Arguments.
1023
+ * @param {string[]} args.languages Programming languages used in the code blocks.
1024
+ * @param {() => void} args.$import Function to convert the value to Lexical nodes, called within an
1025
+ * editor update.
1026
+ * @param {() => string} args.$export Function to convert the editor content back to the value.
1027
+ * @param {string} args.formatName Name of the value format, used in the error message.
990
1028
  * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which
991
- * can differ in style from the given value, e.g. `_text_` for `*text*`. `undefined` if another
992
- * import has been started for the same editor in the meantime, in which case this value is skipped.
1029
+ * can differ in style from the given value. `undefined` if another import has been started for the
1030
+ * same editor in the meantime, in which case this value is skipped.
993
1031
  * @throws {Error} Failed to convert the value to Lexical nodes.
994
1032
  */
995
- export const convertMarkdownToLexical = async (editor, value, enabledTransformers) => {
1033
+ const importValue = async (editor, { languages, $import, $export, formatName }) => {
996
1034
  const importId = (latestImports.get(editor) ?? 0) + 1;
997
1035
 
998
1036
  latestImports.set(editor, importId);
@@ -1008,11 +1046,7 @@ export const convertMarkdownToLexical = async (editor, value, enabledTransformer
1008
1046
  try {
1009
1047
  // Preload the highlighter for every language used in the document, so code blocks are
1010
1048
  // highlighted as soon as they appear rather than a moment later
1011
- await Promise.all(
1012
- [...value.matchAll(/^```(?<lang>.+?)\n/gm)].map(async ({ groups: { lang = 'plain' } = {} }) =>
1013
- loadCodeHighlighter(lang),
1014
- ),
1015
- );
1049
+ await Promise.all(languages.map(async (lang) => loadCodeHighlighter(lang)));
1016
1050
  } catch (ex) {
1017
1051
  if (isSuperseded()) {
1018
1052
  return undefined;
@@ -1025,15 +1059,6 @@ export const convertMarkdownToLexical = async (editor, value, enabledTransformer
1025
1059
  return undefined;
1026
1060
  }
1027
1061
 
1028
- // Split multiline formatting into separate lines to prevent Markdown parsing issues
1029
- value = splitMultilineFormatting(value);
1030
-
1031
- // Increase list indentation levels to prevent Markdown parsing issues
1032
- value = increaseListIndentation(value);
1033
-
1034
- // Pad blank blockquote lines so they are not imported as literal `>` text
1035
- value = padBlankBlockquoteLines(value);
1036
-
1037
1062
  // Lexical commits an empty state when the root element is attached, and the history keeps it as
1038
1063
  // the current entry. An empty state can’t be restored, so undoing to it throws an error. Merge
1039
1064
  // the first import into that entry instead of pushing it onto the undo stack
@@ -1044,7 +1069,7 @@ export const convertMarkdownToLexical = async (editor, value, enabledTransformer
1044
1069
  editor.update(
1045
1070
  () => {
1046
1071
  try {
1047
- convertFromMarkdownString(value, enabledTransformers);
1072
+ $import();
1048
1073
  } catch (ex) {
1049
1074
  error = ex;
1050
1075
  }
@@ -1056,10 +1081,118 @@ export const convertMarkdownToLexical = async (editor, value, enabledTransformer
1056
1081
  );
1057
1082
 
1058
1083
  if (error) {
1059
- throw new Error('Failed to convert Markdown', { cause: error });
1084
+ throw new Error(`Failed to convert ${formatName}`, { cause: error });
1060
1085
  }
1061
1086
 
1062
- return editor.read(() => exportMarkdown(enabledTransformers));
1087
+ return editor.read($export);
1088
+ };
1089
+
1090
+ /**
1091
+ * Convert Markdown to Lexical nodes.
1092
+ * @param {LexicalEditor} editor Editor instance.
1093
+ * @param {string} value Current Markdown value.
1094
+ * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1095
+ * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which
1096
+ * can differ in style from the given value, e.g. `_text_` for `*text*`. `undefined` if another
1097
+ * import has been started for the same editor in the meantime, in which case this value is skipped.
1098
+ * @throws {Error} Failed to convert the value to Lexical nodes.
1099
+ */
1100
+ export const convertMarkdownToLexical = async (editor, value, enabledTransformers) =>
1101
+ importValue(editor, {
1102
+ languages: [...value.matchAll(/^```(?<lang>.+?)\n/gm)].map(
1103
+ ({ groups: { lang = 'plain' } = {} }) => lang,
1104
+ ),
1105
+ /**
1106
+ * Import the Markdown.
1107
+ */
1108
+ $import: () => {
1109
+ convertFromMarkdownString(
1110
+ // Split multiline formatting into separate lines to prevent Markdown parsing issues, then
1111
+ // increase list indentation levels to prevent Markdown parsing issues, and pad blank
1112
+ // blockquote lines so they are not imported as literal `>` text
1113
+ padBlankBlockquoteLines(increaseListIndentation(splitMultilineFormatting(value))),
1114
+ enabledTransformers,
1115
+ );
1116
+ },
1117
+ /**
1118
+ * Export the content as Markdown.
1119
+ * @returns {string} Markdown.
1120
+ */
1121
+ $export: () => exportMarkdown(enabledTransformers),
1122
+ formatName: 'Markdown',
1123
+ });
1124
+
1125
+ /**
1126
+ * Convert HTML to Lexical nodes. Inline content outside any block, like bare text, is wrapped with
1127
+ * a paragraph. An element that none of the registered nodes can import, like `<img>` or a heading
1128
+ * with the heading buttons disabled, as well as a comment, causes an error instead of being
1129
+ * silently dropped.
1130
+ * @param {LexicalEditor} editor Editor instance.
1131
+ * @param {string} value Current HTML value.
1132
+ * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which
1133
+ * can differ in style from the given value, e.g. `<strong>` for `<b>`. `undefined` if another
1134
+ * import has been started for the same editor in the meantime, in which case this value is skipped.
1135
+ * @throws {Error} Failed to convert the value to Lexical nodes.
1136
+ */
1137
+ export const convertHtmlToLexical = async (editor, value) => {
1138
+ const dom = new DOMParser().parseFromString(value, 'text/html');
1139
+
1140
+ return importValue(editor, {
1141
+ languages: [...dom.querySelectorAll('pre > code')]
1142
+ .map(getCodeLanguage)
1143
+ .filter((lang) => lang !== undefined),
1144
+ /**
1145
+ * Import the HTML.
1146
+ * @throws {Error} The HTML has an element the editor cannot handle.
1147
+ */
1148
+ $import: () => {
1149
+ const unsupportedNode = findUnsupportedNode(editor, dom);
1150
+
1151
+ if (unsupportedNode) {
1152
+ throw new Error(
1153
+ unsupportedNode.nodeType === Node.COMMENT_NODE
1154
+ ? 'Unsupported comment'
1155
+ : `Unsupported element: <${/** @type {Element} */ (unsupportedNode).localName}>`,
1156
+ );
1157
+ }
1158
+
1159
+ const root = getRoot();
1160
+ /** @type {ElementNode | null} */
1161
+ let paragraph = null;
1162
+
1163
+ root.clear();
1164
+
1165
+ generateNodesFromDOM(editor, dom).forEach((node) => {
1166
+ if (isElementNode(node) ? !node.isInline() : isDecoratorNode(node) && !node.isInline()) {
1167
+ paragraph = null;
1168
+ root.append(node);
1169
+ } else {
1170
+ if (!paragraph) {
1171
+ paragraph = createParagraphNode();
1172
+ root.append(paragraph);
1173
+ }
1174
+
1175
+ paragraph.append(node);
1176
+ }
1177
+ });
1178
+
1179
+ // Like the Markdown import, there should be at least one paragraph
1180
+ // @see https://github.com/facebook/lexical/issues/2308
1181
+ if (root.isEmpty()) {
1182
+ root.append(createParagraphNode());
1183
+ }
1184
+
1185
+ if (getSelection() !== null) {
1186
+ root.selectStart();
1187
+ }
1188
+ },
1189
+ /**
1190
+ * Export the content as HTML.
1191
+ * @returns {string} HTML.
1192
+ */
1193
+ $export: () => exportHtml(editor),
1194
+ formatName: 'HTML',
1195
+ });
1063
1196
  };
1064
1197
 
1065
1198
  /**