@sveltia/ui 0.89.2 → 0.89.3

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 (98) hide show
  1. package/dist/components/checkbox/checkbox.svelte +5 -8
  2. package/dist/components/emoji/emoji-suggestions.svelte +7 -7
  3. package/dist/components/grid/grid-col-header.svelte +4 -0
  4. package/dist/components/grid/grid-head.svelte +1 -1
  5. package/dist/components/grid/grid-head.svelte.d.ts +1 -1
  6. package/dist/components/radio/radio.svelte +9 -9
  7. package/dist/components/resizable-pane/resizable-pane-group.svelte +5 -20
  8. package/dist/components/resizable-pane/sizing.d.ts +6 -0
  9. package/dist/components/resizable-pane/sizing.js +31 -0
  10. package/dist/components/text-editor/code-editor.svelte +22 -39
  11. package/dist/components/text-editor/constants.js +3 -3
  12. package/dist/components/text-editor/conversion/editor-components.d.ts +5 -0
  13. package/dist/components/text-editor/conversion/editor-components.js +228 -0
  14. package/dist/components/text-editor/{html.d.ts → conversion/html.d.ts} +1 -1
  15. package/dist/components/text-editor/{html.js → conversion/html.js} +2 -2
  16. package/dist/components/text-editor/conversion/import.d.ts +12 -0
  17. package/dist/components/text-editor/conversion/import.js +327 -0
  18. package/dist/components/text-editor/conversion/paste.d.ts +4 -0
  19. package/dist/components/text-editor/conversion/paste.js +166 -0
  20. package/dist/components/text-editor/{transformers → conversion/transformers}/raw-syntax.js +4 -4
  21. package/dist/components/text-editor/conversion/transformers/table.js +342 -0
  22. package/dist/components/text-editor/conversion/update.d.ts +6 -0
  23. package/dist/components/text-editor/conversion/update.js +125 -0
  24. package/dist/components/text-editor/core.d.ts +50 -26
  25. package/dist/components/text-editor/core.js +133 -1694
  26. package/dist/components/text-editor/editing/caret.d.ts +4 -0
  27. package/dist/components/text-editor/editing/caret.js +248 -0
  28. package/dist/components/text-editor/editing/commands.d.ts +5 -0
  29. package/dist/components/text-editor/editing/commands.js +205 -0
  30. package/dist/components/text-editor/editing/link.d.ts +19 -0
  31. package/dist/components/text-editor/editing/link.js +222 -0
  32. package/dist/components/text-editor/{raw-markdown.d.ts → editing/raw-markdown.d.ts} +3 -3
  33. package/dist/components/text-editor/{raw-markdown.js → editing/raw-markdown.js} +2 -2
  34. package/dist/components/text-editor/editing/selection.d.ts +5 -0
  35. package/dist/components/text-editor/editing/selection.js +122 -0
  36. package/dist/components/text-editor/editing/single-line.d.ts +8 -0
  37. package/dist/components/text-editor/editing/single-line.js +190 -0
  38. package/dist/components/text-editor/{table.js → editing/table.js} +1 -1
  39. package/dist/components/text-editor/lexical-root.svelte +61 -10
  40. package/dist/components/text-editor/shiki/preload.d.ts +1 -0
  41. package/dist/components/text-editor/shiki/preload.js +30 -0
  42. package/dist/components/text-editor/shiki/version.d.ts +1 -1
  43. package/dist/components/text-editor/shiki/version.js +1 -1
  44. package/dist/components/text-editor/store.svelte.d.ts +5 -0
  45. package/dist/components/text-editor/store.svelte.js +55 -1
  46. package/dist/components/text-editor/text-editor.svelte +29 -41
  47. package/dist/components/text-editor/toolbar/align-menu-button.svelte +1 -1
  48. package/dist/components/text-editor/toolbar/code-language-switcher.svelte +2 -1
  49. package/dist/components/text-editor/toolbar/format-text-button.svelte +6 -2
  50. package/dist/components/text-editor/toolbar/insert-component.js +1 -1
  51. package/dist/components/text-editor/toolbar/insert-horizontal-rule-button.svelte +4 -4
  52. package/dist/components/text-editor/toolbar/insert-link-button.svelte +3 -2
  53. package/dist/components/text-editor/toolbar/insert-table-button.svelte +7 -3
  54. package/dist/components/text-editor/toolbar/table-action-menu.svelte +3 -3
  55. package/dist/components/text-editor/toolbar/text-editor-toolbar.svelte +1 -1
  56. package/dist/components/text-editor/toolbar/toggle-block-menu-item.svelte +2 -2
  57. package/dist/components/text-editor/utils.d.ts +1 -0
  58. package/dist/components/text-editor/utils.js +17 -0
  59. package/dist/components/text-editor/{emoji-autocomplete.svelte → widgets/emoji-autocomplete.svelte} +3 -3
  60. package/dist/components/text-editor/{floating-link-editor.svelte → widgets/floating-link-editor.svelte} +36 -79
  61. package/dist/components/text-editor/{table-cell-menu-button.svelte → widgets/table-cell-menu-button.svelte} +15 -5
  62. package/dist/components/text-field/date-time-input.svelte +8 -8
  63. package/dist/components/text-field/text-area.svelte +10 -10
  64. package/dist/components/text-field/text-input.svelte +7 -7
  65. package/dist/components/util/popup.svelte +1 -1
  66. package/dist/index.d.ts +1 -1
  67. package/dist/index.js +1 -1
  68. package/dist/services/label.d.ts +8 -0
  69. package/dist/services/label.js +15 -0
  70. package/dist/services/popup-position.d.ts +9 -0
  71. package/dist/services/popup-position.js +52 -55
  72. package/dist/styles/mixins.scss +69 -0
  73. package/package.json +5 -3
  74. package/dist/components/text-editor/transformers/table.js +0 -296
  75. /package/dist/components/text-editor/{markdown.d.ts → conversion/markdown.d.ts} +0 -0
  76. /package/dist/components/text-editor/{markdown.js → conversion/markdown.js} +0 -0
  77. /package/dist/components/text-editor/{transformers → conversion/transformers}/block-escape.d.ts +0 -0
  78. /package/dist/components/text-editor/{transformers → conversion/transformers}/block-escape.js +0 -0
  79. /package/dist/components/text-editor/{transformers → conversion/transformers}/code.d.ts +0 -0
  80. /package/dist/components/text-editor/{transformers → conversion/transformers}/code.js +0 -0
  81. /package/dist/components/text-editor/{transformers → conversion/transformers}/formatted-code.d.ts +0 -0
  82. /package/dist/components/text-editor/{transformers → conversion/transformers}/formatted-code.js +0 -0
  83. /package/dist/components/text-editor/{transformers → conversion/transformers}/hr.d.ts +0 -0
  84. /package/dist/components/text-editor/{transformers → conversion/transformers}/hr.js +0 -0
  85. /package/dist/components/text-editor/{transformers → conversion/transformers}/inline-code.d.ts +0 -0
  86. /package/dist/components/text-editor/{transformers → conversion/transformers}/inline-code.js +0 -0
  87. /package/dist/components/text-editor/{transformers → conversion/transformers}/link.d.ts +0 -0
  88. /package/dist/components/text-editor/{transformers → conversion/transformers}/link.js +0 -0
  89. /package/dist/components/text-editor/{transformers → conversion/transformers}/raw-syntax.d.ts +0 -0
  90. /package/dist/components/text-editor/{transformers → conversion/transformers}/table.d.ts +0 -0
  91. /package/dist/components/text-editor/{alignment.d.ts → editing/alignment.d.ts} +0 -0
  92. /package/dist/components/text-editor/{alignment.js → editing/alignment.js} +0 -0
  93. /package/dist/components/text-editor/{block.d.ts → editing/block.d.ts} +0 -0
  94. /package/dist/components/text-editor/{block.js → editing/block.js} +0 -0
  95. /package/dist/components/text-editor/{table.d.ts → editing/table.d.ts} +0 -0
  96. /package/dist/components/text-editor/{emoji-autocomplete.svelte.d.ts → widgets/emoji-autocomplete.svelte.d.ts} +0 -0
  97. /package/dist/components/text-editor/{floating-link-editor.svelte.d.ts → widgets/floating-link-editor.svelte.d.ts} +0 -0
  98. /package/dist/components/text-editor/{table-cell-menu-button.svelte.d.ts → widgets/table-cell-menu-button.svelte.d.ts} +0 -0
@@ -1,11 +1,4 @@
1
- import {
2
- CodeExtension,
3
- CodeHighlightNode,
4
- CodeNode,
5
- $createCodeNode as createCodeNode,
6
- $isCodeHighlightNode as isCodeHighlightNode,
7
- $isCodeNode as isCodeNode,
8
- } from '@lexical/code-core';
1
+ import { CodeExtension, CodeHighlightNode, CodeNode } from '@lexical/code-core';
9
2
  import { registerDragonSupport } from '@lexical/dragon';
