Find text node containing a given ResolvedPos

ResolvedPos has the node method that can return ancestor nodes that contain a given pos, according to the depth param passed.

However when the pos is inside a text node, it doesn’t seem possible to get that node. e.g. say I have $pos for a position inside some text in a paragraph, and $pos.node(3) returns the paragraph node, I would expect $pos.node(4) to return the text node, but it returns null.

Is this by design?

To get the text node I’ve had to do

$pos.doc.nodeAt($pos.pos - $pos.textOffset)

That’s not too bad, but is there a cleaner way I’m missing?

$pos.parent.maybeChild($pos.index()) also works (but note that this may return null when the position is at the end of the node). There are relatively few reasons to access a text node like this, so the API has no specialized functionality for it.


There are relatively few reasons to access a text node like this

That makes me wonder if I’m taking the wrong approach to my wider goal here, which is making an editor for the href attribute of a link mark. I want the editor to appear when the caret is inside the link. Obviously edits need to apply to the entire link, so I need to find the text node which has the link mark applied (plus, possibly, adjacent nodes with the same).

Which probably means you need to do something more involved than just accessing the direct text node around the cursor, such as iterating forwards and backwards from its index to include other nodes with the same link mark.