Skip to content

Commit

Permalink
refactor: simplify code and use of async/await inplace of async lib
Browse files Browse the repository at this point in the history
BREAKING CHANGE
node.js 7.6+ is now needed
  • Loading branch information
Nadav Sinai committed Oct 11, 2018
1 parent 6a17835 commit 123eeae
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 58 deletions.
59 changes: 26 additions & 33 deletions src/helpers/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const parse = require('htmlparser2');
* @param {string} template
* @return {string}
*/
const _createSprite = function(data, template) {
const _createSprite = function (data, template) {
return pug.renderFile(template, data);
};

Expand All @@ -27,7 +27,7 @@ const _createSprite = function(data, template) {
* @param {integer} depth Depth level
* @return {void}
*/
const _log = function(subject, depth) {
const _log = function (subject, depth) {
console.log(util.inspect(subject, {
showHidden: true, depth: depth || 2
}));
Expand All @@ -39,7 +39,7 @@ const _log = function(subject, depth) {
* @param {string} id
* @return {void}
*/
const _fixIds = function(obj, id) {
const _fixIds = function (obj, id) {
// add id
if (obj.attribs && obj.attribs.id) {
obj.attribs.id = [id, obj.attribs.id].join('-');
Expand All @@ -56,7 +56,7 @@ const _fixIds = function(obj, id) {
* @param {string} id
* @return {void}
*/
const _fixUrls = function(obj, id) {
const _fixUrls = function (obj, id) {
let key;
let match;
const json = obj.attribs;
Expand All @@ -78,9 +78,8 @@ const _fixUrls = function(obj, id) {
* @param {[type]} id [description]
* @return {[type]} [description]
*/
const _parseSVG = function(arr, id) {
const data = [];
arr.forEach(function(obj) {
const _parseSVG = function (arr, id) {
arr.forEach(function (obj) {
if (obj) {
// add unic ids to urls
_fixUrls(obj, id);
Expand All @@ -90,11 +89,8 @@ const _parseSVG = function(arr, id) {
if (obj.children && obj.children.length > 0) {
_parseSVG(obj.children, id);
}
data.push(obj, id);
}
});

return data;
};

/**
Expand All @@ -103,15 +99,16 @@ const _parseSVG = function(arr, id) {
* @param {[type]} data [description]
* @return {[type]} [description]
*/
const _defs = function(id, dom, data) {
const _defs = function (id, dom, data) {
// lets find defs into dom
const defs = _.filter(dom.children, { name: 'defs' });
const parseChilds = function(item, data) {
item.forEach(function(child) {
const defs = _.filter(dom.children, {name: 'defs'});
const parseChilds = function (item, data) {
item.forEach(function (child) {
switch (child.name) {
case 'use': {
child.attribs['xlink:href'] = ['#' + id, child.attribs['xlink:href'].replace('#', '') ].join('-');
} break;
child.attribs['xlink:href'] = ['#' + id, child.attribs['xlink:href'].replace('#', '')].join('-');
}
break;
default:
child.attribs && child.attribs.id
? child.attribs.id = [id, child.attribs.id].join('-')
Expand All @@ -128,7 +125,7 @@ const _defs = function(id, dom, data) {
});
};

defs.forEach(function(item) {
defs.forEach(function (item) {
if (item.children && item.children.length > 0) {
parseChilds(item.children, data);
}
Expand All @@ -143,13 +140,13 @@ const _defs = function(id, dom, data) {
* @param {[type]} data [description]
* @return {[type]} [description]
*/
const _symbols = function(id, dom, data, prefix) {
const _symbols = function (id, dom, data, prefix) {
// create symbol object
const symbol = {
type: 'tag',
name: 'symbol',
attribs: {
viewBox: dom.attribs ? dom.attribs.viewBox: null,
viewBox: dom.attribs ? dom.attribs.viewBox : null,
id: prefix + id
},
next: null,
Expand All @@ -158,7 +155,7 @@ const _symbols = function(id, dom, data, prefix) {
};

// add dom children without defs and titles
symbol.children = _.filter(dom.children, function(obj) {
symbol.children = _.filter(dom.children, function (obj) {
return obj.name !== 'defs' && obj.name !== 'title';
});

Expand All @@ -176,7 +173,7 @@ const _symbols = function(id, dom, data, prefix) {
* @param {string} filename [description]
* @return {string} [description]
*/
const _convertFilenameToId = function(filename) {
const _convertFilenameToId = function (filename) {
return filename.split('.').join('-').toLowerCase();
};

Expand All @@ -185,20 +182,16 @@ const _convertFilenameToId = function(filename) {
* @param {string} input Destination path
* @return {array} Array of paths
*/
const _filesMap = function(input, cb) {
const data = input;

globby(data).then(function(fileList) {
cb(fileList);
});
const _filesMap = function (data) {
return globby(data);
};

/**
* Parse dom objects
* @param {[type]} dom [description]
* @return {[type]} [description]
*/
const _parseDomObject = function(data, filename, dom, prefix) {
const _parseDomObject = function (data, filename, dom, prefix) {
const id = _convertFilenameToId(filename);
if (dom && dom[0]) {
_defs(id, dom[0], data.defs);
Expand All @@ -214,7 +207,7 @@ const _parseDomObject = function(data, filename, dom, prefix) {
* @param {integer} loop loop count
* @return {[type]} minified source
*/
const _minify = function(file, svgoOptions) {
const _minify = function (file, svgoOptions) {
const min = new Svgo(svgoOptions);
let source = file;

Expand All @@ -231,7 +224,7 @@ const _minify = function(file, svgoOptions) {
* [parseFiles description]
* @return {[type]} [description]
*/
const _parseFiles = function(files, options) {
const _parseFiles = function (files, options) {
const self = this;
let data = {
svg: options.svg,
Expand All @@ -240,13 +233,13 @@ const _parseFiles = function(files, options) {
};

// each over files
files.forEach(function(file) {
files.forEach(function (file) {
// load and minify
const buffer = _minify(fs.readFileSync(file, 'utf8'), options.svgoOptions);
// get filename for id generation
const filename = path.basename(file, '.svg');

const handler = new parse.DomHandler(function(error, dom) {
const handler = new parse.DomHandler(function (error, dom) {
if (error) self.log(error);
else data = _parseDomObject(data, filename, dom, options.prefix);
});
Expand All @@ -268,7 +261,7 @@ const _parseFiles = function(files, options) {
* @param {[type]} name [description]
* @return {[type]} [description]
*/
const _hash = function(str, hash) {
const _hash = function (str, hash) {
return str.indexOf('[hash]') >= 0
? str.replace('[hash]', hash)
: str;
Expand Down
38 changes: 13 additions & 25 deletions src/svgstore.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ const NullFactory = require('webpack/lib/NullFactory');
const async = require('async');

function compatAddPlugin(tappable, hookName, callback, async = false, forType = null) {
const method = (async) ? 'tapAsync' : 'tap';
const method = (async) ? 'tapPromise' : 'tap';
if (tappable.hooks) {
if (forType) {
tappable.hooks[hookName][method](forType, WebpackSvgStore.name, callback);
Expand Down Expand Up @@ -107,30 +107,18 @@ class WebpackSvgStore {


// save file to fs
compatAddPlugin(compiler, 'emit', (compilation, callback) => {
async.forEach(Object.keys(this.tasks),
(key, outerCallback) => {
async.forEach(this.tasks[key],
(task, callback) => {
utils.filesMap(path.join(task.context, task.path || ''), (files) => {
// fileContent
const fileContent = utils.createSprite(
utils.parseFiles(files, this.options), this.options.template);

// add sprite to assets
compilation.assets[task.fileName] = {
size: function () {
return Buffer.byteLength(fileContent, 'utf8');
},
source: function () {
return Buffer.from(fileContent);
}
};
// done
callback();
});
}, outerCallback);
}, callback);
compatAddPlugin(compiler, 'emit', (compilation) => {
return Promise.all(Object.keys(this.tasks).map(async (key) => {
const tasksJobs = this.tasks[key];
return Promise.all(tasksJobs.map(async task => {
const glob = path.join(task.context, task.path || '');
const files = await utils.filesMap(glob);
const content = utils.parseFiles(files, this.options);
const fileContent = utils.createSprite(content, this.options.template);
// add sprite to assets
compilation.assets[task.fileName] = {size: () => Buffer.byteLength(fileContent, 'utf8'), source: () => Buffer.from(fileContent)};
}))
}));
}, true);

compatAddPlugin(compiler, 'done', () => {
Expand Down

0 comments on commit 123eeae

Please sign in to comment.