symbol.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const { renderer } = require('posthtml-svg-mode');
  2. const { getRoot, getHash } = require('./utils');
  3. const defaultFactory = require('./symbol-factory');
  4. const FileRequest = require('./request');
  5. const clone = require('clone');
  6. class SpriteSymbol {
  7. constructor({ id, tree, request }) {
  8. this.id = id;
  9. this._tree = tree;
  10. this.request = request;
  11. }
  12. /**
  13. * @param {Object} options
  14. * @param {string} options.id
  15. * @param {string} options.content
  16. * @param {string|FileRequest} options.request
  17. * @param {Function<Promise<PostHTMLProcessingResult>>} [options.factory]
  18. * @return {Promise<SpriteSymbol>}
  19. */
  20. static create(options) {
  21. const { content, factory = defaultFactory } = options;
  22. const request = typeof options.request === 'string' ? new FileRequest(options.request) : options.request;
  23. const id = typeof options.id === 'undefined' ? getHash(`${request.toString()}_${content}`) : options.id;
  24. return factory({ content, request, id })
  25. .then(({ tree }) => new SpriteSymbol({ id, request, tree }));
  26. }
  27. /**
  28. * @return {string}
  29. */
  30. get viewBox() {
  31. const root = getRoot(this.tree);
  32. return root.attrs ? root.attrs.viewBox : null;
  33. }
  34. get tree() {
  35. return clone(this._tree);
  36. }
  37. /**
  38. * @return {string}
  39. */
  40. get useId() {
  41. return `${this.id}-usage`;
  42. }
  43. /**
  44. * @return {string}
  45. */
  46. render() {
  47. return renderer(this.tree);
  48. }
  49. }
  50. module.exports = SpriteSymbol;