I work with a database that contains articels saved as simple HTML and want to switch to a WYSIWYG that plays well with React so I am looking into Lexical.
When "feeding" Lexical with the intitial HTML I need to transform it into Nodes first. But: When the initial HTML is not superclean and contains e.g. spaces between the HTML tags, the transformation breaks.
So this as input string works:
const htmlString = '<p><b>I am bold</b></p><p><b><i>I am bold and italic</i></b></p>';
But this does not:
const htmlString = '<p><b>I am bold</b></p> <p><b><i>I am bold and italic</i></b></p>';
(because of the space between the p-tags)
How can I fix this? Since I cannot ensure the source code is well-formed HTML.
function InitialContentPlugin() {
const [editor] = useLexicalComposerContext();
editor.update(() => {
const htmlString = '<p><b>I am bold</b></p><p><b><i>I am bold and italic</i></b></p>';
const parser = new DOMParser();
const dom = parser.parseFromString(htmlString, 'text/html');
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom);
// Select the root
$getRoot().select();
// Insert them at a selection.
$insertNodes(nodes);
});
return null;
}
Edit:
I figured out that the empty space creates a TextNode. I cannot insert this into the root because TextNodes are "leaves" and therefore not allowed as direct children of the root. Need to find a way now how to fix this.