Code coverage report for juice\client.js

Statements: 97.13% (169 / 174)      Branches: 93.27% (97 / 104)      Functions: 100% (25 / 25)      Lines: 97.13% (169 / 174)      Ignored: none     

All files » juice\ » client.js
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321    1   1 2 2   2       2       1   1 1 1 1 1 1             1 1 1   1   51 51   51 51   51 2     51 2 11       51 1 5       51 1     1 366 366 366 366 366     366 400 400 37 37 37 6           360 20 20 20 20 20     360 360 360     4     356 187   187 7     180 18 18 18 8 8 8 8   18     180 117     117 3 3       117       1 183 416 416 416 416 416   416 408         180       1 117 369       117 292     117       369     361     117 115       1 13 8 8 8 2     6         1 16 16 8 8 8 4 4 4   4 2 2             1 3     3 2 4 4             1 8         8   8 8         1 366       366 366 329     37 37 20         1 57     1 20 20       1 22 22 22 22 22     1 29 29   29       29       1 22 22 22 22 19 19 19     19 19 18   19   18       18   2       16     19   22     1 22 22 22    
 "use strict";
 
var utils = require('./lib/utils');
 
var juiceClient = function (html,options) {
  var $ = utils.cheerio(html, { xmlMode: options && options.xmlMode});
  var doc = juiceDocument($,options);
 
  Iif (options && options.xmlMode){
    return doc.xml();
  }
  else {
    return utils.decodeEntities(doc.html());
  }
};
 
module.exports = juiceClient;
 
juiceClient.ignoredPseudos = ['hover', 'active', 'focus', 'visited', 'link'];
juiceClient.widthElements = ['TABLE', 'TD', 'IMG'];
juiceClient.heightElements = ['TABLE', 'TD', 'IMG'];
juiceClient.tableElements = ['TABLE', 'TD', 'TH', 'TR', 'TD', 'CAPTION', 'COLGROUP', 'COL', 'THEAD', 'TBODY', 'TFOOT'];
juiceClient.nonVisualElements = [ "HEAD", "TITLE", "BASE", "LINK", "STYLE", "META", "SCRIPT", "NOSCRIPT" ];
juiceClient.styleToAttribute = {
  'background-color': 'bgcolor',
  'background-image': 'background',
  'text-align': 'align',
  'vertical-align': 'valign'
};
 
juiceClient.juiceDocument = juiceDocument;
juiceClient.inlineDocument = inlineDocument;
juiceClient.inlineContent = inlineContent;
 
