2024-07-01 22:10:22 +08:00
|
|
|
import {$createParagraphNode, $getRoot, $isTextNode, LexicalEditor} from "lexical";
|
2024-06-12 21:01:36 +08:00
|
|
|
import {$generateHtmlFromNodes, $generateNodesFromDOM} from "@lexical/html";
|
2024-07-01 22:10:22 +08:00
|
|
|
import {$createCustomParagraphNode} from "./nodes/custom-paragraph";
|
2024-06-12 21:01:36 +08:00
|
|
|
|
|
|
|
|
|
|
|
export function setEditorContentFromHtml(editor: LexicalEditor, html: string) {
|
|
|
|
const parser = new DOMParser();
|
|
|
|
const dom = parser.parseFromString(html, 'text/html');
|
|
|
|
|
2024-07-01 22:10:22 +08:00
|
|
|
console.log(html);
|
2024-06-12 21:01:36 +08:00
|
|
|
editor.update(() => {
|
2024-07-01 22:10:22 +08:00
|
|
|
// Empty existing
|
2024-06-12 21:01:36 +08:00
|
|
|
const root = $getRoot();
|
|
|
|
for (const child of root.getChildren()) {
|
|
|
|
child.remove(true);
|
|
|
|
}
|
2024-07-01 22:10:22 +08:00
|
|
|
|
|
|
|
const nodes = $generateNodesFromDOM(editor, dom);
|
|
|
|
|
|
|
|
// Wrap top-level text nodes
|
|
|
|
for (let i = 0; i < nodes.length; i++) {
|
|
|
|
const node = nodes[i];
|
|
|
|
if ($isTextNode(node)) {
|
|
|
|
const paragraph = $createCustomParagraphNode();
|
|
|
|
paragraph.append(node);
|
|
|
|
nodes[i] = paragraph;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-06-12 21:01:36 +08:00
|
|
|
root.append(...nodes);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getEditorContentAsHtml(editor: LexicalEditor): Promise<string> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
editor.getEditorState().read(() => {
|
|
|
|
const html = $generateHtmlFromNodes(editor);
|
|
|
|
resolve(html);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|