10
3
  import {
11
4
  buildEditorFromExtensions,
@@ -13,144 +6,44 @@ import {
13
6
  HorizontalRuleNode,
14
7
  } from '@lexical/extension';
15
8
  import { createEmptyHistoryState, registerHistory } from '@lexical/history';
16
- import { $generateNodesFromDOM as generateNodesFromDOM } from '@lexical/html';
17
- import {
18
- $isLinkNode as isLinkNode,
19
- LinkNode,
20
- TOGGLE_LINK_COMMAND,
21
- $toggleLink as toggleLink,
22
- } from '@lexical/link';
23
- import {
24
- $handleListInsertParagraph as handleListInsertParagraph,
25
- INSERT_ORDERED_LIST_COMMAND,
26
- INSERT_UNORDERED_LIST_COMMAND,
27
- $insertList as insertList,
28
- $isListItemNode as isListItemNode,
29
- $isListNode as isListNode,
30
- ListNode,
31
- } from '@lexical/list';
32
- import {
33
- HEADING,
34
- $convertFromMarkdownString as convertFromMarkdownString,
35
- $convertToMarkdownString as convertToMarkdownString,
36
- $generateNodesFromMarkdownString as generateNodesFromMarkdownString,
37
- registerMarkdownShortcuts,
38
- } from '@lexical/markdown';
39
- import {
40
- $isHeadingNode as isHeadingNode,
41
- $isQuoteNode as isQuoteNode,
42
- registerRichText,
43
- } from '@lexical/rich-text';
9
+ import { registerMarkdownShortcuts } from '@lexical/markdown';
10
+ import { registerRichText } from '@lexical/rich-text';
44
11
  import { TableCellNode, TableExtension, TableNode, TableRowNode } from '@lexical/table';
45
- import {
46
- $getNearestNodeOfType as getNearestNodeOfType,
47
- objectKlassEquals,
48
- $unwrapNode as unwrapNode,
49
- } from '@lexical/utils';
50
- import { sleep } from '@sveltia/utils/misc';
51
- import { isURL } from '@sveltia/utils/string';
52
- import { isMac, matchesShortcuts } from '@sveltia/utils/events';
53
- import {
54
- COMMAND_PRIORITY_HIGH,
55
- COMMAND_PRIORITY_LOW,
56
- COMMAND_PRIORITY_NORMAL,
57
- configExtension,
58
- createEditor,
59
- defineExtension,
60
- DELETE_CHARACTER_COMMAND,
61
- $createParagraphNode as createParagraphNode,
62
- $createTextNode as createTextNode,
63
- ElementNode,
64
- $getNearestNodeFromDOMNode as getNearestNodeFromDOMNode,
65
- $getRoot as getRoot,
66
- $getSelection as getSelection,
67
- $setSelection as setSelection,
68
- HISTORY_MERGE_TAG,
69
- INDENT_CONTENT_COMMAND,
70
- INSERT_LINE_BREAK_COMMAND,
71
- INSERT_PARAGRAPH_COMMAND,
72
- KEY_DOWN_COMMAND,
73
- KEY_ENTER_COMMAND,
74
- LineBreakNode,
75
- $insertNodes as insertNodes,
76
- $isDecoratorNode as isDecoratorNode,
77
- $isElementNode as isElementNode,
78
- $isParagraphNode as isParagraphNode,
79
- $isRangeSelection as isRangeSelection,
80
- $isTextNode as isTextNode,
81
- OUTDENT_CONTENT_COMMAND,
82
- PASTE_COMMAND,
83
- PASTE_TAG,
84
- RootNode,
85
- } from 'lexical';
86
- import {
87
- BLOCK_BUTTON_TYPES,
88
- DISABLED_MARKDOWN_TAGS,
89
- EDITOR_THEME,
90
- IMPORT_UPDATE_TAG,
91
- INLINE_BUTTON_TYPES,
92
- NODE_MAP,
93
- TEXT_FORMAT_BUTTON_TYPES,
94
- TRANSFORMER_MAP,
95
- } from './constants.js';
12
+ import { configExtension, defineExtension } from 'lexical';
13
+ import { EDITOR_THEME, NODE_MAP, TRANSFORMER_MAP } from './constants.js';
96
14
  import {
97
15
  editorComponents,
98
- exportHtml,
99
- findUnsupportedNode,
100
- getCodeLanguage,
101
16
  HTML_CODE_IMPORT_MAP,
102
17
  HTML_EXPORT_MAP,
103
18
  HTML_IMPORT_MAP,
104
- } from './html.js';
105
- import {
106
- addImportPlaceholders,
107
- convertSetextHeadings,
108
- convertTildeFences,
109
- padBlankBlockquoteLines,
110
- removeImportPlaceholders,
111
- splitMultilineFormatting,
112
- trimBlankBlockquoteLines,
113
- } from './markdown.js';
114
- import {
115
- isPlainLanguage,
116
- loadCodeLanguage,
117
- loadCodeTheme,
118
- loadEngine,
119
- normalizeCodeLanguage,
120
- } from './shiki/facade.js';
19
+ } from './conversion/html.js';
121
20
  import { registerCodeHighlighting, shikiTokenizer } from './shiki/highlighter.js';
122
21
  import { getCodeTheme, observeCodeTheme } from './shiki/theme.js';
123
- import { BLOCK_SYNTAX_ESCAPE } from './transformers/block-escape.js';
124
- import { CODE } from './transformers/code.js';
125
- import { addCodeSpanSplit } from './transformers/formatted-code.js';
126
- import { HR } from './transformers/hr.js';
22
+ import { CODE } from './conversion/transformers/code.js';
23
+ import { HR } from './conversion/transformers/hr.js';
24
+ import { RAW_HTML, RAW_SYNTAX } from './conversion/transformers/raw-syntax.js';
25
+ import { $ensureParagraphAfterTable, $normalizeTableHeaders } from './editing/table.js';
26
+ import { createTableTransformer } from './conversion/transformers/table.js';
27
+ import { limitToSingleLine, registerSingleLine } from './editing/single-line.js';
28
+ import { removePlaceholdersFromMatch } from './conversion/editor-components.js';
127
29
  import {
128
- getImportedRawSyntax,
129
- HTML_BLOCK_PLACEHOLDER,
130
- RAW_HTML,
131
- RAW_SYNTAX,
132
- } from './transformers/raw-syntax.js';
133
- import { $getSelectedAlignment } from './alignment.js';
134
- import {
135
- $ensureParagraphAfterTable,
136
- $getSelectedTableCellKey,
137
- $normalizeTableHeaders,
138
- } from './table.js';
139
- import { createTableTransformer } from './transformers/table.js';
30
+ registerCodeEditorCommands,
31
+ registerListCommands,
32
+ registerTabIndentation,
33
+ } from './editing/commands.js';
34
+ import { mergeUnregisters } from './utils.js';
35
+ import { registerLinkCommands } from './editing/link.js';
36
+ import { registerUpdateEvent } from './conversion/update.js';
37
+ import { registerPasteAsMarkdown } from './conversion/paste.js';
140
38
 
141
39
  /**
142
- * @import { LexicalEditor, LexicalNode } from 'lexical';
143
- * @import { LinkAttributes } from '@lexical/link';
144
- * @import { ListType } from '@lexical/list';
40
+ * @import { LexicalEditor } from 'lexical';
145
41
  * @import { TextMatchTransformer, Transformer } from '@lexical/markdown';
146
42
  * @import {
147
- * TextEditorBlockType,
148
43
  * TextEditorComponent,
149
44
  * TextEditorConfig,
150
- * TextEditorInlineType,
151
45
  * TextEditorNodeType,
152
46
  * TextEditorValueFormat,
153
- * TextEditorSelectionState,
154
47
  * } from '../../typedefs.js';
155
48
  */
156
49
 
@@ -162,8 +55,20 @@ import { createTableTransformer } from './transformers/table.js';
162
55
  */
163
56
 
164
57
  /**
165
- * Payload of `TOGGLE_LINK_COMMAND` with the URL and the link attributes, like `target`.
166
- * @typedef {LinkAttributes & { url: string }} LinkAttributesWithURL
58
+ * Editor configuration with the defaults applied, and the features derived from it.
59
+ * @typedef {object} EditorSetup
60
+ * @property {TextEditorNodeType[]} enabledButtons Enabled buttons.
61
+ * @property {TextEditorComponent[]} components Editor components.
62
+ * @property {boolean | undefined} useMarkdownShortcuts Whether to enable Markdown shortcuts.
63
+ * @property {boolean} isCodeEditor Whether the editor is a code editor.
64
+ * @property {string} defaultLanguage Default code block language.
65
+ * @property {TextEditorValueFormat} format Value format.
66
+ * @property {boolean} multiline Whether the editor accepts multiple lines.
67
+ * @property {boolean} hasCodeBlock Whether to support code blocks.
68
+ * @property {boolean} hasTable Whether to support table editing.
69
+ * @property {boolean} hasHorizontalRule Whether to support selecting a horizontal rule.
70
+ * @property {boolean} hasBlockSyntax Whether to support horizontal rules and tables in Markdown,
71
+ * even without their buttons.
167
72
  */
168
73
 
