@sveltia/ui 0.79.4 → 0.80.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 (51) hide show
  1. package/dist/components/emoji/position.d.ts +2 -1
  2. package/dist/components/emoji/position.js +11 -3
  3. package/dist/components/text-editor/constants.d.ts +9 -1
  4. package/dist/components/text-editor/constants.js +10 -1
  5. package/dist/components/text-editor/core.d.ts +4 -2
  6. package/dist/components/text-editor/core.js +152 -33
  7. package/dist/components/text-editor/floating-link-editor.svelte +685 -0
  8. package/dist/components/text-editor/floating-link-editor.svelte.d.ts +17 -0
  9. package/dist/components/text-editor/html.d.ts +18 -0
  10. package/dist/components/text-editor/html.js +407 -0
  11. package/dist/components/text-editor/shiki/version.d.ts +1 -1
  12. package/dist/components/text-editor/shiki/version.js +1 -1
  13. package/dist/components/text-editor/store.svelte.js +12 -13
  14. package/dist/components/text-editor/text-editor.svelte +43 -17
  15. package/dist/components/text-editor/text-editor.svelte.d.ts +23 -6
  16. package/dist/components/text-editor/toolbar/insert-link-button.svelte +14 -71
  17. package/dist/components/text-editor/toolbar/text-editor-toolbar.svelte +12 -5
  18. package/dist/locales/ar.yaml +5 -1
  19. package/dist/locales/bg.yaml +5 -1
  20. package/dist/locales/ca.yaml +5 -1
  21. package/dist/locales/cs.yaml +5 -1
  22. package/dist/locales/da.yaml +5 -1
  23. package/dist/locales/de.yaml +5 -1
  24. package/dist/locales/el.yaml +5 -1
  25. package/dist/locales/en-CA.yaml +5 -1
  26. package/dist/locales/en-GB.yaml +5 -1
  27. package/dist/locales/en-US.yaml +5 -1
  28. package/dist/locales/es-CO.yaml +5 -1
  29. package/dist/locales/fa.yaml +5 -1
  30. package/dist/locales/fi.yaml +5 -1
  31. package/dist/locales/fr.yaml +5 -1
  32. package/dist/locales/he.yaml +5 -1
  33. package/dist/locales/hr.yaml +5 -1
  34. package/dist/locales/it.yaml +5 -1
  35. package/dist/locales/ja.yaml +5 -1
  36. package/dist/locales/ko.yaml +5 -1
  37. package/dist/locales/nl.yaml +5 -1
  38. package/dist/locales/pl.yaml +5 -1
  39. package/dist/locales/pt-BR.yaml +5 -1
  40. package/dist/locales/pt-PT.yaml +5 -1
  41. package/dist/locales/ru.yaml +5 -1
  42. package/dist/locales/sk.yaml +5 -1
  43. package/dist/locales/sv.yaml +5 -1
  44. package/dist/locales/tr.yaml +5 -1
  45. package/dist/locales/uk.yaml +5 -1
  46. package/dist/locales/vi.yaml +5 -1
  47. package/dist/locales/zh-CN.yaml +5 -1
  48. package/dist/locales/zh-TW.yaml +5 -1
  49. package/dist/typedefs.d.ts +13 -7
  50. package/dist/typedefs.js +12 -6
  51. package/package.json +5 -4
