Best way to find a position of a node

Hi.

What’s the best way to find the absolute position of a node inside a doc? For now, I’m using the brute-force approach to find the position.

function findNodePosition(doc, target: Node) {
  let result = -1;
  doc.descendants((node, pos) => {
    if (target === node) {
      result = pos;
      return false;
    }
  });
  return result;
}

Couple things that that also help the performance

  • Is it safe to cache (memoize) the result given the same inputs (doc and node)? I’d assume that as long as the same node and document is checked, the same position should be returned?

  • Is there any short path that I may take without looking up all dependents? For example, it seems straightforward skip all the nodes that don’t contain the target node.

Thanks.

It sounds like you’re treating the node’s object identity as a reliable way to identify it, which is not a good idea (the same node object may occur multiple times in a document, or it may be replaced with another object that has the same content by a step). Nodes are ‘value types’ — their content is what matters, their object identity shouldn’t be used.

So, given that, you are probably asking the wrong question. If you want to track a node, get its initial position and map that position through transactions.

1 Like

I see.

No wonder all the mutation APIs take pos as argument, instead of the node. Thanks for the correction :slight_smile: