Hey,
I have a script that generates html to lexical so I can seed data easily.
export const htmlToLexical = (html: string): SerializedEditorState => {
const editor = createHeadlessEditor({
nodes: [],
onError: (error) => { console.error(error); },
});
editor.update(
() => {
// In a headless environment you can use a package such as JSDom to parse the HTML string.
const dom = new JSDOM(`<!DOCTYPE html><body>${html}</body>`);
// Once you have the DOM instance it's easy to generate LexicalNodes.
const nodes = $generateNodesFromDOM(editor, dom.window.document);
// Select the root
$getRoot().select();
// Insert them at a selection.
const selection = $getSelection();
console.log("Generated nodes: ", nodes);
if (selection) selection.insertNodes(nodes);
},
{ discrete: true },
);
return editor.getEditorState().toJSON();
};
I call it like so:
const scratch = () => {
const html = htmlToLexical(
'<h2>Online English Lessons</h2><p>Are you worried about making mistakes</p>',
)
console.log(JSON.stringify(html, null, 2))
}
Unfortunately, it doesn't generate headings and I'm not sure why?
"root": {
"children": [
{
"children": [
{
"detail": 0,
"format": 0,
"mode": "normal",
"style": "",
"text": "Online English Lessons",
"type": "text", // Should be heading?
"version": 1
}
],
"direction": null,
"format": "",
"indent": 0,
"type": "paragraph",
"version": 1,
"textFormat": 0
},
],
"direction": null,
"format": "",
"indent": 0,
"type": "root",
"version": 1
}
}