"use client"; import { $generateNodesFromDOM } from "@lexical/html"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { $getRoot, $getSelection } from "lexical"; import type React from "react"; import { useImperativeHandle } from "react"; export interface RichTextEditorRef { insertContent: (content: string) => void; isFocused: () => boolean; } export function ImperativeHandlePlugin({ editorRef, }: { editorRef?: React.Ref | null; }) { const [editor] = useLexicalComposerContext(); useImperativeHandle( editorRef, () => ({ insertContent: (content: string) => { editor.update(() => { const parser = new DOMParser(); const dom = parser.parseFromString(content, "text/html"); const nodes = $generateNodesFromDOM(editor, dom.body); const selection = $getSelection(); if (selection) { selection.insertNodes(nodes); } else { $getRoot().append(...nodes); } }); }, isFocused: () => { return editor.getRootElement() === document.activeElement; }, }), [editor], ); return null; }