normalize-viewbox.js 782 B

12345678910111213141516171819202122232425262728293031323334
  1. const merge = require('merge-options');
  2. const { getRoot } = require('../utils');
  3. const defaultConfig = {
  4. removeDimensions: false
  5. };
  6. /**
  7. * @param {Object} [config] {@see defaultConfig}
  8. * @return {Function} PostHTML plugin
  9. */
  10. function normalizeViewBox(config = {}) {
  11. const cfg = merge(defaultConfig, config);
  12. return (tree) => {
  13. const root = getRoot(tree);
  14. root.attrs = root.attrs || {};
  15. const attrs = root.attrs;
  16. const { width, height, viewBox } = attrs;
  17. if (!viewBox && width && height) {
  18. attrs.viewBox = `0 0 ${parseFloat(width).toString()} ${parseFloat(height).toString()}`;
  19. if (cfg.removeDimensions) {
  20. delete attrs.width;
  21. delete attrs.height;
  22. }
  23. }
  24. return tree;
  25. };
  26. }
  27. module.exports = normalizeViewBox;