diff --git a/.svgo.yml b/.svgo.yml index e7b046e9..b08cc0ad 100644 --- a/.svgo.yml +++ b/.svgo.yml @@ -42,3 +42,4 @@ plugins: - cleanupIDs - removeUnusedNS - transformsWithOnePath + - sortAttrs diff --git a/plugins/sortAttrs.js b/plugins/sortAttrs.js new file mode 100644 index 00000000..101b45b4 --- /dev/null +++ b/plugins/sortAttrs.js @@ -0,0 +1,54 @@ +'use strict'; + +exports.type = 'perItem'; + +exports.active = true; + +exports.params = { + order: [ + 'xmlns', + 'id', + 'width', 'height', + 'x', 'x1', 'x2', + 'y', 'y1', 'y2', + 'cx', 'cy', 'r', + 'fill', 'fill-opacity', 'fill-rule', + 'stroke', 'stroke-opacity', 'stroke-width', 'stroke-miterlimit', 'stroke-dashoffset', + 'd', 'points' + ] +}; + +/** + * Sort element attributes for epic readability. + * + * @param {Object} item current iteration item + * @param {Object} params plugin params + * + * @author Nikolay Frantsev + */ +exports.fn = function(item, params) { + + var attrs = [], + sorted = {}, + orderlen = params.order.length + 1; + + if (item.elem) { + + item.eachAttr(function(attr) { + attrs.push(attr); + }); + + attrs.sort(function(a, b) { + return ((a = params.order.indexOf(a.name)) > -1 ? a : orderlen) - + ((b = params.order.indexOf(b.name)) > -1 ? b : orderlen); + }); + + attrs.forEach(function (attr) { + sorted[attr.name] = attr; + }); + + item.attrs = sorted; + + } + +}; diff --git a/test/plugins/sortAttrs.01.svg b/test/plugins/sortAttrs.01.svg new file mode 100644 index 00000000..f1bd5777 --- /dev/null +++ b/test/plugins/sortAttrs.01.svg @@ -0,0 +1,9 @@ + + test + + +@@@ + + + test +