2024-07-29 10:27:41 -04:00
|
|
|
import {$getRoot, $getSelection, LexicalEditor} from "lexical";
|
|
|
|
import {$generateHtmlFromNodes} from "@lexical/html";
|
2024-08-03 13:14:01 -04:00
|
|
|
import {$htmlToBlockNodes} from "./nodes";
|
2024-06-12 09:01:36 -04:00
|
|
|
|
|
|
|
export function setEditorContentFromHtml(editor: LexicalEditor, html: string) {
|
|
|
|
editor.update(() => {
|
2024-07-01 10:10:22 -04:00
|
|
|
// Empty existing
|
2024-06-12 09:01:36 -04:00
|
|
|
const root = $getRoot();
|
|
|
|
for (const child of root.getChildren()) {
|
|
|
|
child.remove(true);
|
|
|
|
}
|
2024-07-01 10:10:22 -04:00
|
|
|
|
2024-07-29 10:27:41 -04:00
|
|
|
const nodes = $htmlToBlockNodes(editor, html);
|
|
|
|
root.append(...nodes);
|
2024-07-23 10:35:18 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function appendHtmlToEditor(editor: LexicalEditor, html: string) {
|
|
|
|
editor.update(() => {
|
|
|
|
const root = $getRoot();
|
2024-07-29 10:27:41 -04:00
|
|
|
const nodes = $htmlToBlockNodes(editor, html);
|
|
|
|
root.append(...nodes);
|
2024-07-23 10:35:18 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function prependHtmlToEditor(editor: LexicalEditor, html: string) {
|
|
|
|
editor.update(() => {
|
|
|
|
const root = $getRoot();
|
2024-07-29 10:27:41 -04:00
|
|
|
const nodes = $htmlToBlockNodes(editor, html);
|
2024-07-23 10:35:18 -04:00
|
|
|
let reference = root.getChildren()[0];
|
|
|
|
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
|
|
if (reference) {
|
|
|
|
reference.insertBefore(nodes[i]);
|
|
|
|
} else {
|
|
|
|
root.append(nodes[i])
|
2024-07-01 10:10:22 -04:00
|
|
|
}
|
2024-07-23 10:35:18 -04:00
|
|
|
reference = nodes[i];
|
2024-07-01 10:10:22 -04:00
|
|
|
}
|
2024-07-23 10:35:18 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function insertHtmlIntoEditor(editor: LexicalEditor, html: string) {
|
|
|
|
editor.update(() => {
|
|
|
|
const selection = $getSelection();
|
2024-07-29 10:27:41 -04:00
|
|
|
const nodes = $htmlToBlockNodes(editor, html);
|
2024-07-01 10:10:22 -04:00
|
|
|
|
2024-07-23 10:35:18 -04:00
|
|
|
const reference = selection?.getNodes()[0];
|
|
|
|
const referencesParents = reference?.getParents() || [];
|
|
|
|
const topLevel = referencesParents[referencesParents.length - 1];
|
|
|
|
if (topLevel && reference) {
|
|
|
|
for (let i = nodes.length - 1; i >= 0; i--) {
|
|
|
|
reference.insertAfter(nodes[i]);
|
|
|
|
}
|
|
|
|
}
|
2024-06-12 09:01:36 -04:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getEditorContentAsHtml(editor: LexicalEditor): Promise<string> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
editor.getEditorState().read(() => {
|
|
|
|
const html = $generateHtmlFromNodes(editor);
|
|
|
|
resolve(html);
|
|
|
|
});
|
|
|
|
});
|
2024-07-23 10:35:18 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export function focusEditor(editor: LexicalEditor) {
|
|
|
|
editor.focus(() => {}, {defaultSelection: "rootStart"});
|
2024-06-12 09:01:36 -04:00
|
|
|
}
|