UNPKG

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