Skip to content

Commit

Permalink
Add minifyStyles plugin, test and dependencies.
Browse files Browse the repository at this point in the history
  • Loading branch information
strarsis committed Nov 1, 2015
1 parent 46e1d7b commit 16ea8c8
Show file tree
Hide file tree
Showing 4 changed files with 89 additions and 1 deletion.
1 change: 1 addition & 0 deletions .svgo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ plugins:
- removeMetadata
- removeEditorsNSData
- cleanupAttrs
- minifyStyles
- convertStyleToAttrs
- cleanupIDs
- removeRasterImages
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,8 @@
"js-yaml": "~3.3.1",
"colors": "~1.1.2",
"whet.extend": "~0.9.9",
"mkdirp": "~0.5.1"
"mkdirp": "~0.5.1",
"csso": "~1.4.1"
},
"devDependencies": {
"mocha": "~2.2.5",
Expand Down
71 changes: 71 additions & 0 deletions plugins/minifyStyles.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
'use strict';

exports.type = 'perItem';

exports.active = true;

exports.params = {
svgo: {}
};

exports.description = 'minifies existing styles in svg';

var csso = require('csso');


// wraps css rules into a selector to make it parseable
var rulesToDummySelector = function(str) {
return '.dummy { ' + str + ' }';
};

// helper to extract css rules from full css selector
var extractRuleCss = function(str) {
var strEx = str.match(/\.dummy{(.*)}/i)[1];
return strEx;
};

// minifies css using csso
var minifyCss = function(css, options) {
return csso.minify(css);
};



/**
* Minifies styles (<style> element + style attribute) using svgo
*
* @param {Object} item current iteration item
* @return {Boolean} if false, item will be filtered out
*
* @author strarsis <[email protected]>
*/
exports.fn = function(item, svgoOptions) {

if(item.elem) {
if(item.isElem('style')) {
var styleCss = item.content[0].text;
if(styleCss.length > 0) {
var styleCssMinified = minifyCss(styleCss, svgoOptions);
item.content[0].text = styleCssMinified;
}
}

if(item.hasAttr('style')) {
var itemCss = item.attr('style').value;
if(itemCss.length > 0) {
var itemCssMinified =
extractRuleCss(
minifyCss(
rulesToDummySelector(
itemCss
),
svgoOptions
)
);
item.attr('style').value = itemCssMinified;
}
}
}

return item;
};
15 changes: 15 additions & 0 deletions test/plugins/minifyStyles.01.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 16ea8c8

Please sign in to comment.