@@ -0,0 +1,18 @@
1
+ export function getCodeLanguage(code: Element): string | undefined;
2
+ /**
3
+ * Map of Lexical node classes and functions to export them to clean HTML. A class only takes effect
4
+ * if the node is registered with the editor. Other nodes, including the ones of editor components,
5
+ * are exported with their own `exportDOM` method.
6
+ * @type {DOMExportOutputMap}
7
+ */
8
+ export const HTML_EXPORT_MAP: DOMExportOutputMap;
9
+ /**
10
+ * Additional DOM conversions to import HTML. They take priority over Lexical’s own conversions.
11
+ * @type {DOMConversionMap}
12
+ */
13
+ export const HTML_IMPORT_MAP: DOMConversionMap;
14
+ export function findUnsupportedNode(editor: LexicalEditor, dom: Document): Element | Comment | undefined;
15
+ export function exportHtml(editor: LexicalEditor): string;
16
+ import type { DOMExportOutputMap } from 'lexical';
17
+ import type { DOMConversionMap } from 'lexical';
18
+ import type { LexicalEditor } from 'lexical';
@@ -0,0 +1,407 @@
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
+ $isParagraphNode as isParagraphNode,
11
+ isHTMLElement,
12
+ ParagraphNode,
13
+ TabNode,
14
+ TextNode,
15
+ } from 'lexical';
16
+ import { isPlainLanguage } from './shiki/facade.js';
17
+
18
+ /**
19
+ * @import {
20
+ * DOMConversion,
21
+ * DOMConversionMap,
22
+ * DOMConversionOutput,
23
+ * DOMExportOutput,
24
+ * DOMExportOutputMap,
25
+ * ElementNode,
26
+ * LexicalEditor,
27
+ * LexicalNode,
28
+ * } from 'lexical';
29
+ */
30
+
31
+ /**
32
+ * Attributes to be kept on the exported elements, by tag name. Anything else Lexical adds, like
33
+ * `class`, `dir`, `style`, `value` or `spellcheck`, is only meant for the editor itself.
34
+ * @type {Record<string, string[]>}
35
+ */
36
+ const ALLOWED_ATTRIBUTES = {
37
+ a: ['href', 'rel', 'target', 'title'],
38
+ ol: ['start'],
39
+ td: ['colspan', 'rowspan'],
40
+ th: ['colspan', 'rowspan'],
41
+ };
42
+
43
+ /**
44
+ * Text formats and their HTML tags, from the innermost to the outermost.
45
+ * @type {[import('lexical').TextFormatType, string][]}
46
+ */
47
+ const TEXT_FORMAT_TAGS = [
48
+ ['code', 'code'],
49
+ ['subscript', 'sub'],
50
+ ['superscript', 'sup'],
51
+ ['highlight', 'mark'],
52
+ ['underline', 'u'],
53
+ ['strikethrough', 's'],
54
+ ['italic', 'em'],
55
+ ['bold', 'strong'],
56
+ ];
57
+
58
+ /**
59
+ * Table elements that have no Lexical node of their own. The rows are imported as is, while the
60
+ * column definitions are only used for the column widths.
61
+ */
62
+ const PASSTHROUGH_TAGS = ['tbody', 'thead', 'tfoot', 'colgroup', 'col'];
63
+ /**
64
+ * Elements the HTML parser always creates, which hold the content rather than being part of it.
65
+ */
66
+ const DOCUMENT_TAGS = ['html', 'head', 'body'];
67
+
68
+ /**
69
+ * Get the programming language from the `language-*` or `lang-*` class of the given `<code>`
70
+ * element, which is common in HTML generated from Markdown.
71
+ * @param {Element} code `<code>` element.
72
+ * @returns {string | undefined} Language.
73
+ */
74
+ export const getCodeLanguage = (code) =>
75
+ code.className.match(/(?:^|\s)(?:lang|language)-(\S+)/)?.[1];
76
+
77
+ /**
78
+ * Remove the attributes not listed in {@link ALLOWED_ATTRIBUTES} from the given element.
79
+ * @param {Element} element Element.
80
+ */
81
+ const removeExtraAttributes = (element) => {
82
+ const allowedAttributes = ALLOWED_ATTRIBUTES[element.localName] ?? [];
83
+
84
+ [...element.attributes].forEach(({ name }) => {
85
+ if (!allowedAttributes.includes(name)) {
86
+ element.removeAttribute(name);
87
+ }
88
+ });
89
+ };
90
+
91
+ /**
92
+ * Export an element node with Lexical’s own implementation, then remove the extra attributes from
93
+ * the element, as well as the attribute Lexical adds to the `<br>` terminating a trailing line
94
+ * break. The element’s own `after` function, if any, still runs first, so the structure is kept,
95
+ * like a nested list moved into the previous list item.
96
+ * @param {LexicalEditor} editor Editor instance.
97
+ * @param {ElementNode} node Element node.
98
+ * @returns {DOMExportOutput} Export output.
99
+ */
100
+ const exportElementNode = (editor, node) => {
101
+ const { after, ...output } = node.exportDOM(editor);
102
+
103
+ if (isHTMLElement(output.element)) {
104
+ removeExtraAttributes(output.element);
105
+ }
106
+
107
+ return {
108
+ ...output,
109
+ /**
110
+ * Clean up the element once its children are in place.
111
+ * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.
112
+ * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace
113
+ * the exported one, if any.
114
+ */
115
+ after: (element) => {
116
+ const newElement = after ? after.call(node, element) : undefined;
117
+ const target = newElement ?? element;
118
+
119
+ if (isHTMLElement(target)) {
120
+ removeExtraAttributes(target);
121
+ target.querySelectorAll(':scope > br').forEach(removeExtraAttributes);
122
+ }
123
+
124
+ // Returning the same element would make Lexical replace it with itself
125
+ return newElement === element ? undefined : newElement;
126
+ },
127
+ };
128
+ };
129
+
130
+ /**
131
+ * Export a paragraph node. Empty paragraphs at the end are left out, as they have no content; one
132
+ * may be added just by clicking below a block decorator. A paragraph that is the only child of a
133
+ * table cell is exported without the `<p>` element.
134
+ * @param {LexicalEditor} editor Editor instance.
135
+ * @param {ParagraphNode} node Paragraph node.
136
+ * @returns {DOMExportOutput} Export output.
137
+ */
138
+ const exportParagraphNode = (editor, node) => {
139
+ const parent = node.getParent();
140
+
141
+ if (parent instanceof TableCellNode && parent.getChildrenSize() === 1) {
142
+ return { element: document.createDocumentFragment() };
143
+ }
144
+
145
+ if (
146
+ node.isEmpty() &&
147
+ node.getNextSiblings().every((sibling) => isParagraphNode(sibling) && sibling.isEmpty())
148
+ ) {
149
+ return { element: null };
150
+ }
151
+
152
+ return exportElementNode(editor, node);
153
+ };
154
+
155
+ /**
156
+ * Export a text node as plain text wrapped with the elements for its formats, instead of the
157
+ * `<span>`, `<b>` and `<i>` elements with styles and classes Lexical uses.
158
+ * @param {LexicalEditor} _editor Editor instance.
159
+ * @param {TextNode} node Text node.
160
+ * @returns {DOMExportOutput} Export output.
161
+ */
162
+ const exportTextNode = (_editor, node) => {
163
+ /** @type {HTMLElement | Text} */
164
+ let element = document.createTextNode(node.getTextContent());
165
+
166
+ TEXT_FORMAT_TAGS.forEach(([format, tagName]) => {
167
+ if (node.hasFormat(format)) {
168
+ const wrapper = document.createElement(tagName);
169
+
170
+ wrapper.append(element);
171
+ element = wrapper;
172
+ }
173
+ });
174
+
175
+ return { element };
176
+ };
177
+
178
+ /**
179
+ * Export a code block node as `<pre><code>` with the common `language-*` class, instead of the
180
+ * highlighted tokens Lexical renders in the editor. The children are still exported as usual, so
181
+ * copying part of a code block only exports the selected text, then their text is moved into the
182
+ * `<code>` element.
183
+ * @param {LexicalEditor} _editor Editor instance.
184
+ * @param {CodeNode} node Code node.
185
+ * @returns {DOMExportOutput} Export output.
186
+ */
187
+ const exportCodeNode = (_editor, node) => ({
188
+ element: document.createElement('pre'),
189
+ /**
190
+ * Replace the exported children with a `<code>` element holding their text.
191
+ * @param {HTMLElement | DocumentFragment | Text | null | undefined} pre Exported element.
192
+ * @returns {undefined} Nothing, as the element is updated in place.
193
+ */
194
+ after: (pre) => {
195
+ /* v8 ignore next 3 */
196
+ if (!isHTMLElement(pre)) {
197
+ return undefined;
198
+ }
199
+
200
+ const code = document.createElement('code');
201
+ const language = node.getLanguage();
202
+
203
+ if (language && !isPlainLanguage(language)) {
204
+ code.className = `language-${language}`;
205
+ }
206
+
207
+ code.textContent = [...pre.childNodes]
208
+ .map((child) => {
209
+ if (child.nodeName !== 'BR') {
210
+ return child.textContent;
211
+ }
212
+
213
+ // Skip the `<br>` Lexical adds to terminate a trailing line break
214
+ return isHTMLElement(child) && child.hasAttribute('data-lexical-managed-linebreak')
215
+ ? ''
216
+ : '\n';
217
+ })
218
+ .join('');
219
+
220
+ pre.replaceChildren(code);
221
+
222
+ return undefined;
223
+ },
224
+ });
225
+
226
+ /**
227
+ * Selector for the structural elements of a table, excluding the cell content.
228
+ */
229
+ const TABLE_STRUCTURE_SELECTOR = [
230
+ ':scope > :is(thead, tbody, tfoot)',
231
+ ':scope > :is(thead, tbody, tfoot) > tr',
232
+ ':scope > :is(thead, tbody, tfoot) > tr > :is(th, td)',
233
+ ':scope > tr',
234
+ ':scope > tr > :is(th, td)',
235
+ ].join(', ');
236
+
237
+ /**
238
+ * Export a table node, then remove the column definitions and extra attributes Lexical adds to the
239
+ * table and its descendants. The cleanup has to wait until the table is complete, as Lexical uses
240
+ * temporary attributes on the cells to compute the columns.
241
+ * @param {LexicalEditor} editor Editor instance.
242
+ * @param {TableNode} node Table node.
243
+ * @returns {DOMExportOutput} Export output.
244
+ */
245
+ const exportTableNode = (editor, node) => {
246
+ const { after, ...output } = node.exportDOM(editor);
247
+
248
+ return {
249
+ ...output,
250
+ /**
251
+ * Clean up the table once Lexical has completed it.
252
+ * @param {HTMLElement | DocumentFragment | Text | null | undefined} element Exported element.
253
+ * @returns {HTMLElement | DocumentFragment | Text | null | undefined} New element to replace
254
+ * the exported one, if any.
255
+ */
256
+ after: (element) => {
257
+ const newElement = after ? after.call(node, element) : undefined;
258
+ const target = newElement ?? element;
259
+
260
+ if (isHTMLElement(target)) {
261
+ target.querySelectorAll(':scope > colgroup').forEach((colgroup) => colgroup.remove());
262
+ // Leave the cell content alone, which has been cleaned up by its own nodes, while the
263
+ // content of an editor component may need its attributes
264
+ [target, ...target.querySelectorAll(TABLE_STRUCTURE_SELECTOR)].forEach(
265
+ removeExtraAttributes,
266
+ );
267
+ }
268
+
269
+ // Returning the same element would make Lexical replace it with itself
270
+ return newElement === element ? undefined : newElement;
271
+ },
272
+ };
273
+ };
274
+
275
+ /**
276
+ * Map of Lexical node classes and functions to export them to clean HTML. A class only takes effect
277
+ * if the node is registered with the editor. Other nodes, including the ones of editor components,
278
+ * are exported with their own `exportDOM` method.
279
+ * @type {DOMExportOutputMap}
280
+ */
281
+ export const HTML_EXPORT_MAP = new Map(
282
+ /** @type {[any, (editor: LexicalEditor, node: any) => DOMExportOutput][]} */ ([
283
+ [TextNode, exportTextNode],
284
+ [TabNode, exportTextNode],
285
+ [CodeHighlightNode, exportTextNode],
286
+ [ParagraphNode, exportParagraphNode],
287
+ [HeadingNode, exportElementNode],
288
+ [QuoteNode, exportElementNode],
289
+ [ListNode, exportElementNode],
290
+ [ListItemNode, exportElementNode],
291
+ [LinkNode, exportElementNode],
292
+ [HorizontalRuleNode, exportElementNode],
293
+ [CodeNode, exportCodeNode],
294
+ [TableNode, exportTableNode],
295
+ ]),
296
+ );
297
+
298
+ /**
299
+ * Get the text content of the given element, with `<br>` elements as line breaks.
300
+ * @param {Element} element Element.
301
+ * @returns {string} Text.
302
+ */
303
+ const getTextWithLineBreaks = (element) => {
304
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_ALL);
305
+ let text = '';
306
+
307
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
308
+ if (node.nodeType === Node.TEXT_NODE) {
309
+ text += /** @type {Text} */ (node).data;
310
+ } else if (node.nodeName === 'BR') {
311
+ text += '\n';
312
+ }
313
+ }
314
+
315
+ return text;
316
+ };
317
+
318
+ /**
319
+ * Convert a `<pre>` element to a code block node, taking the language from the `language-*` or
320
+ * `lang-*` class of the `<code>` element within it, which is common in HTML generated from
321
+ * Markdown, as well as the `data-language` attribute Lexical uses. The content is imported as plain
322
+ * text, so any markup within it, like highlighted tokens, is dropped, while a `<br>` element
323
+ * becomes a line break.
324
+ * @param {HTMLElement} pre `<pre>` element.
325
+ * @returns {DOMConversionOutput} Conversion output.
326
+ */
327
+ const convertPreElement = (pre) => {
328
+ const code = pre.querySelector(':scope > code');
329
+ const language = (code ? getCodeLanguage(code) : undefined) ?? pre.getAttribute('data-language');
330
+ const node = createCodeNode(language);
331
+ // A code block generated from Markdown ends with a line break
332
+ const text = getTextWithLineBreaks(pre).replace(/\n$/, '');
333
+
334
+ if (text) {
335
+ node.append(createTextNode(text));
336
+ }
337
+
338
+ return {
339
+ node,
340
+ /**
341
+ * Drop the child nodes, which are already imported as the text content.
342
+ * @returns {LexicalNode[]} Nodes.
343
+ */
344
+ after: () => [],
345
+ };
346
+ };
347
+
348
+ /**
349
+ * Additional DOM conversions to import HTML. They take priority over Lexical’s own conversions.
350
+ * @type {DOMConversionMap}
351
+ */
352
+ export const HTML_IMPORT_MAP = {
353
+ /**
354
+ * Get the conversion for a `<pre>` element.
355
+ * @returns {DOMConversion} Conversion.
356
+ */
357
+ pre: () => ({ conversion: convertPreElement, priority: 2 }),
358
+ };
359
+
360
+ /**
361
+ * Get the first node in the given document that the editor cannot import, which would be silently
362
+ * dropped, possibly along with its content:
363
+ *
364
+ * - An element none of the registered nodes, including the ones of editor components, handle. This
365
+ * includes an element the parser moves to `<head>`, like a `<script>` at the beginning.
366
+ * - A comment, like `<!-- more -->`.
367
+ *
368
+ * The elements within a `<pre>` element are ignored, as its content is imported as plain text.
369
+ * @param {LexicalEditor} editor Editor instance.
370
+ * @param {Document} dom Parsed document.
371
+ * @returns {Element | Comment | undefined} Unsupported node.
372
+ */
373
+ export const findUnsupportedNode = (editor, dom) => {
374
+ const walker = dom.createTreeWalker(dom, NodeFilter.SHOW_ALL);
375
+
376
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
377
+ if (node.nodeType === Node.COMMENT_NODE) {
378
+ return /** @type {Comment} */ (node);
379
+ }
380
+
381
+ if (node.nodeType === Node.ELEMENT_NODE) {
382
+ const element = /** @type {Element} */ (node);
383
+ const tagName = element.localName;
384
+
385
+ // `_htmlConversions` holds the conversions of all the registered nodes, along with the ones
386
+ // in the `html.import` editor config. A conversion may still skip an element on purpose,
387
+ // like a `<br>` at the end of a paragraph, which browsers don’t render
388
+ if (
389
+ !DOCUMENT_TAGS.includes(tagName) &&
390
+ !PASSTHROUGH_TAGS.includes(tagName) &&
391
+ !element.parentElement?.closest('pre') &&
392
+ !editor._htmlConversions.has(tagName)
393
+ ) {
394
+ return element;
395
+ }
396
+ }
397
+ }
398
+
399
+ return undefined;
400
+ };
401
+
402
+ /**
403
+ * Convert the editor content to HTML. Call this within an editor update or read.
404
+ * @param {LexicalEditor} editor Editor instance.
405
+ * @returns {string} HTML value.
406
+ */
407
+ export const exportHtml = (editor) => generateHtmlFromNodes(editor);
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.
3
3
  */