169
74
  /**
@@ -172,1354 +77,11 @@ import { createTableTransformer } from './transformers/table.js';
172
77
  const HISTORY_MAX_DEPTH = 200;
173
78
 
174
79
  /**
175
- * Selector for the elements in a decorator node, like an editor component, that handle a click on
176
- * their own.
177
- */
178
- const DECORATOR_INTERACTIVE_SELECTOR = [
179
- 'input',
180
- 'textarea',
181
- 'select',
182
- 'button',
183
- 'a[href]',
184
- // A label moves the focus to its control on click
185
- 'label',
186
- 'summary',
187
- 'video[controls]',
188
- 'audio[controls]',
189
- '[tabindex]',
190
- '[draggable="true"]',
191
- '[contenteditable]:not([contenteditable="false"])',
192
- ].join(', ');
193
-
194
- /**
195
- * Whether a click on the given element would put the caret on the static content of a decorator
196
- * node, like the label or padding of an editor component. The editor cannot map such a position to
197
- * a node, so the caret appears there but typing does nothing.
198
- * @param {EventTarget | null} target Event target.
199
- * @returns {boolean} Result.
200
- */
201
- export const isStaticDecoratorContent = (target) => {
202
- if (!(target instanceof Element)) {
203
- return false;
204
- }
205
-
206
- const decorator = target.closest('[data-lexical-decorator]');
207
-
208
- if (!decorator) {
209
- return false;
210
- }
211
-
212
- const interactive = target.closest(DECORATOR_INTERACTIVE_SELECTOR);
213
-
214
- // An interactive element outside the decorator is the editor root or one of its ancestors
215
- return !interactive || !decorator.contains(interactive);
216
- };
217
-
218
- /**
219
- * Move a caret placed directly on the root node into a block: the adjacent paragraph or other
220
- * block, or a new paragraph if the adjacent nodes are decorators, where nothing can be typed.
221
- * @returns {boolean} Whether the selection has been moved.
222
- */
223
- const $moveCaretIntoBlock = () => {
224
- const selection = getSelection();
225
-
226
- if (
227
- !isRangeSelection(selection) ||
228
- !selection.isCollapsed() ||
229
- selection.anchor.type !== 'element'
230
- ) {
231
- return false;
232
- }
233
-
234
- const root = getRoot();
235
-
236
- if (!selection.anchor.getNode().is(root)) {
237
- return false;
238
- }
239
-
240
- const { offset } = selection.anchor;
241
- const before = root.getChildAtIndex(offset - 1);
242
- const after = root.getChildAtIndex(offset);
243
-
244
- if (isElementNode(after)) {
245
- after.selectStart();
246
- } else if (isElementNode(before)) {
247
- before.selectEnd();
248
- } else {
249
- const paragraph = createParagraphNode();
250
-
251
- if (before) {
252
- before.insertAfter(paragraph);
253
- } else if (after) {
254
- after.insertBefore(paragraph);
255
- } else {
256
- root.append(paragraph);
257
- }
258
-
259
- paragraph.select();
260
- }
261
-
262
- return true;
263
- };
264
-
265
- /**
266
- * Move the focus to the editor, and run the given function with the node of the given element
267
- * within an editor update.
268
- * @param {LexicalEditor} editor Editor instance.
269
- * @param {Element} element Element of the node.
270
- * @param {(node: ReturnType<typeof getNearestNodeFromDOMNode>) => void} callback Function to be
271
- * called with the node.
272
- */
273
- const updateNodeWithFocus = (editor, element, callback) => {
274
- editor.getRootElement()?.focus({ preventScroll: true });
275
-
276
- editor.update(() => {
277
- callback(getNearestNodeFromDOMNode(element));
278
- });
279
- };
280
-
281
- /**
282
- * Move the focus to the editor, and the caret to right after the given decorator node, like an
283
- * editor component: the start of the next block, or a new paragraph if there’s none to type in.
284
- * @param {LexicalEditor} editor Editor instance.
285
- * @param {Element} decorator Element of the decorator node.
286
- */
287
- const placeCaretAfterDecorator = (editor, decorator) => {
288
- updateNodeWithFocus(editor, decorator, (node) => {
289
- // The element has been found by its `data-lexical-decorator` attribute
290
- /* v8 ignore next 3 */
291
- if (!isDecoratorNode(node)) {
292
- return;
293
- }
294
-
295
- node.selectNext();
296
- $moveCaretIntoBlock();
297
- });
298
- };
299
-
300
- /**
301
- * Move the focus to the editor, and the caret to the end of the given block.
302
- * @param {LexicalEditor} editor Editor instance.
303
- * @param {Element} block Element of the block node.
304
- */
305
- const placeCaretAtBlockEnd = (editor, block) => {
306
- updateNodeWithFocus(editor, block, (node) => {
307
- /* v8 ignore next 3 */
308
- if (!isElementNode(node)) {
309
- return;
310
- }
311
-
312
- node.selectEnd();
313
- });
314
- };
315
-
316
- /**
317
- * Handle a `mousedown` event on the editor, placing the caret where the user expects, rather than
318
- * leaving it to the browser, when the pointer is not on any editable text. Browsers disagree on
319
- * where the caret goes in these cases, and some put it within a decorator node, like an editor
320
- * component, where the editor cannot map it to a node, so typing does nothing:
321
- *
322
- * - The static content of a decorator, like its label or padding, places the caret after it.
323
- * - The empty area of the editor, outside any block, places the caret after the decorator above
324
- * the pointer, or at the end of the block above the pointer.
325
- * @param {LexicalEditor} editor Editor instance.
326
- * @param {MouseEvent} event `mousedown` event.
327
- * @returns {boolean} Whether the event has been handled.
328
- */
329
- export const handleEditorMouseDown = (editor, event) => {
330
- const { target, button, shiftKey, clientY } = event;
331
- const root = editor.getRootElement();
332
-
333
- // Leave the primary button with Shift, which extends the selection, and other buttons alone.
334
- // Leave a read-only editor alone as well, as a paragraph may be added, and an event already
335
- // handled by a nested editor, like one in an editor component
336
- if (
337
- !root ||
338
- !editor.isEditable() ||
339
- event.defaultPrevented ||
340
- button !== 0 ||
341
- shiftKey ||
342
- !(target instanceof Element)
343
- ) {
344
- return false;
345
- }
346
-
347
- if (isStaticDecoratorContent(target)) {
348
- const decorator = /** @type {Element} */ (target.closest('[data-lexical-decorator]'));
349
-
350
- // A decorator of a nested editor, like one in an editor component, is handled by that editor
351
- if (decorator.parentElement?.closest('[data-lexical-editor]') !== root) {
352
- return false;
353
- }
354
-
355
- event.preventDefault();
356
- placeCaretAfterDecorator(editor, decorator);
357
-
358
- return true;
359
- }
360
-
361
- if (target !== root) {
362
- return false;
363
- }
364
-
365
- // Find the last block starting above the pointer. Lexical adds a hidden element to the root
366
- // after a decorator, which has no size
367
- const block = [...root.children]
368
- .filter((element) => !element.hasAttribute('data-lexical-decorator-boundary'))
369
- .findLast((element) => element.getBoundingClientRect().top <= clientY);
370
-
371
- if (!block) {
372
- return false;
373
- }
374
-
375
- if (block.hasAttribute('data-lexical-decorator')) {
376
- event.preventDefault();
377
- placeCaretAfterDecorator(editor, block);
378
-
379
- return true;
380
- }
381
-
382
- // Beside a block, the browser can find the nearest text on its own
383
- if (clientY <= block.getBoundingClientRect().bottom) {
384
- return false;
385
- }
386
-
387
- event.preventDefault();
388
- placeCaretAtBlockEnd(editor, block);
389
-
390
- return true;
391
- };
392
-
393
- /**
394
- * URL schemes allowed in a link, the same as the ones Lexical renders as is.
395
- */
396
- const SAFE_LINK_URL_SCHEMES = ['http', 'https', 'mailto', 'sms', 'tel'];
397
-
398
- /**
399
- * Whether the given URL is safe to be used as a link, meaning it’s either relative or uses one of
400
- * the {@link SAFE_LINK_URL_SCHEMES}. This keeps a URL like `javascript:alert(1)` out of the
401
- * Markdown, where the site that renders it may not sanitize it.
402
- * @param {string} url URL.
403
- * @returns {boolean} Result.
404
- */
405
- export const isSafeLinkURL = (url) => {
406
- // Browsers ignore control characters and spaces around a URL as well as tabs and newlines within
407
- // it, e.g. `java\tscript:`, so strip them all before looking for the scheme
408
- // eslint-disable-next-line no-control-regex
409
- const normalizedURL = url.replace(/[\u0000-\u0020]/g, '');
410
-
411
- // Markdown decodes character references and backslash escapes in a link destination, so a scheme
412
- // can be hidden with them, e.g. `&#106;avascript:`, `javascript&colon;` or `javascript\:`. Reject
413
- // any of them before the path, query or fragment.
414
- if (/^[^/?#]*[&\\]/.test(normalizedURL)) {
415
- return false;
416
- }
417
-
418
- const scheme = /^([a-z][a-z\d+.-]*):/i.exec(normalizedURL)?.[1];
419
-
420
- return !scheme || SAFE_LINK_URL_SCHEMES.includes(scheme.toLowerCase());
421
- };
422
-
423
- /**
424
- * Get the given node itself if it’s an element node, or its nearest element node ancestor.
425
- * @param {LexicalNode} node Node.
426
- * @returns {ElementNode | null} Element node.
427
- */
428
- const getNearestElementNode = (node) =>
429
- node instanceof ElementNode ? node : getNearestNodeOfType(node, ElementNode);
430
-
431
- /**
432
- * Get the current selection’s block node key as well as block and inline level types.
433
- * @internal
434
- * @returns {TextEditorSelectionState} Current selection state.
435
- */
436
- export const getSelectionTypes = () => {
437
- const selection = getSelection();
438
-
439
- if (!isRangeSelection(selection)) {
440
- return {
441
- blockNodeKey: null,
442
- blockType: 'paragraph',
443
- inlineTypes: [],
444
- // Several cells can be selected at once
445
- tableCellKey: $getSelectedTableCellKey(),
446
- alignment: '',
447
- };
448
- }
449
-
450
- const anchor = selection.anchor.getNode();
451
- /** @type {ElementNode | null} */
452
- let parent = null;
453
- /** @type {TextEditorInlineType[]} */
454
- const inlineTypes = TEXT_FORMAT_BUTTON_TYPES.filter((type) => selection.hasFormat(type));
455
-
456
- if (anchor.getType() !== 'root') {
457
- parent = getNearestElementNode(anchor);
458
-
459
- if (isLinkNode(parent)) {
460
- inlineTypes.push('link');
461
- // `getNearestNodeOfType()` would return the link itself, so start from its parent to find the
462
- // block the link is in
463
- parent = parent.getParent();
464
- }
465
-
466
- if (isListItemNode(parent)) {
467
- parent = getNearestNodeOfType(parent, ListNode);
468
- }
469
- }
470
-
471
- const blockType = /** @type {TextEditorBlockType} */ (
472
- (() => {
473
- if (!parent) {
474
- return 'paragraph';
475
- }
476
-
477
- if (isHeadingNode(parent)) {
478
- return `heading-${parent.getTag().match(/\d/)?.[0]}`;
479
- }
480
-
481
- if (isListNode(parent)) {
482
- return parent.getListType() === 'bullet' ? 'bulleted-list' : 'numbered-list';
483
- }
484
-
485
- if (isQuoteNode(parent)) {
486
- return 'blockquote';
487
- }
488
-
489
- if (isCodeNode(parent) || isCodeHighlightNode(parent)) {
490
- return 'code-block';
491
- }
492
-
493
- const type = parent.getType();
494
-
495
- if (BLOCK_BUTTON_TYPES.includes(/** @type {any} */ (type))) {
496
- return type;
497
- }
498
-
499
- return 'paragraph';
500
- })()
501
- );
502
-
503
- return {
504
- blockNodeKey: parent?.getKey() ?? null,
505
- blockType,
506
- inlineTypes,
507
- tableCellKey: $getSelectedTableCellKey(),
508
- alignment: $getSelectedAlignment(),
509
- };
510
- };
511
-
512
- /**
513
- * Convert the editor content to Markdown. Call this within an editor update or read.
514
- * @internal
515
- * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.
516
- * @returns {string} Markdown value.
517
- */
518
- export const exportMarkdown = (enabledTransformers) => {
519
- const transformers = [
520
- ...enabledTransformers.filter(
521
- (/** @type {any} */ { tag }) => !DISABLED_MARKDOWN_TAGS.includes(tag),
522
- ),
523
- // Tidy up the escapes in text and escape the block syntax at the start of a line. Last, so a
524
- // transformer of the editor’s own, such as a link, comes first
525
- BLOCK_SYNTAX_ESCAPE,
526
- ];
527
-
528
- return trimBlankBlockquoteLines(
529
- convertToMarkdownString(transformers)
530
- // Remove the line breaks left by empty paragraphs at the end, which have no content. One
531
- // may be added just by clicking below a block decorator; see `$moveCaretIntoBlock()`
532
- .replace(/\n+$/, ''),
533
- );
534
- };
535
-
536
- /**
537
- * Listen to changes made on the editor and trigger the Update event.
538
- * @internal
539
- * @param {LexicalEditor} editor Editor instance.
540
- * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.
541
- * @param {string} [cachedValue] Value from a previous call, to be reused instead of converting the
542
- * whole document again when only the selection has changed.
543
- * @param {TextEditorValueFormat} [format] Value format.
544
- * @returns {string} Markdown or HTML value.
545
- */
546
- export const onEditorUpdate = (editor, enabledTransformers, cachedValue, format = 'markdown') => {
547
- const value =
548
- cachedValue ?? (format === 'html' ? exportHtml(editor) : exportMarkdown(enabledTransformers));
549
-
550
- editor.getRootElement()?.dispatchEvent(
551
- new CustomEvent('Update', {
552
- detail: {
553
- value,
554
- selection: getSelectionTypes(),
555
- },
556
- }),
557
- );
558
-
559
- return value;
560
- };
561
-
562
- /**
563
- * Get the Markdown of a new instance of the given editor component, to insert it in the plain text
564
- * mode. The component’s own `createMarkdown` function is used if any. Otherwise, a new node is
565
- * created in a temporary editor and exported with the component’s transformer, just like the rich
566
- * text editor does.
567
- * @param {TextEditorComponent} component Editor component.
568
- * @returns {string} Markdown. It can be empty, for example if the component’s output depends on a
569
- * field value that is not set yet.
570
- */
571
- export const getComponentMarkdown = ({ node, createNode, transformer, createMarkdown }) => {
572
- if (createMarkdown) {
573
- return createMarkdown().trim();
574
- }
575
-
576
- const editor = createEditor({
577
- namespace: 'component',
578
- nodes: node ? [/** @type {any} */ (node)] : [],
579
- /**
580
- * Throw an error, so the export below fails as a whole.
581
- * @param {Error} error Error.
582
- * @throws {Error} Always.
583
- */
584
- onError: (error) => {
585
- throw error;
586
- },
587
- });
588
-
589
- let markdown = '';
590
-
591
- try {
592
- editor.update(
593
- () => {
594
- const newNode = createNode();
595
-
596
- // An inline node needs a paragraph to live in
597
- getRoot().append(newNode.isInline() ? createParagraphNode().append(newNode) : newNode);
598
-
599
- markdown = onEditorUpdate(editor, [transformer]);
600
- },
601
- { discrete: true },
602
- );
603
- } catch {
604
- // The component cannot be created or exported outside the rich text editor
605
- }
606
-
607
- return markdown.trim();
608
- };
609
-
610
- /**
611
- * Combine the given cleanup handlers into one, which calls them in the given order. Missing
612
- * handlers, like those of the features that are not enabled, are skipped.
613
- * @param {...((() => void) | undefined | null)} unregisters Cleanup handlers.
614
- * @returns {() => void} Combined cleanup handler.
615
- */
616
- const mergeUnregisters = (...unregisters) => {
617
- const handlers = unregisters.filter((unregister) => typeof unregister === 'function');
618
-
619
- return () => {
620
- handlers.forEach((unregister) => unregister());
621
- };
622
- };
623
-
624
- /**
625
- * Register the commands and transform specific to the code editor, which only holds a single code
626
- * block.
627
- * @param {LexicalEditor} editor Editor instance.
628
- * @param {string} defaultLanguage Default language of the code block.
629
- * @returns {() => void} Cleanup handler.
630
- */
631
- const registerCodeEditorCommands = (editor, defaultLanguage) =>
632
- mergeUnregisters(
633
- // Pressing Backspace at the very beginning of a code block converts it to a paragraph by
634
- // default (`CodeNode.collapseAtStart()`), which makes no sense when the editor only holds a
635
- // single code block, so ignore it
636
- editor.registerCommand(
637
- DELETE_CHARACTER_COMMAND,
638
- (isBackward) => {
639
- const selection = getSelection();
640
-
641
- if (!isBackward || !isRangeSelection(selection) || !selection.isCollapsed()) {
642
- return false;
643
- }
644
-
645
- const { offset } = selection.anchor;
646
- const node = selection.anchor.getNode();
647
- const codeNode = isCodeNode(node) ? node : getNearestNodeOfType(node, CodeNode);
648
-
649
- return (
650
- !!codeNode &&
651
- offset === 0 &&
652
- (node.is(codeNode) || !!codeNode.getFirstDescendant()?.is(node))
653
- );
654
- },
655
- COMMAND_PRIORITY_LOW,
656
- ),
657
- // Pressing Enter after two blank lines at the end of a code block exits it by default
658
- // (`CodeExtension`), adding a paragraph after it, which would be left out of the code. Insert a
659
- // new line instead, which `CodeNode.insertNewAfter()` does without exiting when the extension
660
- // is in place. This has to take priority over the extension’s own handler
661
- editor.registerCommand(
662
- KEY_ENTER_COMMAND,
663
- (event) => {
664
- const selection = getSelection();
665
-
666
- if (!isRangeSelection(selection)) {
667
- return false;
668
- }
669
-
670
- event?.preventDefault();
671
-
672
- return editor.dispatchCommand(INSERT_PARAGRAPH_COMMAND, undefined);
673
- },
674
- COMMAND_PRIORITY_NORMAL,
675
- ),
676
- // Make sure the editor always has a single code block. This runs within the same update that
677
- // made the change, so the user never gets a chance to type in anything else
678
- editor.registerNodeTransform(RootNode, (root) => {
679
- const children = root.getChildren();
680
-
681
- if (children.length === 1 && isCodeNode(children[0])) {
682
- return;
683
- }
684
-
685
- const [firstChild] = children;
686
-
687
- if (children.length === 1 && isElementNode(firstChild)) {
688
- const node = createCodeNode(defaultLanguage);
689
-
690
- // Keep the content and the selection
691
- firstChild.replace(node, true);
692
- } else if (children.length === 0) {
693
- const node = createCodeNode(defaultLanguage);
694
-
695
- root.append(node);
696
- node.selectStart();
697
- }
698
- }),
699
- );
700
-
701
- /**
702
- * Check if the given editor component is inline, which means its Markdown is matched within a line
703
- * of text by a text match transformer. Only an inline component can be inserted into a Markdown
704
- * table cell or a single-line editor.
705
- * @param {TextEditorComponent} component Editor component.
706
- * @returns {boolean} Result.
707
- */
708
- export const isInlineComponent = ({ transformer }) => transformer.type === 'text-match';
709
-
710
- /**
711
- * Limit the given editor configuration to what a single-line editor can hold, if it’s one: only
712
- * the inline buttons and components, and no plain text mode for HTML, whose source can’t be kept to
713
- * a single paragraph by keeping it on a single line. Any other configuration is returned as is.
714
- * @param {TextEditorConfig} config Editor configuration.
715
- * @returns {TextEditorConfig} Limited configuration.
716
- */
717
- export const limitToSingleLine = (config) => {
718
- if (config.multiline !== false || config.isCodeEditor) {
719
- return config;
720
- }
721
-
722
- return {
723
- ...config,
724
- modes: config.format === 'html' ? ['rich-text'] : config.modes,
725
- enabledButtons: (config.enabledButtons ?? []).filter((button) =>
726
- /** @type {TextEditorNodeType[]} */ (INLINE_BUTTON_TYPES).includes(button),
727
- ),
728
- components: (config.components ?? []).filter(isInlineComponent),
729
- };
730
- };
731
-
732
- /**
733
- * Get the inline content of the given top-level node, looking into any block within it.
734
- * @param {LexicalNode} node Node.
735
- * @returns {LexicalNode[]} Inline nodes, or an empty array for a block that has no inline content,
736
- * like a horizontal rule.
737
- */
738
- const getInlineContent = (node) => {
739
- if (isElementNode(node) && !node.isInline()) {
740
- return node.getChildren().flatMap(getInlineContent);
741
- }
742
-
743
- return node.isInline() ? [node] : [];
744
- };
745
-
746
- /**
747
- * Join the top-level nodes of the given root into a single paragraph, with a space between the
748
- * content of each, for a single-line editor.
749
- * @param {RootNode} root Root node.
750
- */
751
- export const $joinIntoSingleParagraph = (root) => {
752
- const children = root.getChildren();
753
- const [firstChild] = children;
754
-
755
- if (!firstChild || (children.length === 1 && isParagraphNode(firstChild))) {
756
- return;
757
- }
758
-
759
- const paragraph = isParagraphNode(firstChild) ? firstChild : createParagraphNode();
760
-
761
- if (paragraph !== firstChild) {
762
- firstChild.insertBefore(paragraph);
763
- }
764
-
765
- // Keep track of the last character rather than reading the growing text of the paragraph again
766
- // for each block, which would take quadratic time on a long pasted document
767
- let lastChar = paragraph.getTextContent().at(-1) ?? '';
768
-
769
- children
770
- .filter((child) => child !== paragraph)
771
- .forEach((child) => {
772
- const content = getInlineContent(child);
773
- const text = content.map((node) => node.getTextContent()).join('');
774
-
775
- // Add a space between the content of each block, unless there’s one already
776
- if (content.length && paragraph.getChildrenSize() && !/\s/.test(lastChar + text.charAt(0))) {
777
- paragraph.append(createTextNode(' '));
778
- }
779
-
780
- paragraph.append(...content);
781
- lastChar = text.at(-1) ?? lastChar;
782
- // Lexical moves the selection out of a removed node on its own
783
- child.remove();
784
- });
785
- };
786
-
787
- /**
788
- * Replace the given line break with a space for a single-line editor, with the formats the text on
789
- * both sides shares, so a line break within bold text doesn’t split it. With a space on either side
790
- * already, or nothing at all, the line break is just removed.
791
- * @param {LineBreakNode} node Line break.
792
- */
793
- export const $replaceLineBreak = (node) => {
794
- const previous = node.getPreviousSibling();
795
- const next = node.getNextSibling();
796
-
797
- // A line break at either end of the paragraph separates nothing, so it leaves no space
798
- if (
799
- !previous ||
800
- !next ||
801
- /\s$/.test(previous.getTextContent()) ||
802
- /^\s/.test(next.getTextContent())
803
- ) {
804
- node.remove();
805
-
806
- return;
807
- }
808
-
809
- const space = createTextNode(' ');
810
-
811
- // A link split over lines, like the ones `splitMultilineFormatting()` makes from a link within
812
- // formatting, is joined back into one link
813
- const isSameLink =
814
- isLinkNode(previous) &&
815
- isLinkNode(next) &&
816
- previous.getURL() === next.getURL() &&
817
- previous.getTitle() === next.getTitle() &&
818
- previous.getTarget() === next.getTarget() &&
819
- previous.getRel() === next.getRel();
820
-
821
- // The text next to the line break, also within an inline element like a link
822
- const before = isElementNode(previous) ? previous.getLastDescendant() : previous;
823
- const after = isElementNode(next) ? next.getFirstDescendant() : next;
824
-
825
- if (isTextNode(before) && isTextNode(after)) {
826
- // Keep the formats both sides share, e.g. italic between italic and bold italic text
827
- TEXT_FORMAT_BUTTON_TYPES.forEach((format) => {
828
- if (before.hasFormat(format) && after.hasFormat(format)) {
829
- space.toggleFormat(format);
830
- }
831
- });
832
-
833
- if (before.getStyle() === after.getStyle()) {
834
- space.setStyle(before.getStyle());
835
- }
836
- }
837
-
838
- if (isSameLink) {
839
- previous.append(space, ...next.getChildren());
840
- next.remove();
841
- node.remove();
842
-
843
- return;
844
- }
845
-
846
- node.replace(space);
847
- };
848
-
849
- /**
850
- * Register the commands and transforms that keep a single-line editor on one line. Neither a new
851
- * paragraph nor a line break can be inserted, and any content that brings them in anyway, like
852
- * pasted text or an imported value, is joined into a single paragraph with spaces.
853
- * @param {LexicalEditor} editor Editor instance.
854
- * @returns {() => void} Cleanup handler.
855
- */
856
- const registerSingleLine = (editor) =>
857
- mergeUnregisters(
858
- // The emoji autocomplete, which selects an emoji with the Enter key, takes priority
859
- editor.registerCommand(
860
- KEY_ENTER_COMMAND,
861
- (event) => {
862
- event?.preventDefault();
863
-
864
- return true;
865
- },
866
- COMMAND_PRIORITY_HIGH,
867
- ),
868
- editor.registerCommand(INSERT_PARAGRAPH_COMMAND, () => true, COMMAND_PRIORITY_HIGH),
869
- editor.registerCommand(INSERT_LINE_BREAK_COMMAND, () => true, COMMAND_PRIORITY_HIGH),
870
- editor.registerNodeTransform(LineBreakNode, $replaceLineBreak),
871
- editor.registerNodeTransform(RootNode, $joinIntoSingleParagraph),
872
- );
873
-
874
- /**
875
- * Register the link command, the paste handler that turns a pasted URL into a link, and the
876
- * transform that removes a link with an unsafe URL.
877
- * @param {LexicalEditor} editor Editor instance.
878
- * @returns {() => void} Cleanup handler.
879
- * @see https://github.com/facebook/lexical/blob/main/packages/lexical-link/src/LexicalLinkExtension.ts
880
- */
881
- const registerLinkCommands = (editor) =>
882
- mergeUnregisters(
883
- // A link can also be created by importing the value or pasting rich text, which bypass the
884
- // command below. Unwrap a link with an unsafe URL, keeping its text, so the URL never reaches
885
- // the Markdown or HTML value
886
- editor.registerNodeTransform(LinkNode, (node) => {
887
- if (!isSafeLinkURL(node.getURL())) {
888
- unwrapNode(node);
889
- }
890
- }),
891
- editor.registerCommand(
892
- TOGGLE_LINK_COMMAND,
893
- (payload) => {
894
- // The payload is the URL, or an object with the URL and attributes like `target`
895
- const url = typeof payload === 'string' ? payload : (payload?.url ?? null);
896
-
897
- // Ignore an unsafe URL rather than linking to it
898
- if (url !== null && !isSafeLinkURL(url)) {
899
- return true;
900
- }
901
-
902
- toggleLink(url === null ? null : /** @type {string | LinkAttributesWithURL} */ (payload));
903
-
904
- return true;
905
- },
906
- COMMAND_PRIORITY_NORMAL,
907
- ),
908
- editor.registerCommand(
909
- PASTE_COMMAND,
910
- (event) => {
911
- const selection = getSelection();
912
-
913
- if (
914
- !isRangeSelection(selection) ||
915
- !objectKlassEquals(event, ClipboardEvent) ||
916
- !event.clipboardData ||
917
- /** @type {HTMLElement} */ (event.target).matches('input, textarea')
918
- ) {
919
- return false;
920
- }
921
-
922
- const clipboardText = event.clipboardData.getData('text').trim();
923
-
924
- // Paste an unsafe URL as plain text rather than as a link
925
- if (!isURL(clipboardText) || !isSafeLinkURL(clipboardText)) {
926
- return false;
927
- }
928
-
929
- if (selection.isCollapsed()) {
930
- insertNodes([createTextNode(clipboardText)]);
931
- }
932
-
933
- if (
934
- !selection
935
- .getNodes()
936
- .some((node) => isElementNode(node) || (isTextNode(node) && !node.isSimpleText()))
937
- ) {
938
- editor.dispatchCommand(TOGGLE_LINK_COMMAND, clipboardText);
939
- event.preventDefault();
940
- return true;
941
- }
942
-
943
- return false;
944
- },
945
- COMMAND_PRIORITY_LOW,
946
- ),
947
- );
948
-
949
- /**
950
- * List buttons, along with the command to insert the list and its type.
951
- * @type {[TextEditorBlockType, typeof INSERT_UNORDERED_LIST_COMMAND, ListType][]}
952
- */
953
- const LIST_COMMANDS = [
954
- ['bulleted-list', INSERT_UNORDERED_LIST_COMMAND, 'bullet'],
955
- ['numbered-list', INSERT_ORDERED_LIST_COMMAND, 'number'],
956
- ];
957
-
958
- /**
959
- * Register the commands for the enabled list buttons.
960
- * @param {LexicalEditor} editor Editor instance.
961
- * @param {TextEditorConfig['enabledButtons']} enabledButtons Enabled buttons.
962
- * @returns {() => void} Cleanup handler.
963
- */
964
- const registerListCommands = (editor, enabledButtons = []) => {
965
- const enabledLists = LIST_COMMANDS.filter(([button]) => enabledButtons.includes(button));
966
-
967
- return mergeUnregisters(
968
- ...enabledLists.map(([, command, listType]) =>
969
- editor.registerCommand(
970
- command,
971
- () => {
972
- insertList(listType);
973
-
974
- return true;
975
- },
976
- COMMAND_PRIORITY_NORMAL,
977
- ),
978
- ),
979
- // https://github.com/facebook/lexical/blob/main/packages/lexical-react/src/shared/useList.ts
980
- enabledLists.length
981
- ? editor.registerCommand(
982
- INSERT_PARAGRAPH_COMMAND,
983
- () => handleListInsertParagraph(),
984
- COMMAND_PRIORITY_NORMAL,
985
- )
986
- : undefined,
987
- );
988
- };
989
-
990
- /**
991
- * Register an update listener that triggers the Update event with the Markdown or HTML value,
992
- * debounced so only the latest update in a burst triggers it.
993
- * @param {LexicalEditor} editor Editor instance.
994
- * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.
995
- * @param {TextEditorValueFormat} format Value format.
996
- * @returns {() => void} Cleanup handler.
997
- */
998
- const registerUpdateEvent = (editor, enabledTransformers, format) => {
999
- /** Incremented on every update, so only the latest one in a burst triggers the Update event. */
1000
- let updateCount = 0;
1001
- /** Whether the content has changed since the Update event was last triggered. */
1002
- let contentChanged = true;
1003
- /** @type {string | undefined} */
1004
- let lastValue = undefined;
1005
- let disposed = false;
1006
-
1007
- return mergeUnregisters(
1008
- () => {
1009
- disposed = true;
1010
- },
1011
- editor.registerUpdateListener(({ dirtyElements, dirtyLeaves } = /** @type {any} */ ({})) => {
1012
- // An update that only moves the selection leaves no dirty nodes. Remember whether any update
1013
- // in the burst changed the content, so the document is only converted again when needed.
1014
- // This includes the updates made while composing, which are otherwise skipped.
1015
- contentChanged ||= !dirtyElements || dirtyElements.size > 0 || dirtyLeaves.size > 0;
1016
-
1017
- if (editor?.isComposing()) {
1018
- return;
1019
- }
1020
-
1021
- updateCount += 1;
1022
-
1023
- const currentCount = updateCount;
1024
-
1025
- (async () => {
1026
- await sleep(100);
1027
-
1028
- // Skip if a newer update has been made in the meantime, or the editor has been disposed
1029
- if (currentCount !== updateCount || disposed) {
1030
- return;
1031
- }
1032
-
1033
- editor.update(() => {
1034
- lastValue = onEditorUpdate(
1035
- editor,
1036
- enabledTransformers,
1037
- contentChanged ? undefined : lastValue,
1038
- format,
1039
- );
1040
- contentChanged = false;
1041
- });
1042
- })();
1043
- }),
1044
- );
1045
- };
1046
-
1047
- /**
1048
- * Register a handler for the Tab key that indents a list item, or unindents it with Shift.
1049
- * `editor.registerCommand(KEY_TAB_COMMAND, listener, priority)` doesn’t work for some reason, so
1050
- * listen to the `keydown` event on the root element instead.
1051
- * @param {LexicalEditor} editor Editor instance.
1052
- * @returns {() => void} Cleanup handler.
1053
- */
1054
- const registerTabIndentation = (editor) =>
1055
- editor.registerRootListener((root) => {
1056
- if (!root) {
1057
- return undefined;
1058
- }
1059
-
1060
- /**
1061
- * Handle Tab indentation shortcuts.
1062
- * @param {KeyboardEvent} event Keydown event.
1063
- */
1064
- const onKeydown = (event) => {
1065
- editor.update(() => {
1066
- if (event.key === 'Tab') {
1067
- const selection = getSelection();
1068
-
1069
- if (!isRangeSelection(selection)) {
1070
- return;
1071
- }
1072
-
1073
- const parent = getNearestElementNode(selection.anchor.getNode());
1074
-
1075
- if (isListItemNode(parent) && parent.canIndent()) {
1076
- if (!event.shiftKey) {
1077
- event.preventDefault();
1078
- editor.dispatchCommand(INDENT_CONTENT_COMMAND, undefined);
1079
- } else if (parent.getIndent() > 0) {
1080
- event.preventDefault();
1081
- editor.dispatchCommand(OUTDENT_CONTENT_COMMAND, undefined);
1082
- }
1083
- }
1084
- }
1085
- });
1086
- };
1087
-
1088
- root.addEventListener('keydown', onKeydown);
1089
-
1090
- return () => {
1091
- root.removeEventListener('keydown', onKeydown);
1092
- };
1093
- });
1094
-
1095
- /**
1096
- * Remove the placeholders added by `addImportPlaceholders()` from a regular expression match.
1097
- * @param {RegExpMatchArray} match Match.
1098
- * @returns {RegExpMatchArray} Match without the placeholders, with the same index and input.
1099
- */
1100
- const cleanMatch = (match) => {
1101
- /**
1102
- * Remove the placeholders from a captured string, if any.
1103
- * @param {string | undefined} value Captured string.
1104
- * @returns {string | undefined} Cleaned string.
1105
- */
1106
- const clean = (value) => (value === undefined ? value : removeImportPlaceholders(value));
1107
-
1108
- return /** @type {RegExpMatchArray} */ (
1109
- Object.assign(match.map(clean), {
1110
- index: match.index,
1111
- input: match.input,
1112
- groups: match.groups
1113
- ? Object.fromEntries(
1114
- Object.entries(match.groups).map(([key, value]) => [key, clean(value)]),
1115
- )
1116
- : undefined,
1117
- })
1118
- );
1119
- };
1120
-
1121
- /**
1122
- * Make a regular expression match the text after the placeholder at the start of a line of an HTML
1123
- * block, if any, so the pattern of an editor component, like `^<aside>`, still matches the line.
1124
- * @param {RegExp} regExp Regular expression without the `g` flag.
1125
- * @param {boolean} isLineStart Whether Lexical takes the match as the start of the line and removes
1126
- * it by its length, like that of an element transformer, in which case the match includes the
1127
- * placeholder. Otherwise its index is moved past the placeholder.
1128
- * @returns {RegExp} Regular expression.
1129
- */
1130
- const skipHtmlBlockPlaceholder = (regExp, isLineStart) =>
1131
- // Lexical matches the text with `String.prototype.match()`, which calls this method
1132
- Object.assign(new RegExp(regExp), {
1133
- /**
1134
- * Match the text after the placeholder at its start, if any.
1135
- * @param {string} text Text.
1136
- * @returns {RegExpMatchArray | null} Match.
1137
- */
1138
- [Symbol.match]: (text) => {
1139
- const offset = text.startsWith(HTML_BLOCK_PLACEHOLDER) ? 1 : 0;
1140
- const match = text.slice(offset).match(regExp);
1141
-
1142
- if (!match || !offset) {
1143
- return match;
1144
- }
1145
-
1146
- match.input = text;
1147
-
1148
- if (isLineStart && match.index === 0) {
1149
- match[0] = `${HTML_BLOCK_PLACEHOLDER}${match[0]}`;
1150
- } else {
1151
- // The pattern has no `g` flag, so the match has an index
1152
- /** @type {number} */ (match.index) += offset;
1153
- }
1154
-
1155
- return match;
1156
- },
1157
- });
1158
-
1159
- /**
1160
- * Remove the placeholders added by `addImportPlaceholders()` from an argument of a transformer’s
1161
- * `replace()`: a regular expression match, or the lines of a multiline element.
1162
- * @param {any} arg Argument.
1163
- * @returns {any} Argument without the placeholders.
1164
- */
1165
- const cleanReplaceArg = (arg) => {
1166
- if (!Array.isArray(arg)) {
1167
- return arg;
1168
- }
1169
-
1170
- if ('index' in arg) {
1171
- return cleanMatch(/** @type {RegExpMatchArray} */ (arg));
1172
- }
1173
-
1174
- return arg.every((item) => typeof item === 'string')
1175
- ? arg.map((line) => removeImportPlaceholders(line))
1176
- : arg;
1177
- };
1178
-
1179
- /**
1180
- * Make an editor component’s transformer import the Markdown without the placeholders added by
1181
- * `addImportPlaceholders()`, which `removePlaceholders()` can’t remove from the properties of the
1182
- * component node it creates, like the alt text of an image. The line of an HTML block starts with
1183
- * a placeholder, so the patterns of a component, like `^<aside>`, are matched after it.
1184
- * @param {Transformer} transformer Transformer.
1185
- * @returns {Transformer} Transformer.
1186
- */
1187
- export const removePlaceholdersFromMatch = (transformer) => {
1188
- /** @type {any} */
1189
- const {
1190
- type,
1191
- handleImportAfterStartMatch,
1192
- importRegExp,
1193
- regExp,
1194
- regExpStart,
1195
- regExpEnd,
1196
- replace,
1197
- } = transformer;
1198
-
1199
- /** @type {Record<string, any>} */
1200
- const overrides = {};
1201
-
1202
- if (handleImportAfterStartMatch) {
1203
- /**
1204
- * Import the lines without the placeholders.
1205
- * @param {{ lines: string[] }} args Arguments.
1206
- * @returns {any} Result.
1207
- */
1208
- overrides.handleImportAfterStartMatch = (args) =>
1209
- handleImportAfterStartMatch({
1210
- ...args,
1211
- lines: args.lines.map((line) => removeImportPlaceholders(line)),
1212
- });
1213
- }
1214
-
1215
- if (importRegExp) {
1216
- overrides.importRegExp = skipHtmlBlockPlaceholder(importRegExp, false);
1217
- }
1218
-
1219
- // The regular expression of an element is matched against the start of a line on import
1220
- if (type === 'element' && regExp) {
1221
- overrides.regExp = skipHtmlBlockPlaceholder(regExp, true);
1222
- }
1223
-
1224
- if (regExpStart) {
1225
- overrides.regExpStart = skipHtmlBlockPlaceholder(regExpStart, true);
1226
- }
1227
-
1228
- if (regExpEnd instanceof RegExp) {
1229
- overrides.regExpEnd = skipHtmlBlockPlaceholder(regExpEnd, true);
1230
- } else if (regExpEnd?.regExp) {
1231
- overrides.regExpEnd = {
1232
- ...regExpEnd,
1233
- regExp: skipHtmlBlockPlaceholder(regExpEnd.regExp, true),
1234
- };
1235
- }
1236
-
1237
- if (replace) {
1238
- /**
1239
- * Import the match and the lines without the placeholders.
1240
- * @param {...any} args Arguments.
1241
- * @returns {any} Result.
1242
- */
1243
- overrides.replace = (...args) => replace(...args.map(cleanReplaceArg));
1244
- }
1245
-
1246
- return /** @type {Transformer} */ ({ ...transformer, ...overrides });
1247
- };
1248
-
1249
- /**
1250
- * Preload the syntax highlighter for the given programming language.
1251
- *
1252
- * Highlighting also works without this — the transform loads whatever it needs and re-highlights
1253
- * once it arrives — but preloading avoids a visible flash of unhighlighted code.
1254
- * @param {string} lang Language name, like scss.
1255
- */
1256
- export const loadCodeHighlighter = async (lang) => {
1257
- if (isPlainLanguage(lang)) {
1258
- return;
1259
- }
1260
-
1261
- // The grammar and theme loaders are no-ops until the engine is in place
1262
- await loadEngine();
1263
-
1264
- await Promise.all([loadCodeLanguage(normalizeCodeLanguage(lang)), loadCodeTheme(getCodeTheme())]);
1265
- };
1266
-
1267
- /**
1268
- * Remove the placeholders added by `addImportPlaceholders()` from the imported nodes: the text, the
1269
- * Markdown of raw syntax, and the URL and title of a link. The text of raw syntax is restored from
1270
- * the Markdown it was imported from, as Lexical has removed its escapes, which are not escapes in
1271
- * raw HTML; see `RAW_HTML`.
1272
- * @param {LexicalNode[]} nodes Imported nodes.
1273
- */
1274
- const removePlaceholders = (nodes) => {
1275
- nodes
1276
- .flatMap((node) => (isElementNode(node) ? node.getAllTextNodes() : node))
1277
- .filter((node) => isTextNode(node))
1278
- .forEach((node) => {
1279
- const text = node.getTextContent();
1280
- const newText = removeImportPlaceholders(getImportedRawSyntax(node) ?? text);
1281
- const link = node.getParent();
1282
-
1283
- if (newText !== text) {
1284
- node.setTextContent(newText);
1285
- }
1286
-
1287
- if (isLinkNode(link)) {
1288
- const url = link.getURL();
1289
- const title = link.getTitle();
1290
-
1291
- if (removeImportPlaceholders(url) !== url) {
1292
- link.setURL(removeImportPlaceholders(url));
1293
- }
1294
-
1295
- if (title && removeImportPlaceholders(title) !== title) {
1296
- link.setTitle(removeImportPlaceholders(title));
1297
- }
1298
- }
1299
- });
1300
- };
1301
-
1302
- /**
1303
- * Prepare Markdown for the import: convert the syntax Lexical doesn’t support to the one it does,
1304
- * if the element is enabled, and list the programming languages used in the code blocks.
1305
- * @param {string} value Markdown.
1306
- * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1307
- * @returns {{ markdown: string, languages: string[] }} Normalized Markdown and the languages.
1308
- */
1309
- const prepareMarkdown = (value, enabledTransformers) => {
1310
- // Tilde code fences are converted to backtick ones, and setext headings to ATX ones. Otherwise
1311
- // the syntax is kept as text, as written. A transformer is found by its regular expression,
1312
- // because the transformers can come wrapped in a `$state` proxy, which leaves a regular
1313
- // expression as is but not the transformer object itself
1314
- const hasCodeBlocks = enabledTransformers.some(
1315
- (transformer) => 'regExpStart' in transformer && transformer.regExpStart === CODE.regExpStart,
1316
- );
1317
-
1318
- const hasHeadings = enabledTransformers.some(
1319
- (transformer) => 'regExp' in transformer && transformer.regExp === HEADING.regExp,
1320
- );
1321
-
1322
- const fencedValue = hasCodeBlocks ? convertTildeFences(value) : value;
1323
- const markdown = hasHeadings ? convertSetextHeadings(fencedValue) : fencedValue;
1324
-
1325
- return {
1326
- markdown,
1327
- // The language is the leading word of the info string, like `js` in ```` ``` js title=x ````;
1328
- // see `CODE`
1329
- languages: [...markdown.matchAll(/^`{3,}[ \t]*(?<lang>[\w-]+)/gm)].map(
1330
- ({ groups: { lang = 'plain' } = {} }) => lang,
1331
- ),
1332
- };
1333
- };
1334
-
1335
- /**
1336
- * Convert Markdown prepared with {@link prepareMarkdown} to Lexical nodes, either replacing the
1337
- * content of the root or returning the nodes to be inserted somewhere. Called within an editor
1338
- * update.
1339
- * @param {string} markdown Markdown.
1340
- * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1341
- * @param {object} [options] Options.
1342
- * @param {boolean} [options.toRoot] Whether to replace the content of the root.
1343
- * @returns {LexicalNode[]} Imported nodes.
1344
- */
1345
- const $importMarkdown = (markdown, enabledTransformers, { toRoot = false } = {}) => {
1346
- // Split multiline formatting into separate lines to prevent Markdown parsing issues
1347
- const splitValue = splitMultilineFormatting(markdown);
1348
- // Add placeholders so Lexical reads the backslashes, the tabs in code spans and raw HTML right
1349
- const markedValue = addImportPlaceholders(splitValue);
1350
- // Pad blank blockquote lines so they are not imported as literal `>` text
1351
- const paddedValue = padBlankBlockquoteLines(markedValue);
1352
- // Keep the formatting around a code span after other formatting
1353
- const transformers = addCodeSpanSplit(enabledTransformers);
1354
- /** @type {LexicalNode[]} */
1355
- let nodes;
1356
-
1357
- if (toRoot) {
1358
- convertFromMarkdownString(paddedValue, transformers);
1359
- nodes = getRoot().getChildren();
1360
- } else {
1361
- nodes = generateNodesFromMarkdownString(paddedValue, transformers);
1362
- }
1363
-
1364
- // The text of raw HTML and raw syntax is restored as well. The lines of an HTML block have a
1365
- // placeholder. Other raw syntax, like an autolink or a definition label, only differs from its
1366
- // text if Lexical has decoded an escape or a character reference in it
1367
- if (markedValue !== splitValue || /[\\&]/.test(markedValue)) {
1368
- removePlaceholders(nodes);
1369
- }
1370
-
1371
- return nodes;
1372
- };
1373
-
1374
- /**
1375
- * Insert the given Markdown at the selection, converted to Lexical nodes, as if it were pasted. The
1376
- * content stays as it is if the editor is read-only or has no selection.
1377
- * @param {LexicalEditor} editor Editor instance.
1378
- * @param {string} value Markdown.
1379
- * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1380
- * @returns {Promise<void>} Nothing.
1381
- */
1382
- export const pasteMarkdown = async (editor, value, enabledTransformers) => {
1383
- const { markdown, languages } = prepareMarkdown(value, enabledTransformers);
1384
-
1385
- // Preload the highlighter like the import does, but carry on without it if it fails to load: the
1386
- // code is highlighted once it’s available, if ever
1387
- await Promise.allSettled(languages.map((lang) => loadCodeHighlighter(lang)));
1388
-
1389
- if (!editor.isEditable()) {
1390
- return;
1391
- }
1392
-
1393
- editor.update(
1394
- () => {
1395
- // The Markdown import moves the selection to the nodes it creates, so keep a copy to insert
1396
- // the nodes where the caret was
1397
- const selection = getSelection()?.clone();
1398
-
1399
- if (!selection) {
1400
- return;
1401
- }
1402
-
1403
- /** @type {LexicalNode[] | undefined} */
1404
- let nodes;
1405
-
1406
- try {
1407
- nodes = $importMarkdown(markdown, enabledTransformers);
1408
- } catch (ex) {
1409
- // The browser paste has been canceled, so paste the text as is rather than nothing
1410
- // eslint-disable-next-line no-console
1411
- console.error(ex);
1412
- }
1413
-
1414
- setSelection(selection);
1415
-
1416
- if (nodes) {
1417
- selection.insertNodes(nodes);
1418
- } else {
1419
- selection.insertRawText(value);
1420
- }
1421
- },
1422
- { tag: PASTE_TAG },
1423
- );
1424
- };
1425
-
1426
- /**
1427
- * How long to wait for the `paste` event after a Paste as Markdown shortcut, in milliseconds.
1428
- */
1429
- const PASTE_AS_MARKDOWN_TIMEOUT = 1000;
1430
-
1431
- /**
1432
- * Keyboard shortcuts to paste the text on the clipboard as Markdown: the browser’s own shortcuts to
1433
- * paste plain text, Accel+Shift+V, plus Command+Option+Shift+V, the macOS Paste and Match Style.
1434
- * @returns {string} Shortcuts.
1435
- */
1436
- const getPasteAsMarkdownShortcuts = () =>
1437
- isMac() ? 'Meta+Shift+V Meta+Alt+Shift+V' : 'Ctrl+Shift+V';
1438
-
1439
- /**
1440
- * Register the keyboard shortcuts to paste the text on the clipboard as Markdown. A regular paste
1441
- * prefers the HTML on the clipboard, so text copied from a code editor or a terminal ends up in a
1442
- * code block, while Markdown pasted as plain text is kept as literal text. The shortcuts make the
1443
- * browser paste plain text, which is then converted from Markdown. The browser does the paste,
1444
- * because a script can’t read the clipboard after a key combination in every browser: Firefox
1445
- * doesn’t allow it after a key pressed with Ctrl, Alt or Command.
1446
- * @param {LexicalEditor} editor Editor instance.
1447
- * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1448
- * @returns {() => void} Cleanup handler.
1449
- */
1450
- const registerPasteAsMarkdown = (editor, enabledTransformers) => {
1451
- const shortcuts = getPasteAsMarkdownShortcuts();
1452
- /** Whether the paste that follows was started with one of the shortcuts. */
1453
- let pasteAsMarkdown = false;
1454
- let timer = 0;
1455
-
1456
- return mergeUnregisters(
1457
- () => {
1458
- clearTimeout(timer);
1459
- },
1460
- editor.registerCommand(
1461
- KEY_DOWN_COMMAND,
1462
- (event) => {
1463
- // Any other key cancels the shortcut. Chrome on macOS fires the `paste` event in a later
1464
- // task, so wait a moment for it, but not too long, in case the browser doesn’t paste with
1465
- // the shortcut, like Safari with Command+Shift+V
1466
- pasteAsMarkdown = matchesShortcuts(event, shortcuts);
1467
- clearTimeout(timer);
1468
-
1469
- if (pasteAsMarkdown) {
1470
- timer = window.setTimeout(() => {
1471
- pasteAsMarkdown = false;
1472
- }, PASTE_AS_MARKDOWN_TIMEOUT);
1473
- }
1474
-
1475
- // Let the browser paste
1476
- return false;
1477
- },
1478
- COMMAND_PRIORITY_NORMAL,
1479
- ),
1480
- editor.registerCommand(
1481
- PASTE_COMMAND,
1482
- (event) => {
1483
- if (!pasteAsMarkdown) {
1484
- return false;
1485
- }
1486
-
1487
- pasteAsMarkdown = false;
1488
-
1489
- const isClipboardEvent = objectKlassEquals(event, ClipboardEvent);
1490
-
1491
- // Safari pastes with an `insertFromPaste` input event instead of a `paste` event
1492
- const dataTransfer = isClipboardEvent
1493
- ? /** @type {ClipboardEvent} */ (event).clipboardData
1494
- : objectKlassEquals(event, InputEvent)
1495
- ? /** @type {InputEvent} */ (event).dataTransfer
1496
- : null;
1497
-
1498
- const text = dataTransfer?.getData('text/plain');
1499
-
1500
- // Leave a URL to the link paste handler, which links the selected text. It only handles a
1501
- // `paste` event, so Safari still pastes a URL as Markdown
1502
- if (!text || (isClipboardEvent && isURL(text.trim()))) {
1503
- return false;
1504
- }
1505
-
1506
- event.preventDefault();
1507
- pasteMarkdown(editor, text, enabledTransformers);
1508
-
1509
- return true;
1510
- },
1511
- // Before the link paste handler and Lexical’s own one
1512
- COMMAND_PRIORITY_NORMAL,
1513
- ),
1514
- );
1515
- };
1516
-
1517
- /**
1518
- * Initialize the Lexical editor.
80
+ * Apply the defaults to the editor configuration, and derive the features from it.
1519
81
  * @param {TextEditorConfig} config Editor configuration.
1520
- * @returns {InitEditorResult} Editor instance and cleanup.
82
+ * @returns {EditorSetup} Editor setup.
1521
83
  */
1522
- export const initEditor = (config) => {
84
+ const getEditorSetup = (config) => {
1523
85
  const {
1524
86
  enabledButtons = [],
1525
87
  components = [],
@@ -1530,13 +92,53 @@ export const initEditor = (config) => {
1530
92
  multiline = true,
1531
93
  } = limitToSingleLine(config);
1532
94
 
1533
- const hasCodeBlock = enabledButtons.includes('code-block') || isCodeEditor;
1534
- const hasTable = enabledButtons.includes('table') && !isCodeEditor;
1535
- const hasHorizontalRule = enabledButtons.includes('horizontal-rule') && !isCodeEditor;
1536
- /** Whether to support horizontal rules and tables in Markdown, even without their buttons. */
1537
- const hasBlockSyntax = !isCodeEditor && multiline;
95
+ return {
96
+ enabledButtons,
97
+ components,
98
+ useMarkdownShortcuts,
99
+ isCodeEditor,
100
+ defaultLanguage,
101
+ format,
102
+ multiline,
103
+ hasCodeBlock: enabledButtons.includes('code-block') || isCodeEditor,
104
+ hasTable: enabledButtons.includes('table') && !isCodeEditor,
105
+ hasHorizontalRule: enabledButtons.includes('horizontal-rule') && !isCodeEditor,
106
+ hasBlockSyntax: !isCodeEditor && multiline,
107
+ };
108
+ };
1538
109
 
1539
- const editorExtension = defineExtension({
110
+ /**
111
+ * Get the unique items of a map keyed by button type, for the enabled buttons.
112
+ * @template T
113
+ * @param {Partial<Record<TextEditorNodeType, T[]>>} map Items by button type.
114
+ * @param {TextEditorNodeType[]} enabledButtons Enabled buttons.
115
+ * @returns {T[]} Items.
116
+ */
117
+ const pickForButtons = (map, enabledButtons) => [
118
+ ...new Set(
119
+ Object.entries(map)
120
+ .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))
121
+ .flatMap(([, items]) => /** @type {T[]} */ (items)),
122
+ ),
123
+ ];
124
+
125
+ /**
126
+ * Define the Lexical extension the editor is built from, with the nodes and the dependencies the
127
+ * enabled features need.
128
+ * @param {EditorSetup} setup Editor setup.
129
+ * @returns {ReturnType<typeof defineExtension>} Extension.
130
+ */
131
+ const createEditorExtension = ({
132
+ enabledButtons,
133
+ components,
134
+ isCodeEditor,
135
+ format,
136
+ hasCodeBlock,
137
+ hasTable,
138
+ hasHorizontalRule,
139
+ hasBlockSyntax,
140
+ }) =>
141
+ defineExtension({
1540
142
  name: '@sveltia/ui/editor',
1541
143
  namespace: 'editor',
1542
144
  dependencies: [
@@ -1564,11 +166,7 @@ export const initEditor = (config) => {
1564
166
  $initialEditorState: null,
1565
167
  nodes: [
1566
168
  ...components.map(({ node }) => node),
1567
- ...new Set(
1568
- Object.entries(NODE_MAP)
1569
- .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))
1570
- .flatMap(([, nodes]) => nodes),
1571
- ),
169
+ ...pickForButtons(NODE_MAP, enabledButtons),
1572
170
  ...(isCodeEditor ? [CodeNode, CodeHighlightNode] : []),
1573
171
  // We haven’t implemented buttons for horizontal rules and tables yet, but we still want to
1574
172
  // support them in Markdown, so always include them in the node list, unless the editor is
@@ -1595,23 +193,24 @@ export const initEditor = (config) => {
1595
193
  },
1596
194
  });
1597
195
 
196
+ /**
197
+ * Get the Markdown transformers for the enabled features, in the order they have to be applied.
198
+ * @param {EditorSetup} setup Editor setup.
199
+ * @returns {Transformer[]} Transformers.
200
+ */
201
+ const getEnabledTransformers = ({ enabledButtons, components, isCodeEditor, hasBlockSyntax }) => {
1598
202
  const componentTransformers = components.map(({ transformer }) =>
1599
203
  removePlaceholdersFromMatch(transformer),
1600
204
  );
1601
205
 
1602
- /** @type {Transformer[]} */
1603
- const enabledTransformers = [
206
+ return [
1604
207
  ...componentTransformers,
1605
208
  // Raw HTML comes before the editor’s own syntax, so a line of an HTML block that starts like a
1606
209
  // link, for example, is still raw HTML. Only an editor component takes precedence
1607
210
  ...(isCodeEditor ? [] : [RAW_HTML]),
1608
- ...new Set(
1609
- Object.entries(TRANSFORMER_MAP)
1610
- .filter(([button]) => enabledButtons.includes(/** @type {TextEditorNodeType} */ (button)))
1611
- .flatMap(([, transformers]) => transformers),
1612
- ),
211
+ ...pickForButtons(TRANSFORMER_MAP, enabledButtons),
1613
212
  ...(isCodeEditor ? [CODE] : []),
1614
- // See the comment above for why we always include horizontal rules and tables
213
+ // Horizontal rules and tables are always supported in Markdown; see `createEditorExtension()`
1615
214
  ...(hasBlockSyntax
1616
215
  ? [
1617
216
  HR,
@@ -1627,14 +226,31 @@ export const initEditor = (config) => {
1627
226
  // Last, so the syntax of the editor’s own comes first
1628
227
  ...(isCodeEditor ? [] : [RAW_SYNTAX]),
1629
228
  ];
229
+ };
1630
230
 
1631
- const editor = buildEditorFromExtensions(editorExtension);
1632
-
1633
- // Let the HTML import tell the elements the components import
1634
- editorComponents.set(editor, components);
1635
-
231
+ /**
232
+ * Register the Lexical listeners for the enabled features.
233
+ * @param {LexicalEditor} editor Editor instance.
234
+ * @param {EditorSetup} setup Editor setup.
235
+ * @param {Transformer[]} enabledTransformers Enabled Markdown transformers.
236
+ * @returns {() => void} Function to unregister them all.
237
+ */
238
+ const registerEditorListeners = (
239
+ editor,
240
+ {
241
+ enabledButtons,
242
+ useMarkdownShortcuts,
243
+ isCodeEditor,
244
+ defaultLanguage,
245
+ format,
246
+ multiline,
247
+ hasCodeBlock,
248
+ hasTable,
249
+ },
250
+ enabledTransformers,
251
+ ) =>
1636
252
  // The order matters, as listeners with the same priority are called in the registration order
1637
- const unregister = mergeUnregisters(
253
+ mergeUnregisters(
1638
254
  registerRichText(editor),
1639
255
  registerDragonSupport(editor),
1640
256
  // Cap the undo stack, as each entry holds a snapshot of the whole document
@@ -1675,6 +291,21 @@ export const initEditor = (config) => {
1675
291
  isCodeEditor ? undefined : registerPasteAsMarkdown(editor, enabledTransformers),
1676
292
  );
1677
293
 
294
+ /**
295
+ * Initialize the Lexical editor.
296
+ * @param {TextEditorConfig} config Editor configuration.
297
+ * @returns {InitEditorResult} Editor instance and cleanup.
298
+ */
299
+ export const initEditor = (config) => {
300
+ const setup = getEditorSetup(config);
301
+ const enabledTransformers = getEnabledTransformers(setup);
302
+ const editor = buildEditorFromExtensions(createEditorExtension(setup));
303
+
304
+ // Let the HTML import tell the elements the components import
305
+ editorComponents.set(editor, setup.components);
306
+
307
+ const unregister = registerEditorListeners(editor, setup, enabledTransformers);
308
+
1678
309
  return {
1679
310
  editor,
1680
311
  enabledTransformers,
@@ -1687,195 +318,3 @@ export const initEditor = (config) => {
1687
318
  },
1688
319
  };
1689
320
  };
1690
-
1691
- /**
1692
- * Number of the latest import started for each editor.
1693
- * @type {WeakMap<LexicalEditor, number>}
1694
- */
1695
- const latestImports = new WeakMap();
1696
-
1697
- /**
1698
- * Import a value to the editor, replacing the current content.
1699
- * @param {LexicalEditor} editor Editor instance.
1700
- * @param {object} args Arguments.
1701
- * @param {string[]} args.languages Programming languages used in the code blocks.
1702
- * @param {() => void} args.$import Function to convert the value to Lexical nodes, called within an
1703
- * editor update.
1704
- * @param {() => string} args.$export Function to convert the editor content back to the value.
1705
- * @param {string} args.formatName Name of the value format, used in the error message.
1706
- * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which
1707
- * can differ in style from the given value. `undefined` if another import has been started for the
1708
- * same editor in the meantime, in which case this value is skipped.
1709
- * @throws {Error} Failed to convert the value to Lexical nodes.
1710
- */
1711
- const importValue = async (editor, { languages, $import, $export, formatName }) => {
1712
- const importId = (latestImports.get(editor) ?? 0) + 1;
1713
-
1714
- latestImports.set(editor, importId);
1715
-
1716
- /**
1717
- * Check if a newer import has been started while waiting for the highlighter. Imports can finish
1718
- * out of order, as only those with code blocks have to wait, and an older value must not
1719
- * overwrite a newer one.
1720
- * @returns {boolean} Result.
1721
- */
1722
- const isSuperseded = () => latestImports.get(editor) !== importId;
1723
-
1724
- try {
1725
- // Preload the highlighter for every language used in the document, so code blocks are
1726
- // highlighted as soon as they appear rather than a moment later
1727
- await Promise.all(languages.map(async (lang) => loadCodeHighlighter(lang)));
1728
- } catch (ex) {
1729
- if (isSuperseded()) {
1730
- return undefined;
1731
- }
1732
-
1733
- throw ex;
1734
- }
1735
-
1736
- if (isSuperseded()) {
1737
- return undefined;
1738
- }
1739
-
1740
- // Lexical commits an empty state when the root element is attached, and the history keeps it as
1741
- // the current entry. An empty state can’t be restored, so undoing to it throws an error. Merge
1742
- // the first import into that entry instead of pushing it onto the undo stack
1743
- const isEmpty = editor.getEditorState().isEmpty();
1744
- /** @type {unknown} */
1745
- let error;
1746
-
1747
- editor.update(
1748
- () => {
1749
- try {
1750
- $import();
1751
- } catch (ex) {
1752
- error = ex;
1753
- }
1754
- },
1755
- // Tell the import from a change made by the user, and commit it right away, so the node
1756
- // transforms, e.g. the one giving a code block its default language, have run by the time the
1757
- // content is exported below
1758
- { tag: isEmpty ? [IMPORT_UPDATE_TAG, HISTORY_MERGE_TAG] : IMPORT_UPDATE_TAG, discrete: true },
1759
- );
1760
-
1761
- if (error) {
1762
- throw new Error(`Failed to convert ${formatName}`, { cause: error });
1763
- }
1764
-
1765
- return editor.read($export);
1766
- };
1767
-
1768
- /**
1769
- * Convert Markdown to Lexical nodes.
1770
- * @param {LexicalEditor} editor Editor instance.
1771
- * @param {string} value Current Markdown value.
1772
- * @param {Transformer[]} enabledTransformers List of enabled Markdown transformers.
1773
- * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which
1774
- * can differ in style from the given value, e.g. `_text_` for `*text*`. `undefined` if another
1775
- * import has been started for the same editor in the meantime, in which case this value is skipped.
1776
- * @throws {Error} Failed to convert the value to Lexical nodes.
1777
- */
1778
- export const convertMarkdownToLexical = async (editor, value, enabledTransformers) => {
1779
- const { markdown, languages } = prepareMarkdown(value, enabledTransformers);
1780
-
1781
- return importValue(editor, {
1782
- languages,
1783
- /**
1784
- * Import the Markdown.
1785
- */
1786
- $import: () => {
1787
- $importMarkdown(markdown, enabledTransformers, { toRoot: true });
1788
- },
1789
- /**
1790
- * Export the content as Markdown.
1791
- * @returns {string} Markdown.
1792
- */
1793
- $export: () => exportMarkdown(enabledTransformers),
1794
- formatName: 'Markdown',
1795
- });
1796
- };
1797
-
1798
- /**
1799
- * Convert HTML to Lexical nodes. Inline content outside any block, like bare text, is wrapped with
1800
- * a paragraph. An element that none of the registered nodes can import, like `<img>` or a heading
1801
- * with the heading buttons disabled, as well as a comment, causes an error instead of being
1802
- * silently dropped.
1803
- * @param {LexicalEditor} editor Editor instance.
1804
- * @param {string} value Current HTML value.
1805
- * @returns {Promise<string | undefined>} The value as the editor exports it once imported, which
1806
- * can differ in style from the given value, e.g. `<strong>` for `<b>`. `undefined` if another
1807
- * import has been started for the same editor in the meantime, in which case this value is skipped.
1808
- * @throws {Error} Failed to convert the value to Lexical nodes.
1809
- */
1810
- export const convertHtmlToLexical = async (editor, value) => {
1811
- const dom = new DOMParser().parseFromString(value, 'text/html');
1812
-
1813
- return importValue(editor, {
1814
- languages: [...dom.querySelectorAll('pre > code')]
1815
- .map(getCodeLanguage)
1816
- .filter((lang) => lang !== undefined),
1817
- /**
1818
- * Import the HTML.
1819
- * @throws {Error} The HTML has an element the editor cannot handle.
1820
- */
1821
- $import: () => {
1822
- const unsupportedNode = findUnsupportedNode(editor, dom);
1823
-
1824
- if (unsupportedNode) {
1825
- throw new Error(
1826
- unsupportedNode.nodeType === Node.COMMENT_NODE
1827
- ? 'Unsupported comment'
1828
- : `Unsupported element: <${/** @type {Element} */ (unsupportedNode).localName}>`,
1829
- );
1830
- }
1831
-
1832
- const root = getRoot();
1833
- /** @type {ElementNode | null} */
1834
- let paragraph = null;
1835
-
1836
- root.clear();
1837
-
1838
- generateNodesFromDOM(editor, dom).forEach((node) => {
1839
- if (isElementNode(node) ? !node.isInline() : isDecoratorNode(node) && !node.isInline()) {
1840
- paragraph = null;
1841
- root.append(node);
1842
- } else {
1843
- if (!paragraph) {
1844
- paragraph = createParagraphNode();
1845
- root.append(paragraph);
1846
- }
1847
-
1848
- paragraph.append(node);
1849
- }
1850
- });
1851
-
1852
- // Like the Markdown import, there should be at least one paragraph
1853
- // @see https://github.com/facebook/lexical/issues/2308
1854
- if (root.isEmpty()) {
1855
- root.append(createParagraphNode());
1856
- }
1857
-
1858
- if (getSelection() !== null) {
1859
- root.selectStart();
1860
- }
1861
- },
1862
- /**
1863
- * Export the content as HTML.
1864
- * @returns {string} HTML.
1865
- */
1866
- $export: () => exportHtml(editor),
1867
- formatName: 'HTML',
1868
- });
1869
- };
1870
-
1871
- /**
1872
- * Move focus to the editor so the user can start editing immediately.
1873
- * @param {LexicalEditor} editor Editor instance.
1874
- * @returns {Promise<void>} Nothing.
1875
- */
1876
- export const focusEditor = async (editor) =>
1877
- new Promise((resolve) => {
1878
- editor.focus(() => {
1879
- resolve(undefined);
1880
- });
1881
- });