All files / src normalize-ast.js

95% Statements 19/20
92.31% Branches 12/13
100% Functions 7/7
94.44% Lines 17/18

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      1x     649x       486x     262x 20x     262x       150x 150x   150x 58x     92x 92x                           792x 486x     792x 649x 644x      
/* eslint-disable no-param-reassign */
import { isElement, isParentNode } from './parse5-utils';
 
const defaultIgnoresTags = ['style', 'script', '#comment'];
 
function filterNode(node, ignoredTags) {
  return !defaultIgnoresTags.includes(node.nodeName) && !ignoredTags.includes(node.nodeName);
}
 
function sortAttributes(attrs) {
  return attrs
    // Sort attributes
    .map((attr) => {
      if (attr.name === 'class') {
        attr.value = attr.value.trim().split(/\s+/).sort().join(' ');
      }
 
      return attr;
    })
    // Sort classes
    .sort((attrA, attrB) => {
      const a = attrA.name.toLowerCase();
      const b = attrB.name.toLowerCase();
 
      if (a < b) {
        return -1;
      }
 
      Eif (a > b) {
        return 1;
      }
 
      return 0;
    });
}
 
/**
 * Normalized AST tree, normlaizing whitespace, attribute + class order etc. Not a pure function,
 * mutates input.
 * @param {ASTNode} node
 * @param {string[]} ignoredTags
 */
export function normalizeAST(node, ignoredTags = []) {
  if (isElement(node)) {
    node.attrs = sortAttributes(node.attrs);
  }
 
  if (isParentNode(node)) {
    node.childNodes = node.childNodes.filter(child => filterNode(child, ignoredTags));
    node.childNodes.forEach(child => normalizeAST(child, ignoredTags));
  }
}