]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/lexical/html/index.ts
Lexical: Fixed code in lists, removed extra old alignment code
[bookstack] / resources / js / wysiwyg / lexical / html / index.ts
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   LexicalEditor,
15   LexicalNode,
16 } from 'lexical';
17
18 import {$sliceSelectedTextNodeContent} from '@lexical/selection';
19 import {isBlockDomNode, isHTMLElement} from '@lexical/utils';
20 import {
21   $cloneWithProperties,
22   $createLineBreakNode,
23   $createParagraphNode,
24   $getRoot,
25   $isBlockElementNode,
26   $isElementNode,
27   $isRootOrShadowRoot,
28   $isTextNode,
29   ArtificialNode__DO_NOT_USE,
30   ElementNode,
31   isInlineDomNode,
32 } from 'lexical';
33
34 /**
35  * How you parse your html string to get a document is left up to you. In the browser you can use the native
36  * DOMParser API to generate a document (see clipboard.ts), but to use in a headless environment you can use JSDom
37  * or an equivalent library and pass in the document here.
38  */
39 export function $generateNodesFromDOM(
40   editor: LexicalEditor,
41   dom: Document,
42 ): Array<LexicalNode> {
43   const elements = dom.body ? dom.body.childNodes : [];
44   let lexicalNodes: Array<LexicalNode> = [];
45   const allArtificialNodes: Array<ArtificialNode__DO_NOT_USE> = [];
46   for (let i = 0; i < elements.length; i++) {
47     const element = elements[i];
48     if (!IGNORE_TAGS.has(element.nodeName)) {
49       const lexicalNode = $createNodesFromDOM(
50         element,
51         editor,
52         allArtificialNodes,
53         false,
54       );
55       if (lexicalNode !== null) {
56         lexicalNodes = lexicalNodes.concat(lexicalNode);
57       }
58     }
59   }
60
61   $unwrapArtificalNodes(allArtificialNodes);
62
63   return lexicalNodes;
64 }
65
66 export function $generateHtmlFromNodes(
67   editor: LexicalEditor,
68   selection?: BaseSelection | null,
69 ): string {
70   if (
71     typeof document === 'undefined' ||
72     (typeof window === 'undefined' && typeof global.window === 'undefined')
73   ) {
74     throw new Error(
75       'To use $generateHtmlFromNodes in headless mode please initialize a headless browser implementation such as JSDom before calling this function.',
76     );
77   }
78
79   const container = document.createElement('div');
80   const root = $getRoot();
81   const topLevelChildren = root.getChildren();
82
83   for (let i = 0; i < topLevelChildren.length; i++) {
84     const topLevelNode = topLevelChildren[i];
85     $appendNodesToHTML(editor, topLevelNode, container, selection);
86   }
87
88   return container.innerHTML;
89 }
90
91 function $appendNodesToHTML(
92   editor: LexicalEditor,
93   currentNode: LexicalNode,
94   parentElement: HTMLElement | DocumentFragment,
95   selection: BaseSelection | null = null,
96 ): boolean {
97   let shouldInclude =
98     selection !== null ? currentNode.isSelected(selection) : true;
99   const shouldExclude =
100     $isElementNode(currentNode) && currentNode.excludeFromCopy('html');
101   let target = currentNode;
102
103   if (selection !== null) {
104     let clone = $cloneWithProperties(currentNode);
105     clone =
106       $isTextNode(clone) && selection !== null
107         ? $sliceSelectedTextNodeContent(selection, clone)
108         : clone;
109     target = clone;
110   }
111   const children = $isElementNode(target) ? target.getChildren() : [];
112   const registeredNode = editor._nodes.get(target.getType());
113   let exportOutput;
114
115   // Use HTMLConfig overrides, if available.
116   if (registeredNode && registeredNode.exportDOM !== undefined) {
117     exportOutput = registeredNode.exportDOM(editor, target);
118   } else {
119     exportOutput = target.exportDOM(editor);
120   }
121
122   const {element, after} = exportOutput;
123
124   if (!element) {
125     return false;
126   }
127
128   const fragment = document.createDocumentFragment();
129
130   for (let i = 0; i < children.length; i++) {
131     const childNode = children[i];
132     const shouldIncludeChild = $appendNodesToHTML(
133       editor,
134       childNode,
135       fragment,
136       selection,
137     );
138
139     if (
140       !shouldInclude &&
141       $isElementNode(currentNode) &&
142       shouldIncludeChild &&
143       currentNode.extractWithChild(childNode, selection, 'html')
144     ) {
145       shouldInclude = true;
146     }
147   }
148
149   if (shouldInclude && !shouldExclude) {
150     if (isHTMLElement(element)) {
151       element.append(fragment);
152     }
153     parentElement.append(element);
154
155     if (after) {
156       const newElement = after.call(target, element);
157       if (newElement) {
158         element.replaceWith(newElement);
159       }
160     }
161   } else {
162     parentElement.append(fragment);
163   }
164
165   return shouldInclude;
166 }
167
168 function getConversionFunction(
169   domNode: Node,
170   editor: LexicalEditor,
171 ): DOMConversionFn | null {
172   const {nodeName} = domNode;
173
174   const cachedConversions = editor._htmlConversions.get(nodeName.toLowerCase());
175
176   let currentConversion: DOMConversion | null = null;
177
178   if (cachedConversions !== undefined) {
179     for (const cachedConversion of cachedConversions) {
180       const domConversion = cachedConversion(domNode);
181       if (
182         domConversion !== null &&
183         (currentConversion === null ||
184           (currentConversion.priority || 0) < (domConversion.priority || 0))
185       ) {
186         currentConversion = domConversion;
187       }
188     }
189   }
190
191   return currentConversion !== null ? currentConversion.conversion : null;
192 }
193
194 const IGNORE_TAGS = new Set(['STYLE', 'SCRIPT']);
195
196 function $createNodesFromDOM(
197   node: Node,
198   editor: LexicalEditor,
199   allArtificialNodes: Array<ArtificialNode__DO_NOT_USE>,
200   hasBlockAncestorLexicalNode: boolean,
201   forChildMap: Map<string, DOMChildConversion> = new Map(),
202   parentLexicalNode?: LexicalNode | null | undefined,
203 ): Array<LexicalNode> {
204   let lexicalNodes: Array<LexicalNode> = [];
205
206   if (IGNORE_TAGS.has(node.nodeName)) {
207     return lexicalNodes;
208   }
209
210   let currentLexicalNode = null;
211   const transformFunction = getConversionFunction(node, editor);
212   const transformOutput = transformFunction
213     ? transformFunction(node as HTMLElement)
214     : null;
215   let postTransform = null;
216
217   if (transformOutput !== null) {
218     postTransform = transformOutput.after;
219     const transformNodes = transformOutput.node;
220
221     if (transformNodes === 'ignore') {
222       return lexicalNodes;
223     }
224
225     currentLexicalNode = Array.isArray(transformNodes)
226       ? transformNodes[transformNodes.length - 1]
227       : transformNodes;
228
229     if (currentLexicalNode !== null) {
230       for (const [, forChildFunction] of forChildMap) {
231         currentLexicalNode = forChildFunction(
232           currentLexicalNode,
233           parentLexicalNode,
234         );
235
236         if (!currentLexicalNode) {
237           break;
238         }
239       }
240
241       if (currentLexicalNode) {
242         lexicalNodes.push(
243           ...(Array.isArray(transformNodes)
244             ? transformNodes
245             : [currentLexicalNode]),
246         );
247       }
248     }
249
250     if (transformOutput.forChild != null) {
251       forChildMap.set(node.nodeName, transformOutput.forChild);
252     }
253   }
254
255   // If the DOM node doesn't have a transformer, we don't know what
256   // to do with it but we still need to process any childNodes.
257   const children = node.childNodes;
258   let childLexicalNodes = [];
259
260   const hasBlockAncestorLexicalNodeForChildren =
261     currentLexicalNode != null && $isRootOrShadowRoot(currentLexicalNode)
262       ? false
263       : (currentLexicalNode != null &&
264           $isBlockElementNode(currentLexicalNode)) ||
265         hasBlockAncestorLexicalNode;
266
267   for (let i = 0; i < children.length; i++) {
268     childLexicalNodes.push(
269       ...$createNodesFromDOM(
270         children[i],
271         editor,
272         allArtificialNodes,
273         hasBlockAncestorLexicalNodeForChildren,
274         new Map(forChildMap),
275         currentLexicalNode,
276       ),
277     );
278   }
279
280   if (postTransform != null) {
281     childLexicalNodes = postTransform(childLexicalNodes);
282   }
283
284   if (isBlockDomNode(node)) {
285     if (!hasBlockAncestorLexicalNodeForChildren) {
286       childLexicalNodes = wrapContinuousInlines(
287         node,
288         childLexicalNodes,
289         $createParagraphNode,
290       );
291     } else {
292       childLexicalNodes = wrapContinuousInlines(node, childLexicalNodes, () => {
293         const artificialNode = new ArtificialNode__DO_NOT_USE();
294         allArtificialNodes.push(artificialNode);
295         return artificialNode;
296       });
297     }
298   }
299
300   if (currentLexicalNode == null) {
301     if (childLexicalNodes.length > 0) {
302       // If it hasn't been converted to a LexicalNode, we hoist its children
303       // up to the same level as it.
304       lexicalNodes = lexicalNodes.concat(childLexicalNodes);
305     } else {
306       if (isBlockDomNode(node) && isDomNodeBetweenTwoInlineNodes(node)) {
307         // Empty block dom node that hasnt been converted, we replace it with a linebreak if its between inline nodes
308         lexicalNodes = lexicalNodes.concat($createLineBreakNode());
309       }
310     }
311   } else {
312     if ($isElementNode(currentLexicalNode)) {
313       // If the current node is a ElementNode after conversion,
314       // we can append all the children to it.
315       currentLexicalNode.append(...childLexicalNodes);
316     }
317   }
318
319   return lexicalNodes;
320 }
321
322 function wrapContinuousInlines(
323   domNode: Node,
324   nodes: Array<LexicalNode>,
325   createWrapperFn: () => ElementNode,
326 ): Array<LexicalNode> {
327   const out: Array<LexicalNode> = [];
328   let continuousInlines: Array<LexicalNode> = [];
329   // wrap contiguous inline child nodes in para
330   for (let i = 0; i < nodes.length; i++) {
331     const node = nodes[i];
332     if ($isBlockElementNode(node)) {
333       out.push(node);
334     } else {
335       continuousInlines.push(node);
336       if (
337         i === nodes.length - 1 ||
338         (i < nodes.length - 1 && $isBlockElementNode(nodes[i + 1]))
339       ) {
340         const wrapper = createWrapperFn();
341         wrapper.append(...continuousInlines);
342         out.push(wrapper);
343         continuousInlines = [];
344       }
345     }
346   }
347   return out;
348 }
349
350 function $unwrapArtificalNodes(
351   allArtificialNodes: Array<ArtificialNode__DO_NOT_USE>,
352 ) {
353   for (const node of allArtificialNodes) {
354     if (node.getNextSibling() instanceof ArtificialNode__DO_NOT_USE) {
355       node.insertAfter($createLineBreakNode());
356     }
357   }
358   // Replace artificial node with it's children
359   for (const node of allArtificialNodes) {
360     const children = node.getChildren();
361     for (const child of children) {
362       node.insertBefore(child);
363     }
364     node.remove();
365   }
366 }
367
368 function isDomNodeBetweenTwoInlineNodes(node: Node): boolean {
369   if (node.nextSibling == null || node.previousSibling == null) {
370     return false;
371   }
372   return (
373     isInlineDomNode(node.nextSibling) && isInlineDomNode(node.previousSibling)
374   );
375 }