removeDimensions.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. 'use strict';
  2. exports.name = 'removeDimensions';
  3. exports.type = 'perItem';
  4. exports.active = false;
  5. exports.description =
  6. 'removes width and height in presence of viewBox (opposite to removeViewBox, disable it first)';
  7. /**
  8. * Remove width/height attributes and add the viewBox attribute if it's missing
  9. *
  10. * @example
  11. * <svg width="100" height="50" />
  12. * ↓
  13. * <svg viewBox="0 0 100 50" />
  14. *
  15. * @param {Object} item current iteration item
  16. * @return {Boolean} if true, with and height will be filtered out
  17. *
  18. * @author Benny Schudel
  19. */
  20. exports.fn = function (item) {
  21. if (item.type === 'element' && item.name === 'svg') {
  22. if (item.attributes.viewBox != null) {
  23. delete item.attributes.width;
  24. delete item.attributes.height;
  25. } else if (
  26. item.attributes.width != null &&
  27. item.attributes.height != null &&
  28. Number.isNaN(Number(item.attributes.width)) === false &&
  29. Number.isNaN(Number(item.attributes.height)) === false
  30. ) {
  31. const width = Number(item.attributes.width);
  32. const height = Number(item.attributes.height);
  33. item.attributes.viewBox = `0 0 ${width} ${height}`;
  34. delete item.attributes.width;
  35. delete item.attributes.height;
  36. }
  37. }
  38. };