Bug: $insertNodeToNearestRoot don't insert at selection if editor is unfocused and after promise resolve
Lexical version: v0.10.0
Steps To Reproduce
- Open https://codesandbox.io/s/compassionate-keller-px504c
- Write 3 line of text
- Click at the middle line (line 2 in this case)
- Click on the input and type anything
- Click add to add a node
- You will see the new node is added at the end of the document
Link to code example: https://codesandbox.io/s/compassionate-keller-px504c
The node insertion code is at src/plugins/DemoPlugins.js
The current behavior
When user attempt to insert a node via $insertNodeToNearestRoot to editor with following circumstances:
- The document is focusing at the editor
- Awaited some promise before calling $insertNodeToNearestRoot
Lexical don't insert at last selection, and instead inserting at the end of the document.
https://github.com/facebook/lexical/assets/46393179/025c514b-37bd-4006-a413-5d60704743f6
The expected behavior
It will insert at last selection location. (line 2)
I took some time to poke around and see whats happening:
I notice that the selection is gone ($getSelection is null) if editor unfocused and async. However, the selection state is kept in editorState, so we can use $getPreviousSelection() to retrieve back the selection.
To make the behavior consistent with non-async, I suggest that in $insertNodeToNearestRoot implementation, fetch selection from $getPreviousSelection if the result of getSelection is null.
I can submit a PR if it sounds good :)
Yep we can definitely use prev selection right at the top of the util, would appreciate PR 👍