@lexical/html 0.44.1-nightly.20260518.0 → 0.45.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 (66) hide show
  1. package/{DOMRenderExtension.d.ts → dist/DOMRenderExtension.d.ts} +12 -1
  2. package/dist/DOMRenderRuntime.d.ts +51 -0
  3. package/dist/LexicalHtml.dev.js +3192 -0
  4. package/dist/LexicalHtml.dev.mjs +3146 -0
  5. package/{LexicalHtml.js.flow → dist/LexicalHtml.js.flow} +16 -16
  6. package/dist/LexicalHtml.mjs +56 -0
  7. package/dist/LexicalHtml.node.mjs +54 -0
  8. package/dist/LexicalHtml.prod.js +9 -0
  9. package/dist/LexicalHtml.prod.mjs +9 -0
  10. package/dist/RenderContext.d.ts +68 -0
  11. package/{compileDOMRenderConfigOverrides.d.ts → dist/compileDOMRenderConfigOverrides.d.ts} +1 -1
  12. package/{constants.d.ts → dist/constants.d.ts} +2 -0
  13. package/dist/domOverride.d.ts +23 -0
  14. package/dist/import/CoreImportExtension.d.ts +11 -0
  15. package/dist/import/DOMImportExtension.d.ts +82 -0
  16. package/dist/import/HorizontalRuleImportExtension.d.ts +27 -0
  17. package/dist/import/ImportContext.d.ts +208 -0
  18. package/dist/import/compileImportRules.d.ts +50 -0
  19. package/dist/import/coreImportRules.d.ts +25 -0
  20. package/dist/import/defineImportRule.d.ts +32 -0
  21. package/dist/import/defineOverlayRules.d.ts +66 -0
  22. package/dist/import/index.d.ts +38 -0
  23. package/dist/import/inlineStylesFromStyleSheets.d.ts +28 -0
  24. package/dist/import/parseCss.d.ts +18 -0
  25. package/dist/import/runImport.d.ts +19 -0
  26. package/dist/import/schemas.d.ts +91 -0
  27. package/dist/import/sel.d.ts +74 -0
  28. package/dist/import/types.d.ts +394 -0
  29. package/dist/index.d.ts +44 -0
  30. package/{types.d.ts → dist/types.d.ts} +96 -8
  31. package/package.json +33 -18
  32. package/src/ContextRecord.ts +243 -0
  33. package/src/DOMRenderExtension.ts +96 -0
  34. package/src/DOMRenderRuntime.ts +265 -0
  35. package/src/RenderContext.ts +168 -0
  36. package/src/compileDOMRenderConfigOverrides.ts +416 -0
  37. package/src/constants.ts +18 -0
  38. package/src/domOverride.ts +46 -0
  39. package/src/import/CoreImportExtension.ts +26 -0
  40. package/src/import/DOMImportExtension.ts +221 -0
  41. package/src/import/HorizontalRuleImportExtension.ts +53 -0
  42. package/src/import/ImportContext.ts +339 -0
  43. package/src/import/compileImportRules.ts +178 -0
  44. package/src/import/coreImportRules.ts +485 -0
  45. package/src/import/defineImportRule.ts +40 -0
  46. package/src/import/defineOverlayRules.ts +105 -0
  47. package/src/import/index.ts +96 -0
  48. package/src/import/inlineStylesFromStyleSheets.ts +104 -0
  49. package/src/import/parseCss.ts +219 -0
  50. package/src/import/runImport.ts +245 -0
  51. package/src/import/schemas.ts +236 -0
  52. package/src/import/sel.ts +314 -0
  53. package/src/import/types.ts +471 -0
  54. package/src/index.ts +555 -0
  55. package/src/types.ts +470 -0
  56. package/LexicalHtml.dev.js +0 -914
  57. package/LexicalHtml.dev.mjs +0 -900
  58. package/LexicalHtml.mjs +0 -24
  59. package/LexicalHtml.node.mjs +0 -22
  60. package/LexicalHtml.prod.js +0 -9
  61. package/LexicalHtml.prod.mjs +0 -9
  62. package/RenderContext.d.ts +0 -32
  63. package/domOverride.d.ts +0 -18
  64. package/index.d.ts +0 -32
  65. /package/{ContextRecord.d.ts → dist/ContextRecord.d.ts} +0 -0
  66. /package/{LexicalHtml.js → dist/LexicalHtml.js} +0 -0
