Need some clarification regarding the getPos() function of a custom view

Hello,

I’m implementing a custom view, but I’m not sure about the behavior of the getPos() function. The document (ProseMirror Guide) doesn’t seem to mention its details. As we know, a node can span multiple positions. Which position is the one returned by getPos? is it the first position?

If I have nested nodes like this, and a custom view for the parent_node

<parent_node>
<child_node></child_node>
</parent_node>

Will getPos() + this.view.state.doc.nodeAt() guarantee to return the parentNode?

  const pos = this.getPos();
  const currentNode = this.view.state.doc.nodeAt(pos);
  if (!currentNode) return;

Or do I need to traverse the document tree upwards until I see the parentNode?

  const { $from } = state.selection;
  
  // Walk up the tree to find the node
  for (let depth = $from.depth; depth >= 0; depth--) {
    const node = $from.node(depth);
    if (node.type.name === 'parent_node') {
      return { node, pos: $from.start(depth) };
    }
  }

It will return the position right in front of the node that the view represents.

Thank you very much! but I feel that “in front of” is a bit unclear,

0 <parent_node> 1 <child_node> 2 </child_node> </parent_node>

is it 0 or 1?

In front of means before the node’s opening token.