removeViewBox.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. 'use strict';
  2. exports.type = 'visitor';
  3. exports.name = 'removeViewBox';
  4. exports.active = true;
  5. exports.description = 'removes viewBox attribute when possible';
  6. const viewBoxElems = ['svg', 'pattern', 'symbol'];
  7. /**
  8. * Remove viewBox attr which coincides with a width/height box.
  9. *
  10. * @see https://www.w3.org/TR/SVG11/coords.html#ViewBoxAttribute
  11. *
  12. * @example
  13. * <svg width="100" height="50" viewBox="0 0 100 50">
  14. * ⬇
  15. * <svg width="100" height="50">
  16. *
  17. * @author Kir Belevich
  18. *
  19. * @type {import('../lib/types').Plugin<void>}
  20. */
  21. exports.fn = () => {
  22. return {
  23. element: {
  24. enter: (node, parentNode) => {
  25. if (
  26. viewBoxElems.includes(node.name) &&
  27. node.attributes.viewBox != null &&
  28. node.attributes.width != null &&
  29. node.attributes.height != null
  30. ) {
  31. // TODO remove width/height for such case instead
  32. if (node.name === 'svg' && parentNode.type !== 'root') {
  33. return;
  34. }
  35. const nums = node.attributes.viewBox.split(/[ ,]+/g);
  36. if (
  37. nums[0] === '0' &&
  38. nums[1] === '0' &&
  39. node.attributes.width.replace(/px$/, '') === nums[2] && // could use parseFloat too
  40. node.attributes.height.replace(/px$/, '') === nums[3]
  41. ) {
  42. delete node.attributes.viewBox;
  43. }
  44. }
  45. },
  46. },
  47. };
  48. };