3

I am trying to use lexical js to build a text editor that supports mentions as in fb messenger. I have not been able to find many examples. I am trying to insert a div of possible auto-complete options that will show up under the text being entered. I assume this would be done with a decorator node? But I keep running into problems. Every time I try to insert it after the selected node, I get this error:

Lexical node does not exist in active editor state. Avoid using the same node references between nested closures from editor.read/editor.update

Here is my code snippet:

export class MenuNode extends DecoratorNode<ReactNode> {
  __searchText: string;

  static getType(): string {
    return 'menu';
  }

  static clone(node: MenuNode): MenuNode {
    return new MenuNode(node.__searchText, node.__key);
  }

  constructor(searchText: string, key?: string) {
    super(key);
    this.__searchText = searchText;
  }

  createDOM(): HTMLElement {
    return document.createElement('div');
  }

  updateDOM(): false {
    return false;
  }

  decorate(): ReactNode {
    return <WordOptions searchText={this.__searchText}/>;
  }
}


function onChange(editorState: EditorState, editor: LexicalEditor) {

  editor.update(() => {

    const selection = $getSelection();
    const selectedNode = (selection as RangeSelection).anchor.getNode();
    const menuNode = new MenuNode(selectedNode.getTextContent(), "results");
    $insertNodes([menuNode]);

    selectedNode.insertAfter(menuNode);
  });

//...

export default function Editor() {
  const initialConfig = {
    namespace: 'MyEditor', 
    theme,
    editable: true,
    onError,
    nodes: [MenuNode]
  };

  return (
    <LexicalComposer initialConfig={initialConfig}>
      <PlainTextPlugin
        contentEditable={<ContentEditable />}
        placeholder={<div>Enter some text...</div>}
        ErrorBoundary={LexicalErrorBoundary}
      />
      <OnChangePlugin onChange={onChange} />
      <HistoryPlugin />
      <MyCustomAutoFocusPlugin />
    </LexicalComposer>
  );
}


}

Is there some sample code I could see to help me understand what I'm doing wrong?

Lioness
  • 500
  • 8
  • 13

2 Answers2

1

The Lexical Playground includes mentioning functionality with auto-complete popup. The code for the functionality is available here.

mmurto
  • 56
  • 2
  • 4
0

@mmurto 's answer has the example code that Lexical provides, and should be the correct answer; however, based on your current code, there's a different problem. I've ran into the same error myself and haven't found a solution yet, but the problem stems from attempting to replace a TextNode with a DecoratorNode.

If you change the class you're extending from DecoratorNode to TextNode (which will also make the decorate method useless), your code should work, but of course that removes the ability to render a React component in the Node.

aal
  • 51
  • 2