@sveltia/ui 0.89.3 → 0.91.0

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 (77) hide show
  1. package/dist/components/dialog/dialog.svelte +149 -9
  2. package/dist/components/text-editor/constants.d.ts +40 -6
  3. package/dist/components/text-editor/constants.js +81 -7
  4. package/dist/components/text-editor/conversion/html/components.d.ts +16 -0
  5. package/dist/components/text-editor/conversion/html/components.js +87 -0
  6. package/dist/components/text-editor/conversion/html/export.d.ts +10 -0
  7. package/dist/components/text-editor/conversion/html/export.js +360 -0
  8. package/dist/components/text-editor/conversion/html/import-rules.d.ts +12 -0
  9. package/dist/components/text-editor/conversion/html/import-rules.js +234 -0
  10. package/dist/components/text-editor/conversion/html/index.d.ts +10 -0
  11. package/dist/components/text-editor/conversion/html/index.js +33 -0
  12. package/dist/components/text-editor/conversion/html/paragraph.d.ts +1 -0
  13. package/dist/components/text-editor/conversion/html/paragraph.js +123 -0
  14. package/dist/components/text-editor/conversion/html/task-list.d.ts +13 -0
  15. package/dist/components/text-editor/conversion/html/task-list.js +82 -0
  16. package/dist/components/text-editor/conversion/html/unsupported.d.ts +2 -0
  17. package/dist/components/text-editor/conversion/html/unsupported.js +122 -0
  18. package/dist/components/text-editor/conversion/html/utils.d.ts +6 -0
  19. package/dist/components/text-editor/conversion/html/utils.js +34 -0
  20. package/dist/components/text-editor/conversion/import.js +1 -1
  21. package/dist/components/text-editor/conversion/transformers/task-list.d.ts +24 -0
  22. package/dist/components/text-editor/conversion/transformers/task-list.js +53 -0
  23. package/dist/components/text-editor/conversion/update.js +1 -1
  24. package/dist/components/text-editor/core.js +4 -12
  25. package/dist/components/text-editor/editing/commands.js +9 -18
  26. package/dist/components/text-editor/editing/guards.d.ts +7 -0
  27. package/dist/components/text-editor/editing/guards.js +123 -0
  28. package/dist/components/text-editor/editing/raw-markdown.d.ts +4 -2
  29. package/dist/components/text-editor/editing/raw-markdown.js +22 -6
  30. package/dist/components/text-editor/editing/selection.js +6 -2
  31. package/dist/components/text-editor/lexical-root.svelte +40 -0
  32. package/dist/components/text-editor/shiki/version.d.ts +1 -1
  33. package/dist/components/text-editor/shiki/version.js +1 -1
  34. package/dist/components/text-editor/text-editor.svelte +7 -4
  35. package/dist/components/text-editor/text-editor.svelte.d.ts +4 -2
  36. package/dist/components/text-editor/toolbar/format-text-button.svelte +7 -1
  37. package/dist/components/text-editor/toolbar/text-editor-toolbar.svelte +19 -8
  38. package/dist/components/text-editor/toolbar/toggle-block-menu-item.svelte +7 -14
  39. package/dist/components/util/modal.svelte +41 -12
  40. package/dist/locales/ar.yaml +2 -0
  41. package/dist/locales/bg.yaml +2 -0
  42. package/dist/locales/ca.yaml +2 -0
  43. package/dist/locales/cs.yaml +2 -0
  44. package/dist/locales/da.yaml +2 -0
  45. package/dist/locales/de.yaml +2 -0
  46. package/dist/locales/el.yaml +2 -0
  47. package/dist/locales/en-CA.yaml +2 -0
  48. package/dist/locales/en-GB.yaml +2 -0
  49. package/dist/locales/en-US.yaml +2 -0
  50. package/dist/locales/en-ZA.yaml +2 -0
  51. package/dist/locales/es-CO.yaml +2 -0
  52. package/dist/locales/es-ES.yaml +176 -0
  53. package/dist/locales/fa.yaml +2 -0
  54. package/dist/locales/fi.yaml +2 -0
  55. package/dist/locales/fr.yaml +2 -0
  56. package/dist/locales/he.yaml +2 -0
  57. package/dist/locales/hr.yaml +2 -0
  58. package/dist/locales/it.yaml +2 -0
  59. package/dist/locales/ja.yaml +2 -0
  60. package/dist/locales/ko.yaml +2 -0
  61. package/dist/locales/nl.yaml +2 -0
  62. package/dist/locales/pl.yaml +2 -0
  63. package/dist/locales/pt-BR.yaml +2 -0
  64. package/dist/locales/pt-PT.yaml +2 -0
  65. package/dist/locales/ru.yaml +2 -0
  66. package/dist/locales/sk.yaml +2 -0
  67. package/dist/locales/sv.yaml +2 -0
  68. package/dist/locales/tr.yaml +2 -0
  69. package/dist/locales/uk.yaml +2 -0
  70. package/dist/locales/vi.yaml +2 -0
  71. package/dist/locales/zh-CN.yaml +2 -0
  72. package/dist/locales/zh-TW.yaml +2 -0
  73. package/dist/typedefs.d.ts +33 -3
  74. package/dist/typedefs.js +19 -3
  75. package/package.json +13 -13
  76. package/dist/components/text-editor/conversion/html.d.ts +0 -30
  77. package/dist/components/text-editor/conversion/html.js +0 -719
