All files / src get-diff-path.js

93.55% Statements 29/31
85% Branches 17/20
100% Functions 4/4
93.1% Lines 27/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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              19x 1x     18x 18x 18x 2x     16x 16x 2x       14x                 13x 13x   13x 51x   51x 19x 19x 19x       32x 23x 23x             9x     42x 19x 19x 18x         13x    
import { isParentNode, isElement } from './parse5-utils';
 
/**
 * @param {*} node The AST Node
 * @returns {string | null} the AST node name
 */
function getNodeName(node) {
  if (!isElement(node)) {
    return null;
  }
 
  Eif (node.attrs) {
    const idAttr = node.attrs.find(attr => attr.name === 'id');
    if (idAttr) {
      return `${node.nodeName}#${idAttr.value}`;
    }
 
    const classAttr = node.attrs.find(attr => attr.name === 'class');
    if (classAttr) {
      return `${node.nodeName}.${classAttr.value.split(' ').join('.')}`;
    }
  }
 
  return node.nodeName;
}
 
/**
 * @param {ASTNode | ASTNode[]} root the root to walk from
 * @param {string[]} path the full path to the dom element
 * @returns {string[]} the human readable path to a dom element
 */
export function getDiffPath(root, path) {
  const names = [];
  let node = root;
 
  for (let i = 0; i < path.length; i += 1) {
    const step = path[i];
 
    if (Array.isArray(node)) {
      const intStep = parseFloat(step);
      Eif (Number.isInteger(intStep)) {
        node = node[intStep];
      } else {
        throw new Error(`Non-integer step: ${step} for array node.`);
      }
    } else if (step === 'childNodes') {
      Eif (isParentNode(node)) {
        node = node.childNodes;
      } else {
        throw new Error('Cannot read childNodes from non-parent node.');
      }
    } else {
      // Break loop if we end up at a type of path section we don't want
      // walk further into
      break;
    }
 
    if (!Array.isArray(node)) {
      const name = getNodeName(node);
      if (name) {
        names.push(name);
      }
    }
  }
 
  return names.join(' > ');
}