Skip to content

Restore Editor State Plugin (components/Editor/plugins/restoreEditorStatePlugin.tsx)

Overview

A Lexical editor plugin that handles the restoration of editor state from HTML content, managing the parsing and insertion of nodes while maintaining editor history and state consistency.

Features

  • HTML state restoration
  • DOM parsing
  • Node generation
  • History management
  • State tracking
  • Error handling
  • Single update
  • Clean restoration

Implementation

Props Interface

type RestoreEditorStateProps = {
  state?: string | null;
}

Plugin Component

export function RestoreEditorStatePlugin({ state }: RestoreEditorStateProps) {
  const [editor] = useLexicalComposerContext();
  const [isUpdated, setIsUpdated] = useState(false);

  useEffect(() => {
    function restoreEditorState(state?: string | null) {
      if (state && typeof state === 'string' && !isUpdated) {
        editor.update(() => {
          const parser = new DOMParser();
          const dom = parser.parseFromString(state, 'text/html');
          const nodes = $generateNodesFromDOM(editor, dom);

          const root = $getRoot();
          const selection = root.select();
          root.clear();
          selection.insertNodes(nodes);

          editor.dispatchCommand(CLEAR_HISTORY_COMMAND, undefined);
          setIsUpdated(true);
        });
      }
    }
    restoreEditorState(state);
  }, [state, editor, isUpdated]);

  return null;
}

Dependencies

import { useEffect, useState } from 'react'
import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'
import { $getRoot, CLEAR_HISTORY_COMMAND } from 'lexical'
import { $generateNodesFromDOM } from '@lexical/html'

Components Using This

State Management

  • Tracks update status
  • Manages editor state
  • Controls history
  • Handles DOM parsing
  • Maintains selection
  • Manages node insertion
  • Controls updates

Integration Points

  • Lexical editor context
  • DOM parser
  • Node generation
  • History commands
  • State restoration
  • Selection management
  • Update control

Usage Example

<LexicalComposer initialConfig={editorConfig}>
  <RestoreEditorStatePlugin
    state="<p>Restored content</p>"
  />
  {/* Other plugins */}
</LexicalComposer>

Notes

  • Handles HTML parsing
  • Manages state restoration
  • Clears editor history
  • Prevents multiple updates
  • Maintains selection state
  • Supports null states
  • Efficient node generation
  • Clean implementation