react-native-visit-rn-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/LICENSE +20 -0
  2. package/README.md +31 -0
  3. package/android/build.gradle +108 -0
  4. package/android/gradle.properties +5 -0
  5. package/android/src/main/AndroidManifest.xml +3 -0
  6. package/android/src/main/AndroidManifestNew.xml +2 -0
  7. package/android/src/main/java/com/visitrnsdk/VisitRnSdkPackage.kt +17 -0
  8. package/android/src/main/java/com/visitrnsdk/VisitRnSdkViewManager.kt +20 -0
  9. package/ios/VisitRnSdk.xcodeproj/project.pbxproj +274 -0
  10. package/ios/VisitRnSdkViewManager.h +20 -0
  11. package/ios/VisitRnSdkViewManager.m +1240 -0
  12. package/lib/commonjs/Services.js +34 -0
  13. package/lib/commonjs/Services.js.map +1 -0
  14. package/lib/commonjs/constants.js +12 -0
  15. package/lib/commonjs/constants.js.map +1 -0
  16. package/lib/commonjs/index.android.js +364 -0
  17. package/lib/commonjs/index.android.js.map +1 -0
  18. package/lib/commonjs/index.ios.js +296 -0
  19. package/lib/commonjs/index.ios.js.map +1 -0
  20. package/lib/module/Services.js +26 -0
  21. package/lib/module/Services.js.map +1 -0
  22. package/lib/module/constants.js +5 -0
  23. package/lib/module/constants.js.map +1 -0
  24. package/lib/module/index.android.js +352 -0
  25. package/lib/module/index.android.js.map +1 -0
  26. package/lib/module/index.ios.js +286 -0
  27. package/lib/module/index.ios.js.map +1 -0
  28. package/lib/typescript/index.test.d.ts +1 -0
  29. package/lib/typescript/index.test.d.ts.map +1 -0
  30. package/package.json +177 -0
  31. package/react-native-visit-rn-sdk.podspec +42 -0
  32. package/src/Services.js +39 -0
  33. package/src/constants.js +4 -0
  34. package/src/index.android.js +488 -0
  35. package/src/index.ios.js +359 -0
