UNPKG

2.55 kBJavaScriptView Raw
1'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 return new Promise((resolve, reject) => {
26 if (this.config.error) {
27 reject(this.config.error);
28 return;
29 }
30
31 var config = this.config,
32 maxPassCount = config.multipass ? 10 : 1,
33 counter = 0,
34 prevResultSize = Number.POSITIVE_INFINITY,
35 optimizeOnceCallback = (svgjs) => {
36 if (svgjs.error) {
37 reject(svgjs.error);
38 return;
39 }
40
41 if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
42 prevResultSize = svgjs.data.length;
43 this._optimizeOnce(svgjs.data, info, optimizeOnceCallback);
44 } else {
45 if (config.datauri) {
46 svgjs.data = encodeSVGDatauri(svgjs.data, config.datauri);
47 }
48 if (info && info.path) {
49 svgjs.path = info.path;
50 }
51 resolve(svgjs);
52 }
53 };
54
55 this._optimizeOnce(svgstr, info, optimizeOnceCallback);
56 });
57};
58
59SVGO.prototype._optimizeOnce = function(svgstr, info, callback) {
60 var config = this.config;
61
62 SVG2JS(svgstr, function(svgjs) {
63 if (svgjs.error) {
64 callback(svgjs);
65 return;
66 }
67
68 svgjs = PLUGINS(svgjs, info, config.plugins);
69
70 callback(JS2SVG(svgjs, config.js2svg));
71 });
72};
73
74/**
75 * The factory that creates a content item with the helper methods.
76 *
77 * @param {Object} data which passed to jsAPI constructor
78 * @returns {JSAPI} content item
79 */
80SVGO.prototype.createContentItem = function(data) {
81 return new JSAPI(data);
82};
83
84module.exports = SVGO;
85// Offer ES module interop compatibility.
86module.exports.default = SVGO;