All files / lib/filter removeGroups.js

88% Statements 22/25
52.17% Branches 12/23
100% Functions 5/5
88% Lines 22/25

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 69 70 71 722x                           2x 1x   1x 2x 2x 2x 2x   2x 2x     2x     2x                     2x 2x     2x         1x             2x 1x 1x 1x 1x                 2x  
const { SLICE } = require('../utils.js')
 
/**
 * transRemoveNode 递归遍历去除<g>
 * @example
 * <g transform="scale(2)">
 *     <path transform="rotate(45)" d="M0,0 L10,20"/>
 *     <path transform="translate(10, 20)" d="M0,10 L20,30"/>
 * </g>
 *                          ⬇
 * <path transform="scale(2) rotate(45)" d="M0,0 L10,20"/>
 * <path transform="scale(2) translate(10, 20)" d="M0,10 L20,30"/>
 * @param {*} node
 */
const transRemoveNode = node => {
  const ATTR = SLICE.call(node.attributes)
 
  SLICE.call(node.childNodes).map(item => {
    Eif (ATTR.length > 0) {
      ATTR.map(attr => {
        Eif (attr.nodeName.toLowerCase() === 'transform') {
          let transfromStr = attr.value
 
          Eif (item.hasAttribute('transform')) {
            transfromStr += ` ${item.getAttribute('transform')}`
          }
 
          item.setAttribute(attr.nodeName, transfromStr)
        }
 
        Iif (
          item.hasAttribute &&
          !item.hasAttribute(attr.nodeName) &&
          attr.nodeName.toLowerCase() !== 'transform'
        ) {
          item.setAttribute(attr.nodeName, attr.value)
        }
      })
    }
 
    // 除了 <g></g> 以外都 insert Node
    Eif (!(item.nodeName.toUpperCase() === 'G' && !item.hasChildNodes())) {
      node.parentNode.insertBefore(item, node)
    }
 
    Iif (item.nodeName.toUpperCase() === 'G' && item.hasChildNodes()) {
      transRemoveNode(item)
    }
  })
 
  node.parentNode.removeChild(node)
}
 
/**
 * removeGroups 去除 <g> 插件方法
 * @param {*} Doc
 */
const removeGroups = Doc => {
  SLICE.call(Doc.documentElement.childNodes).forEach(node => {
    Eif (node.nodeName.toUpperCase() === 'G') {
      Eif (node.hasChildNodes()) {
        transRemoveNode(node)
      } else {
        // empty
        node.parentNode.removeChild(node)
      }
    }
  })
}
 
exports.fn = removeGroups