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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const micromatch = require('micromatch');
 
const { getRoot } = require('../utils');
 
const defaultConfig = {
  id: undefined,
  preserve: [
    'viewBox',
    'preserveAspectRatio',
    'class',
    'overflow',
    'stroke?(-*)',
    'fill?(-*)',
    'xmlns?(:*)',
    'role',
    'aria-*'
  ]
};
 
/**
 * @param {Object} [config] {@see defaultConfig}
 * @return {Function} PostHTML plugin
 */
function svgToSymbol(config = null) {
  const cfg = Object.assign({}, defaultConfig, config);
 
  return (tree) => {
    const root = getRoot(tree);
    root.tag = 'symbol';
    root.attrs = root.attrs || {};
 
    const attrNames = Object.keys(root.attrs);
    const attrNamesToPreserve = micromatch(attrNames, cfg.preserve);
 
    attrNames.forEach((name) => {
      if (!attrNamesToPreserve.includes(name)) {
        delete root.attrs[name];
      }
    });
 
    if (cfg.id) {
      root.attrs.id = cfg.id;
    }
 
    // Remove all elements and add symbol node
    tree.splice(0, tree.length, root);
 
    return tree;
  };
}
 
module.exports = svgToSymbol;