forked from vault-development/react-native-svg-uri
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
242 lines (207 loc) · 7.53 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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import React, { Component } from "react";
import { View } from 'react-native';
import PropTypes from 'prop-types'
import xmldom from 'xmldom';
import resolveAssetSource from 'react-native/Libraries/Image/resolveAssetSource';
import Svg, {
Circle,
Ellipse,
ClipPath,
G,
LinearGradient,
RadialGradient,
Line,
Path,
Polygon,
Polyline,
Rect,
Text,
TSpan,
Defs,
Stop
} from 'react-native-svg';
import * as utils from './utils';
class SvgUri extends Component {
constructor(props) {
super(props);
this.state = { fill: props.fill, svgXmlData: props.svgXmlData };
this.isComponentMounted = false;
// Gets the image data from an URL or a static file
if (props.source) {
const source = resolveAssetSource(props.source) || {};
this.fetchSVGData(source.uri);
}
}
tagHandlers = {
'defs': (index, node, childs) =>
<Defs key={index++}>{childs}</Defs>,
'g': (index, node, childs, styleClasses) =>
<G key={index} {...this.obtainComponentAtts(node, styleClasses)}> {childs}</G>,
'clipPath': (index, node, childs, styleClasses) =>
<ClipPath key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</ClipPath>,
'path': (index, node, childs, styleClasses) =>
<Path key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Path>,
'circle': (index, node, childs, styleClasses) =>
<Circle key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Circle>,
'rect': (index, node, childs, styleClasses) =>
<Rect key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Rect>,
'line': (index, node, childs, styleClasses) =>
<Line key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Line>,
'linearGradient': (index, node, childs, styleClasses) =>
<LinearGradient key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</LinearGradient>,
'radialGradient': (index, node, childs, styleClasses) =>
<RadialGradient key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</RadialGradient>,
'stop': (index, node, childs, styleClasses) =>
<Stop key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Stop>,
'ellipse': (index, node, childs, styleClasses) =>
<Ellipse key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Ellipse>,
'polygon': (index, node, childs, styleClasses) =>
<Polygon key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Polygon>,
'polyline': (index, node, childs, styleClasses) =>
<Polyline key={index} {...this.obtainComponentAtts(node, styleClasses)}>{childs}</Polyline>,
'text': (index, node, childs, styleClasses) =>
<Text key={index} {...utils.fixTextAttributes(componentthis.obtainComponentAtts(node, styleClasses), node)}>{childs}</Text>,
'tspan': (index, node, childs, styleClasses) =>
<TSpan key={index} {...utils.fixTextAttributes(componentthis.obtainComponentAtts(node, styleClasses), node)}>{childs}</TSpan>,
'svg': (index, node, childs, styleClasses) =>
<Svg key={index} {...this.overrideRootElementAttributes(this.obtainComponentAtts(node, styleClasses))}>{childs}</Svg>
}
componentWillMount() {
this.isComponentMounted = true;
}
componentWillReceiveProps(nextProps) {
if (nextProps.source) {
const source = resolveAssetSource(nextProps.source) || {};
const oldSource = resolveAssetSource(this.props.source) || {};
if (source.uri !== oldSource.uri) {
this.fetchSVGData(source.uri);
}
}
if (nextProps.svgXmlData !== this.props.svgXmlData) {
this.setState({ svgXmlData: nextProps.svgXmlData });
}
if (nextProps.fill !== this.props.fill) {
this.setState({ fill: nextProps.fill });
}
}
componentWillUnmount() {
this.isComponentMounted = false
}
async fetchSVGData(uri) {
let responseXML = null;
try {
const response = await fetch(uri);
responseXML = await response.text();
} catch (e) {
console.error("ERROR SVG", e);
} finally {
if (this.isComponentMounted) {
this.setState({ svgXmlData: responseXML });
}
}
return responseXML;
}
overrideRootElementAttributes(attributes) {
if (!attributes.viewBox) {
attributes.viewBox = `0 0 ${attributes.width} ${attributes.height}`;
}
if (this.props.width) {
attributes.width = this.props.width;
}
if (this.props.height) {
attributes.height = this.props.height;
}
return attributes;
}
overrideFillAttribute(attributes) {
if (this.state.fill && (!attributes.fill || attributes.fill !== 'none')) {
attributes.fill = this.state.fill
}
return attributes;
}
getStyleAttsForClass(attributes, styleClasses) {
const classObj = Array.from(attributes).find(attr => attr.name === 'class');
if (!classObj || !styleClasses) {
return {};
}
const regex = utils.getRegExpForClassName(classObj.nodeValue)
return Object.keys(styleClasses).reduce((aggr, key) => {
if(regex.test(key)){
Object.assign(aggr, styleClasses[key])
}
return aggr
}, {})
}
obtainComponentAtts({ attributes }, styleClasses) {
const styleAtts = this.getStyleAttsForClass(attributes, styleClasses)
Array.from(attributes).forEach(({ nodeName, nodeValue }) => {
Object.assign(styleAtts, utils.transformStyle({ nodeName, nodeValue }, this.state.fill));
});
const componentAtts = Array.from(attributes)
.map(utils.camelCaseNodeName)
.map(utils.removePixelsFromNodeValue)
.reduce((acc, { nodeName, nodeValue }) => {
acc[nodeName] = nodeValue
return acc
}, {});
Object.assign(componentAtts, styleAtts);
return this.overrideFillAttribute(componentAtts);
}
// Remove empty strings from children array
trimElementChilden = (childrens) => childrens.filter((children) => typeof children !== 'string' || children.trim.length !== 0)
processNode(node, styleClasses) {
// check if is text value
if (node.nodeValue) {
return node.nodeValue
}
// Only process accepted elements
if (!this.tagHandlers[node.nodeName]) {
return null;
}
// if have children process them.
// Recursive function.
let childrens = [];
if (node.childNodes) {
childrens = Array.from(node.childNodes).reduce((aggr, childNode) => {
const node = this.processNode(childNode, styleClasses);
if (node) {
childrens.push(node);
}
return childrens
}, childrens)
}
return this.tagHandlers[node.nodeName](index++, node, this.trimElementChilden(childrens), styleClasses);
}
index;
render() {
try {
if (this.state.svgXmlData == null) {
return null;
}
const doc = new xmldom.DOMParser().parseFromString(
this.state.svgXmlData.substring(
this.state.svgXmlData.indexOf("<svg "),
this.state.svgXmlData.indexOf("</svg>") + 6
)
);
index = 1;
return (
<View style={this.props.style}>
{this.processNode(doc.childNodes[0], utils.extractStyleClasses(doc.childNodes[0]))}
</View>
);
} catch (e) {
console.error("ERROR SVG", e);
return null;
}
}
}
SvgUri.propTypes = {
style: PropTypes.object,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
svgXmlData: PropTypes.string,
source: PropTypes.any,
fill: PropTypes.string,
}
module.exports = SvgUri;