UNPKG

2.1 kBJavaScriptView Raw
1export function cssToObject(css) {
2 let o = {};
3 let elements = css.split(';');
4 elements
5 .filter(i => !!i)
6 .map(function(i) {
7 let s = i.split(':');
8 let key = s.shift().trim();
9 let value = s.join(':').trim();
10 o[key] = value;
11 });
12 return o;
13}
14
15export function cssToJsxStr(css) {
16 let o = cssToObject(css);
17 return `{${JSON.stringify(o)}}`;
18}
19
20// here we assume that there are no escaped
21// double quotes inside the style tag value
22export function styleAttrToJsx(xml) {
23 let rx = / style="([^"]*)"/g;
24 let arr = rx.exec(xml);
25 if (!arr) return xml;
26 return xml.replace(rx, ' style=' + cssToJsxStr(arr[1]));
27}
28
29// we assume that the ouput of xml2js is always outputted
30// with lower-case and that it uses double quotes for
31// all attr values
32// Another assumption is that there are no
33// escaped double quotes in the attr value
34export function attrsToObj(attrs) {
35 let o = {};
36 // a non whitespace character can be an attr name
37 let rx = / (\S+)="/g;
38 let elements = [], tmp;
39 while(tmp = rx.exec(attrs)) elements.push(tmp[1]);
40
41 elements
42 .map(function(i) {
43 // non double quote character can be an attr value
44 let rx2 = new RegExp(` ${i}="([^\"]*)"`, 'g');
45 let arr = rx2.exec(attrs);
46 o[i] = arr[1];
47 });
48 return o;
49}
50
51export function convertRootToProps(xml) {
52 // Note: There is a space after svg, which means that
53 // there is at least one attribute defined for the
54 // root element. This is safe to assume because, we
55 // check if at least width and height are defined for the
56 // root svg element
57 let rx = /<svg (.*)>/;
58 let arr = rx.exec(xml);
59 let o = attrsToObj(arr[1]);
60 let keys = Object.keys(o);
61 keys.map(function(key) {
62 if (key === 'style') return;
63 o[key] = `{'undefined' === typeof this.props['${key}'] ? ${JSON.stringify(o[key])} : this.props['${key}']}`;
64 });
65 let proped = keys.map(function(key) {
66 return `${key}=${o[key]}`;
67 }).join(' ');
68 return xml.replace(arr[1], proped);
69}
70
71export function hyphenToCamel(name) {
72 return name.replace(/-([a-z])/g, g => g[1].toUpperCase());
73}