2023-02-28 17:24:17 +01:00
|
|
|
import {optimize} from 'svgo';
|
2022-08-10 09:10:53 +02:00
|
|
|
import prettier from 'prettier';
|
2023-02-28 17:24:17 +01:00
|
|
|
import {parseSync, stringify} from 'svgson';
|
2022-08-10 09:10:53 +02:00
|
|
|
import DEFAULT_ATTRS from './default-attrs.json' assert { type: 'json' };
|
2020-10-06 20:23:26 +02:00
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* 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
|
|
|
*/
|
2023-02-28 17:24:17 +01:00
|
|
|
async function optimizeSvg(svg, path) {
|
2022-04-06 11:10:10 +02:00
|
|
|
const result = optimize(svg, {
|
2023-02-28 17:24:17 +01:00
|
|
|
path,
|
2020-10-06 20:23:26 +02:00
|
|
|
plugins: [
|
2022-04-06 11:10:10 +02:00
|
|
|
{
|
|
|
|
|
name: 'preset-default',
|
|
|
|
|
params: {
|
|
|
|
|
overrides: {
|
|
|
|
|
convertShapeToPath: false,
|
|
|
|
|
mergePaths: false,
|
|
|
|
|
},
|
|
|
|
|
},
|
|
|
|
|
},
|
2023-02-28 17:24:17 +01:00
|
|
|
{
|
|
|
|
|
name: 'removeAttrs',
|
|
|
|
|
params: {
|
|
|
|
|
attrs: '(fill|stroke.*)',
|
|
|
|
|
}
|
|
|
|
|
}
|
2020-10-06 20:23:26 +02:00
|
|
|
],
|
|
|
|
|
});
|
|
|
|
|
|
2022-04-06 11:10:10 +02:00
|
|
|
return result.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
|
|
|
|
|
*/
|
2023-02-28 17:24:17 +01:00
|
|
|
function processSvg(svg, path) {
|
2021-03-23 19:26:50 +01:00
|
|
|
return (
|
2023-02-28 17:24:17 +01:00
|
|
|
optimizeSvg(svg, path)
|
2021-03-23 19:26:50 +01:00
|
|
|
.then(setAttrs)
|
2022-11-07 22:29:19 +01:00
|
|
|
.then((optimizedSvg) =>
|
2023-02-28 17:24:17 +01:00
|
|
|
prettier.format(optimizedSvg, {parser: 'babel'}),
|
2022-11-07 22:29:19 +01:00
|
|
|
)
|
2021-03-23 19:26:50 +01:00
|
|
|
// remove semicolon inserted by prettier
|
|
|
|
|
// because prettier thinks it's formatting JSX not HTML
|
2022-11-07 22:29:19 +01:00
|
|
|
.then((svg) => svg.replace(/;/g, ''))
|
2021-03-23 19:26:50 +01:00
|
|
|
);
|
2020-10-06 20:23:26 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export default processSvg;
|