Getting the last node and its pos in the document

Hey,

I’m trying to get the last node and its position in the document. I just can’t seem to find out how to do it. I know I can get the last node by: state.doc.lastChild however, how do I get its position?

I’m trying to place the cursor (selection) at the very beginning of that node. However, in order to change the selection, I need a pos.

How can I get the position of the node?

Thanks

You can do this to get a before of the last node:

editor.state.doc.content.size - editor.state.doc.lastChild.nodeSize

Add a 1 to get the start of last node, provided it is a text node.

That said, curious to hear what the most pragmatic approach to this will be, I did consider doing something like

editor.state.doc.descendants((node, pos) => 
  node === editor.state.doc.lastChild && console.log(node, pos)
)

but I feel that it is inefficient to iterate through all the nodes just for finding the position.

Hey @kepta

I guess your solution is right. I will give it a shot and let you know.

By the way, I think the most pragmatic way to do this is:

const startPos = editor.state.doc.content.size - editor.sate.doc.lastChild.nodeSize;
const endPos = editor.state.doc.content.size;
editor.state.doc.nodesBetween(startPos, endPos, (node, pos) => {
  console.log(node, pos);

  return false; // don't recurse into the node.
});

Well, it worked. Didn’t need to add 1 to the result.

I’ve created a TextSelection with a resolved pos:

const pos = editor.state.doc.content.size - editor.sate.doc.lastChild.nodeSize;
const {tr} = editor.state;
tr.setSelection(
  new TextSelection(editor.state.doc.resolve(pos))
);
state.view.dispatch(tr);

glad it worked out. you can also use the static method create to directly use the numerical position instead of resolving it. As far as I understand, adding 1 is important if you want to insert at start but still inside the the last node.