function inlineDocument($, css, options) {
 
  var rules = utils.parseCSS(css);
  var editedElements = [];
 
  rules.forEach(handleRule);
  editedElements.forEach(setStyleAttrs);
 
  if (options && options.inlinePseudoElements) {
    editedElements.forEach(inlinePseudoElements);
  }
 
  if (options && options.applyWidthAttributes) {
    editedElements.forEach(function(el) {
      setDimensionAttrs(el, 'width');
    });
  }
 
  if (options && options.applyHeightAttributes) {
    editedElements.forEach(function(el) {
      setDimensionAttrs(el, 'height');
    });
  }
 
  if (options && options.applyAttributesTableElements) {
    editedElements.forEach(setAttributesOnTableElements);
  }
 
  function handleRule(rule) {
    var sel = rule[0];
    var style = rule[1];
    var selector = new utils.Selector(sel);
    var parsedSelector = selector.parsed();
    var pseudoElementType = getPseudoElementType(parsedSelector);
 
    // skip rule if the selector has any pseudos which are ignored
    for (var i = 0; i < parsedSelector.length; ++i) {
      var subSel = parsedSelector[i];
      if (subSel.pseudos) {
        for (var j = 0; j < subSel.pseudos.length; ++j) {
          var subSelPseudo = subSel.pseudos[j];
          if (juiceClient.ignoredPseudos.indexOf(subSelPseudo.name) >= 0) {
            return;
          }
        }
      }
    }
 
    if (pseudoElementType) {
      var last = parsedSelector[parsedSelector.length - 1];
      var pseudos = last.pseudos;
      last.pseudos = filterElementPseudos(last.pseudos);
      sel = parsedSelector.toString();
      last.pseudos = pseudos;
    }
 
    var els;
    try {
      els = $(sel);
    } catch (err) {
      // skip invalid selector
      return;
    }
 
    els.each(function () {
      var el = this;
 
      if (el.name && juiceClient.nonVisualElements.indexOf(el.name.toUpperCase()) >= 0) {
          return;
      }
 
      if (pseudoElementType) {
        var pseudoElPropName = "pseudo" + pseudoElementType;
        var pseudoEl = el[pseudoElPropName];
        if (!pseudoEl) {
          pseudoEl = el[pseudoElPropName] = $("<span />").get(0);
          pseudoEl.pseudoElementType = pseudoElementType;
          pseudoEl.pseudoElementParent = el;
          el[pseudoElPropName] = pseudoEl;
        }
        el = pseudoEl;
      }
 
      if (!el.styleProps) {
        el.styleProps = {};
 
        // if the element has inline styles, fake selector with topmost specificity
        if ($(el).attr('style')) {
          var cssText = '* { ' + $(el).attr('style') + ' } ';
          addProps(utils.parseCSS(cssText)[0][1], utils.styleSelector);
        }
 
        // store reference to an element we need to compile style="" attr for
        editedElements.push(el);
      }
 
      // go through the properties
      function addProps (style, selector) {
        for (var i = 0, l = style.length; i < l; i++) {
          var name = style[i];
          var value = style[name] + (options && options.preserveImportant && style._importants[name] ? ' !important' : '');
          var sel = style._importants[name] ? utils.importantSelector : selector;
          var prop = new utils.Property(name, value, sel);
          var existing = el.styleProps[name];
 
          if (existing && existing.compare(prop) === prop || !existing) {
            el.styleProps[name] = prop;
          }
        }
      }
 
      addProps(style, selector);
    });
  }
 
  function setStyleAttrs(el) {
    var props = Object.keys(el.styleProps).map(function(key) {
      return el.styleProps[key];
    });
    // sort properties by their originating selector's specificity so that
    // props like "padding" and "padding-bottom" are resolved as expected.
    props.sort(function(a, b) {
      return a.selector.specificity().join("").localeCompare(
        b.selector.specificity().join(""));
    });
    var string = props
      .filter(function(prop) {
        // Content becomes the innerHTML of pseudo elements, not used as a
        // style property
        return prop.prop !== "content";
      })
      .map(function(prop) {
        return prop.prop + ": " + prop.value.replace(/["]/g, "'") + ";";
      })
      .join(" ");
    if (string) {
      $(el).attr('style', string);
    }
  }
 
  function inlinePseudoElements(el) {
    if (el.pseudoElementType && el.styleProps.content) {
      $(el).html(parseContent(el.styleProps.content.value));
      var parent = el.pseudoElementParent;
      if (el.pseudoElementType === "before") {
        $(parent).prepend(el);
      }
      else {
        $(parent).append(el);
      }
    }
  }
 
  function setDimensionAttrs(el, dimension) {
    var elName = el.name.toUpperCase();
    if (juiceClient[dimension + 'Elements'].indexOf(elName) > -1) {
      for (var i in el.styleProps) {
        Eif (el.styleProps[i].prop === dimension) {
          if (el.styleProps[i].value.match(/px/)) {
            var pxSize = el.styleProps[i].value.replace('px', '');
            $(el).attr(dimension, pxSize);
            return;
          }
          if (juiceClient.tableElements.indexOf(elName) > -1 && el.styleProps[i].value.match(/\%/)) {
            $(el).attr(dimension, el.styleProps[i].value);
            return;
          }
        }
      }
    }
  }
 
  function setAttributesOnTableElements(el) {
    var elName = el.name.toUpperCase(),
        styleProps = Object.keys(juiceClient.styleToAttribute);
 
    if (juiceClient.tableElements.indexOf(elName) > -1) {
      for (var i in el.styleProps) {
        Eif (styleProps.indexOf(el.styleProps[i].prop) > -1) {
          $(el).attr(juiceClient.styleToAttribute[el.styleProps[i].prop], el.styleProps[i].value);
        }
      }
    }
  }
}
 
function parseContent(content) {
  Iif (content === "none" || content === "normal") {
    return "";
  }
 
  // Naive parsing, assume well-formed value
  content = content.slice(1, content.length - 1);
  // Naive unescape, assume no unicode char codes
  content = content.replace(/\\/g, "");
  return content;
}
 
// Return "before" or "after" if the given selector is a pseudo element (e.g.,
// a::after).
function getPseudoElementType(selector) {
  Iif (selector.length === 0) {
    return;
  }
 
  var pseudos = selector[selector.length - 1].pseudos;
  if (!pseudos) {
    return;
  }
 
  for (var i = 0; i < pseudos.length; i++) {
    if (isPseudoElementName(pseudos[i])) {
      return pseudos[i].name;
    }
  }
}
 
function isPseudoElementName(pseudo) {
  return pseudo.name === "before" || pseudo.name === "after";
}
 
function filterElementPseudos(pseudos) {
  return pseudos.filter(function(pseudo) {
    return !isPseudoElementName(pseudo);
  });
}
 
function juiceDocument($, options) {
  options = utils.getDefaultOptions(options);
  var css = extractCssFromDocument($, options);
  css += "\n" + options.extraCss;
  inlineDocument($, css, options);
  return $;
}
 
function inlineContent(html, css, options) {
    var $ = utils.cheerio(html, { xmlMode: options && options.xmlMode});
    inlineDocument($, css, options);
 
    Iif (options && options.xmlMode){
      return $.xml();
    }
    else {
      return utils.decodeEntities($.html());
    }
}
 
function getStylesData($, options) {
  var results = [];
  var stylesList = $("style");
  var styleDataList, styleData, styleElement;
  stylesList.each(function () {
    styleElement = this;
    styleDataList = styleElement.childNodes;
    Iif (styleDataList.length !== 1) {
      return;
    }
    styleData = styleDataList[0].data;
    if ( options.applyStyleTags && styleElement.attribs['data-embed'] === undefined  ) {
      results.push( styleData );
    }
    if ( options.removeStyleTags && styleElement.attribs['data-embed'] === undefined  )
    {
      var preservedText = utils.getPreservedText( styleElement.childNodes[0].nodeValue, {
          mediaQueries: options.preserveMediaQueries,
          fontFaces: options.preserveFontFaces
      } );
      if ( preservedText )
      {
        styleElement.childNodes[0].nodeValue = preservedText;
      }
      else
      {
        $(styleElement).remove();
      }
    }
    delete styleElement.attribs['data-embed'];
  });
  return results;
}
 
function extractCssFromDocument($, options) {
  var results = getStylesData($, options);
  var css = results.join("\n");
  return css;
}