forked from YanYuanFE/react-native-signature-canvas
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
104 lines (93 loc) · 2.78 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
import React, { useState, useMemo, useRef } from "react";
import { View, StyleSheet, ActivityIndicator } from "react-native";
import htmlContent from "./h5/html";
import injectedSignaturePad from "./h5/js/signature_pad";
import injectedApplication from "./h5/js/app";
import { WebView } from "react-native-webview";
const styles = StyleSheet.create({
webBg: {
width: "100%",
backgroundColor: "#FFF",
flex: 1
},
loadingOverlayContainer: { position: "absolute", top: 0, bottom: 0, left: 0, right: 0, alignItems: "center", justifyContent: "center" },
});
var webViewRef;
const SignatureView = ({
webStyle = "",
onOK = () => { },
onEmpty = () => { },
onClear = () => { },
onBegin = () => { },
onEnd = () => { },
descriptionText = "Sign above",
clearText = "Clear",
confirmText = "Confirm",
customHtml = null,
autoClear = false,
imageType = "",
}) => {
const [loading, setLoading] = useState(true);
webViewRef = useRef();
const source = useMemo(() => {
let injectedJavaScript = injectedSignaturePad + injectedApplication;
const htmlContentValue = customHtml ? customHtml : htmlContent;
injectedJavaScript = injectedJavaScript.replace("<%autoClear%>", autoClear);
injectedJavaScript = injectedJavaScript.replace("<%imageType%>", imageType);
let html = htmlContentValue(injectedJavaScript);
html = html.replace("<%style%>", webStyle);
html = html.replace("<%description%>", descriptionText);
html = html.replace("<%confirm%>", confirmText);
html = html.replace("<%clear%>", clearText);
return { html };
}, [customHtml, autoClear, imageType, webStyle, descriptionText, confirmText, clearText])
const getSignature = e => {
switch (e.nativeEvent.data) {
case "BEGIN":
onBegin();
break;
case "END":
onEnd();
break;
case "EMPTY":
onEmpty();
break;
case "CLEAR":
onClear();
break;
default:
onOK(e.nativeEvent.data);
}
};
const renderError = e => {
const { nativeEvent } = e;
console.warn("WebView error: ", nativeEvent);
};
return (
<View style={styles.webBg}>
<WebView
ref={webViewRef}
useWebKit={true}
source={source}
onMessage={getSignature}
javaScriptEnabled={true}
onError={renderError}
onLoadEnd={() => setLoading(false)}
/>
{loading && <View style={styles.loadingOverlayContainer}>
<ActivityIndicator />
</View>}
</View>
);
}
export default SignatureView;
export function readSignature() {
if (webViewRef.current) {
webViewRef.current.injectJavaScript("readSignature();true;");
}
}
export function clearSignature() {
if (webViewRef.current) {
webViewRef.current.injectJavaScript("clearSignature();true;");
}
}