UNPKG

2.12 kBJavaScriptView Raw
1import xml2js from 'xml2js';
2import builder from './build-xml';
3import filter from './deep-filter';
4import {svgTags, svgAttrs} from './react-svg-elements';
5import makeComponent from './make-component';
6import {styleAttrToJsx, convertRootToProps, hyphenToCamel} from './parsers';
7
8export default function(content) {
9
10 this.cacheable && this.cacheable(true);
11 this.addDependency(this.resourcePath);
12
13 let loaderContext = this;
14 let callback = this.async();
15
16 let parser = new xml2js.Parser({
17 normalize: true,
18 normalizeTags: true,
19 explicitArray: true,
20 explicitChildren: true,
21 preserveChildrenOrder: true
22 });
23
24 parser.addListener('error', err => callback(err));
25
26 parser.addListener('end', function(result) {
27 let svg = result.svg;
28 let allowedTags = svgTags.concat(['$', '$$', '#name']);
29 let filtered = filter(result, function(value, key, parent, parentKey) {
30 if ('number' === typeof key) {
31 if (parentKey === '$$')
32 return allowedTags.indexOf(value['#name']) > -1;
33 return true;
34 }
35 if (parentKey === '$') {
36 // if the attribute is a namespace attr, then ignore
37 if (key.indexOf(':') > -1) return false;
38 // convert hyphens to camelcase
39 if (key.indexOf('-') > -1) return hyphenToCamel(key);
40 return true;
41 }
42 return allowedTags.indexOf(key) > -1;
43 });
44
45 // add some basic props by default
46 if ('undefined' === typeof filtered.svg['$'].width)
47 filtered.svg['$'].width = "300";
48 if ('undefined' === typeof filtered.svg['$'].height)
49 filtered.svg['$'].height = "300";
50
51 // pass things through the pipeline
52 // everything is synchronous anyway,
53 // but the promise chain gives us a neat way to
54 // list a pipeline - a list of transformations to
55 // be done on some initial data
56 Promise
57 .resolve(filtered)
58 .then(builder)
59 .then(styleAttrToJsx)
60 .then(convertRootToProps)
61 .then(makeComponent)
62 .then(component => callback(null, component))
63 .catch(err => callback(err));
64
65 });
66
67 parser.parseString(content.toString());
68
69};