Blame view

lib/jsdom/living/helpers/node.js 1.29 KB
858f2bdf5   Boyan Georgiev   fixes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
  "use strict";
  
  const NODE_TYPE = require("../node-type");
  const { domSymbolTree } = require("./internal-constants");
  
  // https://dom.spec.whatwg.org/#concept-node-length
  function nodeLength(node) {
    switch (node.nodeType) {
      case NODE_TYPE.DOCUMENT_TYPE_NODE:
        return 0;
  
      case NODE_TYPE.TEXT_NODE:
      case NODE_TYPE.PROCESSING_INSTRUCTION_NODE:
      case NODE_TYPE.COMMENT_NODE:
        return node.data.length;
  
      default:
        return domSymbolTree.childrenCount(node);
    }
  }
  
  // https://dom.spec.whatwg.org/#concept-tree-root
  function nodeRoot(node) {
    while (domSymbolTree.parent(node)) {
      node = domSymbolTree.parent(node);
    }
  
    return node;
  }
  
  // https://dom.spec.whatwg.org/#concept-tree-inclusive-ancestor
  function isInclusiveAncestor(ancestorNode, node) {
    while (node) {
      if (ancestorNode === node) {
        return true;
      }
  
      node = domSymbolTree.parent(node);
    }
  
    return false;
  }
  
  // https://dom.spec.whatwg.org/#concept-tree-following
  function isFollowing(nodeA, nodeB) {
    if (nodeA === nodeB) {
      return false;
    }
  
    let current = nodeB;
    while (current) {
      if (current === nodeA) {
        return true;
      }
  
      current = domSymbolTree.following(current);
    }
  
    return false;
  }
  
  module.exports = {
    nodeLength,
    nodeRoot,
  
    isInclusiveAncestor,
    isFollowing
  };