-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathSvgImage.js
105 lines (94 loc) · 2.46 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
// @flow
import React, { useEffect, useState } from "react";
import { View, StyleSheet, Platform } from "react-native";
import { WebView } from "react-native-webview";
const heightUnits = Platform.OS === "ios" ? "vh" : "%";
const getHTML = (svgContent, style) => `
<html data-key="key-${style.height}-${style.width}">
<head>
<style>
html, body {
margin: 0;
padding: 0;
height: 100${heightUnits};
width: 100${heightUnits};
overflow: hidden;
background-color: transparent;
}
svg {
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 100%;
overflow: hidden;
}
</style>
</head>
<body>
${svgContent}
</body>
</html>
`;
function SvgImage({ source, onLoadStart, onLoadEnd, style, containerStyle }) {
const [svgContent, setSvgContent] = useState(null);
const uri = source && source.uri;
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
async function doFetch() {
if (uri) {
onLoadStart && onLoadStart();
if (uri.match(/^data:image\/svg/)) {
const index = uri.indexOf("<svg");
setSvgContent(uri.slice(index));
} else {
try {
const res = await fetch(uri, { signal });
const text = await res.text();
setSvgContent(text);
} catch (err) {
console.error("got error", err);
}
}
onLoadEnd && onLoadEnd();
}
}
doFetch();
return () => {
controller.abort();
};
}, [uri]);
if (svgContent) {
const flattenedStyle = StyleSheet.flatten(style) || {};
const html = getHTML(svgContent, flattenedStyle);
return (
<View
pointerEvents="none"
style={[style, containerStyle]}
renderToHardwareTextureAndroid={true}
>
<WebView
originWhitelist={["*"]}
scalesPageToFit={true}
useWebKit={false}
style={[
{
width: 200,
height: 100,
backgroundColor: "transparent",
},
style,
]}
scrollEnabled={false}
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
source={{ html }}
/>
</View>
);
} else {
return <View pointerEvents="none" style={[containerStyle, style]} />;
}
}
export default SvgImage;