removeUselessStrokeAndFill.js 2.4 KB

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