Search code examples
lexicallexicaljs

How to check if the editor is empty?


I have two editor instances. One is editable Second one is read only for preview what user is typed I'm copied editor state beetwen those editors - wtih no problems But i want to hide second editor when first one is empty. I'm trying something like this but it always return false

...
function onChange(editorState) {
  console.log(editorState.isEmpty())
}

function Editor() {
...

  return (
      <>
        <LexicalComposer initialConfig={editorConfig}>
            <ToolbarPlugin />
              <RichTextPlugin
                contentEditable={<ContentEditable className="editor-input" />}
                placeholder={<Placeholder />}
                ErrorBoundary={LexicalErrorBoundary}
              />
              <OnChangePlugin onChange={onChange} />
          <LexicalComposer />
   )
}

Solution

  • There are, unfortunately, currently several different ways to do this, depending on exactly what you mean by "empty". You can us EditorState.isEmpty, but this is checking to see if the _nodeMap contains only a single node (the root) and the selection is null - so it's really about emptiness in the sense that the EditorState is in the same state it would be in had it just been initialized. However, this is might not be what you want - usually a visually empty editor will have a RootNode with a single ParagraphNode child, and you may or may not care if the Selection is null. So, you could look at using ElementNode.isEmpty:

    $getRoot().isEmpty()
    

    This checks if the RootNode has 0 children. Once again, in a typical editor, that might return false in a lot of cases where you would expect it to return true (like if the editor is initialized with an empty ParagraphNode under the RootNode). So, you could do:

    const isEditorEmpty = editorState.read(() => {
      const root = $getRoot();
      const isEmpty = root.getFirstChild().isEmpty() && root.getChildrenSize() === 1
    
      return isEmpty;
    });
    

    However, this wouldn't account for whitespace - which you might also care about. If you want to consider an editor with only whitespace as empty, then you might want to use $isRootTextContentEmpty from @lexical/text. You can also look at the implementation of this function to see how you might go about tweaking it for your use case.