"use client"; import { $generateHtmlFromNodes, $generateNodesFromDOM } from "@lexical/html"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import type { ParagraphNode } from "lexical"; import { $createParagraphNode, $getRoot, $isTextNode } from "lexical"; import { useEffect, useRef } from "react"; export function SyncPlugin({ value, onChange, }: { value: string; onChange: (html: string) => void; }): null { const [editor] = useLexicalComposerContext(); const lastHtmlRef = useRef(null); const isUpdatingFromPropRef = useRef(false); // 1. Sync value prop -> editor (including initial mount) useEffect(() => { const nextHtml = value || ""; // Only update if the prop value is different from our last known pushed value if (nextHtml !== lastHtmlRef.current) { isUpdatingFromPropRef.current = true; editor.update( () => { const root = $getRoot(); const parser = new DOMParser(); const dom = parser.parseFromString(nextHtml, "text/html"); // Generate nodes from body const nodes = $generateNodesFromDOM(editor, dom.body); root.clear(); if (nodes.length === 0) { root.append($createParagraphNode()); } else { // Wrap inline nodes at root let currentParagraph: ParagraphNode | null = null; nodes.forEach((node) => { const isInline = $isTextNode(node) || node.getType() === "link" || node.getType() === "autolink" || node.getType() === "linebreak"; if (isInline) { if (!currentParagraph) { currentParagraph = $createParagraphNode(); root.append(currentParagraph); } currentParagraph.append(node); } else { root.append(node); currentParagraph = null; } }); } lastHtmlRef.current = nextHtml; }, { onUpdate: () => { isUpdatingFromPropRef.current = false; }, }, ); } }, [editor, value]); // 2. Sync editor -> onChange callback useEffect(() => { return editor.registerUpdateListener(({ editorState, dirtyElements, dirtyLeaves }) => { if (isUpdatingFromPropRef.current) return; if (dirtyElements.size === 0 && dirtyLeaves.size === 0) return; editorState.read(() => { const html = $generateHtmlFromNodes(editor); if (html !== (lastHtmlRef.current ?? "")) { lastHtmlRef.current = html; onChange(html); } }); }); }, [editor, onChange]); return null; }