process-svg.js 1.27 KB
Newer Older
1 2 3 4 5
/* eslint-disable import/no-extraneous-dependencies */
import Svgo from 'svgo';
import cheerio from 'cheerio';
import { format } from 'prettier';

Cole Bemis's avatar
Cole Bemis committed
6
import DEFAULT_ATTRS from '../src/default-attrs.json';
7 8 9 10 11 12 13 14 15

/**
 * Process SVG string.
 * @param {string} svg - An SVG string.
 * @param {Promise<string>}
 */
function processSvg(svg) {
  return (
    optimize(svg)
Cole Bemis's avatar
Cole Bemis committed
16
      .then(setAttrs)
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
      .then(format)
      // remove semicolon inserted by prettier
      // because prettier thinks it's formatting JSX not HTML
      .then(svg => svg.replace(/;/g, ''))
  );
}

/**
 * Optimize SVG with `svgo`.
 * @param {string} svg - An SVG string.
 * @returns {Promise<string>}
 */
function optimize(svg) {
  const svgo = new Svgo({
    plugins: [
      { convertShapeToPath: false },
      { mergePaths: false },
      { removeAttrs: { attrs: '(fill|stroke.*)' } },
      { removeTitle: true },
    ],
  });

  return new Promise(resolve => {
    svgo.optimize(svg, ({ data }) => resolve(data));
  });
}

/**
 * Set default attibutes on SVG.
 * @param {string} svg - An SVG string.
 * @returns {string}
 */
Cole Bemis's avatar
Cole Bemis committed
49
function setAttrs(svg) {
50 51
  const $ = cheerio.load(svg);

Cole Bemis's avatar
Cole Bemis committed
52 53
  Object.keys(DEFAULT_ATTRS).forEach(key =>
    $('svg').attr(key, DEFAULT_ATTRS[key]),
54 55 56 57 58 59
  );

  return $('body').html();
}

export default processSvg;