4
- export const UI_VERSION: "0.79.4";
4
+ export const UI_VERSION: "0.80.0";
@@ -3,4 +3,4 @@
3
3
  /**
4
4
  * Version of this package, used to resolve the prebuilt Shiki engine chunk from a CDN.
5
5
  */
6
- export const UI_VERSION = '0.79.4';
6
+ export const UI_VERSION = '0.80.0';
@@ -1,5 +1,5 @@
1
1
  import { generateElementId } from '@sveltia/utils/element';
2
- import { convertMarkdownToLexical } from './core.js';
2
+ import { convertHtmlToLexical, convertMarkdownToLexical } from './core.js';
3
3
 
4
4
  /**
5
5
  * @import { LexicalEditor } from 'lexical';
@@ -51,7 +51,7 @@ export const createEditorStore = () => {
51
51
  */
52
52
  let runningOperations = $state(0);
53
53
  /**
54
- * Value last imported to the Lexical editor, and the Markdown the editor exports for it.
54
+ * Value last imported to the Lexical editor, and the Markdown or HTML the editor exports for it.
55
55
  * @type {{ source: string, exported: string } | undefined}
56
56
  */
57
57
  let lastImport = undefined;
@@ -81,10 +81,10 @@ export const createEditorStore = () => {
81
81
  };
