Diptaneal Roy
Diptaneal Roy

Reputation: 25

Not seeing to original text when I edit for my form developed using Lexical

My code is presented below. Tried number of options to ensure that when I hit edit option from my form which renders this Lexical editor, I am able to retain the original text. But as of now, it clears the text and allows me to save fresh.

Read through the documents available on net, however, it did not work. Any help in this regards will be highly appreciated.

export const LexicalEditor = ({ onChange, initialHtmlContent }: LexicalEditorProps) => {
    const [editor] = useLexicalComposerContext();

    useEffect(() => {
        if (initialHtmlContent) {
            console.log('Initial HTML Content:', initialHtmlContent);
            const parser = new DOMParser();
            const dom = parser.parseFromString(initialHtmlContent, 'text/html');
            const body = dom.body;

            editor.update(() => {
                const root = $getRoot();
                root.clear(); // Clear existing content

                // Convert HTML content to Lexical nodes
                const convertHtmlToLexicalNodes = (element: Element): LexicalNode[] => {
                    const nodes: LexicalNode[] = [];
                    Array.from(element.childNodes).forEach((node) => {
                        if (node.nodeType === Node.TEXT_NODE) {
                            const textNode = $createTextNode(node.textContent || '');
                            nodes.push(textNode);
                        } else if (node.nodeType === Node.ELEMENT_NODE) {
                            const elementNode = node as HTMLElement;
                            if (elementNode.tagName === 'P') {
                                const paragraphNode = $createParagraphNode();
                                const childNodes = convertHtmlToLexicalNodes(elementNode);
                                childNodes.forEach((childNode) => paragraphNode.append(childNode));
                                nodes.push(paragraphNode);
                            } else if (elementNode.tagName === 'STRONG') {
                                const textNode = $createTextNode(elementNode.textContent || '');
                                textNode.toggleFormat('bold');
                                nodes.push(textNode);
                            } else if (elementNode.tagName === 'SPAN') {
                                const textNode = $createTextNode(elementNode.textContent || '');
                                nodes.push(textNode);
                            }
                        }
                    });
                    return nodes;
                };

                const lexicalNodes = convertHtmlToLexicalNodes(body);
                console.log('Lexical Nodes:', lexicalNodes);
                lexicalNodes.forEach((node) => root.append(node));
            }, { discrete: true });
        }
    }, [initialHtmlContent, editor]);

    useEffect(() => {
        return editor.registerUpdateListener(({ editorState }) => {
            editorState.read(() => {
                const root = $getRoot();
                const htmlContent = root.getTextContent();
                onChange(htmlContent);
            });
        });
    }, [editor, onChange]);

    const CustomContent = useMemo(() => {
        return <ContentEditable className="editor-input" />;
    }, []);

    const CustomPlaceholder = useMemo(() => {
        return (
            <div
                style={{
                    position: 'relative',
                    top: -19,
                    left: 23,
                    color: 'rgba(0,0,0,0.42)',
                    zIndex: -10,
                    pointerEvents: 'none',
                }}
            >
                Start typing...
            </div>
        );
    }, []);

    const lexicalConfig: InitialConfigType = {
        namespace: 'My Rich Text Editor',
        nodes: [
            HeadingNode,
            QuoteNode,
            CodeNode,
            ListNode,
            ListItemNode,
            LinkNode,
            AutoLinkNode,
        ],
        editable: true,
        theme: {
            root: 'root',
            text: {
                bold: 'text-bold',
                italic: 'text-italic',
                underline: 'text-underline',
                code: 'text-code',
                highlight: 'text-highlight',
                strikethrough: 'text-strikethrough',
                subscript: 'text-subscript',
                superscript: 'text-superscript',
            },
            image: 'h-auto max-w-full',
            heading: {
                h1: 'mb-5 text-5xl font-extrabold',
                h2: 'mb-4 text-4xl font-bold',
                h3: 'mb-3 text-3xl font-bold',
                h4: 'mb-2 text-2xl font-bold',
                h5: 'mb-1 text-xl font-bold',
            },
            paragraph: 'mb-3',
            banner: 'banner',
            divider: 'divider',
            code: 'markdown-code',
            embedBlock: {
                base: 'embedBlock',
                focus: 'embedBlock_focus',
            },
        },
        onError: (e) => {
            console.log('ERROR:', e);
        },
    };

    return (
        <div className="editor-container">
            <LexicalComposer initialConfig={lexicalConfig}>
                <ToolbarComponent />
                <RichTextPlugin
                    contentEditable={CustomContent}
                    placeholder={CustomPlaceholder}
                    ErrorBoundary={LexicalErrorBoundary}
                />
                <HistoryPlugin />
                <CustomHeadingPlugin />
                <LexicalClickableLinkPlugin />
                <LinkPlugin />
                <ListPlugin />
                <EditorOnChangePlugin onChange={onChange} />
            </LexicalComposer>
        </div>
    );
};

Upvotes: 0

Views: 84

Answers (0)

Related Questions