Skip to content

Commit

Permalink
Merge branch 'removeAttrsPlugin' of git://github.com/bennyschudel/svg…
Browse files Browse the repository at this point in the history
…o into removeAttrsPlugin
  • Loading branch information
GreLI committed Jun 21, 2015
2 parents 1336ebf + 8a693e7 commit 55fd495
Show file tree
Hide file tree
Showing 7 changed files with 172 additions and 18 deletions.
1 change: 1 addition & 0 deletions .svgo.yml
Original file line number Diff line number Diff line change
Expand Up @@ -49,4 +49,5 @@ plugins:
- removeTitle
- removeDesc
- removeDimensions
- removeAttrs
- addClassesToSVGElement
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ Today we have:
* [ [ sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) ] sort element attributes for epic readability (disabled by default)
* [ [ transformsWithOnePath](https://github.com/svg/svgo/blob/master/plugins/transformsWithOnePath.js) ] apply transforms, crop by real width, center vertical alignment and resize SVG with one Path inside (disabled by default)
* [ [ removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) ] remove width/height attributes if viewBox is present (disabled by default)
* [ [ removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) ] remove attributes by pattern

Want to know how it works and how to write your own plugin? [Of course you want to](https://github.com/svg/svgo/blob/master/docs/how-it-works/en.md).

Expand Down
1 change: 1 addition & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ SVGO имеет расширяемую архитектуру, в которой
* [ [ sortAttrs](https://github.com/svg/svgo/blob/master/plugins/sortAttrs.js) ] сортировка атрибутов элементов для удобочитаемости (выключено по умолчанию)
* [ [ transformsWithOnePath](https://github.com/svg/svgo/blob/master/plugins/transformsWithOnePath.js) ] применение трансформаций, обрезка по реальной ширине, вертикальное выравнивание по центру и изменение размеров SVG с одним Path внутри
* [ [ removeDimensions](https://github.com/svg/svgo/blob/master/plugins/removeDimensions.js) ] удаляет атрибуты width/height при наличии viewBox (выключено по умолчанию)
* [ [ removeAttrs](https://github.com/svg/svgo/blob/master/plugins/removeAttrs.js) ] удаляет атрибуты по указанному паттерну

Хотите узнать, как это работает и как написать свой плагин? [Конечно же, да!](https://github.com/svg/svgo/blob/master/docs/how-it-works/ru.md).

Expand Down
112 changes: 112 additions & 0 deletions plugins/removeAttrs.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
'use strict';

var ELEM_SEP = ':';

exports.type = 'perItem';

exports.active = false;

exports.params = {
attrs: []
};

/**
* Remove attributes
*
* @param attrs:
*
* format: [ element* : attribute* ]
*
* element : regexp (wrapped into ^...$), single * or omitted > all elements
* attribute : regexp (wrapped into ^...$)
*
* examples:
*
* > remove fill attribute on path element
* ---
* attrs: 'path:fill'
*
*
* > remove all fill and stroke attribute
* ---
* attrs:
* - 'fill'
* - 'stroke'
*
* [is same as]
*
* attrs: '(fill|stroke)'
*
* [is same as]
*
* attrs: '*:(fill|stroke)'
*
* [is same as]
*
* attrs: '.*:(fill|stroke)'
*
*
* > remove all stroke related attributes
* ----
* attrs: 'stroke.*'
*
*
* @param {Object} item current iteration item
* @param {Object} params plugin params
* @return {Boolean} if false, item will be filtered out
*
* @author Benny Schudel
*/
exports.fn = function(item, params) {

// wrap into an array if params is not
if (!Array.isArray(params.attrs)) {
params.attrs = [params.attrs];
}

if (item.isElem()) {

// prepare patterns
var patterns = params.attrs.map(function(pattern) {

// apply to all elements if specifc element is omitted
if (pattern.indexOf(ELEM_SEP) === -1) {
pattern = ['.*', ELEM_SEP, pattern].join('');
}

// create regexps for element and attribute name
return pattern.split(ELEM_SEP)
.map(function(value) {

// adjust single * to match anything
if (value === '*') { value = '.*'; }

return new RegExp(['^', value, '$'].join(''), 'i');
});

});

// loop patterns
patterns.forEach(function(pattern) {

// matches element
if (pattern[0].test(item.elem)) {

// loop attributes
item.eachAttr(function(attr) {
var name = attr.name;

// matches attribute name
if (pattern[1].test(name)) {
item.removeAttr(name);
}

});

}

});

}

};
37 changes: 19 additions & 18 deletions test/plugins/_index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,38 +13,39 @@ describe('plugins tests', function() {

var match = file.match(regFilename),
index,
name,
svgo,
plugins;
name;

if (match) {

name = match[1];
name = match[1];
index = match[2];

file = PATH.resolve(__dirname, file);

plugins = {};
plugins[name] = true;

svgo = new SVGO({
full: true,
plugins: [ plugins ],
js2svg: { pretty: true }
});

it(name + '.' + index, function(done) {

FS.readFile(file, 'utf8', function(err, data) {

var splitted = data.split('@@@'),
orig = splitted[0],
should = splitted[1];
var splitted = data.trim().split(/\s*@@@\s*/),
orig = splitted[0],
should = splitted[1],
params = splitted[2],

plugins = {},
svgo;

plugins[name] = (params) ? JSON.parse(params) : true;

svgo = new SVGO({
full : true,
plugins : [ plugins ],
js2svg : { pretty: true }
});

svgo.optimize(orig, function(result) {
result = '\n\n' + result.data;

result.should.be.equal(should);
//FIXME: results.data has a '\n' at the end while it should not
( result.data.trim() ).should.be.equal(should);
done();
});

Expand Down
19 changes: 19 additions & 0 deletions test/plugins/removeAttrs.01.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
19 changes: 19 additions & 0 deletions test/plugins/removeAttrs.02.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 55fd495

Please sign in to comment.