variable-on-change-plugin.tsx


Overview

The variable-on-change-plugin.tsx file defines a React plugin component for the Lexical editor framework that monitors changes in the editor state and triggers a callback when the content is updated by user interaction. It ensures that only manual changes (not programmatic updates) invoke the onChange callback, which helps keep the editor’s state in sync with external components or logic.

This plugin is useful for cases where you want to react to user edits in the editor, for example, to autosave content, validate input, or update application state, without being triggered by internal programmatic updates that should not cause side effects.


Detailed Documentation

IProps Interface

interface IProps {
  onChange: (
    editorState: EditorState,
    editor?: LexicalEditor,
    tags?: Set<string>,
  ) => void;
}

VariableOnChangePlugin Component

export function VariableOnChangePlugin({ onChange }: IProps)
import { VariableOnChangePlugin } from './variable-on-change-plugin';

function MyEditorWrapper() {
  const handleEditorChange = (editorState, editor, tags) => {
    console.log('Editor content changed manually:', editorState);
    // Additional logic like saving or validation can be invoked here
  };

  return (
    <>
      {/* Other editor components */}
      <VariableOnChangePlugin onChange={handleEditorChange} />
    </>
  );
}

Implementation Details and Algorithms


Interaction with Other Parts of the System


Mermaid Component Diagram

componentDiagram
    component VariableOnChangePlugin {
        +onChange(editorState, editor?, tags?)
        -useEffect()
        -registerUpdateListener()
    }
    
    component LexicalEditor {
        +registerUpdateListener()
        +editorState
        +tags
        +dirtyElements
    }
    
    component ProgrammaticTag
    
    VariableOnChangePlugin --> LexicalEditor : uses context
    VariableOnChangePlugin --> ProgrammaticTag : checks tag to filter updates

Summary

The variable-on-change-plugin.tsx file provides a clean, efficient integration point for detecting user-initiated content changes in a Lexical editor instance. By filtering out programmatic updates, it ensures that onChange callbacks represent meaningful user edits, enabling robust and predictable synchronization with application state or UI components. The component leverages React hooks and Lexical's update listener API to maintain clean lifecycle management and performance.


End of Documentation for variable-on-change-plugin.tsx