blob: cd1569fdb991e9506ba40581c7a1fed0927bda7f [file] [log] [blame]
Leo Repp58b9f112021-11-22 11:57:47 +01001'use strict';
2
3/**
4 * SVGO is a Nodejs-based tool for optimizing SVG vector graphics files.
5 *
6 * @see https://github.com/svg/svgo
7 *
8 * @author Kir Belevich <kir@soulshine.in> (https://github.com/deepsweet)
9 * @copyright © 2012 Kir Belevich
10 * @license MIT https://raw.githubusercontent.com/svg/svgo/master/LICENSE
11 */
12
13var CONFIG = require('./svgo/config.js'),
14 SVG2JS = require('./svgo/svg2js.js'),
15 PLUGINS = require('./svgo/plugins.js'),
16 JSAPI = require('./svgo/jsAPI.js'),
17 encodeSVGDatauri = require('./svgo/tools.js').encodeSVGDatauri,
18 JS2SVG = require('./svgo/js2svg.js');
19
20var SVGO = function(config) {
21 this.config = CONFIG(config);
22};
23
24SVGO.prototype.optimize = function(svgstr, info) {
25 info = info || {};
26 return new Promise((resolve, reject) => {
27 if (this.config.error) {
28 reject(this.config.error);
29 return;
30 }
31
32 var config = this.config,
33 maxPassCount = config.multipass ? 10 : 1,
34 counter = 0,
35 prevResultSize = Number.POSITIVE_INFINITY,
36 optimizeOnceCallback = (svgjs) => {
37 if (svgjs.error) {
38 reject(svgjs.error);
39 return;
40 }
41
42 info.multipassCount = counter;
43 if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
44 prevResultSize = svgjs.data.length;
45 this._optimizeOnce(svgjs.data, info, optimizeOnceCallback);
46 } else {
47 if (config.datauri) {
48 svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
49 }
50 if (info && info.path) {
51 svgjs.path = info.path;
52 }
53 resolve(svgjs);
54 }
55 };
56
57 this._optimizeOnce(svgstr, info, optimizeOnceCallback);
58 });
59};
60
61SVGO.prototype._optimizeOnce = function(svgstr, info, callback) {
62 var config = this.config;
63
64 SVG2JS(svgstr, function(svgjs) {
65 if (svgjs.error) {
66 callback(svgjs);
67 return;
68 }
69
70 svgjs = PLUGINS(svgjs, info, config.plugins);
71
72 callback(JS2SVG(svgjs, config.js2svg));
73 });
74};
75
76/**
77 * The factory that creates a content item with the helper methods.
78 *
79 * @param {Object} data which passed to jsAPI constructor
80 * @returns {JSAPI} content item
81 */
82SVGO.prototype.createContentItem = function(data) {
83 return new JSAPI(data);
84};
85
86SVGO.Config = CONFIG;
87
88module.exports = SVGO;
89// Offer ES module interop compatibility.
90module.exports.default = SVGO;