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 |
|
7 | const 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 |
|
22 |
|
23 |
|
24 |
|
25 | function 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 |
|
72 |
|
73 |
|
74 | function spriteFactory(options) {
|
75 | const plugins = [
|
76 | createSprite(options),
|
77 | extractNamespacesToRoot(),
|
78 | moveFromSymbolToRoot()
|
79 | ];
|
80 | return processor(plugins).process('');
|
81 | }
|
82 |
|
83 | module.exports = spriteFactory;
|
84 | module.exports.createSprite = createSprite;
|