Code coverage report for juice\lib\juice.js

Statements: 94.49% (120 / 127)      Branches: 79.17% (38 / 48)      Functions: 95% (19 / 20)      Lines: 95.12% (117 / 123)      Ignored: none     

All files » juice\lib\ » juice.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              1       1           1                           1           1           1           1     1 1   1 1 1 1 1   1   29     29 29   29 1     1 234         234 234 256 256 16 16 16         228 228 228     8   220 59 59 41     41 3 3       41       1 62 80           80 11     11   69         59       1 41 41 69     41   39 39 39   41     1 3 3 2 2 2 2 2             1 8 8 8 8 8 8             1 8   8 8     8 8     8         8     1 21                     1   5 5 5 5 5 5   5       1 21 21     21 21     21     1 8 8 8 8 8 8 8     8 8 8   8   1 1       7       8     1 8 8 8      
 
/**
 * juice
 * Copyright(c) 2011 LearnBoost <dev@learnboost.com>
 * MIT Licensed
 */
 
var juice = function () {
  throw new Error("The juice() function has been removed; use juice.juiceDocument, juice.juiceFile, or juice.juiceContent.");
};
 
module.exports = juice;
 
/**
 * Module dependencies.
 */
 
var utils = require('./utils')
  , Selector = require('./selector')
  , Property = require('./property')
  , packageJson = require('../package')
  , fs = require('fs')
  , path = require('path')
  , assert = require('assert')
  , styleSelector = new Selector('<style attribute>', [1, 0, 0, 0])
  , importantSelector = new Selector('<!important>', [2, 0, 0, 0]);
 
/**
 * Package version
 */
 
juice.version = packageJson.version;
 
/**
 * Export Selector.
 */
 
juice.Selector = Selector;
 
/**
 * Export Property.
 */
 
juice.Property = Property;
 
/**
 * Export utils.
 */
 
juice.utils = require('./utils');
 
 
juice.ignoredPseudos = ['hover', 'active', 'focus', 'visited', 'link'];
juice.widthElements = ['TABLE', 'TD', 'IMG'];
 
juice.juiceDocument = juiceDocument;
juice.juiceContent = juiceContent;
juice.juiceFile = juiceFile;
juice.inlineDocument = inlineDocument;
juice.inlineContent = inlineContent;
 
function inlineDocument($, css, options) {
 
  var rules = utils.parseCSS(css)
    , editedElements = [];
 
  rules.forEach(handleRule);
  editedElements.forEach(setStyleAttrs);
 
  if (options && options.applyWidthAttributes) {
    editedElements.forEach(setWidthAttrs);
  }
 
  function handleRule(rule) {
    var sel = rule[0]
      , style = rule[1]
      , selector = new Selector(sel);
 
    // skip rule if the selector has any pseudos which are ignored
    var parsedSelector = selector.parsed();
    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 (juice.ignoredPseudos.indexOf(subSelPseudo.name) >= 0) return;
        }
      }
    }
 
    var els;
    try {
      els = $(sel);
    } catch (err) {
      // skip invalid selector
      return;
    }
    els.each(function () {
      var el = this;
      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], 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]
            , value = style[name]
            , sel = style._importants[name] ? importantSelector : selector
            , prop = new Property(name, value, sel)
            , existing = el.styleProps[name];
 
          if (existing) {
            var winner = existing.compare(prop)
              , loser = prop === winner ? existing : prop
 
            if (winner === prop) el.styleProps[name] = prop;
          } else {
            el.styleProps[name] = prop;
          }
        }
      }
 
      addProps(style, selector);
    });
  }
 
  function setStyleAttrs(el) {
    var style = [];
    for (var i in el.styleProps) {
      style.push(el.styleProps[i].prop + ": " + el.styleProps[i].value.replace(/["]/g, "'") + ";");
    }
    // sorting will arrange styles like padding: before padding-bottom: which will preserve the expected styling
    style = style.sort( function ( a, b )
    {
      var aProp = a.split( ':' )[0];
      var bProp = b.split( ':' )[0];
      return ( aProp > bProp ? 1 : aProp < bProp ? -1 : 0 );
    } );
    $(el).attr('style', style.join(' '));
  }
 
  function setWidthAttrs(el) {
    var elName = el.name.toUpperCase();
    if (juice.widthElements.indexOf(elName) > -1) {
      for (var i in el.styleProps) {
        Eif (el.styleProps[i].prop === 'width' && el.styleProps[i].value.match(/px/)) {
          var pxWidth = el.styleProps[i].value.replace('px', '');
          $(el).attr('width', pxWidth);
          return;
        }
      }
    }
  }
}
 
function juiceDocument($, options, callback) {
  try {
    options = getDefaultOptions(options);
    var css = extractCssFromDocument($, options);
    css += "\n" + options.extraCss;
    inlineDocument($, css, options);
    callback(null, $);
  }
  catch(err){
    callback(err);
  }
}
 
function juiceContent(html, options, callback) {
  options = getDefaultOptions(options);
 
  var onDom = function(err, $) {
    Iif(err){
      return callback(err);
    }
    juiceDocument($, options, function(err) {
      Iif (err) {
        return callback(err);
      } else {
        return callback(null, $.html());
      }
    });
  };
 
  utils.cheerio(html, options, onDom);
}
 
function getDefaultOptions(options) {
  return utils.extend({
    extraCss: "",
    applyStyleTags: true,
    removeStyleTags: true,
    applyLinkTags: true,
    removeLinkTags: true,
    preserveMediaQueries: false,
    applyWidthAttributes: false,
  }, options);
}
 
function juiceFile(filePath, options, callback) {
  // set default options
  fs.readFile(filePath, 'utf8', function(err, content) {
    Iif (err) return callback(err);
    options = getDefaultOptions(options); // so we can mutate options without guilt
    Eif(!options.relativeTo){
      var rel = path.dirname(path.relative(process.cwd(),filePath));
      options.relativeTo = rel;
    };
    juiceContent(content, options, callback);
  });
}
 
function inlineContent(html, css, options, callback) {
  var onDom = function(err, $){
    Iif(err){
      return callback(err);
    }
    inlineDocument($, css, {});
    callback(null, $.html());
  }
 
  utils.cheerio(html, options, onDom);
}
 
function getStylesData($, options) {
  var results = [];
  var stylesList = $("style");
  var i, styleDataList, styleData, styleElement;
  stylesList.each(function () {
    styleElement = this;
    styleDataList = styleElement.childNodes;
    Iif (styleDataList.length !== 1) {
      return;
    }
    styleData = styleDataList[0].data;
    Eif ( options.applyStyleTags ) results.push( styleData );
    Eif ( options.removeStyleTags )
    {
      if ( options.preserveMediaQueries )
      {
        var mediaQueries = utils.getMediaQueryText( styleElement.childNodes[0].nodeValue );
        styleElement.childNodes[0].nodeValue = mediaQueries;
      }
      else
      {
        $(styleElement).remove();
      }
    }
  });
  return results;
}
 
function extractCssFromDocument($, options) {
  var results = getStylesData($, options);
  var css = results.join("\n");
  return css;
}