ianstormtaylor / slate

A completely customizable framework for building rich text editors. (Currently in beta.)
http://slatejs.org
MIT License
30.02k stars 3.26k forks source link

Cannot insert a node at the start of the editor after removing all its contents #3753

Open silviubogan opened 4 years ago

silviubogan commented 4 years ago

Do you want to request a feature or report a bug?

Bug.

What's the current behavior?

Transforms.insertNodes(editor, { text: 'a' }, { at: Editor.start(editor, [0]) }); fails because there is no node at [0] to insert at, and Editor.start(editor, []) throws an error because [] is the root path at which there is no Text node, but the editor. So I cannot insert something at the beginning of the editor.

So the relevant code from the sandbox is inside the click handler of the button:

const handleClick = () => {
  Transforms.removeNodes(editor, { at: [0] })

  // with 0 between `[` and `]`, or without, there are two different errors:

  // case 1
  // Transforms.insertNodes(
  //   editor,
  //   { text: 'a' },
  //   { at: Editor.start(editor, []) }
  // )

  // case 2
  Transforms.insertNodes(
    editor,
    { text: 'a' },
    { at: Editor.start(editor, [0]) }
  )
}

I am not sure which case should work but I think that both would be great to work.

The sandbox: https://codesandbox.io/s/slate-reproductions-zkghr?file=/index.js (in the sandbox, just click the button, watch the error console, then switch the comments so that case 1 is executed and not case 2 and then click the button again).

Slate: 0.58.3 Browser: Chrome, Firefox (although I think it is a cross-browser issue) OS: Linux (Ubuntu 20.04)

What's the expected behavior?

No errors in the console. Text is inserted at the beginning of the editor which should be empty before the insertNodes call.

Thank you.

LeonAlvarez commented 4 years ago

Transforms.removeNodes(editor, { at: [0, 0]})

silviubogan commented 4 years ago

@LeonAlvarez Thank you for your answer. Do you have any idea how can I remove nodes that are not leaf (Text) nodes? At [0] I have a numbered list, I want to delete it entirely. I think that this would be a useful walk-around for me to the issue.

TheSpyder commented 4 years ago

I'm a little surprised normalisation doesn't adjust the empty document, but I guess it can't know how your elements are structured. Anyway, there are a couple of ways to fix this. Note that text nodes must have blocks around them, so both of these require changing the insert to { children: [{text: 'a'}] }