removeUnusedNS.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. 'use strict';
  2. exports.type = 'full';
  3. exports.active = true;
  4. exports.description = 'removes unused namespaces declaration';
  5. /**
  6. * Remove unused namespaces declaration.
  7. *
  8. * @param {Object} item current iteration item
  9. * @return {Boolean} if false, item will be filtered out
  10. *
  11. * @author Kir Belevich
  12. */
  13. exports.fn = function(data) {
  14. var svgElem,
  15. xmlnsCollection = [];
  16. /**
  17. * Remove namespace from collection.
  18. *
  19. * @param {String} ns namescape name
  20. */
  21. function removeNSfromCollection(ns) {
  22. var pos = xmlnsCollection.indexOf(ns);
  23. // if found - remove ns from the namespaces collection
  24. if (pos > -1) {
  25. xmlnsCollection.splice(pos, 1);
  26. }
  27. }
  28. /**
  29. * Bananas!
  30. *
  31. * @param {Array} items input items
  32. *
  33. * @return {Array} output items
  34. */
  35. function monkeys(items) {
  36. var i = 0,
  37. length = items.content.length;
  38. while(i < length) {
  39. var item = items.content[i];
  40. if (item.isElem('svg')) {
  41. item.eachAttr(function(attr) {
  42. // collect namespaces
  43. if (attr.prefix === 'xmlns' && attr.local) {
  44. xmlnsCollection.push(attr.local);
  45. }
  46. });
  47. // if svg element has ns-attr
  48. if (xmlnsCollection.length) {
  49. // save svg element
  50. svgElem = item;
  51. }
  52. }
  53. if (xmlnsCollection.length) {
  54. // check item for the ns-attrs
  55. if (item.prefix) {
  56. removeNSfromCollection(item.prefix);
  57. }
  58. // check each attr for the ns-attrs
  59. item.eachAttr(function(attr) {
  60. removeNSfromCollection(attr.prefix);
  61. });
  62. }
  63. // if nothing is found - go deeper
  64. if (xmlnsCollection.length && item.content) {
  65. monkeys(item);
  66. }
  67. i++;
  68. }
  69. return items;
  70. }
  71. data = monkeys(data);
  72. // remove svg element ns-attributes if they are not used even once
  73. if (xmlnsCollection.length) {
  74. xmlnsCollection.forEach(function(name) {
  75. svgElem.removeAttr('xmlns:' + name);
  76. });
  77. }
  78. return data;
  79. };