2020-10-06 20:23:26 +02:00
|
|
|
/* eslint-disable import/no-extraneous-dependencies */
|
|
|
|
|
import Svgo from 'svgo';
|
|
|
|
|
import { format } from 'prettier';
|
2021-03-23 19:26:50 +01:00
|
|
|
import { parseSync, stringify } from 'svgson';
|
2020-10-06 20:23:26 +02:00
|
|
|
import DEFAULT_ATTRS from './default-attrs.json';
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Optimize SVG with `svgo`.
|
|
|
|
|
* @param {string} svg - An SVG string.
|
2021-03-23 19:26:50 +01:00
|
|
|
* @returns {Promise<string>} An optimized svg
|
2020-10-06 20:23:26 +02:00
|
|
|
*/
|
|
|
|
|
function optimize(svg) {
|
|
|
|
|
const svgo = new Svgo({
|
|
|
|
|
plugins: [
|
|
|
|
|
{ convertShapeToPath: false },
|
|
|
|
|
{ mergePaths: false },
|
|
|
|
|
{ removeAttrs: { attrs: '(fill|stroke.*)' } },
|
|
|
|
|
{ removeTitle: true },
|
|
|
|
|
],
|
|
|
|
|
});
|
|
|
|
|
|
2020-12-30 14:23:46 -05:00
|
|
|
return svgo.optimize(svg).then(({ data }) => data);
|
2020-10-06 20:23:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Set default attibutes on SVG.
|
|
|
|
|
* @param {string} svg - An SVG string.
|
2021-03-23 19:26:50 +01:00
|
|
|
* @returns {string} An SVG string, included with the default attributes.
|
2020-10-06 20:23:26 +02:00
|
|
|
*/
|
|
|
|
|
function setAttrs(svg) {
|
2021-03-23 19:26:50 +01:00
|
|
|
const contents = parseSync(svg);
|
|
|
|
|
|
|
|
|
|
contents.attributes = DEFAULT_ATTRS;
|
2020-10-06 20:23:26 +02:00
|
|
|
|
2021-03-23 19:26:50 +01:00
|
|
|
return stringify(contents);
|
|
|
|
|
}
|
2020-10-06 20:23:26 +02:00
|
|
|
|
2021-03-23 19:26:50 +01:00
|
|
|
/**
|
|
|
|
|
* Process SVG string.
|
|
|
|
|
* @param {string} svg An SVG string.
|
|
|
|
|
* @returns {Promise<string>} An optimized svg
|
|
|
|
|
*/
|
|
|
|
|
function processSvg(svg) {
|
|
|
|
|
return (
|
|
|
|
|
optimize(svg)
|
|
|
|
|
.then(setAttrs)
|
|
|
|
|
.then(optimizedSvg => format(optimizedSvg, { parser: 'babel' }))
|
|
|
|
|
// remove semicolon inserted by prettier
|
|
|
|
|
// because prettier thinks it's formatting JSX not HTML
|
|
|
|
|
.then(svg => svg.replace(/;/g, ''))
|
|
|
|
|
);
|
2020-10-06 20:23:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default processSvg;
|