This repository has been archived by the owner on Sep 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
170 lines (146 loc) · 4.96 KB
/
App.tsx
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
import messaging, { FirebaseMessagingTypes } from '@react-native-firebase/messaging';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import {
ActivityIndicator,
BackHandler,
Platform,
SafeAreaView,
Share,
StyleSheet,
Text,
TouchableOpacity,
} from 'react-native';
import RNBootSplash from 'react-native-bootsplash';
import WebView, { WebViewMessageEvent } from 'react-native-webview';
import { WebViewNavigation, WebViewProgressEvent } from 'react-native-webview/lib/WebViewTypes';
const COLORS = {
primary: '#ad3636',
secondary: '#faf2de',
};
const USER_AGENT = 'skole-native-app';
const SOURCE = 'https://www.skoleapp.com';
type RemoteMessage = FirebaseMessagingTypes.RemoteMessage;
const styles = StyleSheet.create({
container: {
height: '100%',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: COLORS.primary,
padding: 20,
},
header: {
color: COLORS.secondary,
textAlign: 'center',
fontSize: 20,
fontWeight: 'bold',
marginBottom: 20,
},
text: {
color: COLORS.secondary,
textAlign: 'center',
},
tryAgainButton: {
marginTop: 20,
padding: 10,
},
tryAgainText: {
color: COLORS.secondary,
},
});
export const App: React.FC = () => {
const webViewRef = useRef<WebView>(null);
const [webViewLoaded, setWebViewLoaded] = useState(false);
const [webViewNavigationState, setWebViewNavigationState] = useState<WebViewNavigation | null>(
null,
);
const handleTryAgainButtonPress = (): void => webViewRef.current?.reload();
// When using hardware back button in landing or home page on Android, exit the app.
// Otherwise navigate back in the webview.
// https://reactnative.dev/docs/backhandler#pattern
const backAction = useCallback((): boolean => {
if (
webViewNavigationState?.url &&
[SOURCE, `${SOURCE}/home`].includes(webViewNavigationState?.url)
) {
return false;
}
webViewRef.current?.goBack();
return true;
}, [webViewNavigationState?.url]);
const handleNotificationOpened = ({ data }: RemoteMessage): void =>
webViewRef.current?.postMessage(JSON.stringify({ key: 'NOTIFICATION_OPENED', data }));
const handleLoadProgress = (e: WebViewProgressEvent): void => {
if (e.nativeEvent.progress === 1) {
setWebViewLoaded(true);
}
};
useEffect(() => {
RNBootSplash.hide({ fade: true }); // https://github.com/zoontek/react-native-bootsplash#usage
// Request push notification permission on iOS: https://rnfirebase.io/messaging/usage#ios---requesting-permissions
messaging().requestPermission();
// Tell web app which view should be opened.
messaging().onNotificationOpenedApp(handleNotificationOpened);
// @ts-ignore: `BackHandler` expects `boolean | void | null` type for the event handler return type.
BackHandler.addEventListener('hardwareBackPress', backAction);
// @ts-ignore: Same as above.
return (): void => BackHandler.removeEventListener('hardwareBackPress', backAction);
}, [backAction]);
// When opening app from quit state by clicking a notification, wait until the webview has loaded.
useEffect(() => {
(async () => {
if (webViewLoaded) {
const message = await messaging().getInitialNotification();
if (message) {
handleNotificationOpened(message);
}
}
})();
}, [webViewLoaded]);
const handleMessage = async ({ nativeEvent: { data } }: WebViewMessageEvent): Promise<void> => {
try {
const { key, payload } = JSON.parse(data);
if (key === 'SHARE') {
if (Platform.OS === 'android') {
await Share.share(payload);
}
}
} catch {
// Data was not JSON.
if (data === 'GET_FCM_TOKEN') {
const token = await messaging().getToken();
webViewRef.current?.postMessage(JSON.stringify({ key: 'REGISTER_FCM_TOKEN', token }));
}
}
};
const renderLoading = () => (
<SafeAreaView style={styles.container}>
<ActivityIndicator size="large" color={COLORS.secondary} />
</SafeAreaView>
);
const renderError = () => (
<SafeAreaView style={styles.container}>
<Text style={styles.header}>Offline</Text>
<Text style={styles.text}>
Make sure you have a valid internet connection and try again in a moment.
</Text>
<TouchableOpacity style={styles.tryAgainButton} onPress={handleTryAgainButtonPress}>
<Text style={styles.tryAgainText}>Try Again</Text>
</TouchableOpacity>
</SafeAreaView>
);
return (
<WebView
ref={webViewRef}
userAgent={USER_AGENT}
source={{ uri: SOURCE }}
allowsBackForwardNavigationGestures // Enable back/forward gestures on iOS.
decelerationRate="normal" // Enable smooth scrolling on iOS.
onMessage={handleMessage}
onLoadProgress={handleLoadProgress}
startInLoadingState
renderLoading={renderLoading}
renderError={renderError}
onNavigationStateChange={setWebViewNavigationState}
/>
);
};