You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

svgo.js 2.6KB

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