lexical icon indicating copy to clipboard operation
lexical copied to clipboard

Bug: $insertNodeToNearestRoot don't insert at selection if editor is unfocused and after promise resolve

Open kalvin807 opened this issue 3 years ago • 1 comments

Lexical version: v0.10.0

Steps To Reproduce

  1. Open https://codesandbox.io/s/compassionate-keller-px504c
  2. Write 3 line of text
  3. Click at the middle line (line 2 in this case)
  4. Click on the input and type anything
  5. Click add to add a node
  6. 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:

  1. The document is focusing at the editor
  2. 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 :)

kalvin807 avatar May 15 '23 08:05 kalvin807

Yep we can definitely use prev selection right at the top of the util, would appreciate PR 👍

fantactuka avatar May 28 '23 17:05 fantactuka