compareDocumentPosition method
Implementation
DocumentPosition compareDocumentPosition(Node other) {
if (this == other) {
return DocumentPosition.EQUIVALENT;
}
// We need to find a common ancestor container, and then compare the indices of the two immediate children.
List<Node> chain1 = [];
List<Node> chain2 = [];
Node? current = this;
while (current != null && current.parentNode != null) {
chain1.insert(0, current);
current = current.parentNode;
}
current = other;
while (current != null && current.parentNode != null) {
chain2.insert(0, current);
current = current.parentNode;
}
// If the two elements don't have a common root, they're not in the same tree.
if (chain1.first != chain2.first) {
return DocumentPosition.DISCONNECTED;
}
// Walk the two chains backwards and look for the first difference.
for (int i = 0; i < math.min(chain1.length, chain2.length); i++) {
if (chain1[i] != chain2[i]) {
if (chain2[i].nextSibling == null) {
return DocumentPosition.FOLLOWING;
}
if (chain1[i].nextSibling == null) {
return DocumentPosition.PRECEDING;
}
// Otherwise we need to see which node occurs first. Crawl backwards from child2 looking for child1.
Node? previousSibling = chain2[i].previousSibling;
while (previousSibling != null) {
if (chain1[i] == previousSibling) {
return DocumentPosition.FOLLOWING;
}
previousSibling = previousSibling.previousSibling;
}
return DocumentPosition.PRECEDING;
}
}
// There was no difference between the two parent chains, i.e., one was a subset of the other. The shorter
// chain is the ancestor.
return chain1.length < chain2.length ? DocumentPosition.FOLLOWING : DocumentPosition.PRECEDING;
}