svgo.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. JS2SVG = require('./svgo/js2svg.js');
  16. var SVGO = module.exports = function(config) {
  17. this.config = CONFIG(config);
  18. };
  19. SVGO.prototype.optimize = function(svgstr, callback) {
  20. if (this.config.error) return callback(this.config);
  21. var _this = this,
  22. config = this.config,
  23. maxPassCount = config.multipass ? 10 : 1,
  24. counter = 0,
  25. prevResultSize = Number.POSITIVE_INFINITY,
  26. optimizeOnceCallback = function(svgjs) {
  27. if (svgjs.error) {
  28. callback(svgjs);
  29. return;
  30. }
  31. if (++counter < maxPassCount && svgjs.data.length < prevResultSize) {
  32. prevResultSize = svgjs.data.length;
  33. _this._optimizeOnce(svgjs.data, optimizeOnceCallback);
  34. } else {
  35. callback(svgjs);
  36. }
  37. };
  38. _this._optimizeOnce(svgstr, optimizeOnceCallback);
  39. };
  40. SVGO.prototype._optimizeOnce = function(svgstr, callback) {
  41. var config = this.config;
  42. SVG2JS(svgstr, function(svgjs) {
  43. if (svgjs.error) {
  44. callback(svgjs);
  45. return;
  46. }
  47. svgjs = PLUGINS(svgjs, config.plugins);
  48. callback(JS2SVG(svgjs, config.js2svg));
  49. });
  50. };
  51. /**
  52. * The factory that creates a content item with the helper methods.
  53. *
  54. * @param {Object} data which passed to jsAPI constructor
  55. * @returns {JSAPI} content item
  56. */
  57. SVGO.prototype.createContentItem = function(data) {
  58. return new JSAPI(data);
  59. };