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