1
0
mirror of https://github.com/svg/svgo.git synced 2025-07-29 20:21:14 +03:00

Make optimize synchronous (#1322)

Ref https://github.com/svg/svgo/issues/1015

Looks like `sax` is synchronous and we do not need to listen "end"
event. This allows to avoid all callbacks and make `optimize` method
synchronous.
This commit is contained in:
Bogdan Chadkin
2021-02-14 14:59:50 +03:00
committed by GitHub
parent b85d7f9885
commit 1dc5ee3ee1
8 changed files with 75 additions and 113 deletions

View File

@ -21,56 +21,37 @@ var SVGO = function(config) {
this.config = CONFIG(config);
};
SVGO.prototype.optimize = function(svgstr, info) {
info = info || {};
return new Promise((resolve, reject) => {
if (this.config.error) {
reject(this.config.error);
return;
SVGO.prototype.optimize = function(svgstr, info = {}) {
const config = this.config;
if (config.error) {
throw Error(config.error);
}
const maxPassCount = config.multipass ? 10 : 1;
let prevResultSize = Number.POSITIVE_INFINITY;
let svgjs = null;
for (let i = 0; i < maxPassCount; i += 1) {
svgjs = SVG2JS(svgstr);
if (svgjs.error == null) {
svgjs = PLUGINS(svgjs, info, config.plugins);
}
var config = this.config,
maxPassCount = config.multipass ? 10 : 1,
counter = 0,
prevResultSize = Number.POSITIVE_INFINITY,
optimizeOnceCallback = (svgjs) => {
if (svgjs.error) {
reject(svgjs.error);
return;
}
info.multipassCount = counter;
if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
prevResultSize = svgjs.data.length;
this._optimizeOnce(svgjs.data, info, optimizeOnceCallback);
} else {
if (config.datauri) {
svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
}
if (info && info.path) {
svgjs.path = info.path;
}
resolve(svgjs);
}
};
this._optimizeOnce(svgstr, info, optimizeOnceCallback);
});
};
SVGO.prototype._optimizeOnce = function(svgstr, info, callback) {
var config = this.config;
SVG2JS(svgstr, function(svgjs) {
svgjs = JS2SVG(svgjs, config.js2svg);
if (svgjs.error) {
callback(svgjs);
return;
throw Error(svgjs.error);
}
svgjs = PLUGINS(svgjs, info, config.plugins);
callback(JS2SVG(svgjs, config.js2svg));
});
info.multipassCount = i;
if (svgjs.data.length < prevResultSize) {
prevResultSize = svgjs.data.length
} else {
if (config.datauri) {
svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
}
if (info && info.path) {
svgjs.path = info.path;
}
return svgjs;
}
}
return svgjs;
};
/**