@@ -0,0 +1,359 @@
1
+ import axios from 'axios';
2
+ import React, {
3
+ useRef,
4
+ useEffect,
5
+ useState,
6
+ useCallback,
7
+ useMemo,
8
+ } from 'react';
9
+ import {
10
+ StyleSheet,
11
+ SafeAreaView,
12
+ NativeModules,
13
+ NativeEventEmitter,
14
+ Linking,
15
+ Platform,
16
+ ActivityIndicator,
17
+ Dimensions,
18
+ } from 'react-native';
19
+ import { EventRegister } from 'react-native-event-listeners';
20
+ import { WebView } from 'react-native-webview';
21
+ import DeviceInfo from 'react-native-device-info';
22
+ import { getWebViewLink } from './Services';
23
+ import constants from './constants';
24
+
25
+ const LINKING_ERROR =
26
+ `The package 'react-native-visit-rn-sdk' doesn't seem to be linked. Make sure: \n\n` +
27
+ Platform.select({ ios: "- You have run 'pod install'\n", default: '' }) +
28
+ '- You rebuilt the app after installing the package\n' +
29
+ '- You are not using Expo Go\n';
30
+
31
+ const escapeChars = {
32
+ lt: '<',
33
+ gt: '>',
34
+ quot: '"',
35
+ apos: "'",
36
+ amp: '&',
37
+ };
38
+
39
+ const unescapeHTML = (str) =>
40
+ // modified from underscore.string and string.js
41
+ str.replace(/\&([^;]+);/g, (entity, entityCode) => {
42
+ let match;
43
+
44
+ if (entityCode in escapeChars) {
45
+ return escapeChars[entityCode];
46
+ } else if ((match = entityCode.match(/^#x([\da-fA-F]+)$/))) {
47
+ return String.fromCharCode(parseInt(match[1], 16));
48
+ } else if ((match = entityCode.match(/^#(\d+)$/))) {
49
+ return String.fromCharCode(~~match[1]);
50
+ } else {
51
+ return entity;
52
+ }
53
+ });
54
+
55
+ const visitEvent = 'visit-event';
56
+
57
+ const VisitRnSdkView = ({
58
+ baseUrl,
59
+ errorBaseUrl,
60
+ token,
61
+ id,
62
+ phone,
63
+ environment,
64
+ moduleName,
65
+ magicLink,
66
+ isLoggingEnabled,
67
+ }) => {
68
+ const [source, setSource] = useState('');
69
+ const [loading, setLoading] = useState(true);
70
+ useEffect(() => {
71
+ if (magicLink?.trim()?.length) {
72
+ setSource(magicLink);
73
+ setLoading(false);
74
+ } else {
75
+ const systemVersion = DeviceInfo.getSystemVersion();
76
+ const version = DeviceInfo.getVersion();
77
+ DeviceInfo.getUniqueId()
78
+ .then((uniqueId) =>
79
+ getWebViewLink(
80
+ baseUrl,
81
+ token,
82
+ phone,
83
+ id,
84
+ 'iPhone',
85
+ uniqueId,
86
+ version,
87
+ systemVersion,
88
+ environment
89
+ )
90
+ )
91
+ .then((res) => {
92
+ if (res.data?.errorMessage) {
93
+ const { errorMessage } = res.data;
94
+ const errorUrl = `${errorBaseUrl}/star-health?error=${errorMessage}`;
95
+ setSource(errorUrl);
96
+ if (res.data?.errorMessage === 'Please login again') {
97
+ EventRegister.emitEvent(visitEvent, {
98
+ message: 'unauthorized-wellness-access',
99
+ errorMessage: errorMessage,
100
+ });
101
+ }
102
+ } else if (res.data.message === 'success') {
103
+ const magicCode = res.data?.magicCode;
104
+ let finalBaseUrl = '';
105
+ if (magicCode) {
106
+ if (environment.toUpperCase() === 'PROD') {
107
+ finalBaseUrl = constants.PROD_BASE_URL;
108
+ } else {
109
+ finalBaseUrl = constants.STAGE_BASE_URL;
110
+ }
111
+ }
112
+ if (finalBaseUrl && magicCode) {
113
+ setSource(`${finalBaseUrl}=${magicCode}`);
114
+ }
115
+ } else {
116
+ EventRegister.emitEvent('visit-event', {
117
+ message: 'generate-magic-link-failed',
118
+ errorMessage: `${res.data}`,
119
+ });
120
+ }
121
+ })
122
+ .catch((err) => {
123
+ console.log('getWebViewLink err', { err })
124
+ EventRegister.emitEvent('visit-event', {
125
+ message: 'generate-magic-link-failed',
126
+ errorMessage: `${err}`,
127
+ });
128
+ })
129
+ .finally(() => {
130
+ setLoading(false);
131
+ });
132
+ }
133
+ }, [
134
+ id,
135
+ token,
136
+ baseUrl,
137
+ errorBaseUrl,
138
+ phone,
139
+ environment,
140
+ moduleName,
141
+ magicLink,
142
+ isLoggingEnabled,
143
+ ]);
144
+
145
+ const VisitRnSdkViewManager = useMemo(
146
+ () =>
147
+ NativeModules.VisitRnSdkViewManager
148
+ ? NativeModules.VisitRnSdkViewManager
149
+ : new Proxy(
150
+ {},
151
+ {
152
+ get() {
153
+ throw new Error(LINKING_ERROR);
154
+ },
155
+ }
156
+ ),
157
+ []
158
+ );
159
+
160
+ const webviewRef = useRef(null);
161
+ const [apiBaseUrl, setApiBaseUrl] = useState('');
162
+ const [authToken, setAuthToken] = useState('');
163
+ const [hasLoadedOnce, setHasLoadedOnce] = useState(false);
164
+
165
+ const callSyncApi = useCallback(
166
+ (data) =>
167
+ axios
168
+ .post(`${apiBaseUrl}/users/data-sync`, data, {
169
+ headers: {
170
+ Authorization: authToken,
171
+ },
172
+ })
173
+ .then((res) => console.log('callSyncData response,', res))
174
+ .catch((err) => console.log('callSyncData err,', { err })),
175
+ [apiBaseUrl, authToken]
176
+ );
177
+
178
+ const callEmbellishApi = useCallback(
179
+ (data) =>
180
+ axios
181
+ .post(`${apiBaseUrl}/users/embellish-sync`, data, {
182
+ headers: {
183
+ Authorization: authToken,
184
+ },
185
+ })
186
+ .then((res) => console.log('callEmbellishApi response,', res))
187
+ .catch((err) => console.log('callEmbellishApi err,', { err })),
188
+ [apiBaseUrl, authToken]
189
+ );
190
+
191
+ useEffect(() => {
192
+ const apiManagerEmitter = new NativeEventEmitter(VisitRnSdkViewManager);
193
+ const subscription = apiManagerEmitter.addListener(
194
+ 'EventReminder',
195
+ (reminder) => {
196
+ if (reminder?.callSyncData && reminder?.callSyncData?.length) {
197
+ callSyncApi(reminder?.callSyncData[0]);
198
+ }
199
+ if (reminder?.callEmbellishApi && reminder?.callEmbellishApi?.length) {
200
+ callEmbellishApi(reminder?.callEmbellishApi[0]);
201
+ }
202
+ }
203
+ );
204
+ return () => {
205
+ subscription.remove();
206
+ };
207
+ }, [VisitRnSdkViewManager, callEmbellishApi, callSyncApi]);
208
+
209
+ const handleMessage = async (event) => {
210
+ const data = JSON.parse(unescapeHTML(event.nativeEvent.data));
211
+ const {
212
+ method,
213
+ type,
214
+ frequency,
215
+ timestamp,
216
+ apiBaseUrl,
217
+ authtoken,
218
+ googleFitLastSync,
219
+ gfHourlyLastSync,
220
+ url,
221
+ } = data;
222
+ console.log('handleMessage data is', data);
223
+ console.log(unescapeHTML(event.nativeEvent.data));
224
+ switch (method) {
225
+ case 'UPDATE_PLATFORM':
226
+ webviewRef.current?.injectJavaScript('window.setSdkPlatform("IOS")');
227
+ break;
228
+ case 'CONNECT_TO_GOOGLE_FIT':
229
+ if (DeviceInfo.getModel() === 'iPad') {
230
+ console.log('unsupportedHealthKitDevice triggered');
231
+ webviewRef.current?.injectJavaScript(
232
+ 'window.unsupportedHealthKitDevice(true)'
233
+ );
234
+ } else {
235
+ VisitRnSdkViewManager?.connectToAppleHealth((res) => {
236
+ if (res?.sleepTime || res?.numberOfSteps) {
237
+ webviewRef.current?.injectJavaScript(
238
+ `window.updateFitnessPermissions(true,${res?.numberOfSteps},${res?.sleepTime})`
239
+ );
240
+ } else {
241
+ webviewRef.current?.injectJavaScript(
242
+ 'window.updateFitnessPermissions(true,0,0)'
243
+ );
244
+ }
245
+ });
246
+ }
247
+ break;
248
+ case 'GET_DATA_TO_GENERATE_GRAPH':
249
+ VisitRnSdkViewManager?.renderGraph(
250
+ { type, frequency, timestamp },
251
+ (err, results) => {
252
+ if (err) {
253
+ console.log('error initializing Healthkit: ', err);
254
+ return;
255
+ }
256
+ if (results[0]) {
257
+ console.log('results initializing Healthkit: ', results[0]);
258
+ webviewRef.current?.injectJavaScript(`window.${results[0]}`);
259
+ }
260
+ }
261
+ );
262
+ break;
263
+ case 'UPDATE_API_BASE_URL':
264
+ if (!hasLoadedOnce) {
265
+ console.log('apiBaseUrl is,', apiBaseUrl);
266
+ setApiBaseUrl(apiBaseUrl);
267
+ setAuthToken(authtoken);
268
+ VisitRnSdkViewManager?.updateApiUrl({
269
+ googleFitLastSync,
270
+ gfHourlyLastSync,
271
+ });
272
+ setHasLoadedOnce(true);
273
+ }
274
+ break;
275
+
276
+ case 'OPEN_PDF':
277
+ Linking.openURL(url);
278
+ break;
279
+ case 'CLOSE_VIEW':
280
+ break;
281
+ case 'GET_LOCATION_PERMISSIONS':
282
+ webviewRef.current?.injectJavaScript(
283
+ 'window.checkTheGpsPermission(true)'
284
+ );
285
+ break;
286
+
287
+ default:
288
+ break;
289
+ }
290
+ };
291
+
292
+ const { height, width } = Dimensions.get('screen');
293
+
294
+ return (
295
+ <SafeAreaView style={{ flex: 1, backgroundColor: 'white', height, width }}>
296
+ {loading ? (
297
+ <LoadingIndicator />
298
+ ) : (
299
+ <WebView
300
+ ref={webviewRef}
301
+ source={{ uri: source }}
302
+ style={styles.webView}
303
+ javascriptEnabled
304
+ onMessage={handleMessage}
305
+ onError={(errorMessage) => {
306
+ EventRegister.emitEvent(visitEvent, {
307
+ message: 'web-view-error',
308
+ errorMessage: errorMessage,
309
+ });
310
+ if (isLoggingEnabled) {
311
+ console.warn('Webview error: ', errorMessage);
312
+ }
313
+ }}
314
+ />
315
+ )}
316
+ </SafeAreaView>
317
+ );
318
+ };
319
+
320
+ const styles = StyleSheet.create({
321
+ webViewContainer: {
322
+ flex: 1,
323
+ backgroundColor: 'white',
324
+ },
325
+ webView: {
326
+ flex: 1,
327
+ },
328
+ });
329
+
330
+ VisitRnSdkView.defaultProps = {
331
+ id: '',
332
+ token: '',
333
+ baseUrl: '',
334
+ errorBaseUrl: '',
335
+ phone: '',
336
+ moduleName: '',
337
+ };
338
+
339
+ export default VisitRnSdkView;
340
+
341
+ const LoadingIndicator = () => {
342
+ return (
343
+ <ActivityIndicator
344
+ color="#000"
345
+ size="small"
346
+ style={{
347
+ flex: 1,
348
+ zIndex: 100,
349
+ position: 'absolute',
350
+ backgroundColor: '#fff',
351
+ opacity: 0.4,
352
+ width: '100%',
353
+ height: '100%',
354
+ justifyContent: 'center',
355
+ alignItems: 'center',
356
+ }}
357
+ />
358
+ );
359
+ };