sprite-factory.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const merge = require('merge-options');
  2. const processor = require('posthtml-svg-mode');
  3. const extractNamespacesToRoot = require('./transformations/extract-namespaces-to-root');
  4. const moveFromSymbolToRoot = require('./transformations/move-from-symbol-to-root');
  5. const { svg, xlink } = require('../namespaces');
  6. const defaultConfig = {
  7. attrs: {
  8. [svg.name]: svg.uri,
  9. [xlink.name]: xlink.uri
  10. },
  11. styles: `
  12. .sprite-symbol-usage {display: none;}
  13. .sprite-symbol-usage:target {display: inline;}
  14. `,
  15. usages: true,
  16. symbols: []
  17. };
  18. /**
  19. * TODO simplify
  20. * @param {Object} [config] {@see defaultConfig}
  21. * @return {Function} PostHTML plugin
  22. */
  23. function createSprite(config = {}) {
  24. const cfg = merge(defaultConfig, config);
  25. const symbols = cfg.symbols;
  26. const trees = symbols.map(s => s.tree);
  27. let usages = [];
  28. if (cfg.usages) {
  29. usages = symbols.map((symbol) => {
  30. const { id, useId } = symbol;
  31. return {
  32. tag: 'use',
  33. attrs: {
  34. id: useId,
  35. 'xlink:href': `#${id}`,
  36. class: 'sprite-symbol-usage'
  37. }
  38. };
  39. });
  40. }
  41. let defsContent = [];
  42. if (cfg.styles !== false) {
  43. defsContent.push({
  44. tag: 'style',
  45. content: cfg.styles
  46. });
  47. }
  48. defsContent = defsContent.concat(trees);
  49. return (tree) => {
  50. tree[0] = {
  51. tag: 'svg',
  52. attrs: cfg.attrs,
  53. content: [{
  54. tag: 'defs',
  55. content: defsContent
  56. }].concat(usages)
  57. };
  58. return tree;
  59. };
  60. }
  61. /**
  62. * @param {Object} options {@see defaultConfig}
  63. * @return {Promise<PostHTMLProcessingResult>}
  64. */
  65. function spriteFactory(options) {
  66. const plugins = [
  67. createSprite(options),
  68. extractNamespacesToRoot(),
  69. moveFromSymbolToRoot()
  70. ];
  71. return processor(plugins).process('');
  72. }
  73. module.exports = spriteFactory;
  74. module.exports.createSprite = createSprite;