82
82
 
83
83
  /**
84
- * Convert the Markdown {@link inputValue} to Lexical nodes. Disable the rich text mode and
85
- * restore the original value when there is an error while conversion.
84
+ * Convert the Markdown or HTML {@link inputValue} to Lexical nodes. Disable the rich text mode
85
+ * and restore the original value when there is an error while conversion.
86
86
  */
87
- const convertMarkdown = async () => {
87
+ const convertToLexical = async () => {
88
88
  if (!editor || !initialized) {
89
89
  return;
90
90
  }
@@ -101,11 +101,10 @@ export const createEditorStore = () => {
101
101
  // We should avoid an empty editor; there should be at least one `<p>`, so give it an empty
102
102
  // string if the `value` is `undefined`
103
103
  // @see https://github.com/facebook/lexical/issues/2308
104
- const exported = await convertMarkdownToLexical(
105
- editor,
106
- inputValue || '',
107
- enabledTransformers,
108
- );
104
+ const exported =
105
+ config.format === 'html'
106
+ ? await convertHtmlToLexical(editor, inputValue || '')
107
+ : await convertMarkdownToLexical(editor, inputValue || '', enabledTransformers);
109
108
 
110
109
  // Skip an import superseded by a newer one, which sets its own value
111
110
  if (exported !== undefined) {
@@ -163,7 +162,7 @@ export const createEditorStore = () => {
163
162
  }
164
163
 
165
164
  if (useRichText && (hasChange || editor?.getEditorState().isEmpty())) {
166
- convertMarkdown();
165
+ convertToLexical();
167
166
  }
168
167
  },
169
168
  get selection() {
@@ -209,7 +208,7 @@ export const createEditorStore = () => {
209
208
  return importing;
210
209
  },
211
210
  editorId,
212
- convertMarkdown,
211
+ convertToLexical,
213
212
  /**
214
213
  * Mark an operation the user started as running, which makes the content count as
215
214
  * {@link TextEditorStore.pending} until it’s done. Use it for an operation that only reaches
@@ -233,7 +232,7 @@ export const createEditorStore = () => {
233
232
  },
234
233
  /**
235
234
  * Get the value last imported if the given value, exported by the editor, is only that value
236
- * written in the editor’s own Markdown style.
235
+ * written in the editor’s own Markdown or HTML style.
237
236
  * @param {string} value Exported value.
238
237
  * @returns {string | undefined} Imported value, or `undefined` if the content has changed.
239
238
  */
@@ -11,6 +11,7 @@
11
11
  import { BLOCK_BUTTON_TYPES, INLINE_BUTTON_TYPES } from './constants.js';
12
12
  import { loadCodeHighlighter } from './core.js';
13
13
  import EmojiAutocomplete from './emoji-autocomplete.svelte';
14
+ import FloatingLinkEditor from './floating-link-editor.svelte';
14
15
  import LexicalRoot from './lexical-root.svelte';
15
16
  import { getBlockType, getRawTextState } from './raw-markdown.js';
16
17
  import { highlightCodeToTokens } from './shiki/facade.js';
@@ -20,15 +21,25 @@
20
21
 
21
22
  /**
22
23
  * @import { Snippet } from 'svelte';
23
- * @import { TextEditorComponent, TextEditorMode, TextEditorNodeType } from '../../typedefs.js';
24
+ * @import {
25
+ * TextEditorComponent,
26
+ * TextEditorMode,
27
+ * TextEditorNodeType,
28
+ * TextEditorValueFormat,
29
+ * } from '../../typedefs.js';
24
30
  * @import { HighlightedToken } from '../../typedefs.js';
25
31
  */
26
32
 
27
33
  /**
28
34
  * @typedef {object} Props
29
- * @property {string} [value] Input value. A value set from outside is kept as is until the user
30
- * changes the content, although the rich text editor writes Markdown in its own style, such as
31
- * `_text_` for `*text*`.
35
+ * @property {string} [value] Input value in the {@link format}. A value set from outside
36
+ * is kept as is until the user changes the content, although the rich text editor writes Markdown
37
+ * or HTML in its own style, such as `_text_` for `*text*` or `<strong>` for `<b>`.
38
+ * @property {TextEditorValueFormat} [format] Format of the {@link value}: `markdown` or `html`.
39
+ * With `html`, the plain text mode shows the HTML source, and editor components have to
40
+ * implement `importDOM` and `exportDOM` for their nodes. HTML with an element the editor cannot
41
+ * handle, like `<img>`, can only be edited in the plain text mode. Attributes not used by the
42
+ * editor, like `class`, are dropped once the content is changed in the rich text mode.
32
43
  * @property {boolean} [pending] Whether the user has changed the rich text content, and the
33
44
  * editor has yet to update {@link value}, which it does a moment later. Bind it to wait for the
34
45
  * change before reading the value, for example to save it. Read-only.
@@ -67,6 +78,7 @@
67
78
  /* eslint-disable prefer-const */
68
79
  value = $bindable(''),
69
80
  pending = $bindable(false),
81
+ format = 'markdown',
70
82
  flex = false,
71
83
  dir = undefined,
72
84
  modes = ['rich-text', 'plain-text'],
@@ -110,13 +122,19 @@
110
122
  components,
111
123
  useMarkdownShortcuts,
112
124
  useEmojiAutocomplete,
125
+ format,
113
126
  };
114
127
 
115
128
  setContext('editorStore', editorStore);
116
129
 
130
+ /** Language of the source shown in the plain text mode. */
131
+ // svelte-ignore state_referenced_locally
132
+ const sourceLanguage = format === 'html' ? 'html' : 'markdown';
133
+
117
134
  /**
118
- * Maximum length of the Markdown source to highlight in the plain text mode. The whole source is
119
- * tokenized on every keystroke, so highlighting a longer one would make typing sluggish.
135
+ * Maximum length of the Markdown or HTML source to highlight in the plain text mode. The whole
136
+ * source is tokenized on every keystroke, so highlighting a longer one would make typing
137
+ * sluggish.
120
138
  */
121
139
  const MAX_HIGHLIGHT_LENGTH = 20_000;
122
140
 
@@ -127,11 +145,16 @@
127
145
 
128
146
  const usePlainText = $derived(!editorStore.useRichText && !hidden);
129
147
  /**
130
- * Comma-separated languages used in the fenced code blocks, which are highlighted as well. It’s a
131
- * string rather than an array, so the highlighter isn’t reloaded on every keystroke.
148
+ * Comma-separated languages used in the fenced code blocks of the Markdown source, which are
149
+ * highlighted as well. It’s a string rather than an array, so the highlighter isn’t reloaded on
150
+ * every keystroke.
132
151
  */
133
152
  const codeLanguages = $derived.by(() => {
134
- if (!usePlainText || editorStore.inputValue.length > MAX_HIGHLIGHT_LENGTH) {
153
+ if (
154
+ !usePlainText ||
155
+ sourceLanguage !== 'markdown' ||
156
+ editorStore.inputValue.length > MAX_HIGHLIGHT_LENGTH
157
+ ) {
135
158
  return '';
136
159
  }
137
160
 
@@ -145,12 +168,12 @@
145
168
  });
146
169
 
147
170
  /**
148
- * Highlight the Markdown source in the plain text mode.
149
- * @param {string} source Markdown source.
171
+ * Highlight the Markdown or HTML source in the plain text mode.
172
+ * @param {string} source Markdown or HTML source.
150
173
  * @returns {HighlightedToken[][] | undefined} Tokens, or `undefined` while the highlighter is
151
174
  * still loading.
152
175
  */
153
- const highlightMarkdown = (source) => {
176
+ const highlightSource = (source) => {
154
177
  void highlighterLoadCount;
155
178
 
156
179
  // Don’t waste time on tokenizing the source while the rich text mode is shown
@@ -158,7 +181,7 @@
158
181
  return undefined;
159
182
  }
160
183
 
161
- return highlightCodeToTokens(source, 'markdown', { theme: codeTheme });
184
+ return highlightCodeToTokens(source, sourceLanguage, { theme: codeTheme });
162
185
  };
163
186
 
164
187
  $effect(() =>
@@ -167,7 +190,7 @@
167
190
 
168
191
  // Keep the current highlighting until the new theme is ready, so the text doesn’t flash
169
192
  if (usePlainText) {
170
- await loadCodeHighlighter('markdown');
193
+ await loadCodeHighlighter(sourceLanguage);
171
194
  }
172
195
 
173
196
  // Ignore an outdated change, in case the appearance has changed again while loading
@@ -188,9 +211,9 @@
188
211
  void codeTheme;
189
212
 
190
213
  untrack(() => {
191
- // The Markdown grammar is loaded first, because the engine has to be in place before
214
+ // The Markdown or HTML grammar is loaded first, because the engine has to be in place before
192
215
  // anything else can be loaded
193
- loadCodeHighlighter('markdown').then(async () => {
216
+ loadCodeHighlighter(sourceLanguage).then(async () => {
194
217
  highlighterLoadCount += 1;
195
218
  await Promise.all(languages.map((lang) => loadCodeHighlighter(lang)));
196
219
  highlighterLoadCount += 1;
@@ -291,7 +314,7 @@
291
314
  autoResize={true}
292
315
  bind:value={editorStore.inputValue}
293
316
  {useEmojiAutocomplete}
294
- highlight={highlightMarkdown}
317
+ highlight={highlightSource}
295
318
  {flex}
296
319
  {dir}
297
320
  hidden={editorStore.useRichText || hidden}
@@ -303,6 +326,9 @@
303
326
  {#if editorStore.config.useEmojiAutocomplete && !disabled && !readonly}
304
327
  <EmojiAutocomplete />
305
328
  {/if}
329
+ {#if editorStore.config.enabledButtons.includes('link') && !disabled && !readonly}
330
+ <FloatingLinkEditor />
331
+ {/if}
306
332
  </div>
307
333
 
308
334
  {#if editorStore.showConverterError}