removeAttrs.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. 'use strict';
  2. var ELEM_SEP = ':';
  3. exports.type = 'perItem';
  4. exports.active = false;
  5. exports.description = 'removes specified attributes';
  6. exports.params = {
  7. attrs: []
  8. };
  9. /**
  10. * Remove attributes
  11. *
  12. * @param attrs:
  13. *
  14. * format: [ element* : attribute* ]
  15. *
  16. * element : regexp (wrapped into ^...$), single * or omitted > all elements
  17. * attribute : regexp (wrapped into ^...$)
  18. *
  19. * examples:
  20. *
  21. * > basic: remove fill attribute
  22. * ---
  23. * removeAttrs:
  24. * attrs: 'fill'
  25. *
  26. * > remove fill attribute on path element
  27. * ---
  28. * attrs: 'path:fill'
  29. *
  30. *
  31. * > remove all fill and stroke attribute
  32. * ---
  33. * attrs:
  34. * - 'fill'
  35. * - 'stroke'
  36. *
  37. * [is same as]
  38. *
  39. * attrs: '(fill|stroke)'
  40. *
  41. * [is same as]
  42. *
  43. * attrs: '*:(fill|stroke)'
  44. *
  45. * [is same as]
  46. *
  47. * attrs: '.*:(fill|stroke)'
  48. *
  49. *
  50. * > remove all stroke related attributes
  51. * ----
  52. * attrs: 'stroke.*'
  53. *
  54. *
  55. * @param {Object} item current iteration item
  56. * @param {Object} params plugin params
  57. * @return {Boolean} if false, item will be filtered out
  58. *
  59. * @author Benny Schudel
  60. */
  61. exports.fn = function(item, params) {
  62. // wrap into an array if params is not
  63. if (!Array.isArray(params.attrs)) {
  64. params.attrs = [params.attrs];
  65. }
  66. if (item.isElem()) {
  67. // prepare patterns
  68. var patterns = params.attrs.map(function(pattern) {
  69. // apply to all elements if specifc element is omitted
  70. if (pattern.indexOf(ELEM_SEP) === -1) {
  71. pattern = ['.*', ELEM_SEP, pattern].join('');
  72. }
  73. // create regexps for element and attribute name
  74. return pattern.split(ELEM_SEP)
  75. .map(function(value) {
  76. // adjust single * to match anything
  77. if (value === '*') { value = '.*'; }
  78. return new RegExp(['^', value, '$'].join(''), 'i');
  79. });
  80. });
  81. // loop patterns
  82. patterns.forEach(function(pattern) {
  83. // matches element
  84. if (pattern[0].test(item.elem)) {
  85. // loop attributes
  86. item.eachAttr(function(attr) {
  87. var name = attr.name;
  88. // matches attribute name
  89. if (pattern[1].test(name)) {
  90. item.removeAttr(name);
  91. }
  92. });
  93. }
  94. });
  95. }
  96. };