Approaches for finding the position of nodes

After numerous attempts I think I’m finally getting the hang of this.

For example, to get the start/end positions of the previous node in the document:

// first get the index of the current node at the root level
const parentIndex = $cursor.index(0);

// iterate the doc to find the offset of the previous index
let startPos, endPos;

doc.forEach((node, offset, index) => {
    if (index === parentIndex - 1) {
        startPos = offset;
        endPos = offset + node.nodeSize;
    }
});

Or to get the positions of the last child of the previous block:

doc.forEach((node, offset, index) => {
    if (index === parentIndex - 1) {
        node.forEach((childNode, childOffset, childIndex) => {
            if (childIndex === node.childCount - 1) {
                startPos = offset + childOffset;
                endPos = startPos + node.nodeSize;
            }
        })
    }
});

I tried many attempts which all ended up using node.eq(anotherNode) to determine if I had “found” the node I was interested in, but as @marijn has stated this is a bad idea. When iterating it’s possible you could get a different node if these are identical.

I also tried resolving positions inside a node (other than the document) but this was useless. All transforms require absolute global positions and I couldn’t find a way to “translate” a local position to a global one.