@lexical/html 0.3.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.
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,25 @@
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
+ LexicalEditor,
11
+ LexicalNode,
12
+ RangeSelection,
13
+ NodeSelection,
14
+ GridSelection,
15
+ } from 'lexical';
16
+
17
+ export function $generateHtmlFromNodes(
18
+ editor: LexicalEditor,
19
+ selection?: RangeSelection | NodeSelection | GridSelection | null,
20
+ ): string;
21
+
22
+ export function $generateNodesFromDOM(
23
+ editor: LexicalEditor,
24
+ dom: Document,
25
+ ): Array<LexicalNode>;
@@ -0,0 +1,192 @@
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
+ 'use strict';
8
+
9
+ var selection = require('@lexical/selection');
10
+ var lexical = require('lexical');
11
+
12
+ /**
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ *
18
+ */
19
+ /**
20
+ * How you parse your html string to get a document is left up to you. In the browser you can use the native
21
+ * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
22
+ * or an equivilant library and pass in the document here.
23
+ */
24
+
25
+ function $generateNodesFromDOM(editor, dom) {
26
+ let lexicalNodes = [];
27
+ const elements = dom.body ? Array.from(dom.body.childNodes) : [];
28
+ const elementsLength = elements.length;
29
+
30
+ for (let i = 0; i < elementsLength; i++) {
31
+ const element = elements[i];
32
+
33
+ if (!IGNORE_TAGS.has(element.nodeName)) {
34
+ const lexicalNode = $createNodesFromDOM(element, editor);
35
+
36
+ if (lexicalNode !== null) {
37
+ lexicalNodes = lexicalNodes.concat(lexicalNode);
38
+ }
39
+ }
40
+ }
41
+
42
+ return lexicalNodes;
43
+ }
44
+ function $generateHtmlFromNodes(editor, selection) {
45
+ if (document == null || window == null) {
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
+
49
+ const container = document.createElement('div');
50
+ const root = lexical.$getRoot();
51
+ const topLevelChildren = root.getChildren();
52
+
53
+ for (let i = 0; i < topLevelChildren.length; i++) {
54
+ const topLevelNode = topLevelChildren[i];
55
+ $appendNodesToHTML(editor, selection, topLevelNode, container);
56
+ }
57
+
58
+ return container.innerHTML;
59
+ }
60
+
61
+ function $appendNodesToHTML(editor, selection$1, currentNode, parentElement) {
62
+ let shouldInclude = selection$1 != null ? currentNode.isSelected() : true;
63
+ const shouldExclude = lexical.$isElementNode(currentNode) && currentNode.excludeFromCopy('html');
64
+ let clone = selection.$cloneWithProperties(currentNode);
65
+ clone = lexical.$isTextNode(clone) && selection$1 != null ? selection.$sliceSelectedTextNodeContent(selection$1, clone) : clone;
66
+ const children = lexical.$isElementNode(clone) ? clone.getChildren() : [];
67
+ const {
68
+ element,
69
+ after
70
+ } = clone.exportDOM(editor);
71
+
72
+ if (!element) {
73
+ return false;
74
+ }
75
+
76
+ const fragment = new DocumentFragment();
77
+
78
+ for (let i = 0; i < children.length; i++) {
79
+ const childNode = children[i];
80
+ const shouldIncludeChild = $appendNodesToHTML(editor, selection$1, childNode, fragment);
81
+
82
+ if (!shouldInclude && lexical.$isElementNode(currentNode) && shouldIncludeChild && currentNode.extractWithChild(childNode, selection$1, 'html')) {
83
+ shouldInclude = true;
84
+ }
85
+ }
86
+
87
+ if (shouldInclude && !shouldExclude) {
88
+ element.append(fragment);
89
+ parentElement.append(element);
90
+
91
+ if (after) {
92
+ const newElement = after.call(clone, element);
93
+ if (newElement) element.replaceWith(newElement);
94
+ }
95
+ } else {
96
+ parentElement.append(fragment);
97
+ }
98
+
99
+ return shouldInclude;
100
+ }
101
+
102
+ function getConversionFunction(domNode, editor) {
103
+ const {
104
+ nodeName
105
+ } = domNode;
106
+
107
+ const cachedConversions = editor._htmlConversions.get(nodeName.toLowerCase());
108
+
109
+ let currentConversion = null;
110
+
111
+ if (cachedConversions !== undefined) {
112
+ cachedConversions.forEach(cachedConversion => {
113
+ const domConversion = cachedConversion(domNode);
114
+
115
+ if (domConversion !== null) {
116
+ if (currentConversion === null || currentConversion.priority < domConversion.priority) {
117
+ currentConversion = domConversion;
118
+ }
119
+ }
120
+ });
121
+ }
122
+
123
+ return currentConversion !== null ? currentConversion.conversion : null;
124
+ }
125
+
126
+ const IGNORE_TAGS = new Set(['STYLE']);
127
+
128
+ function $createNodesFromDOM(node, editor, forChildMap = new Map(), parentLexicalNode) {
129
+ let lexicalNodes = [];
130
+
131
+ if (IGNORE_TAGS.has(node.nodeName)) {
132
+ return lexicalNodes;
133
+ }
134
+
135
+ let currentLexicalNode = null;
136
+ const transformFunction = getConversionFunction(node, editor);
137
+ const transformOutput = transformFunction ? transformFunction(node) : null;
138
+ let postTransform = null;
139
+
140
+ if (transformOutput !== null) {
141
+ postTransform = transformOutput.after;
142
+ currentLexicalNode = transformOutput.node;
143
+
144
+ if (currentLexicalNode !== null) {
145
+ for (const [, forChildFunction] of forChildMap) {
146
+ currentLexicalNode = forChildFunction(currentLexicalNode, parentLexicalNode);
147
+
148
+ if (!currentLexicalNode) {
149
+ break;
150
+ }
151
+ }
152
+
153
+ if (currentLexicalNode) {
154
+ lexicalNodes.push(currentLexicalNode);
155
+ }
156
+ }
157
+
158
+ if (transformOutput.forChild != null) {
159
+ forChildMap.set(node.nodeName, transformOutput.forChild);
160
+ }
161
+ } // If the DOM node doesn't have a transformer, we don't know what
162
+ // to do with it but we still need to process any childNodes.
163
+
164
+
165
+ const children = node.childNodes;
166
+ let childLexicalNodes = [];
167
+
168
+ for (let i = 0; i < children.length; i++) {
169
+ childLexicalNodes.push(...$createNodesFromDOM(children[i], editor, new Map(forChildMap), currentLexicalNode));
170
+ }
171
+
172
+ if (postTransform != null) {
173
+ childLexicalNodes = postTransform(childLexicalNodes);
174
+ }
175
+
176
+ if (currentLexicalNode == null) {
177
+ // If it hasn't been converted to a LexicalNode, we hoist its children
178
+ // up to the same level as it.
179
+ lexicalNodes = lexicalNodes.concat(childLexicalNodes);
180
+ } else {
181
+ if (lexical.$isElementNode(currentLexicalNode)) {
182
+ // If the current node is a ElementNode after conversion,
183
+ // we can append all the children to it.
184
+ currentLexicalNode.append(...childLexicalNodes);
185
+ }
186
+ }
187
+
188
+ return lexicalNodes;
189
+ }
190
+
191
+ exports.$generateHtmlFromNodes = $generateHtmlFromNodes;
192
+ exports.$generateNodesFromDOM = $generateNodesFromDOM;
package/LexicalHtml.js ADDED
@@ -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
+ 'use strict'
8
+ const LexicalHtml = process.env.NODE_ENV === 'development' ? require('./LexicalHtml.dev.js') : require('./LexicalHtml.prod.js')
9
+ module.exports = LexicalHtml;
@@ -0,0 +1,28 @@
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
+ LexicalEditor,
12
+ LexicalNode,
13
+ EditorState,
14
+ EditorThemeClasses,
15
+ RangeSelection,
16
+ NodeSelection,
17
+ GridSelection,
18
+ } from 'lexical';
19
+
20
+ declare export function $generateHtmlFromNodes(
21
+ editor: LexicalEditor,
22
+ selection?: RangeSelection | NodeSelection | GridSelection | null,
23
+ ): string;
24
+
25
+ declare export function $generateNodesFromDOM(
26
+ editor: LexicalEditor,
27
+ dom: Document,
28
+ ): Array<LexicalNode>;
@@ -0,0 +1,12 @@
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
+ 'use strict';var l=require("@lexical/selection"),p=require("lexical");
8
+ function q(d,b,e,c){let a=null!=b?e.isSelected():!0,f=p.$isElementNode(e)&&e.excludeFromCopy("html"),g=l.$cloneWithProperties(e);g=p.$isTextNode(g)&&null!=b?l.$sliceSelectedTextNodeContent(b,g):g;let k=p.$isElementNode(g)?g.getChildren():[],{element:h,after:r}=g.exportDOM(d);if(!h)return!1;let m=new DocumentFragment;for(let n=0;n<k.length;n++){let t=k[n],w=q(d,b,t,m);!a&&p.$isElementNode(e)&&w&&e.extractWithChild(t,b,"html")&&(a=!0)}a&&!f?(h.append(m),c.append(h),r&&(d=r.call(g,h))&&h.replaceWith(d)):
9
+ c.append(m);return a}function u(d,b){let {nodeName:e}=d;b=b._htmlConversions.get(e.toLowerCase());let c=null;void 0!==b&&b.forEach(a=>{a=a(d);null!==a&&(null===c||c.priority<a.priority)&&(c=a)});return null!==c?c.conversion:null}let v=new Set(["STYLE"]);
10
+ function x(d,b,e=new Map,c){let a=[];if(v.has(d.nodeName))return a;let f=null;var g=u(d,b);let k=g?g(d):null;g=null;if(null!==k){g=k.after;f=k.node;if(null!==f){for(var [,h]of e)if(f=h(f,c),!f)break;f&&a.push(f)}null!=k.forChild&&e.set(d.nodeName,k.forChild)}d=d.childNodes;c=[];for(h=0;h<d.length;h++)c.push(...x(d[h],b,new Map(e),f));null!=g&&(c=g(c));null==f?a=a.concat(c):p.$isElementNode(f)&&f.append(...c);return a}
11
+ exports.$generateHtmlFromNodes=function(d,b){if(null==document||null==window)throw Error("To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.");let e=document.createElement("div"),c=p.$getRoot().getChildren();for(let a=0;a<c.length;a++)q(d,b,c[a],e);return e.innerHTML};
12
+ exports.$generateNodesFromDOM=function(d,b){let e=[];b=b.body?Array.from(b.body.childNodes):[];let c=b.length;for(let f=0;f<c;f++){var a=b[f];v.has(a.nodeName)||(a=x(a,d),null!==a&&(e=e.concat(a)))}return e}
package/README.md ADDED
@@ -0,0 +1,35 @@
1
+ # `@lexical/html`
2
+
3
+ # HTML
4
+ 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.
5
+
6
+ [Full documentation can be found here.](https://lexical.dev/docs/concepts/serialization)
7
+
8
+ ### Exporting
9
+ ```js
10
+ // When converting to HTML you can pass in a selection object to narrow it
11
+ // down to a certain part of the editor's contents.
12
+ const htmlString = $generateHtmlFromNodes(editor, selection | null);
13
+ ```
14
+
15
+ ### Importing
16
+ First we need to parse the HTML string into a DOM instance.
17
+ ```js
18
+ // In the browser you can use the native DOMParser API to parse the HTML string.
19
+ const parser = new DOMParser();
20
+ const dom = parser.parseFromString(htmlString, textHtmlMimeType);
21
+
22
+ // In a headless environment you can use a package such as JSDom to parse the HTML string.
23
+ const dom = new JSDOM(htmlString);
24
+ ```
25
+ And once you have the DOM instance.
26
+ ```js
27
+ const nodes = $generateNodesFromDOM(editor, dom);
28
+
29
+ // Once you have the lexical nodes you can initialize an editor instance with the parsed nodes.
30
+ const editor = createEditor({ ...config, nodes });
31
+
32
+ // Or insert them at a selection.
33
+ const selection = $getSelection();
34
+ selection.insertNodes(nodes);
35
+ ```
package/package.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "name": "@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.3.0",
12
+ "main": "LexicalHtml.js",
13
+ "peerDependencies": {
14
+ "lexical": "0.3.0"
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/facebook/lexical",
19
+ "directory": "packages/lexical-html"
20
+ }
21
+ }