-
Notifications
You must be signed in to change notification settings - Fork 18
/
index.js
189 lines (152 loc) · 5.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
'use strict';
var q = require('q');
var assign = require('object-assign');
var parseString = require('xml2js').parseString;
var xmlbuilder = require('xmlbuilder');
var utils = require('./utils.js');
var defaults = {
passProps: false,
passChildren: false,
root: null,
refs: null
};
function cleanupParsedSVGElement(xpath, previousSibling, element) {
return {
tagName: element['#name'],
attributes: element.$ || {},
children: element.$$ || [],
text: element._
};
}
function parseSVG(svg, callback) {
parseString(svg, {
explicitArray: true,
explicitChildren: true,
explicitRoot: false,
mergeAttrs: false,
normalize: true,
normalizeTags: false,
preserveChildrenOrder: true,
attrNameProcessors: [utils.processAttributeName],
validator: cleanupParsedSVGElement
}, callback);
}
function afterParseSVG(parsedSVG) {
utils.forEach(parsedSVG, function(element) {
if (element.tagName === 'use') {
var referenceHref = element.attributes['xlink:href'] || '';
var referenceID = referenceHref.slice(1);
var reference = utils.filter(parsedSVG, function(ch) {
return ch.attributes.id === referenceID;
}).shift();
if (reference) {
element.attributes = assign({}, reference.attributes, element.attributes);
element.children = reference.children;
element.tagName = reference.tagName;
element.text = reference.text;
delete element.attributes.id;
delete element.attributes['xlink:href'];
}
}
if (!utils.supportsAllAttributes(element)) {
element.attributes = utils.sanitizeAttributes(element.attributes);
}
element.children = utils.sanitizeChildren(element.children);
});
return parsedSVG;
}
function formatElementForXMLBuilder(element) {
var attributes = element.attributes;
var children = element.children && element.children.map(formatElementForXMLBuilder);
var result = Object.keys(attributes).reduce(function(hash, name) {
hash['@' + name] = attributes[name];
return hash;
}, {});
if (element.text) result['#text'] = element.text;
if (children && children.length) {
children.forEach(function(child) {
var tagName = Object.keys(child)[0];
var existingValue = result[tagName];
if (existingValue) {
if (Array.isArray(existingValue)) {
// existing element array, push new element
existingValue.push(child[tagName]);
} else {
// create array with existing and new elements
result[tagName] = [existingValue, child[tagName]];
}
} else {
// first child element with this tag name
result[tagName] = child[tagName];
}
});
}
var wrapped = {};
wrapped[element.tagName] = result;
return wrapped;
}
function beforeBuildSVG(options, parsed) {
if (options.root) {
var root = utils.findById(parsed, options.root);
if (!root) throw new Error('Cannot find root element #' + options.root);
parsed = root;
}
if (options.refs) {
Object.keys(options.refs).forEach(function(id) {
var ref = options.refs[id];
var element = utils.findById(parsed, id);
if (!element) throw new Error('Cannot find element #' + id + ' for ref ' + ref);
element.attributes.ref = ref;
});
}
if (options.passProps) {
parsed.attributes.passProps = 1;
}
if (options.renderChildren) {
var passChildrenToSpecificId = typeof(options.renderChildren) === 'string';
var passChildrenTo = passChildrenToSpecificId ? utils.findById(parsed, options.renderChildren) : parsed;
if (!passChildrenTo) throw new Error('Cannot find element #' + options.renderChildren + ' to render children into');
passChildrenTo.text = [passChildrenTo.text || '', '{this.props.children}'].join('\n');
}
return formatElementForXMLBuilder(parsed);
}
function afterBuildSVG(built) {
return built
.replace(/style="((?:[^"\\]|\\.)*)"/ig, function(matched, styleString) {
var style = styleString.split(/\s*;\s*/g).filter(Boolean).reduce(function(hash, rule) {
var keyValue = rule.split(/\s*\:\s*(.*)/);
var property = utils.cssProperty(keyValue[0]);
var value = keyValue[1];
hash[property] = value;
return hash;
}, {});
return 'style={' + JSON.stringify(style) + '}';
})
.replace(/passProps="1"/, '{...this.props}');
}
function buildSVG(object) {
return xmlbuilder
.create(object, { headless: true })
.end({ pretty: true, indent: '\t', newline: '\n' });
}
module.exports = function svgToJsx(svg, options, callback) {
if (arguments.length === 2) {
callback = options;
options = {};
}
options = assign({}, defaults, options);
var promise = q
.nfcall(parseSVG, svg)
.then(afterParseSVG)
.then(beforeBuildSVG.bind(null, options))
.then(buildSVG)
.then(afterBuildSVG);
if (callback) {
promise.done(function(result) {
callback(null, result);
}, function(error) {
callback(error, null);
});
}
return promise;
};