@@ -1,719 +0,0 @@
1
- import { CodeHighlightNode, CodeNode, $createCodeNode as createCodeNode } from '@lexical/code-core';
2
- import { HorizontalRuleNode } from '@lexical/extension';
3
- import { $generateHtmlFromNodes as generateHtmlFromNodes } from '@lexical/html';
4
- import { LinkNode } from '@lexical/link';
5
- import { ListItemNode, ListNode } from '@lexical/list';
6
- import { HeadingNode, QuoteNode } from '@lexical/rich-text';
7
- import { TableCellNode, TableNode } from '@lexical/table';
8
- import {
9
- $createTextNode as createTextNode,
10
- $getEditor as getEditor,
11
- $isParagraphNode as isParagraphNode,
12
- isDOMTextNode,
13
- isHTMLElement,
14
- isInlineDomNode,
15
- ParagraphNode,
16
- TabNode,
17
- TextNode,
18
- } from 'lexical';
19
- import { isPlainLanguage } from '../shiki/facade.js';
20
-
21
- /**
22
- * @import {
23
- * DOMConversion,
24
- * DOMConversionMap,
25
- * DOMConversionOutput,
26
- * DOMExportOutput,
27
- * DOMExportOutputMap,
28
- * ElementNode,
29
- * LexicalEditor,
30
- * LexicalNode,
31
- * } from 'lexical';
32
- * @import { TextEditorComponent } from '../../../typedefs.js';
33
- */
34
-
35
- /**
36
- * Attributes to be kept on the exported elements, by tag name. Anything else Lexical adds, like
37
- * `class`, `dir`, `style`, `value` or `spellcheck`, is only meant for the editor itself, except for
38
- * the text alignment of a block; see {@link ALIGNABLE_TAGS}.
39
- * @type {Record<string, string[]>}
40
- */
41
- const ALLOWED_ATTRIBUTES = {
42
- a: ['href', 'rel', 'target', 'title'],
43
- ol: ['start'],
44
- td: ['colspan', 'rowspan'],
45
- th: ['colspan', 'rowspan'],
46
- };
47
-
48
- /**
49
- * Text formats and their HTML tags, from the innermost to the outermost.
50
- * @type {[import('lexical').TextFormatType, string][]}
51
- */
52
- const TEXT_FORMAT_TAGS = [
53
- ['code', 'code'],
54
- ['subscript', 'sub'],
55
- ['superscript', 'sup'],
56
- ['highlight', 'mark'],
57
- ['underline', 'u'],
58
- ['strikethrough', 's'],
59
- ['italic', 'em'],
60
- ['bold', 'strong'],
61
- ];
62
-
63
- /**
64
- * Table elements that have no Lexical node of their own. The rows are imported as is, while the
65
- * column definitions are only used for the column widths.
66
- */
67
- const PASSTHROUGH_TAGS = ['tbody', 'thead', 'tfoot', 'colgroup', 'col'];
68
- /**
69
- * Elements the HTML parser always creates, which hold the content rather than being part of it.
70
- */
71
- const DOCUMENT_TAGS = ['html', 'head', 'body'];
72
-
73
- /**
74
- * Get the programming language from the `language-*` or `lang-*` class of the given `<code>`
75
- * element, which is common in HTML generated from Markdown.
76
- * @param {Element} code `<code>` element.
77
- * @returns {string | undefined} Language.
78
- */
79
- export const getCodeLanguage = (code) =>
80
- code.className.match(/(?:^|\s)(?:lang|language)-(\S+)/)?.[1];
81
-
82
- /**
83
- * Elements that keep their text alignment, which is the only style kept in the exported HTML.
84
- * Lexical writes it as `style="text-align: …"` for the blocks it can be set on.
85
- */
86
- const ALIGNABLE_TAGS = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'li'];
87
-
88
- /**
89
- * Remove the attributes not listed in {@link ALLOWED_ATTRIBUTES} from the given element, as well as
90
- * any style but the text alignment of a block listed in {@link ALIGNABLE_TAGS}.
91
- * @param {Element} element Element.
92
- */
93
- const removeExtraAttributes = (element) => {
94
- const allowedAttributes = ALLOWED_ATTRIBUTES[element.localName] ?? [];
95
-
96
- const textAlign = ALIGNABLE_TAGS.includes(element.localName)
97
- ? /** @type {HTMLElement} */ (element).style.textAlign
98
- : '';
99
-
100
- [...element.attributes].forEach(({ name }) => {
101
- if (!allowedAttributes.includes(name)) {
102
- element.removeAttribute(name);
103
- }
104
- });
105
-
106
- if (textAlign) {
107
- /** @type {HTMLElement} */ (element).style.textAlign = textAlign;
108
- }
109
- };
110
-
111
- /**
112
- * Export an element node with Lexical’s own implementation, then remove the extra attributes from
113
- * the element, as well as the attribute Lexical adds to the `<br>` terminating a trailing line
114
- * break. The element’s own `after` function, if any, still runs first, so the structure is kept,
115
- * like a nested list moved into the previous list item.
116
- * @param {LexicalEditor} editor Editor instance.
117
- * @param {ElementNode} node Element node.
118
- * @returns {DOMExportOutput} Export output.
119
- */
120
- const exportElementNode = (editor, node) => {
121
- const { after, ...output } = node.exportDOM(editor);
122
-
123
- if (isHTMLElement(output.element)) {
124
- removeExtraAttributes(output.element);
125
- }
126
-
127
- return {
128
- ...output,
129
- /**
130
- * Clean up the element once its children are in place.
131
- * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.
132
- * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace
133
- * the exported one, if any.
134
- */
135
- after: (element) => {
136
- const newElement = after ? after.call(node, element) : undefined;
137
- const target = newElement ?? element;
138
-
139
- if (isHTMLElement(target)) {
140
- removeExtraAttributes(target);
141
- target.querySelectorAll(':scope > br').forEach(removeExtraAttributes);
142
- }
143
-
144
- // Returning the same element would make Lexical replace it with itself
145
- return newElement === element ? undefined : newElement;
146
- },
147
- };
148
- };
149
-
150
- /**
151
- * Export a paragraph node. Empty paragraphs at the end are left out, as they have no content; one
152
- * may be added just by clicking below a block decorator. A paragraph that is the only child of a
153
- * table cell is exported without the `<p>` element, unless it’s aligned.
154
- * @param {LexicalEditor} editor Editor instance.
155
- * @param {ParagraphNode} node Paragraph node.
156
- * @returns {DOMExportOutput} Export output.
157
- */
158
- const exportParagraphNode = (editor, node) => {
159
- const parent = node.getParent();
160
-
161
- // Keep the `<p>` of an aligned paragraph, which holds the alignment
162
- if (parent instanceof TableCellNode && parent.getChildrenSize() === 1 && !node.getFormatType()) {
163
- return { element: document.createDocumentFragment() };
164
- }
165
-
166
- if (
167
- node.isEmpty() &&
168
- node.getNextSiblings().every((sibling) => isParagraphNode(sibling) && sibling.isEmpty())
169
- ) {
170
- return { element: null };
171
- }
172
-
173
- return exportElementNode(editor, node);
174
- };
175
-
176
- /**
177
- * Export a text node as plain text wrapped with the elements for its formats, instead of the
178
- * `<span>`, `<b>` and `<i>` elements with styles and classes Lexical uses.
179
- * @param {LexicalEditor} _editor Editor instance.
180
- * @param {TextNode} node Text node.
181
- * @returns {DOMExportOutput} Export output.
182
- */
183
- const exportTextNode = (_editor, node) => {
184
- /** @type {HTMLElement | Text} */
185
- let element = document.createTextNode(node.getTextContent());
186
-
187
- TEXT_FORMAT_TAGS.forEach(([format, tagName]) => {
188
- if (node.hasFormat(format)) {
189
- const wrapper = document.createElement(tagName);
190
-
191
- wrapper.append(element);
192
- element = wrapper;
193
- }
194
- });
195
-
196
- return { element };
197
- };
198
-
199
- /**
200
- * Export a code block node as `<pre><code>` with the common `language-*` class, instead of the
201
- * highlighted tokens Lexical renders in the editor. The children are still exported as usual, so
202
- * copying part of a code block only exports the selected text, then their text is moved into the
203
- * `<code>` element.
204
- * @param {LexicalEditor} _editor Editor instance.
205
- * @param {CodeNode} node Code node.
206
- * @returns {DOMExportOutput} Export output.
207
- */
208
- const exportCodeNode = (_editor, node) => ({
209
- element: document.createElement('pre'),
210
- /**
211
- * Replace the exported children with a `<code>` element holding their text.
212
- * @param {HTMLElement | DocumentFragment | Text | null | undefined} pre Exported element.
213
- * @returns {undefined} Nothing, as the element is updated in place.
214
- */
215
- after: (pre) => {
216
- /* v8 ignore next 3 */
217
- if (!isHTMLElement(pre)) {
218
- return undefined;
219
- }
220
-
221
- const code = document.createElement('code');
222
- const language = node.getLanguage();
223
-
224
- if (language && !isPlainLanguage(language)) {
225
- code.className = `language-${language}`;
226
- }
227
-
228
- code.textContent = [...pre.childNodes]
229
- .map((child) => {
230
- if (child.nodeName !== 'BR') {
231
- return child.textContent;
232
- }
233
-
234
- // Skip the `<br>` Lexical adds to terminate a trailing line break
235
- return isHTMLElement(child) && child.hasAttribute('data-lexical-managed-linebreak')
236
- ? ''
237
- : '\n';
238
- })
239
- .join('');
240
-
241
- pre.replaceChildren(code);
242
-
243
- return undefined;
244
- },
245
- });
246
-
247
- /**
248
- * Selector for the structural elements of a table, excluding the cell content.
249
- */
250
- const TABLE_STRUCTURE_SELECTOR = [
251
- ':scope > :is(thead, tbody, tfoot)',
252
- ':scope > :is(thead, tbody, tfoot) > tr',
253
- ':scope > :is(thead, tbody, tfoot) > tr > :is(th, td)',
254
- ':scope > tr',
255
- ':scope > tr > :is(th, td)',
256
- ].join(', ');
257
-
258
- /**
259
- * Export a table node, then remove the column definitions and extra attributes Lexical adds to the
260
- * table and its descendants. The cleanup has to wait until the table is complete, as Lexical uses
261
- * temporary attributes on the cells to compute the columns.
262
- * @param {LexicalEditor} editor Editor instance.
263
- * @param {TableNode} node Table node.
264
- * @returns {DOMExportOutput} Export output.
265
- */
266
- const exportTableNode = (editor, node) => {
267
- const { after, ...output } = node.exportDOM(editor);
268
-
269
- return {
270
- ...output,
271
- /**
272
- * Clean up the table once Lexical has completed it.
273
- * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.
274
- * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace
275
- * the exported one, if any.
276
- */
277
- after: (element) => {
278
- const newElement = after ? after.call(node, element) : undefined;
279
- const target = newElement ?? element;
280
-
281
- if (isHTMLElement(target)) {
282
- target.querySelectorAll(':scope > colgroup').forEach((colgroup) => colgroup.remove());
283
- // Leave the cell content alone, which has been cleaned up by its own nodes, while the
284
- // content of an editor component may need its attributes
285
- [target, ...target.querySelectorAll(TABLE_STRUCTURE_SELECTOR)].forEach(
286
- removeExtraAttributes,
287
- );
288
- }
289
-
290
- // Returning the same element would make Lexical replace it with itself
291
- return newElement === element ? undefined : newElement;
292
- },
293
- };
294
- };
295
-
296
- /**
297
- * Map of Lexical node classes and functions to export them to clean HTML. A class only takes effect
298
- * if the node is registered with the editor. Other nodes, including the ones of editor components,
299
- * are exported with their own `exportDOM` method.
300
- * @type {DOMExportOutputMap}
301
- */
302
- export const HTML_EXPORT_MAP = new Map(
303
- /** @type {[any, (editor: LexicalEditor, node: any) => DOMExportOutput][]} */ ([
304
- [TextNode, exportTextNode],
305
- [TabNode, exportTextNode],
306
- [CodeHighlightNode, exportTextNode],
307
- [ParagraphNode, exportParagraphNode],
308
- [HeadingNode, exportElementNode],
309
- [QuoteNode, exportElementNode],
310
- [ListNode, exportElementNode],
311
- [ListItemNode, exportElementNode],
312
- [LinkNode, exportElementNode],
313
- [HorizontalRuleNode, exportElementNode],
314
- [CodeNode, exportCodeNode],
315
- [TableNode, exportTableNode],
316
- ]),
317
- );
318
-
319
- /**
320
- * Get the text content of the given element, with `<br>` elements as line breaks.
321
- * @param {Element} element Element.
322
- * @returns {string} Text.
323
- */
324
- const getTextWithLineBreaks = (element) => {
325
- const walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL);
326
- let text = '';
327
-
328
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
329
- if (node.nodeType === Node.TEXT_NODE) {
330
- text += /** @type {Text} */ (node).data;
331
- } else if (node.nodeName === 'BR') {
332
- text += '\n';
333
- }
334
- }
335
-
336
- return text;
337
- };
338
-
339
- /**
340
- * Convert a `<pre>` element to a code block node, taking the language from the `language-*` or
341
- * `lang-*` class of the `<code>` element within it, which is common in HTML generated from
342
- * Markdown, as well as the `data-language` attribute Lexical uses. The content is imported as plain
343
- * text, so any markup within it, like highlighted tokens, is dropped, while a `<br>` element
344
- * becomes a line break.
345
- * @param {HTMLElement} pre `<pre>` element.
346
- * @returns {DOMConversionOutput} Conversion output.
347
- */
348
- const convertPreElement = (pre) => {
349
- const code = pre.querySelector(':scope > code');
350
- const language = (code ? getCodeLanguage(code) : undefined) ?? pre.getAttribute('data-language');
351
- const node = createCodeNode(language);
352
- // A code block generated from Markdown ends with a line break
353
- const text = getTextWithLineBreaks(pre).replace(/\n$/, '');
354
-
355
- if (text) {
356
- node.append(createTextNode(text));
357
- }
358
-
359
- return {
360
- node,
361
- /**
362
- * Drop the child nodes, which are already imported as the text content.
363
- * @returns {LexicalNode[]} Nodes.
364
- */
365
- after: () => [],
366
- };
367
- };
368
-
369
- /**
370
- * Editor components of each editor, used to tell the elements they import, which come with their
371
- * content, when HTML is imported.
372
- * @type {WeakMap<LexicalEditor, TextEditorComponent[]>}
373
- */
374
- export const editorComponents = new WeakMap();
375
-
376
- /**
377
- * Conversion maps of the editor component nodes, cached as each `importDOM()` call can create a new
378
- * map.
379
- * @type {WeakMap<any, DOMConversionMap>}
380
- */
381
- const componentConversionMaps = new WeakMap();
382
-
383
- /**
384
- * Get the conversion map of the given editor component node.
385
- * @param {any} node Lexical node class.
386
- * @returns {DOMConversionMap} Conversion map.
387
- */
388
- const getComponentConversionMap = (node) => {
389
- let map = componentConversionMaps.get(node);
390
-
391
- if (!map) {
392
- map = node.importDOM?.() ?? {};
393
- componentConversionMaps.set(node, /** @type {DOMConversionMap} */ (map));
394
- }
395
-
396
- return /** @type {DOMConversionMap} */ (map);
397
- };
398
-
399
- /**
400
- * Editor component that imports each element, or `null` if none does, cached as the same element is
401
- * checked many times during an import, and a conversion can run developer code. An element is only
402
- * imported to one editor, as each import parses the HTML anew.
403
- * @type {WeakMap<Element, TextEditorComponent | null>}
404
- */
405
- const elementComponents = new WeakMap();
406
-
407
- /**
408
- * Get the editor component that imports the given element, if any. The element’s content is then
409
- * part of the component.
410
- * @param {LexicalEditor} editor Editor instance.
411
- * @param {Element} element Element.
412
- * @returns {TextEditorComponent | undefined} Component.
413
- */
414
- const getElementComponent = (editor, element) => {
415
- let component = elementComponents.get(element);
416
-
417
- if (component === undefined) {
418
- component =
419
- editorComponents
420
- .get(editor)
421
- ?.find(
422
- ({ node }) =>
423
- !!getComponentConversionMap(node)[element.localName]?.(
424
- /** @type {HTMLElement} */ (element),
425
- ),
426
- ) ?? null;
427
- elementComponents.set(element, component);
428
- }
429
-
430
- return component ?? undefined;
431
- };
432
-
433
- /**
434
- * Check if the given element is imported by an inline editor component, like an image, which is
435
- * content in the line just like text.
436
- * @param {Element} element Element.
437
- * @returns {boolean} Result.
438
- */
439
- const isInlineComponentElement = (element) => {
440
- const component = getElementComponent(getEditor(), element);
441
-
442
- // The `node` is actually a node class
443
- return !!component && !!(/** @type {any} */ (component.node).prototype.isInline?.());
444
- };
445
-
446
- /**
447
- * Find the text or the inline editor component element next to the given text in the same line,
448
- * like Lexical’s own `findTextInLine()` does for text only. Without the component, Lexical takes an
449
- * element like an image for the end of the line, or skips it, and drops the space between it and
450
- * the text, e.g. `a <img> b` becomes `a<img>b`.
451
- * @param {Node} text Text node.
452
- * @param {boolean} forward Whether to search forward.
453
- * @returns {Text | Element | null} Text or element, or `null` if the line ends.
454
- */
455
- const findContentInLine = (text, forward) => {
456
- let node = text;
457
-
458
- for (;;) {
459
- let sibling = forward ? node.nextSibling : node.previousSibling;
460
-
461
- while (!sibling) {
462
- const { parentElement } = node;
463
-
464
- if (!parentElement) {
465
- return null;
466
- }
467
-
468
- node = parentElement;
469
- sibling = forward ? node.nextSibling : node.previousSibling;
470
- }
471
-
472
- node = sibling;
473
-
474
- if (isHTMLElement(node)) {
475
- if (isInlineComponentElement(node)) {
476
- return node;
477
- }
478
-
479
- const { display } = node.style;
480
-
481
- if (display ? !display.startsWith('inline') : !isInlineDomNode(node)) {
482
- return null;
483
- }
484
- }
485
-
486
- let descendant = forward ? node.firstChild : node.lastChild;
487
-
488
- while (descendant) {
489
- node = descendant;
490
-
491
- if (isHTMLElement(node) && isInlineComponentElement(node)) {
492
- return node;
493
- }
494
-
495
- descendant = forward ? node.firstChild : node.lastChild;
496
- }
497
-
498
- if (isDOMTextNode(node)) {
499
- return node;
500
- }
501
-
502
- if (node.nodeName === 'BR') {
503
- return null;
504
- }
505
- }
506
- };
507
-
508
- /**
509
- * Check if the given node is within a `<pre>` element or an element with preformatted whitespace,
510
- * whose text is imported by Lexical’s own conversion as is.
511
- * @param {Node} node Node.
512
- * @returns {boolean} Result.
513
- */
514
- const isPreformatted = (node) => {
515
- for (let element = node.parentElement; element; element = element.parentElement) {
516
- if (element.localName === 'pre' || element.style.whiteSpace.startsWith('pre')) {
517
- return true;
518
- }
519
- }
520
-
521
- return false;
522
- };
523
-
524
- /**
525
- * Convert a text node, collapsing whitespace like Lexical’s own conversion does, except that an
526
- * inline editor component element counts as content. See {@link findContentInLine}.
527
- * @param {Text} domNode Text node.
528
- * @returns {DOMConversionOutput} Conversion output.
529
- */
530
- const convertTextNode = (domNode) => {
531
- let textContent = domNode.data.replace(/\r/g, '').replace(/[ \t\n]+/g, ' ');
532
-
533
- if (textContent.startsWith(' ')) {
534
- let previous = findContentInLine(domNode, false);
535
- // Drop the space at the start of a line, or after another space
536
- let drop = true;
537
-
538
- for (; previous; previous = findContentInLine(previous, false)) {
539
- if (!isDOMTextNode(previous)) {
540
- drop = false;
541
- break;
542
- }
543
-
544
- const previousText = previous.data;
545
-
546
- // Skip empty text
547
- if (previousText) {
548
- drop = /[ \t\n]$/.test(previousText);
549
- break;
550
- }
551
- }
552
-
553
- if (drop) {
554
- textContent = textContent.slice(1);
555
- }
556
- }
557
-
558
- if (textContent.endsWith(' ')) {
559
- let next = findContentInLine(domNode, true);
560
- let isEndOfLine = true;
561
-
562
- // Skip any text that only has whitespace, which is dropped as well
563
- for (; next; next = findContentInLine(next, true)) {
564
- if (!isDOMTextNode(next) || next.data.replace(/^[ \t\n]+/, '')) {
565
- isEndOfLine = false;
566
- break;
567
- }
568
- }
569
-
570
- if (isEndOfLine) {
571
- textContent = textContent.slice(0, -1);
572
- }
573
- }
574
-
575
- return { node: textContent ? createTextNode(textContent) : null };
576
- };
577
-
578
- /**
579
- * Additional DOM conversions to import HTML. They take priority over Lexical’s own conversions.
580
- * @type {DOMConversionMap}
581
- */
582
- export const HTML_IMPORT_MAP = {
583
- /**
584
- * Get the conversion for a text node, unless it’s preformatted, which Lexical’s own conversion
585
- * handles.
586
- * @param {Node} node Text node.
587
- * @returns {DOMConversion | null} Conversion.
588
- */
589
- '#text': (node) =>
590
- isPreformatted(node)
591
- ? null
592
- : {
593
- /**
594
- * Convert the text node.
595
- * @param {Node} domNode Text node.
596
- * @returns {DOMConversionOutput} Conversion output.
597
- */
598
- conversion: (domNode) => convertTextNode(/** @type {Text} */ (domNode)),
599
- priority: 1,
600
- },
601
- };
602
-
603
- /**
604
- * Additional DOM conversions to import HTML with code blocks.
605
- * @type {DOMConversionMap}
606
- */
607
- export const HTML_CODE_IMPORT_MAP = {
608
- /**
609
- * Get the conversion for a `<pre>` element.
610
- * @returns {DOMConversion} Conversion.
611
- */
612
- pre: () => ({ conversion: convertPreElement, priority: 2 }),
613
- };
614
-
615
- /**
616
- * Get the names of the elements only editor components import, which no other node handles.
617
- * @param {LexicalEditor} editor Editor instance.
618
- * @returns {Set<string>} Tag names.
619
- */
620
- const getComponentOnlyTagNames = (editor) => {
621
- const components = editorComponents.get(editor) ?? [];
622
- // The `node` is actually a node class
623
- const componentNodes = new Set(components.map(({ node }) => /** @type {any} */ (node)));
624
-
625
- const otherTagNames = new Set(
626
- [...editor._nodes.values()]
627
- .filter(({ klass }) => !componentNodes.has(klass))
628
- .flatMap(({ klass }) => Object.keys(klass.importDOM?.() ?? {})),
629
- );
630
-
631
- return new Set(
632
- components
633
- .flatMap(({ node }) => Object.keys(getComponentConversionMap(node)))
634
- .filter((tagName) => !otherTagNames.has(tagName)),
635
- );
636
- };
637
-
638
- /**
639
- * Get the first node in the given document that the editor cannot import, which would be silently
640
- * dropped, possibly along with its content:
641
- *
642
- * - An element none of the registered nodes, including the ones of editor components, handle. This
643
- * includes an element the parser moves to `<head>`, like a `<script>` at the beginning, and an
644
- * element only editor components handle, but none of them imports, like a `<figure>` that isn’t an
645
- * instance of a component for `<figure class="photo">`, which would be unwrapped.
646
- * - A comment, like `<!-- more -->`.
647
- *
648
- * The content of an element an editor component imports is part of the component, which is
649
- * expected to drop the children, and the elements within a `<pre>` element are imported as plain
650
- * text, so they’re ignored.
651
- * @param {LexicalEditor} editor Editor instance.
652
- * @param {Document} dom Parsed document.
653
- * @returns {Element | Comment | undefined} Unsupported node.
654
- */
655
- export const findUnsupportedNode = (editor, dom) => {
656
- const componentOnlyTagNames = getComponentOnlyTagNames(editor);
657
-
658
- /**
659
- * Find an unsupported node among the descendants of the given node.
660
- * @param {Node} parent Parent node.
661
- * @returns {Element | Comment | undefined} Unsupported node.
662
- */
663
- const findWithin = (parent) => {
664
- /** @type {Element | Comment | undefined} */
665
- let found;
666
-
667
- [...parent.childNodes].some((node) => {
668
- if (node.nodeType === Node.COMMENT_NODE) {
669
- found = /** @type {Comment} */ (node);
670
-
671
- return true;
672
- }
673
-
674
- if (node.nodeType !== Node.ELEMENT_NODE) {
675
- return false;
676
- }
677
-
678
- const element = /** @type {Element} */ (node);
679
- const tagName = element.localName;
680
-
681
- if (getElementComponent(editor, element)) {
682
- return false;
683
- }
684
-
685
- // `_htmlConversions` holds the conversions of all the registered nodes, along with the ones
686
- // in the `html.import` editor config. A conversion may still skip an element on purpose,
687
- // like a `<br>` at the end of a paragraph, which browsers don’t render
688
- if (
689
- !DOCUMENT_TAGS.includes(tagName) &&
690
- !PASSTHROUGH_TAGS.includes(tagName) &&
691
- (!editor._htmlConversions.has(tagName) || componentOnlyTagNames.has(tagName))
692
- ) {
693
- found = element;
694
-
695
- return true;
696
- }
697
-
698
- found =
699
- tagName === 'pre'
700
- ? /** @type {Comment | undefined} */ (
701
- dom.createTreeWalker(element, NodeFilter.SHOW_COMMENT).nextNode() ?? undefined
702
- )
703
- : findWithin(element);
704
-
705
- return !!found;
706
- });
707
-
708
- return found;
709
- };
710
-
711
- return findWithin(dom);
712
- };
713
-
714
- /**
715
- * Convert the editor content to HTML. Call this within an editor update or read.
716
- * @param {LexicalEditor} editor Editor instance.
717
- * @returns {string} HTML value.
718
- */
719
- export const exportHtml = (editor) => generateHtmlFromNodes(editor);