1
0
mirror of https://github.com/svg/svgo.git synced 2025-07-29 20:21:14 +03:00

new plugin removeUnusedNS

This commit is contained in:
deepsweet
2012-10-15 19:29:26 +03:00
parent 9e5c96b2f5
commit 3204a06ca5
14 changed files with 180 additions and 1 deletions

100
plugins/removeUnusedNS.js Normal file
View File

@ -0,0 +1,100 @@
/**
* Remove unused XLink namespace declaration.
*
* @param {Object} item current iteration item
* @param {Object} params plugin params
* @return {Boolean} if false, item will be filtered out
*
* @author Kir Belevich
*/
exports.removeUnusedNS = function(data, params) {
var svgElem,
xmlnsCollection = [];
/**
* Remove namespace from collection.
*
* @param {String} ns namescape name
*/
function removeNSfromCollection(ns) {
var pos = xmlnsCollection.indexOf(ns);
// if found - remove ns from the namespaces collection
if (pos > -1) {
xmlnsCollection.splice(pos, 1);
}
}
/**
* Bananas!
*
* @param {Array} items input items
*
* @return {Array} output items
*/
function monkeys(items) {
var i = 0,
length = items.content.length;
while(i < length) {
var item = items.content[i];
if (item.isElem('svg')) {
item.eachAttr(function(attr) {
// collect namespaces
if (attr.prefix === 'xmlns' && attr.local) {
xmlnsCollection.push(attr.local);
}
});
// if svg element has ns-attr
if (xmlnsCollection.length) {
// save svg element
svgElem = item;
}
} else if (xmlnsCollection.length) {
// check item for the ns-attrs
if (item.prefix) {
removeNSfromCollection(item.prefix);
}
// check each attr for the ns-attrs
item.eachAttr(function(attr) {
removeNSfromCollection(attr.prefix);
});
}
// if nothing is found - go deeper
if (xmlnsCollection.length && item.content) {
monkeys(item);
}
i++;
}
return items;
}
data = monkeys(data);
// remove svg element ns-attributes if they are not used even once
if (xmlnsCollection.length) {
xmlnsCollection.forEach(function(name) {
svgElem.removeAttr('xmlns:' + name);
});
}
return data;
};