svg-to-symbol.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const micromatch = require('micromatch');
  2. const { getRoot } = require('../utils');
  3. const defaultConfig = {
  4. id: undefined,
  5. preserve: [
  6. 'viewBox',
  7. 'preserveAspectRatio',
  8. 'class',
  9. 'overflow',
  10. 'stroke?(-*)',
  11. 'fill?(-*)',
  12. 'xmlns?(:*)',
  13. 'role',
  14. 'aria-*'
  15. ]
  16. };
  17. /**
  18. * @param {Object} [config] {@see defaultConfig}
  19. * @return {Function} PostHTML plugin
  20. */
  21. function svgToSymbol(config = null) {
  22. const cfg = Object.assign({}, defaultConfig, config);
  23. return (tree) => {
  24. const root = getRoot(tree);
  25. root.tag = 'symbol';
  26. root.attrs = root.attrs || {};
  27. const attrNames = Object.keys(root.attrs);
  28. const attrNamesToPreserve = micromatch(attrNames, cfg.preserve);
  29. attrNames.forEach((name) => {
  30. if (!attrNamesToPreserve.includes(name)) {
  31. delete root.attrs[name];
  32. }
  33. });
  34. if (cfg.id) {
  35. root.attrs.id = cfg.id;
  36. }
  37. // Remove all elements and add symbol node
  38. tree.splice(0, tree.length, root);
  39. return tree;
  40. };
  41. }
  42. module.exports = svgToSymbol;