@ekz/lexical-html 0.40.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.
@@ -0,0 +1,248 @@
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
+ 'use strict';
10
+
11
+ var lexicalSelection = require('@ekz/lexical-selection');
12
+ var lexicalUtils = require('@ekz/lexical-utils');
13
+ var lexical = require('@ekz/lexical');
14
+
15
+ /**
16
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
17
+ *
18
+ * This source code is licensed under the MIT license found in the
19
+ * LICENSE file in the root directory of this source tree.
20
+ *
21
+ */
22
+
23
+
24
+ /**
25
+ * How you parse your html string to get a document is left up to you. In the browser you can use the native
26
+ * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
27
+ * or an equivalent library and pass in the document here.
28
+ */
29
+ function $generateNodesFromDOM(editor, dom) {
30
+ const elements = lexical.isDOMDocumentNode(dom) ? dom.body.childNodes : dom.childNodes;
31
+ let lexicalNodes = [];
32
+ const allArtificialNodes = [];
33
+ for (const element of elements) {
34
+ if (!IGNORE_TAGS.has(element.nodeName)) {
35
+ const lexicalNode = $createNodesFromDOM(element, editor, allArtificialNodes, false);
36
+ if (lexicalNode !== null) {
37
+ lexicalNodes = lexicalNodes.concat(lexicalNode);
38
+ }
39
+ }
40
+ }
41
+ $unwrapArtificialNodes(allArtificialNodes);
42
+ return lexicalNodes;
43
+ }
44
+ function $generateHtmlFromNodes(editor, selection) {
45
+ if (typeof document === 'undefined' || typeof window === 'undefined' && typeof global.window === 'undefined') {
46
+ throw new Error('To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.');
47
+ }
48
+ const container = document.createElement('div');
49
+ const root = lexical.$getRoot();
50
+ const topLevelChildren = root.getChildren();
51
+ for (let i = 0; i < topLevelChildren.length; i++) {
52
+ const topLevelNode = topLevelChildren[i];
53
+ $appendNodesToHTML(editor, topLevelNode, container, selection);
54
+ }
55
+ return container.innerHTML;
56
+ }
57
+ function $appendNodesToHTML(editor, currentNode, parentElement, selection = null) {
58
+ let shouldInclude = selection !== null ? currentNode.isSelected(selection) : true;
59
+ const shouldExclude = lexical.$isElementNode(currentNode) && currentNode.excludeFromCopy('html');
60
+ let target = currentNode;
61
+ if (selection !== null && lexical.$isTextNode(currentNode)) {
62
+ target = lexicalSelection.$sliceSelectedTextNodeContent(selection, currentNode, 'clone');
63
+ }
64
+ const children = lexical.$isElementNode(target) ? target.getChildren() : [];
65
+ const registeredNode = lexical.getRegisteredNode(editor, target.getType());
66
+ let exportOutput;
67
+
68
+ // Use HTMLConfig overrides, if available.
69
+ if (registeredNode && registeredNode.exportDOM !== undefined) {
70
+ exportOutput = registeredNode.exportDOM(editor, target);
71
+ } else {
72
+ exportOutput = target.exportDOM(editor);
73
+ }
74
+ const {
75
+ element,
76
+ after
77
+ } = exportOutput;
78
+ if (!element) {
79
+ return false;
80
+ }
81
+ const fragment = document.createDocumentFragment();
82
+ for (let i = 0; i < children.length; i++) {
83
+ const childNode = children[i];
84
+ const shouldIncludeChild = $appendNodesToHTML(editor, childNode, fragment, selection);
85
+ if (!shouldInclude && lexical.$isElementNode(currentNode) && shouldIncludeChild && currentNode.extractWithChild(childNode, selection, 'html')) {
86
+ shouldInclude = true;
87
+ }
88
+ }
89
+ if (shouldInclude && !shouldExclude) {
90
+ if (lexicalUtils.isHTMLElement(element) || lexical.isDocumentFragment(element)) {
91
+ element.append(fragment);
92
+ }
93
+ parentElement.append(element);
94
+ if (after) {
95
+ const newElement = after.call(target, element);
96
+ if (newElement) {
97
+ if (lexical.isDocumentFragment(element)) {
98
+ element.replaceChildren(newElement);
99
+ } else {
100
+ element.replaceWith(newElement);
101
+ }
102
+ }
103
+ }
104
+ } else {
105
+ parentElement.append(fragment);
106
+ }
107
+ return shouldInclude;
108
+ }
109
+ function getConversionFunction(domNode, editor) {
110
+ const {
111
+ nodeName
112
+ } = domNode;
113
+ const cachedConversions = editor._htmlConversions.get(nodeName.toLowerCase());
114
+ let currentConversion = null;
115
+ if (cachedConversions !== undefined) {
116
+ for (const cachedConversion of cachedConversions) {
117
+ const domConversion = cachedConversion(domNode);
118
+ if (domConversion !== null && (currentConversion === null ||
119
+ // Given equal priority, prefer the last registered importer
120
+ // which is typically an application custom node or HTMLConfig['import']
121
+ (currentConversion.priority || 0) <= (domConversion.priority || 0))) {
122
+ currentConversion = domConversion;
123
+ }
124
+ }
125
+ }
126
+ return currentConversion !== null ? currentConversion.conversion : null;
127
+ }
128
+ const IGNORE_TAGS = new Set(['STYLE', 'SCRIPT']);
129
+ function $createNodesFromDOM(node, editor, allArtificialNodes, hasBlockAncestorLexicalNode, forChildMap = new Map(), parentLexicalNode) {
130
+ let lexicalNodes = [];
131
+ if (IGNORE_TAGS.has(node.nodeName)) {
132
+ return lexicalNodes;
133
+ }
134
+ let currentLexicalNode = null;
135
+ const transformFunction = getConversionFunction(node, editor);
136
+ const transformOutput = transformFunction ? transformFunction(node) : null;
137
+ let postTransform = null;
138
+ if (transformOutput !== null) {
139
+ postTransform = transformOutput.after;
140
+ const transformNodes = transformOutput.node;
141
+ currentLexicalNode = Array.isArray(transformNodes) ? transformNodes[transformNodes.length - 1] : transformNodes;
142
+ if (currentLexicalNode !== null) {
143
+ for (const [, forChildFunction] of forChildMap) {
144
+ currentLexicalNode = forChildFunction(currentLexicalNode, parentLexicalNode);
145
+ if (!currentLexicalNode) {
146
+ break;
147
+ }
148
+ }
149
+ if (currentLexicalNode) {
150
+ lexicalNodes.push(...(Array.isArray(transformNodes) ? transformNodes : [currentLexicalNode]));
151
+ }
152
+ }
153
+ if (transformOutput.forChild != null) {
154
+ forChildMap.set(node.nodeName, transformOutput.forChild);
155
+ }
156
+ }
157
+
158
+ // If the DOM node doesn't have a transformer, we don't know what
159
+ // to do with it but we still need to process any childNodes.
160
+ const children = node.childNodes;
161
+ let childLexicalNodes = [];
162
+ const hasBlockAncestorLexicalNodeForChildren = currentLexicalNode != null && lexical.$isRootOrShadowRoot(currentLexicalNode) ? false : currentLexicalNode != null && lexical.$isBlockElementNode(currentLexicalNode) || hasBlockAncestorLexicalNode;
163
+ for (let i = 0; i < children.length; i++) {
164
+ childLexicalNodes.push(...$createNodesFromDOM(children[i], editor, allArtificialNodes, hasBlockAncestorLexicalNodeForChildren, new Map(forChildMap), currentLexicalNode));
165
+ }
166
+ if (postTransform != null) {
167
+ childLexicalNodes = postTransform(childLexicalNodes);
168
+ }
169
+ if (lexicalUtils.isBlockDomNode(node)) {
170
+ if (!hasBlockAncestorLexicalNodeForChildren) {
171
+ childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, lexical.$createParagraphNode);
172
+ } else {
173
+ childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, () => {
174
+ const artificialNode = new lexical.ArtificialNode__DO_NOT_USE();
175
+ allArtificialNodes.push(artificialNode);
176
+ return artificialNode;
177
+ });
178
+ }
179
+ }
180
+ if (currentLexicalNode == null) {
181
+ if (childLexicalNodes.length > 0) {
182
+ // If it hasn't been converted to a LexicalNode, we hoist its children
183
+ // up to the same level as it.
184
+ lexicalNodes = lexicalNodes.concat(childLexicalNodes);
185
+ } else {
186
+ if (lexicalUtils.isBlockDomNode(node) && isDomNodeBetweenTwoInlineNodes(node)) {
187
+ // Empty block dom node that hasnt been converted, we replace it with a linebreak if its between inline nodes
188
+ lexicalNodes = lexicalNodes.concat(lexical.$createLineBreakNode());
189
+ }
190
+ }
191
+ } else {
192
+ if (lexical.$isElementNode(currentLexicalNode)) {
193
+ // If the current node is a ElementNode after conversion,
194
+ // we can append all the children to it.
195
+ currentLexicalNode.append(...childLexicalNodes);
196
+ }
197
+ }
198
+ return lexicalNodes;
199
+ }
200
+ function wrapContinuousInlines(domNode, nodes, createWrapperFn) {
201
+ const textAlign = domNode.style.textAlign;
202
+ const out = [];
203
+ let continuousInlines = [];
204
+ // wrap contiguous inline child nodes in para
205
+ for (let i = 0; i < nodes.length; i++) {
206
+ const node = nodes[i];
207
+ if (lexical.$isBlockElementNode(node)) {
208
+ if (textAlign && !node.getFormat()) {
209
+ node.setFormat(textAlign);
210
+ }
211
+ out.push(node);
212
+ } else {
213
+ continuousInlines.push(node);
214
+ if (i === nodes.length - 1 || i < nodes.length - 1 && lexical.$isBlockElementNode(nodes[i + 1])) {
215
+ const wrapper = createWrapperFn();
216
+ wrapper.setFormat(textAlign);
217
+ wrapper.append(...continuousInlines);
218
+ out.push(wrapper);
219
+ continuousInlines = [];
220
+ }
221
+ }
222
+ }
223
+ return out;
224
+ }
225
+ function $unwrapArtificialNodes(allArtificialNodes) {
226
+ for (const node of allArtificialNodes) {
227
+ if (node.getNextSibling() instanceof lexical.ArtificialNode__DO_NOT_USE) {
228
+ node.insertAfter(lexical.$createLineBreakNode());
229
+ }
230
+ }
231
+ // Replace artificial node with it's children
232
+ for (const node of allArtificialNodes) {
233
+ const children = node.getChildren();
234
+ for (const child of children) {
235
+ node.insertBefore(child);
236
+ }
237
+ node.remove();
238
+ }
239
+ }
240
+ function isDomNodeBetweenTwoInlineNodes(node) {
241
+ if (node.nextSibling == null || node.previousSibling == null) {
242
+ return false;
243
+ }
244
+ return lexical.isInlineDomNode(node.nextSibling) && lexical.isInlineDomNode(node.previousSibling);
245
+ }
246
+
247
+ exports.$generateHtmlFromNodes = $generateHtmlFromNodes;
248
+ exports.$generateNodesFromDOM = $generateNodesFromDOM;
@@ -0,0 +1,245 @@
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 { $sliceSelectedTextNodeContent } from '@ekz/lexical-selection';
10
+ import { isHTMLElement, isBlockDomNode } from '@ekz/lexical-utils';
11
+ import { isDOMDocumentNode, $getRoot, $isElementNode, $isTextNode, getRegisteredNode, isDocumentFragment, $isRootOrShadowRoot, $isBlockElementNode, $createLineBreakNode, ArtificialNode__DO_NOT_USE, isInlineDomNode, $createParagraphNode } from '@ekz/lexical';
12
+
13
+ /**
14
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
15
+ *
16
+ * This source code is licensed under the MIT license found in the
17
+ * LICENSE file in the root directory of this source tree.
18
+ *
19
+ */
20
+
21
+
22
+ /**
23
+ * How you parse your html string to get a document is left up to you. In the browser you can use the native
24
+ * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
25
+ * or an equivalent library and pass in the document here.
26
+ */
27
+ function $generateNodesFromDOM(editor, dom) {
28
+ const elements = isDOMDocumentNode(dom) ? dom.body.childNodes : dom.childNodes;
29
+ let lexicalNodes = [];
30
+ const allArtificialNodes = [];
31
+ for (const element of elements) {
32
+ if (!IGNORE_TAGS.has(element.nodeName)) {
33
+ const lexicalNode = $createNodesFromDOM(element, editor, allArtificialNodes, false);
34
+ if (lexicalNode !== null) {
35
+ lexicalNodes = lexicalNodes.concat(lexicalNode);
36
+ }
37
+ }
38
+ }
39
+ $unwrapArtificialNodes(allArtificialNodes);
40
+ return lexicalNodes;
41
+ }
42
+ function $generateHtmlFromNodes(editor, selection) {
43
+ if (typeof document === 'undefined' || typeof window === 'undefined' && typeof global.window === 'undefined') {
44
+ throw new Error('To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.');
45
+ }
46
+ const container = document.createElement('div');
47
+ const root = $getRoot();
48
+ const topLevelChildren = root.getChildren();
49
+ for (let i = 0; i < topLevelChildren.length; i++) {
50
+ const topLevelNode = topLevelChildren[i];
51
+ $appendNodesToHTML(editor, topLevelNode, container, selection);
52
+ }
53
+ return container.innerHTML;
54
+ }
55
+ function $appendNodesToHTML(editor, currentNode, parentElement, selection = null) {
56
+ let shouldInclude = selection !== null ? currentNode.isSelected(selection) : true;
57
+ const shouldExclude = $isElementNode(currentNode) && currentNode.excludeFromCopy('html');
58
+ let target = currentNode;
59
+ if (selection !== null && $isTextNode(currentNode)) {
60
+ target = $sliceSelectedTextNodeContent(selection, currentNode, 'clone');
61
+ }
62
+ const children = $isElementNode(target) ? target.getChildren() : [];
63
+ const registeredNode = getRegisteredNode(editor, target.getType());
64
+ let exportOutput;
65
+
66
+ // Use HTMLConfig overrides, if available.
67
+ if (registeredNode && registeredNode.exportDOM !== undefined) {
68
+ exportOutput = registeredNode.exportDOM(editor, target);
69
+ } else {
70
+ exportOutput = target.exportDOM(editor);
71
+ }
72
+ const {
73
+ element,
74
+ after
75
+ } = exportOutput;
76
+ if (!element) {
77
+ return false;
78
+ }
79
+ const fragment = document.createDocumentFragment();
80
+ for (let i = 0; i < children.length; i++) {
81
+ const childNode = children[i];
82
+ const shouldIncludeChild = $appendNodesToHTML(editor, childNode, fragment, selection);
83
+ if (!shouldInclude && $isElementNode(currentNode) && shouldIncludeChild && currentNode.extractWithChild(childNode, selection, 'html')) {
84
+ shouldInclude = true;
85
+ }
86
+ }
87
+ if (shouldInclude && !shouldExclude) {
88
+ if (isHTMLElement(element) || isDocumentFragment(element)) {
89
+ element.append(fragment);
90
+ }
91
+ parentElement.append(element);
92
+ if (after) {
93
+ const newElement = after.call(target, element);
94
+ if (newElement) {
95
+ if (isDocumentFragment(element)) {
96
+ element.replaceChildren(newElement);
97
+ } else {
98
+ element.replaceWith(newElement);
99
+ }
100
+ }
101
+ }
102
+ } else {
103
+ parentElement.append(fragment);
104
+ }
105
+ return shouldInclude;
106
+ }
107
+ function getConversionFunction(domNode, editor) {
108
+ const {
109
+ nodeName
110
+ } = domNode;
111
+ const cachedConversions = editor._htmlConversions.get(nodeName.toLowerCase());
112
+ let currentConversion = null;
113
+ if (cachedConversions !== undefined) {
114
+ for (const cachedConversion of cachedConversions) {
115
+ const domConversion = cachedConversion(domNode);
116
+ if (domConversion !== null && (currentConversion === null ||
117
+ // Given equal priority, prefer the last registered importer
118
+ // which is typically an application custom node or HTMLConfig['import']
119
+ (currentConversion.priority || 0) <= (domConversion.priority || 0))) {
120
+ currentConversion = domConversion;
121
+ }
122
+ }
123
+ }
124
+ return currentConversion !== null ? currentConversion.conversion : null;
125
+ }
126
+ const IGNORE_TAGS = new Set(['STYLE', 'SCRIPT']);
127
+ function $createNodesFromDOM(node, editor, allArtificialNodes, hasBlockAncestorLexicalNode, forChildMap = new Map(), parentLexicalNode) {
128
+ let lexicalNodes = [];
129
+ if (IGNORE_TAGS.has(node.nodeName)) {
130
+ return lexicalNodes;
131
+ }
132
+ let currentLexicalNode = null;
133
+ const transformFunction = getConversionFunction(node, editor);
134
+ const transformOutput = transformFunction ? transformFunction(node) : null;
135
+ let postTransform = null;
136
+ if (transformOutput !== null) {
137
+ postTransform = transformOutput.after;
138
+ const transformNodes = transformOutput.node;
139
+ currentLexicalNode = Array.isArray(transformNodes) ? transformNodes[transformNodes.length - 1] : transformNodes;
140
+ if (currentLexicalNode !== null) {
141
+ for (const [, forChildFunction] of forChildMap) {
142
+ currentLexicalNode = forChildFunction(currentLexicalNode, parentLexicalNode);
143
+ if (!currentLexicalNode) {
144
+ break;
145
+ }
146
+ }
147
+ if (currentLexicalNode) {
148
+ lexicalNodes.push(...(Array.isArray(transformNodes) ? transformNodes : [currentLexicalNode]));
149
+ }
150
+ }
151
+ if (transformOutput.forChild != null) {
152
+ forChildMap.set(node.nodeName, transformOutput.forChild);
153
+ }
154
+ }
155
+
156
+ // If the DOM node doesn't have a transformer, we don't know what
157
+ // to do with it but we still need to process any childNodes.
158
+ const children = node.childNodes;
159
+ let childLexicalNodes = [];
160
+ const hasBlockAncestorLexicalNodeForChildren = currentLexicalNode != null && $isRootOrShadowRoot(currentLexicalNode) ? false : currentLexicalNode != null && $isBlockElementNode(currentLexicalNode) || hasBlockAncestorLexicalNode;
161
+ for (let i = 0; i < children.length; i++) {
162
+ childLexicalNodes.push(...$createNodesFromDOM(children[i], editor, allArtificialNodes, hasBlockAncestorLexicalNodeForChildren, new Map(forChildMap), currentLexicalNode));
163
+ }
164
+ if (postTransform != null) {
165
+ childLexicalNodes = postTransform(childLexicalNodes);
166
+ }
167
+ if (isBlockDomNode(node)) {
168
+ if (!hasBlockAncestorLexicalNodeForChildren) {
169
+ childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, $createParagraphNode);
170
+ } else {
171
+ childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, () => {
172
+ const artificialNode = new ArtificialNode__DO_NOT_USE();
173
+ allArtificialNodes.push(artificialNode);
174
+ return artificialNode;
175
+ });
176
+ }
177
+ }
178
+ if (currentLexicalNode == null) {
179
+ if (childLexicalNodes.length > 0) {
180
+ // If it hasn't been converted to a LexicalNode, we hoist its children
181
+ // up to the same level as it.
182
+ lexicalNodes = lexicalNodes.concat(childLexicalNodes);
183
+ } else {
184
+ if (isBlockDomNode(node) && isDomNodeBetweenTwoInlineNodes(node)) {
185
+ // Empty block dom node that hasnt been converted, we replace it with a linebreak if its between inline nodes
186
+ lexicalNodes = lexicalNodes.concat($createLineBreakNode());
187
+ }
188
+ }
189
+ } else {
190
+ if ($isElementNode(currentLexicalNode)) {
191
+ // If the current node is a ElementNode after conversion,
192
+ // we can append all the children to it.
193
+ currentLexicalNode.append(...childLexicalNodes);
194
+ }
195
+ }
196
+ return lexicalNodes;
197
+ }
198
+ function wrapContinuousInlines(domNode, nodes, createWrapperFn) {
199
+ const textAlign = domNode.style.textAlign;
200
+ const out = [];
201
+ let continuousInlines = [];
202
+ // wrap contiguous inline child nodes in para
203
+ for (let i = 0; i < nodes.length; i++) {
204
+ const node = nodes[i];
205
+ if ($isBlockElementNode(node)) {
206
+ if (textAlign && !node.getFormat()) {
207
+ node.setFormat(textAlign);
208
+ }
209
+ out.push(node);
210
+ } else {
211
+ continuousInlines.push(node);
212
+ if (i === nodes.length - 1 || i < nodes.length - 1 && $isBlockElementNode(nodes[i + 1])) {
213
+ const wrapper = createWrapperFn();
214
+ wrapper.setFormat(textAlign);
215
+ wrapper.append(...continuousInlines);
216
+ out.push(wrapper);
217
+ continuousInlines = [];
218
+ }
219
+ }
220
+ }
221
+ return out;
222
+ }
223
+ function $unwrapArtificialNodes(allArtificialNodes) {
224
+ for (const node of allArtificialNodes) {
225
+ if (node.getNextSibling() instanceof ArtificialNode__DO_NOT_USE) {
226
+ node.insertAfter($createLineBreakNode());
227
+ }
228
+ }
229
+ // Replace artificial node with it's children
230
+ for (const node of allArtificialNodes) {
231
+ const children = node.getChildren();
232
+ for (const child of children) {
233
+ node.insertBefore(child);
234
+ }
235
+ node.remove();
236
+ }
237
+ }
238
+ function isDomNodeBetweenTwoInlineNodes(node) {
239
+ if (node.nextSibling == null || node.previousSibling == null) {
240
+ return false;
241
+ }
242
+ return isInlineDomNode(node.nextSibling) && isInlineDomNode(node.previousSibling);
243
+ }
244
+
245
+ export { $generateHtmlFromNodes, $generateNodesFromDOM };
@@ -0,0 +1,11 @@
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
+ 'use strict'
10
+ const EkzLexicalHtml = process.env.NODE_ENV !== 'production' ? require('./EkzLexicalHtml.dev.js') : require('./EkzLexicalHtml.prod.js');
11
+ module.exports = EkzLexicalHtml;
@@ -0,0 +1,13 @@
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 * as modDev from './EkzLexicalHtml.dev.mjs';
10
+ import * as modProd from './EkzLexicalHtml.prod.mjs';
11
+ const mod = process.env.NODE_ENV !== 'production' ? modDev : modProd;
12
+ export const $generateHtmlFromNodes = mod.$generateHtmlFromNodes;
13
+ export const $generateNodesFromDOM = mod.$generateNodesFromDOM;
@@ -0,0 +1,11 @@
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
+ const mod = await (process.env.NODE_ENV !== 'production' ? import('./EkzLexicalHtml.dev.mjs') : import('./EkzLexicalHtml.prod.mjs'));
10
+ export const $generateHtmlFromNodes = mod.$generateHtmlFromNodes;
11
+ export const $generateNodesFromDOM = mod.$generateNodesFromDOM;
@@ -0,0 +1,9 @@
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
+ "use strict";var e=require("@ekz/lexical-selection"),n=require("@ekz/lexical-utils"),t=require("@ekz/lexical");function o(l,i,r,s=null){let c=null===s||i.isSelected(s);const d=t.$isElementNode(i)&&i.excludeFromCopy("html");let u=i;null!==s&&t.$isTextNode(i)&&(u=e.$sliceSelectedTextNodeContent(s,i,"clone"));const a=t.$isElementNode(u)?u.getChildren():[],f=t.getRegisteredNode(l,u.getType());let m;m=f&&void 0!==f.exportDOM?f.exportDOM(l,u):u.exportDOM(l);const{element:h,after:p}=m;if(!h)return!1;const g=document.createDocumentFragment();for(let e=0;e<a.length;e++){const n=a[e],r=o(l,n,g,s);!c&&t.$isElementNode(i)&&r&&i.extractWithChild(n,s,"html")&&(c=!0)}if(c&&!d){if((n.isHTMLElement(h)||t.isDocumentFragment(h))&&h.append(g),r.append(h),p){const e=p.call(u,h);e&&(t.isDocumentFragment(h)?h.replaceChildren(e):h.replaceWith(e))}}else r.append(g);return c}const l=new Set(["STYLE","SCRIPT"]);function i(e,o,s,c,d=new Map,u){let a=[];if(l.has(e.nodeName))return a;let f=null;const m=function(e,n){const{nodeName:t}=e,o=n._htmlConversions.get(t.toLowerCase());let l=null;if(void 0!==o)for(const n of o){const t=n(e);null!==t&&(null===l||(l.priority||0)<=(t.priority||0))&&(l=t)}return null!==l?l.conversion:null}(e,o),h=m?m(e):null;let p=null;if(null!==h){p=h.after;const n=h.node;if(f=Array.isArray(n)?n[n.length-1]:n,null!==f){for(const[,e]of d)if(f=e(f,u),!f)break;f&&a.push(...Array.isArray(n)?n:[f])}null!=h.forChild&&d.set(e.nodeName,h.forChild)}const g=e.childNodes;let N=[];const $=(null==f||!t.$isRootOrShadowRoot(f))&&(null!=f&&t.$isBlockElementNode(f)||c);for(let e=0;e<g.length;e++)N.push(...i(g[e],o,s,$,new Map(d),f));return null!=p&&(N=p(N)),n.isBlockDomNode(e)&&(N=r(e,N,$?()=>{const e=new t.ArtificialNode__DO_NOT_USE;return s.push(e),e}:t.$createParagraphNode)),null==f?N.length>0?a=a.concat(N):n.isBlockDomNode(e)&&function(e){if(null==e.nextSibling||null==e.previousSibling)return!1;return t.isInlineDomNode(e.nextSibling)&&t.isInlineDomNode(e.previousSibling)}(e)&&(a=a.concat(t.$createLineBreakNode())):t.$isElementNode(f)&&f.append(...N),a}function r(e,n,o){const l=e.style.textAlign,i=[];let r=[];for(let e=0;e<n.length;e++){const s=n[e];if(t.$isBlockElementNode(s))l&&!s.getFormat()&&s.setFormat(l),i.push(s);else if(r.push(s),e===n.length-1||e<n.length-1&&t.$isBlockElementNode(n[e+1])){const e=o();e.setFormat(l),e.append(...r),i.push(e),r=[]}}return i}exports.$generateHtmlFromNodes=function(e,n){if("undefined"==typeof document||"undefined"==typeof window&&void 0===global.window)throw new Error("To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.");const l=document.createElement("div"),i=t.$getRoot().getChildren();for(let t=0;t<i.length;t++){o(e,i[t],l,n)}return l.innerHTML},exports.$generateNodesFromDOM=function(e,n){const o=t.isDOMDocumentNode(n)?n.body.childNodes:n.childNodes;let r=[];const s=[];for(const n of o)if(!l.has(n.nodeName)){const t=i(n,e,s,!1);null!==t&&(r=r.concat(t))}return function(e){for(const n of e)n.getNextSibling()instanceof t.ArtificialNode__DO_NOT_USE&&n.insertAfter(t.$createLineBreakNode());for(const n of e){const e=n.getChildren();for(const t of e)n.insertBefore(t);n.remove()}}(s),r};
@@ -0,0 +1,9 @@
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{$sliceSelectedTextNodeContent as e}from"@ekz/lexical-selection";import{isHTMLElement as n,isBlockDomNode as t}from"@ekz/lexical-utils";import{isDOMDocumentNode as o,$getRoot as l,$isElementNode as r,$isTextNode as i,getRegisteredNode as s,isDocumentFragment as c,$isRootOrShadowRoot as u,$isBlockElementNode as f,$createLineBreakNode as a,ArtificialNode__DO_NOT_USE as d,isInlineDomNode as p,$createParagraphNode as h}from"@ekz/lexical";function m(e,n){const t=o(n)?n.body.childNodes:n.childNodes;let l=[];const r=[];for(const n of t)if(!w.has(n.nodeName)){const t=y(n,e,r,!1);null!==t&&(l=l.concat(t))}return function(e){for(const n of e)n.getNextSibling()instanceof d&&n.insertAfter(a());for(const n of e){const e=n.getChildren();for(const t of e)n.insertBefore(t);n.remove()}}(r),l}function g(e,n){if("undefined"==typeof document||"undefined"==typeof window&&void 0===global.window)throw new Error("To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.");const t=document.createElement("div"),o=l().getChildren();for(let l=0;l<o.length;l++){x(e,o[l],t,n)}return t.innerHTML}function x(t,o,l,u=null){let f=null===u||o.isSelected(u);const a=r(o)&&o.excludeFromCopy("html");let d=o;null!==u&&i(o)&&(d=e(u,o,"clone"));const p=r(d)?d.getChildren():[],h=s(t,d.getType());let m;m=h&&void 0!==h.exportDOM?h.exportDOM(t,d):d.exportDOM(t);const{element:g,after:w}=m;if(!g)return!1;const y=document.createDocumentFragment();for(let e=0;e<p.length;e++){const n=p[e],l=x(t,n,y,u);!f&&r(o)&&l&&o.extractWithChild(n,u,"html")&&(f=!0)}if(f&&!a){if((n(g)||c(g))&&g.append(y),l.append(g),w){const e=w.call(d,g);e&&(c(g)?g.replaceChildren(e):g.replaceWith(e))}}else l.append(y);return f}const w=new Set(["STYLE","SCRIPT"]);function y(e,n,o,l,i=new Map,s){let c=[];if(w.has(e.nodeName))return c;let m=null;const g=function(e,n){const{nodeName:t}=e,o=n._htmlConversions.get(t.toLowerCase());let l=null;if(void 0!==o)for(const n of o){const t=n(e);null!==t&&(null===l||(l.priority||0)<=(t.priority||0))&&(l=t)}return null!==l?l.conversion:null}(e,n),x=g?g(e):null;let b=null;if(null!==x){b=x.after;const n=x.node;if(m=Array.isArray(n)?n[n.length-1]:n,null!==m){for(const[,e]of i)if(m=e(m,s),!m)break;m&&c.push(...Array.isArray(n)?n:[m])}null!=x.forChild&&i.set(e.nodeName,x.forChild)}const S=e.childNodes;let v=[];const N=(null==m||!u(m))&&(null!=m&&f(m)||l);for(let e=0;e<S.length;e++)v.push(...y(S[e],n,o,N,new Map(i),m));return null!=b&&(v=b(v)),t(e)&&(v=C(e,v,N?()=>{const e=new d;return o.push(e),e}:h)),null==m?v.length>0?c=c.concat(v):t(e)&&function(e){if(null==e.nextSibling||null==e.previousSibling)return!1;return p(e.nextSibling)&&p(e.previousSibling)}(e)&&(c=c.concat(a())):r(m)&&m.append(...v),c}function C(e,n,t){const o=e.style.textAlign,l=[];let r=[];for(let e=0;e<n.length;e++){const i=n[e];if(f(i))o&&!i.getFormat()&&i.setFormat(o),l.push(i);else if(r.push(i),e===n.length-1||e<n.length-1&&f(n[e+1])){const e=t();e.setFormat(o),e.append(...r),l.push(e),r=[]}}return l}export{g as $generateHtmlFromNodes,m as $generateNodesFromDOM};
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) Meta Platforms, Inc. and affiliates.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,32 @@
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
+ * @flow strict
8
+ */
9
+
10
+ import type {
11
+ BaseSelection,
12
+ LexicalEditor,
13
+ LexicalNode,
14
+ EditorState,
15
+ EditorThemeClasses,
16
+ } from '@ekz/lexical';
17
+
18
+ export type FindCachedParentDOMNode = (
19
+ node: Node,
20
+ searchFn: FindCachedParentDOMNodeSearchFn,
21
+ ) => null | Node;
22
+ export type FindCachedParentDOMNodeSearchFn = (node: Node) => boolean;
23
+
24
+ declare export function $generateHtmlFromNodes(
25
+ editor: LexicalEditor,
26
+ selection?: BaseSelection | null,
27
+ ): string;
28
+
29
+ declare export function $generateNodesFromDOM(
30
+ editor: LexicalEditor,
31
+ dom: Document,
32
+ ): Array<LexicalNode>;
package/README.md ADDED
@@ -0,0 +1,43 @@
1
+ # `@lexical/html`
2
+
3
+ [![See API Documentation](https://lexical.dev/img/see-api-documentation.svg)](https://lexical.dev/docs/api/modules/lexical_html)
4
+
5
+ # HTML
6
+ This package exports utility functions for converting `Lexical` -> `HTML` and `HTML` -> `Lexical`. These same functions are also used in the `lexical-clipboard` package for copy and paste.
7
+
8
+ [Full documentation can be found here.](https://lexical.dev/docs/concepts/serialization)
9
+
10
+ ### Exporting
11
+ ```js
12
+ // In a headless mode, you need to initialize a headless browser implementation such as JSDom.
13
+ const dom = new JSDOM();
14
+ // @ts-expect-error
15
+ global.window = dom.window;
16
+ global.document = dom.window.document;
17
+ // You may also need to polyfill DocumentFragment or navigator in certain cases.
18
+
19
+ // When converting to HTML you can pass in a selection object to narrow it
20
+ // down to a certain part of the editor's contents.
21
+ const htmlString = $generateHtmlFromNodes(editor, selection | null);
22
+ ```
23
+
24
+ ### Importing
25
+ First we need to parse the HTML string into a DOM instance.
26
+ ```js
27
+ // In the browser you can use the native DOMParser API to parse the HTML string.
28
+ const parser = new DOMParser();
29
+ const dom = parser.parseFromString(htmlString, textHtmlMimeType);
30
+
31
+ // In a headless environment you can use a package such as JSDom to parse the HTML string.
32
+ const dom = new JSDOM(htmlString);
33
+ ```
34
+ And once you have the DOM instance.
35
+ ```js
36
+ const nodes = $generateNodesFromDOM(editor, dom);
37
+
38
+ // Once you have the lexical nodes you can initialize an editor instance with the parsed nodes.
39
+ const editor = createEditor({ ...config, nodes });
40
+
41
+ // Or insert them at a selection.
42
+ $insertNodes(nodes);
43
+ ```
package/index.d.ts ADDED
@@ -0,0 +1,15 @@
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
+ import type { BaseSelection, LexicalEditor, LexicalNode } from '@ekz/lexical';
9
+ /**
10
+ * How you parse your html string to get a document is left up to you. In the browser you can use the native
11
+ * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
12
+ * or an equivalent library and pass in the document here.
13
+ */
14
+ export declare function $generateNodesFromDOM(editor: LexicalEditor, dom: Document | ParentNode): Array<LexicalNode>;
15
+ export declare function $generateHtmlFromNodes(editor: LexicalEditor, selection?: BaseSelection | null): string;
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@ekz/lexical-html",
3
+ "description": "This package contains HTML helpers and functionality for Lexical.",
4
+ "keywords": [
5
+ "lexical",
6
+ "editor",
7
+ "rich-text",
8
+ "html"
9
+ ],
10
+ "license": "MIT",
11
+ "version": "0.40.0",
12
+ "main": "LexicalHtml.js",
13
+ "types": "index.d.ts",
14
+ "repository": {
15
+ "type": "git",
16
+ "url": "git+https://github.com/facebook/lexical.git",
17
+ "directory": "packages/lexical-html"
18
+ },
19
+ "dependencies": {
20
+ "@ekz/lexical-selection": "0.40.0",
21
+ "@ekz/lexical-utils": "0.40.0",
22
+ "@ekz/lexical": "0.40.0"
23
+ },
24
+ "module": "LexicalHtml.mjs",
25
+ "sideEffects": false,
26
+ "exports": {
27
+ ".": {
28
+ "import": {
29
+ "types": "./index.d.ts",
30
+ "development": "./LexicalHtml.dev.mjs",
31
+ "production": "./LexicalHtml.prod.mjs",
32
+ "node": "./LexicalHtml.node.mjs",
33
+ "default": "./LexicalHtml.mjs"
34
+ },
35
+ "require": {
36
+ "types": "./index.d.ts",
37
+ "development": "./LexicalHtml.dev.js",
38
+ "production": "./LexicalHtml.prod.js",
39
+ "default": "./LexicalHtml.js"
40
+ }
41
+ }
42
+ }
43
+ }