Inserting a new node at the end of a node and set selection causes range error

I am inserting a new paragraph node at the end of current node. This action is executed when the user presses the Enter key. After inserting, I want to set cursor position to the newly created paragraph node. So, for user, the cursor moves down to the next line.

export const handleKeyDown = (view, event) => {
  if (view.state.selection.$anchor.parent.type.name === 'figcaption') {
    if (event.key === 'Enter') {
      const figure = findParentNodeOfType(view.state.schema.nodes.figure)(
        view.state.selection,
      )
      const tr = view.state.tr
        .insert(
          figure.pos + figure.node.nodeSize,
          view.state.schema.nodes.paragraph.create(),
        )
        .setSelection(
          TextSelection.near(
            view.state.doc.resolve(figure.pos + figure.node.nodeSize + 1),
          ),
        )
      view.dispatch(tr)
      return true
    }
  }

But index.js?6f27:1048 Uncaught RangeError: Position 17 out of range error is thrown.

You appear to be basing the new selection on the old document (view.state.doc). Do the doc update .insert(...) first, and then in a new call to tr.setSelection, base the selection on tr.doc instead of view.state.doc.

1 Like

That works like a charm.