Refactored.

This commit is contained in:
Alexandre Gigliotti
2015-07-23 08:28:22 -07:00
parent e5e1f08fba
commit f4085786f6
13 changed files with 180 additions and 65 deletions

View File

@@ -1,68 +1,29 @@
var _ = require('lodash');
var co = require('co');
var inlineLess = require('inline-less');
var inlineCssUrl = require('inline-css-url');
var cheerio = require('cheerio');
var string = require('string');
var fs = require('mz/fs');
var inlineCss = require('./inline-css');
var inlineImg = require('./inline-img');
var inlineLinkLess = require('./inline-link-less');
// TODO refactor into separate module
// inline html images
var isLocalPath = require('is-local-path');
var datauri = require('datauri');
var path = require('path');
var inlineImg = function (html, filePath) {
var basedir = path.dirname(filePath);
var $ = cheerio.load(html);
var images = $('img').filter(function (index, element) {
return isLocalPath($(element).attr('src'));
var inline = co.wrap(function * (filename, options) {
options = _.defaults(options || {}, {
less: {}
});
images.each(function (index, element) {
var src = $(element).attr('src');
var filePath = path.resolve(basedir, src);
src = datauri(filePath);
$(element).attr('src', src);
});
return $.html();
};
var html = yield fs.readFile(filename, 'utf8');
// TODO refactor into separate module
// inline html url css data types
var inlineUrl = function (html, filePath) {
var $ = cheerio.load(html);
// style elements
var styles = $('style');
styles.each(function (index, element) {
var css = $(element).html();
css = inlineCssUrl(css, filePath);
$(element).html(css);
});
// style attributes
var attributes = $('body *').filter('[style]');
attributes.each(function (index, element) {
var css = $(element).attr('style');
var prefix = 'element {';
var suffix = '}';
css = prefix + css + suffix;
css = inlineCssUrl(css, filePath);
css = string(css).collapseWhitespace().toString();
css = css.replace(new RegExp('^' + prefix + '\\s*(.*)\\s+' + suffix + '$'), '$1');
$(element).attr('style', css);
});
return $.html();
};
var inline = co.wrap(function * (filePath, options) {
var html = yield fs.readFile(filePath, 'utf8');
// inline links: less
html = yield inlineLess(html, filePath, options);
// Inline links
html = yield inlineLinkLess(html, filename, options.less);
// TODO inline links: css
// TODO inline scripts (js + browserify? = scriptify)
// Inline local assets (path -> datauri)
html = inlineUrl(html, filePath);
html = inlineImg(html, filePath);
// svg?
// TODO inline scripts
// browserify js? => scriptify
// Inline paths -> datauris
html = inlineCss(html, filename);
html = inlineImg(html, filename);
return html;
});
module.exports = inline;