svgo.js 2.5 KB

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