removeUselessStrokeAndFill.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. 'use strict';
  2. exports.type = 'perItem';
  3. exports.active = true;
  4. exports.description = 'removes useless stroke and fill attributes';
  5. exports.params = {
  6. stroke: true,
  7. fill: true,
  8. removeNone: false,
  9. hasStyleOrScript: false
  10. };
  11. var shape = require('./_collections').elemsGroups.shape,
  12. regStrokeProps = /^stroke/,
  13. regFillProps = /^fill-/,
  14. styleOrScript = ['style', 'script'];
  15. /**
  16. * Remove useless stroke and fill attrs.
  17. *
  18. * @param {Object} item current iteration item
  19. * @param {Object} params plugin params
  20. * @return {Boolean} if false, item will be filtered out
  21. *
  22. * @author Kir Belevich
  23. */
  24. exports.fn = function(item, params) {
  25. if (item.isElem(styleOrScript)) {
  26. params.hasStyleOrScript = true;
  27. }
  28. if (!params.hasStyleOrScript && item.isElem(shape) && !item.computedAttr('id')) {
  29. var stroke = params.stroke && item.computedAttr('stroke'),
  30. fill = params.fill && !item.computedAttr('fill', 'none');
  31. // remove stroke*
  32. if (
  33. params.stroke &&
  34. (!stroke ||
  35. stroke == 'none' ||
  36. item.computedAttr('stroke-opacity', '0') ||
  37. item.computedAttr('stroke-width', '0')
  38. )
  39. ) {
  40. var parentStroke = item.parentNode.computedAttr('stroke'),
  41. declineStroke = parentStroke && parentStroke != 'none';
  42. item.eachAttr(function(attr) {
  43. if (regStrokeProps.test(attr.name)) {
  44. item.removeAttr(attr.name);
  45. }
  46. });
  47. if (declineStroke) item.addAttr({
  48. name: 'stroke',
  49. value: 'none',
  50. prefix: '',
  51. local: 'stroke'
  52. });
  53. }
  54. // remove fill*
  55. if (
  56. params.fill &&
  57. (!fill || item.computedAttr('fill-opacity', '0'))
  58. ) {
  59. item.eachAttr(function(attr) {
  60. if (regFillProps.test(attr.name)) {
  61. item.removeAttr(attr.name);
  62. }
  63. });
  64. if (fill) {
  65. if (item.hasAttr('fill'))
  66. item.attr('fill').value = 'none';
  67. else
  68. item.addAttr({
  69. name: 'fill',
  70. value: 'none',
  71. prefix: '',
  72. local: 'fill'
  73. });
  74. }
  75. }
  76. if (params.removeNone &&
  77. (!stroke || item.hasAttr('stroke') && item.attr('stroke').value=='none') &&
  78. (!fill || item.hasAttr('fill') && item.attr('fill').value=='none')) {
  79. return false;
  80. }
  81. }
  82. };