package/src/index.ts ADDED
@@ -0,0 +1,555 @@
1
+ /**
2
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ *
4
+ * This source code is licensed under the MIT license found in the
5
+ * LICENSE file in the root directory of this source tree.
6
+ *
7
+ */
8
+
9
+ import type {
10
+ BaseSelection,
11
+ DOMChildConversion,
12
+ DOMConversion,
13
+ DOMConversionFn,
14
+ EditorDOMRenderConfig,
15
+ ElementFormatType,
16
+ LexicalEditor,
17
+ LexicalNode,
18
+ } from 'lexical';
19
+
20
+ import invariant from '@lexical/internal/invariant';
21
+ import {$sliceSelectedTextNodeContent} from '@lexical/selection';
22
+ import {
23
+ $createLineBreakNode,
24
+ $createParagraphNode,
25
+ $getEditor,
26
+ $getEditorDOMRenderConfig,
27
+ $getRoot,
28
+ $isBlockElementNode,
29
+ $isElementNode,
30
+ $isRootOrShadowRoot,
31
+ $isTextNode,
32
+ ArtificialNode__DO_NOT_USE,
33
+ ElementNode,
34
+ isBlockDomNode,
35
+ isDocumentFragment,
36
+ isDOMDocumentNode,
37
+ isHTMLElement,
38
+ isInlineDomNode,
39
+ } from 'lexical';
40
+
41
+ import {contextValue} from './ContextRecord';
42
+ import {$inlineStylesFromStyleSheetsDOM} from './import/inlineStylesFromStyleSheets';
43
+ import {
44
+ $getSessionDOMRenderConfig,
45
+ $withRenderContext,
46
+ RenderContextExport,
47
+ RenderContextRoot,
48
+ } from './RenderContext';
49
+
50
+ export {contextUpdater, contextValue} from './ContextRecord';
51
+ export {domOverride} from './domOverride';
52
+ export {DOMRenderExtension} from './DOMRenderExtension';
53
+ export type {
54
+ AnyDOMImportRule,
55
+ AttrMatchOptions,
56
+ CapturesOfSelector,
57
+ ChildSchema,
58
+ CompiledOverlayRules,
59
+ CompiledSelector,
60
+ DOMImportContext,
61
+ DOMImportExtensionOutput,
62
+ DOMImportFn,
63
+ DOMImportRule,
64
+ DOMImportRuleEntry,
65
+ DOMPreprocessContext,
66
+ DOMPreprocessFn,
67
+ ElementSelectorBuilder,
68
+ GenerateNodesFromDOMOptions,
69
+ ImportChildrenOpts,
70
+ ImportContextPairOrUpdater,
71
+ ImportNodeOpts,
72
+ ImportSession,
73
+ ImportStateConfig,
74
+ NodeOfSelector,
75
+ StyleMatchOptions,
76
+ } from './import';
77
+ export {
78
+ $distributeInlineWrapper,
79
+ $generateNodesFromDOMViaExtension,
80
+ $getImportContextValue,
81
+ $inlineStylesFromStyleSheets,
82
+ $isBlockLevel,
83
+ $withImportContext,
84
+ BlockSchema,
85
+ CoreImportExtension,
86
+ CoreImportRules,
87
+ createImportState,
88
+ defaultIsInline,
89
+ defaultPreservesWhitespace,
90
+ defineImportRule,
91
+ defineOverlayRules,
92
+ type DOMImportConfig,
93
+ DOMImportExtension,
94
+ HorizontalRuleImportExtension,
95
+ HorizontalRuleImportRules,
96
+ ImportOverlays,
97
+ ImportSource,
98
+ ImportSourceDataTransfer,
99
+ type ImportSourceKind,
100
+ ImportTextFormat,
101
+ ImportTextStyle,
102
+ ImportWhitespaceConfig,
103
+ InlineSchema,
104
+ isElementOfTag,
105
+ type IsInlineForWhitespace,
106
+ type IsPreserveWhitespaceDom,
107
+ NestedBlockSchema,
108
+ parseSelector,
109
+ RootSchema,
110
+ sel,
111
+ type WhitespaceImportConfig,
112
+ } from './import';
113
+ export {
114
+ $getRenderContextValue,
115
+ $getSessionDOMRenderConfig,
116
+ $setRenderContextValue,
117
+ $updateRenderContextValue,
118
+ $withRenderContext,
119
+ createRenderState,
120
+ RenderContextExport,
121
+ RenderContextRoot,
122
+ } from './RenderContext';
123
+ export type {
124
+ AnyDOMRenderMatch,
125
+ AnyRenderStateConfig,
126
+ AnyRenderStateConfigPairOrUpdater,
127
+ ContextPairOrUpdater,
128
+ DOMOverrideOptions,
129
+ DOMRenderConfig,
130
+ DOMRenderExtensionOutput,
131
+ DOMRenderMatch,
132
+ DOMRenderMatchConfig,
133
+ NodeMatch,
134
+ RenderContextReader,
135
+ } from './types';
136
+
137
+ const IGNORE_TAGS = new Set(['STYLE', 'SCRIPT']);
138
+
139
+ /**
140
+ * How you parse your html string to get a document is left up to you. In the browser you can use the native
141
+ * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
142
+ * or an equivalent library and pass in the document here.
143
+ */
144
+ export function $generateNodesFromDOM(
145
+ editor: LexicalEditor,
146
+ dom: Document | ParentNode,
147
+ ): Array<LexicalNode> {
148
+ $inlineStylesFromStyleSheetsDOM(dom);
149
+
150
+ const elements = isDOMDocumentNode(dom)
151
+ ? dom.body.childNodes
152
+ : dom.childNodes;
153
+ const lexicalNodes: Array<LexicalNode> = [];
154
+ const allArtificialNodes: Array<ArtificialNode__DO_NOT_USE> = [];
155
+ for (const element of elements) {
156
+ if (!IGNORE_TAGS.has(element.nodeName)) {
157
+ const lexicalNode = $createNodesFromDOM(
158
+ element,
159
+ editor,
160
+ allArtificialNodes,
161
+ false,
162
+ );
163
+ if (lexicalNode !== null) {
164
+ for (const node of lexicalNode) {
165
+ lexicalNodes.push(node);
166
+ }
167
+ }
168
+ }
169
+ }
170
+ $unwrapArtificialNodes(allArtificialNodes);
171
+
172
+ return lexicalNodes;
173
+ }
174
+
175
+ /**
176
+ * Generate DOM nodes from the editor state into the given container element,
177
+ * using the editor's {@link EditorDOMRenderConfig}.
178
+ * @experimental
179
+ */
180
+ export function $generateDOMFromNodes<T extends HTMLElement | DocumentFragment>(
181
+ container: T,
182
+ selection: null | BaseSelection = null,
183
+ editor: LexicalEditor = $getEditor(),
184
+ ): T {
185
+ return $withRenderContext(
186
+ [contextValue(RenderContextExport, true)],
187
+ editor,
188
+ )(() => {
189
+ const root = $getRoot();
190
+ const domConfig = $getSessionDOMRenderConfig(editor);
191
+
192
+ const parentElementAppend = container.append.bind(container);
193
+ for (const topLevelNode of root.getChildren()) {
194
+ $appendNodesToHTML(
195
+ editor,
196
+ topLevelNode,
197
+ parentElementAppend,
198
+ selection,
199
+ domConfig,
200
+ );
201
+ }
202
+ return container;
203
+ });
204
+ }
205
+
206
+ /**
207
+ * Generate DOM nodes from a root node into the given container element,
208
+ * including the root node itself. Uses the editor's {@link EditorDOMRenderConfig}.
209
+ * @experimental
210
+ */
211
+ export function $generateDOMFromRoot<T extends HTMLElement | DocumentFragment>(
212
+ container: T,
213
+ root: LexicalNode = $getRoot(),
214
+ ): T {
215
+ const editor = $getEditor();
216
+ return $withRenderContext(
217
+ [
218
+ contextValue(RenderContextExport, true),
219
+ contextValue(RenderContextRoot, true),
220
+ ],
221
+ editor,
222
+ )(() => {
223
+ const selection = null;
224
+ const domConfig = $getSessionDOMRenderConfig(editor);
225
+ const parentElementAppend = container.append.bind(container);
226
+ $appendNodesToHTML(editor, root, parentElementAppend, selection, domConfig);
227
+ return container;
228
+ });
229
+ }
230
+
231
+ /**
232
+ * Generate an HTML string from the editor's current state (or `selection`
233
+ * if provided).
234
+ *
235
+ * Must be called inside an active editor scope — i.e. `editor.update(...)`,
236
+ * `editor.read(...)`, or `editor.getEditorState().read(callback, {editor})`.
237
+ * The legacy `editor.getEditorState().read(callback)` call (without the
238
+ * `{editor}` option) does not set an active editor and is not supported;
239
+ * `editor.read(...)` is the drop-in replacement.
240
+ */
241
+ export function $generateHtmlFromNodes(
242
+ editor: LexicalEditor,
243
+ selection: BaseSelection | null = null,
244
+ ): string {
245
+ if (
246
+ typeof document === 'undefined' ||
247
+ (typeof window === 'undefined' && typeof global.window === 'undefined')
248
+ ) {
249
+ invariant(
250
+ false,
251
+ 'To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom or use withDOM from @lexical/headless/dom before calling this function.',
252
+ );
253
+ }
254
+ return $generateDOMFromNodes(document.createElement('div'), selection, editor)
255
+ .innerHTML;
256
+ }
257
+
258
+ function $appendNodesToHTML(
259
+ editor: LexicalEditor,
260
+ currentNode: LexicalNode,
261
+ parentElementAppend: (element: Node) => void,
262
+ selection: BaseSelection | null = null,
263
+ domConfig: EditorDOMRenderConfig = $getEditorDOMRenderConfig(editor),
264
+ ): boolean {
265
+ let shouldInclude = domConfig.$shouldInclude(currentNode, selection, editor);
266
+ const shouldExclude = domConfig.$shouldExclude(
267
+ currentNode,
268
+ selection,
269
+ editor,
270
+ );
271
+ let target = currentNode;
272
+
273
+ if (selection !== null && $isTextNode(currentNode)) {
274
+ target = $sliceSelectedTextNodeContent(selection, currentNode, 'clone');
275
+ }
276
+ const exportProps = domConfig.$exportDOM(target, editor);
277
+ const {element, after, append, $getChildNodes} = exportProps;
278
+
279
+ if (!element) {
280
+ return false;
281
+ }
282
+
283
+ const fragment = document.createDocumentFragment();
284
+ const children = $getChildNodes
285
+ ? $getChildNodes()
286
+ : $isElementNode(target)
287
+ ? target.getChildren()
288
+ : [];
289
+
290
+ const fragmentAppend = fragment.append.bind(fragment);
291
+ for (const childNode of children) {
292
+ const shouldIncludeChild = $appendNodesToHTML(
293
+ editor,
294
+ childNode,
295
+ fragmentAppend,
296
+ selection,
297
+ domConfig,
298
+ );
299
+
300
+ if (
301
+ !shouldInclude &&
302
+ shouldIncludeChild &&
303
+ domConfig.$extractWithChild(
304
+ currentNode,
305
+ childNode,
306
+ selection,
307
+ 'html',
308
+ editor,
309
+ )
310
+ ) {
311
+ shouldInclude = true;
312
+ }
313
+ }
314
+
315
+ if (shouldInclude && !shouldExclude) {
316
+ if (isHTMLElement(element) || isDocumentFragment(element)) {
317
+ if (append) {
318
+ append(fragment);
319
+ } else {
320
+ element.append(fragment);
321
+ }
322
+ }
323
+ parentElementAppend(element);
324
+
325
+ if (after) {
326
+ const newElement = after.call(target, element);
327
+ if (newElement) {
328
+ if (isDocumentFragment(element)) {
329
+ element.replaceChildren(newElement);
330
+ } else {
331
+ element.replaceWith(newElement);
332
+ }
333
+ }
334
+ }
335
+ } else {
336
+ parentElementAppend(fragment);
337
+ }
338
+
339
+ return shouldInclude;
340
+ }
341
+
342
+ function getConversionFunction(
343
+ domNode: Node,
344
+ editor: LexicalEditor,
345
+ ): DOMConversionFn | null {
346
+ const {nodeName} = domNode;
347
+
348
+ const cachedConversions = editor._htmlConversions.get(nodeName.toLowerCase());
349
+
350
+ let currentConversion: DOMConversion | null = null;
351
+
352
+ if (cachedConversions !== undefined) {
353
+ for (const cachedConversion of cachedConversions) {
354
+ const domConversion = cachedConversion(domNode);
355
+ if (
356
+ domConversion !== null &&
357
+ (currentConversion === null ||
358
+ // Given equal priority, prefer the last registered importer
359
+ // which is typically an application custom node or HTMLConfig['import']
360
+ (currentConversion.priority || 0) <= (domConversion.priority || 0))
361
+ ) {
362
+ currentConversion = domConversion;
363
+ }
364
+ }
365
+ }
366
+
367
+ return currentConversion !== null ? currentConversion.conversion : null;
368
+ }
369
+
370
+ function $createNodesFromDOM(
371
+ node: Node,
372
+ editor: LexicalEditor,
373
+ allArtificialNodes: Array<ArtificialNode__DO_NOT_USE>,
374
+ hasBlockAncestorLexicalNode: boolean,
375
+ forChildMap: Map<string, DOMChildConversion> = new Map(),
376
+ parentLexicalNode?: LexicalNode | null | undefined,
377
+ ): Array<LexicalNode> {
378
+ const lexicalNodes: Array<LexicalNode> = [];
379
+
380
+ if (IGNORE_TAGS.has(node.nodeName)) {
381
+ return lexicalNodes;
382
+ }
383
+
384
+ let currentLexicalNode = null;
385
+ const transformFunction = getConversionFunction(node, editor);
386
+ const transformOutput = transformFunction
387
+ ? transformFunction(node as HTMLElement)
388
+ : null;
389
+ let postTransform = null;
390
+
391
+ if (transformOutput !== null) {
392
+ postTransform = transformOutput.after;
393
+ const transformNodes = transformOutput.node;
394
+ currentLexicalNode = Array.isArray(transformNodes)
395
+ ? transformNodes[transformNodes.length - 1]
396
+ : transformNodes;
397
+
398
+ if (currentLexicalNode !== null) {
399
+ for (const [, forChildFunction] of forChildMap) {
400
+ currentLexicalNode = forChildFunction(
401
+ currentLexicalNode,
402
+ parentLexicalNode,
403
+ );
404
+
405
+ if (!currentLexicalNode) {
406
+ break;
407
+ }
408
+ }
409
+
410
+ if (currentLexicalNode) {
411
+ lexicalNodes.push(
412
+ ...(Array.isArray(transformNodes)
413
+ ? transformNodes
414
+ : [currentLexicalNode]),
415
+ );
416
+ }
417
+ }
418
+
419
+ if (transformOutput.forChild != null) {
420
+ forChildMap.set(node.nodeName, transformOutput.forChild);
421
+ }
422
+ }
423
+
424
+ // If the DOM node doesn't have a transformer, we don't know what
425
+ // to do with it but we still need to process any childNodes.
426
+ const children = node.childNodes;
427
+ let childLexicalNodes = [];
428
+
429
+ const hasBlockAncestorLexicalNodeForChildren =
430
+ currentLexicalNode != null && $isRootOrShadowRoot(currentLexicalNode)
431
+ ? false
432
+ : (currentLexicalNode != null &&
433
+ $isBlockElementNode(currentLexicalNode)) ||
434
+ hasBlockAncestorLexicalNode;
435
+
436
+ for (let i = 0; i < children.length; i++) {
437
+ childLexicalNodes.push(
438
+ ...$createNodesFromDOM(
439
+ children[i],
440
+ editor,
441
+ allArtificialNodes,
442
+ hasBlockAncestorLexicalNodeForChildren,
443
+ new Map(forChildMap),
444
+ currentLexicalNode,
445
+ ),
446
+ );
447
+ }
448
+
449
+ if (postTransform != null) {
450
+ childLexicalNodes = postTransform(childLexicalNodes);
451
+ }
452
+
453
+ if (isBlockDomNode(node)) {
454
+ if (!hasBlockAncestorLexicalNodeForChildren) {
455
+ childLexicalNodes = wrapContinuousInlines(
456
+ node,
457
+ childLexicalNodes,
458
+ $createParagraphNode,
459
+ );
460
+ } else {
461
+ childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, () => {
462
+ const artificialNode = new ArtificialNode__DO_NOT_USE();
463
+ allArtificialNodes.push(artificialNode);
464
+ return artificialNode;
465
+ });
466
+ }
467
+ }
468
+
469
+ if (currentLexicalNode == null) {
470
+ if (childLexicalNodes.length > 0) {
471
+ // If it hasn't been converted to a LexicalNode, we hoist its children
472
+ // up to the same level as it.
473
+ for (const childNode of childLexicalNodes) {
474
+ lexicalNodes.push(childNode);
475
+ }
476
+ } else {
477
+ if (isBlockDomNode(node) && isDomNodeBetweenTwoInlineNodes(node)) {
478
+ // Empty block dom node that hasnt been converted, we replace it with a linebreak if its between inline nodes
479
+ lexicalNodes.push($createLineBreakNode());
480
+ }
481
+ }
482
+ } else {
483
+ if ($isElementNode(currentLexicalNode)) {
484
+ // If the current node is a ElementNode after conversion,
485
+ // we can append all the children to it.
486
+ currentLexicalNode.append(...childLexicalNodes);
487
+ }
488
+ }
489
+
490
+ return lexicalNodes;
491
+ }
492
+
493
+ function wrapContinuousInlines(
494
+ domNode: Node,
495
+ nodes: Array<LexicalNode>,
496
+ createWrapperFn: () => ElementNode,
497
+ ): Array<LexicalNode> {
498
+ const textAlign = (domNode as HTMLElement).style
499
+ .textAlign as ElementFormatType;
500
+ const out: Array<LexicalNode> = [];
501
+ let continuousInlines: Array<LexicalNode> = [];
502
+ // wrap contiguous inline child nodes in para
503
+ for (let i = 0; i < nodes.length; i++) {
504
+ const node = nodes[i];
505
+ if ($isBlockElementNode(node)) {
506
+ if (textAlign && !node.getFormat()) {
507
+ node.setFormat(textAlign);
508
+ }
509
+ out.push(node);
510
+ } else {
511
+ continuousInlines.push(node);
512
+ if (
513
+ i === nodes.length - 1 ||
514
+ (i < nodes.length - 1 && $isBlockElementNode(nodes[i + 1]))
515
+ ) {
516
+ const wrapper = createWrapperFn();
517
+ wrapper.setFormat(textAlign);
518
+ wrapper.append(...continuousInlines);
519
+ out.push(wrapper);
520
+ continuousInlines = [];
521
+ }
522
+ }
523
+ }
524
+ return out;
525
+ }
526
+
527
+ function $unwrapArtificialNodes(
528
+ allArtificialNodes: Array<ArtificialNode__DO_NOT_USE>,
529
+ ) {
530
+ // Replace artificial node with its children, inserting a linebreak
531
+ // between adjacent artificial nodes
532
+ for (const node of allArtificialNodes) {
533
+ if (
534
+ node.getParent() &&
535
+ node.getNextSibling() instanceof ArtificialNode__DO_NOT_USE
536
+ ) {
537
+ node.insertAfter($createLineBreakNode());
538
+ }
539
+ }
540
+ for (const node of allArtificialNodes) {
541
+ const parent = node.getParent();
542
+ if (parent) {
543
+ parent.splice(node.getIndexWithinParent(), 1, node.getChildren());
544
+ }
545
+ }
546
+ }
547
+
548
+ function isDomNodeBetweenTwoInlineNodes(node: Node): boolean {
549
+ if (node.nextSibling == null || node.previousSibling == null) {
550
+ return false;
551
+ }
552
+ return (
553
+ isInlineDomNode(node.nextSibling) && isInlineDomNode(node.previousSibling)
554
+ );
555
+ }