forked from seekshiva/react-native-remote-svg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SvgImage.js
107 lines (101 loc) · 2.68 KB
/
SvgImage.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
// @flow
import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
import { WebView } from 'react-native-webview';
const getHTML = (svgContent, style) => `
<html data-key="key-${style.height}-${style.width}">
<head>
<style>
html, body {
margin: 0;
padding: 0;
height: 100%;
width: 100%;
overflow: hidden;
background-color: transparent;
}
svg {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body>
${svgContent}
</body>
</html>
`;
class SvgImage extends Component {
state = { fetchingUrl: null, svgContent: null };
componentDidMount() {
this.doFetch(this.props);
}
componentWillReceiveProps(nextProps) {
const prevUri = this.props.source && this.props.source.uri;
const nextUri = nextProps.source && nextProps.source.uri;
if (nextUri && prevUri !== nextUri) {
this.doFetch(nextProps);
}
}
doFetch = async props => {
let uri = props.source && props.source.uri;
if (uri) {
props.onLoadStart && props.onLoadStart();
if (uri.match(/^data:image\/svg/)) {
const index = uri.indexOf('<svg');
this.setState({ fetchingUrl: uri, svgContent: uri.slice(index) });
} else {
try {
const res = await fetch(uri);
const text = await res.text();
this.setState({ fetchingUrl: uri, svgContent: text });
} catch (err) {
console.error('got error', err);
}
}
props.onLoadEnd && props.onLoadEnd();
}
};
render() {
const props = this.props;
const { svgContent } = this.state;
if (svgContent) {
const flattenedStyle = StyleSheet.flatten(props.style) || {};
const html = getHTML(svgContent, flattenedStyle);
return (
<View pointerEvents="none" style={[props.style, props.containerStyle]}
renderToHardwareTextureAndroid={true}>
<WebView
originWhitelist={['*']}
scalesPageToFit={true}
useWebKit={false}
style={[
{
width: 200,
height: 100,
backgroundColor: 'transparent',
},
props.style,
]}
scrollEnabled={false}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
source={{ html }}
/>
</View>
);
} else {
return (
<View
pointerEvents="none"
style={[props.containerStyle, props.style]}
/>
);
}
}
}
export default SvgImage;