0e6f99e9c1bafe6415046e7596e314719b2ee6d4cc04638fce0aeca5a9830fb8e04c073804e33e41003f294525baf0b39858c27a3e808ca862dc6d9b94196f 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import merge from 'deepmerge';
  2. import wrapInSvgString from './utils/wrap-in-svg-string';
  3. import defaultConfig from './sprite.config';
  4. export default class Sprite {
  5. /**
  6. * @param {Object} [config]
  7. */
  8. constructor(config) {
  9. this.config = merge(defaultConfig, config || {});
  10. this.symbols = [];
  11. }
  12. /**
  13. * Add new symbol. If symbol with the same id exists it will be replaced.
  14. * @param {SpriteSymbol} symbol
  15. * @return {boolean} `true` - symbol was added, `false` - replaced
  16. */
  17. add(symbol) {
  18. const { symbols } = this;
  19. const existing = this.find(symbol.id);
  20. if (existing) {
  21. symbols[symbols.indexOf(existing)] = symbol;
  22. return false;
  23. }
  24. symbols.push(symbol);
  25. return true;
  26. }
  27. /**
  28. * Remove symbol & destroy it
  29. * @param {string} id
  30. * @return {boolean} `true` - symbol was found & successfully destroyed, `false` - otherwise
  31. */
  32. remove(id) {
  33. const { symbols } = this;
  34. const symbol = this.find(id);
  35. if (symbol) {
  36. symbols.splice(symbols.indexOf(symbol), 1);
  37. symbol.destroy();
  38. return true;
  39. }
  40. return false;
  41. }
  42. /**
  43. * @param {string} id
  44. * @return {SpriteSymbol|null}
  45. */
  46. find(id) {
  47. return this.symbols.filter(s => s.id === id)[0] || null;
  48. }
  49. /**
  50. * @param {string} id
  51. * @return {boolean}
  52. */
  53. has(id) {
  54. return this.find(id) !== null;
  55. }
  56. /**
  57. * @return {string}
  58. */
  59. stringify() {
  60. const { attrs } = this.config;
  61. const stringifiedSymbols = this.symbols.map(s => s.stringify()).join('');
  62. return wrapInSvgString(stringifiedSymbols, attrs);
  63. }
  64. /**
  65. * @return {string}
  66. */
  67. toString() {
  68. return this.stringify();
  69. }
  70. destroy() {
  71. this.symbols.forEach(s => s.destroy());
  72. }
  73. }