-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.tsx
More file actions
392 lines (350 loc) · 9.83 KB
/
App.tsx
File metadata and controls
392 lines (350 loc) · 9.83 KB
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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
/**
*
*
* PGStore
* https://predictgroup.com
*
*
* @format
*/
import {Asset} from 'expo-asset';
import Constants from 'expo-constants';
import * as SplashScreen from 'expo-splash-screen';
import {RootSiblingParent} from 'react-native-root-siblings';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/lib/integration/react';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {store, persistor} from './src/config/configureStore';
import AsyncStorage from '@react-native-async-storage/async-storage';
import auth from '@react-native-firebase/auth';
import {
InitialState,
NavigationContainer,
NavigationContext,
NavigationRouteContext,
} from '@react-navigation/native';
import {navigationRef} from './src/components/nav/AppNavigation';
import AuthContext from './src/components/auth/AuthContext';
import {useAppDispatch} from './src/hooks';
import * as React from 'react';
import {useState, useEffect, useCallback, useRef, useMemo} from 'react';
import {
Animated,
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
Image,
} from 'react-native';
import {
Provider as PaperProvider,
DarkTheme,
DefaultTheme,
Snackbar,
Button,
Paragraph,
Dialog,
Portal,
withTheme,
} from 'react-native-paper';
import styles_other from './src/config/styles';
import Auth from './src/Auth';
import Main from './src/Main';
import logoImage from './images/logo.png';
const logoImageUri = Image.resolveAssetSource(logoImage).uri;
// Instruct SplashScreen not to hide yet, we want to do this manually
SplashScreen.preventAutoHideAsync().catch(() => {
/* reloading the app might trigger some race conditions, ignore them */
});
const CustomDarkTheme: ReactNativePaper.Theme = {
...DarkTheme,
colors: {
...DarkTheme.colors,
},
fonts: {
...DarkTheme.fonts,
},
animation: {
...DarkTheme.animation,
},
};
const CustomDefaultTheme = {
...DefaultTheme,
colors: {
...DefaultTheme.colors,
primary: '#53B175',
background: '#ffffff', // plum
accent: '#5383EC',
text: '#222233',
disabled: '#F2F3F2',
//backdrop: '#D8D8D8',
},
roundness: 8,
fonts: {
...DefaultTheme.fonts,
regular: {
fontWeight: 'normal',
},
},
animation: {
...DefaultTheme.animation,
},
...styles_other,
};
const PreferencesContext = React.createContext<any>(null);
export default function App() {
return (
<AnimatedAppLoader image={logoImageUri}>
<MainScreen />
</AnimatedAppLoader>
);
}
function AnimatedAppLoader({children, image}) {
const [isSplashReady, setSplashReady] = useState(true);
// useEffect(() => {
// async function prepare() {
// await Asset.fromModule(image.uri).downloadAsync().then(({ uri }) => {
// console.log('Finished downloading to ', uri);
// })
// .catch(error => {
// console.error(error);
// }); //fromURI
// setSplashReady(true);
// }
// prepare();
// }, [image]);
// if (!isSplashReady) {
// return null;
// }
return <AnimatedSplashScreen image={image}>{children}</AnimatedSplashScreen>;
}
function AnimatedSplashScreen({children, image}) {
const animation = useMemo(() => new Animated.Value(1), []);
const [isAppReady, setAppReady] = useState(false);
const [isSplashAnimationComplete, setAnimationComplete] = useState(false);
useEffect(() => {
if (isAppReady) {
Animated.timing(animation, {
toValue: 0,
duration: 500,
useNativeDriver: true,
}).start(() => setAnimationComplete(true));
}
}, [isAppReady]);
const onImageLoaded = useCallback(async () => {
try {
await SplashScreen.hideAsync();
// Load stuff
await Promise.all([]);
} catch (e) {
// handle errors
} finally {
setAppReady(true);
}
}, []);
return (
<View style={{flex: 1}}>
{isAppReady && children}
{!isSplashAnimationComplete && (
<Animated.View
pointerEvents="none"
style={[
StyleSheet.absoluteFill,
{
backgroundColor: '#fff',
opacity: animation,
},
]}>
<Animated.Image
style={{
width: '100%',
height: '100%',
resizeMode: 'contain',
transform: [
{
scale: animation,
},
],
}}
source={{ uri: logoImageUri }}
onLoadEnd={onImageLoaded}
fadeDuration={0}
/>
</Animated.View>
)}
</View>
);
}
type State = {
isLoading: boolean;
isSignout: boolean;
userToken: undefined | string;
};
type Action =
| {type: 'RESTORE_TOKEN'; token: undefined | string}
| {type: 'SIGN_IN'; token: string}
| {type: 'SIGN_OUT'};
const PERSISTENCE_KEY = 'NAVIGATION_STATE';
function MainScreen() {
const [theme, setTheme] =
React.useState<ReactNativePaper.Theme>(CustomDefaultTheme);
const [initialState, setInitialState] = React.useState<
InitialState | undefined
>();
const [isReady, setIsReady] = React.useState(false);
const routeNameRef = React.useRef();
const preferences = React.useMemo(
() => ({
toggleTheme: () => {
setTheme(theme =>
theme === CustomDefaultTheme ? CustomDarkTheme : CustomDefaultTheme,
);
},
theme,
}),
[theme],
);
const [state, dispatch] = React.useReducer<React.Reducer<State, Action>>(
(prevState, action) => {
switch (action.type) {
case 'RESTORE_TOKEN':
return {
...prevState,
userToken: action.token,
isLoading: false,
};
case 'SIGN_IN':
return {
...prevState,
isSignout: false,
userToken: action.token,
};
case 'SIGN_OUT':
return {
...prevState,
isSignout: true,
userToken: undefined,
};
}
},
{
isLoading: true,
isSignout: false,
userToken: undefined,
},
);
// Handle user state changes
function onAuthStateChanged(user) {
if (user) {
//console.log("onAuthStateChanged: ", user.providerData)
if (user.providerData[0].providerId === 'password') {
if (user.emailVerified) {
dispatch({type: 'SIGN_IN', token: 'dummy-auth-token'});
} else {
dispatch({type: 'SIGN_OUT'});
}
} else {
dispatch({type: 'SIGN_IN', token: 'dummy-auth-token'});
}
} else {
//dispatch({type: 'RESTORE_TOKEN', token: 'dummy-auth-token'}); // для теста изменить для статуса "авторизован"
dispatch({type: 'SIGN_OUT'});
} //token: 'dummy-auth-token' / undefined
//console.log("onAuthStateChanged: ", user, state.userToken);
}
React.useEffect(() => {
// const timer = setTimeout(() => {
// dispatch({type: 'RESTORE_TOKEN', token: undefined});
// }, 1000);
// return () => clearTimeout(timer);
let user = auth().currentUser;
if (user) {
//console.log('useEffect: ', user);
user.reload(); // refresh user data
user = auth().currentUser;
if(!user){
dispatch({type: 'SIGN_OUT'});
}
} else {
//console.log('useEffect: SIGN_OUT');
dispatch({type: 'SIGN_OUT'});
}
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
const isSignedIn = state.userToken !== undefined;
const authContext = React.useMemo(
() => ({
isSignedIn,
signIn: () => dispatch({type: 'SIGN_IN', token: 'dummy-auth-token'}),
signOut: () => dispatch({type: 'SIGN_OUT'}),
}),
[isSignedIn],
);
React.useEffect(() => {
const restoreState = async () => {
try {
const state = await AsyncStorage.getItem(PERSISTENCE_KEY)
.then(savedStateString => {
return JSON.parse(savedStateString);
})
.then(json => {
if (json) {
setInitialState(json);
//console.log("Set initial State: ", json);
}
});
} catch (e) {
// ignore error
console.log('Initial State error: ', e);
} finally {
setIsReady(true);
}
};
if (!isReady) {
restoreState();
}
}, [isReady]);
if (!isReady) {
return null;
}
return (
<Provider store={store}>
<RootSiblingParent>
<PersistGate loading={null} persistor={persistor}>
<SafeAreaProvider>
<PaperProvider theme={theme}>
<PreferencesContext.Provider value={preferences}>
<AuthContext.Provider value={authContext}>
<NavigationContainer
ref={navigationRef}
initialState={initialState}
onReady={() => {
routeNameRef.current =
navigationRef.current.getCurrentRoute().name;
}}
onStateChange={async state => {
const previousRouteName = routeNameRef.current;
const currentRouteName =
navigationRef.current.getCurrentRoute().name;
// analytics here
routeNameRef.current = currentRouteName;
await AsyncStorage.setItem(
PERSISTENCE_KEY,
JSON.stringify(state),
);
}}>
{!isSignedIn ? <Auth></Auth> : <Main></Main>}
</NavigationContainer>
</AuthContext.Provider>
</PreferencesContext.Provider>
</PaperProvider>
</SafeAreaProvider>
</PersistGate>
</RootSiblingParent>
</Provider>
);
}