-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathApp.tsx
481 lines (378 loc) · 14.3 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
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
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import React, { useEffect, useState } from 'react';
import {
ApplicationProvider,
IconRegistry,
Layout,
Icon,
IconProps
} from '@ui-kitten/components';
import { ActionSheetProvider } from '@expo/react-native-action-sheet';
import * as eva from '@eva-design/eva';
import { EvaIconsPack } from '@ui-kitten/eva-icons';
import AsyncStorage from '@react-native-community/async-storage';
import { styles } from './styles/styles';
import { List } from './views/List';
import { AddToWallet } from './components/AddToWallet';
import { TrainingMode } from './views/TrainingMode';
import { customTheme } from './utils/customTheme';
import { ChallengeMode } from './views/ChallengeMode';
import { InfoView } from './views/InfoView';
import SafeArea, { SafeAreaInsets } from 'react-native-safe-area';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { NavigationContainer } from '@react-navigation/native';
import { DebugMode } from './views/DebugMode';
// this needs to be updated everytime a change in the words database is released
const DB_VERSION = '5';
const SQLite = require( 'react-native-sqlite-storage' );
const okCallback = () => {
console.log( 'connected to DB' );
};
const errorCallback = ( error: any ) => {
console.log( 'DB connection error', error );
};
const db = SQLite.openDatabase( { name: 'dictionary.db', createFromLocation: 1 }, okCallback, errorCallback );
const okDeletionCallback = () => {
console.log( 'I deleted the database' );
SQLite.openDatabase( { name: 'dictionary.db', createFromLocation: 1 }, okCallback, errorCallback );
};
const errorDeletionCallback = ( error: any ) => {
console.log( 'Error while deleting DB', error );
};
export const AddWordIcon = ( props: IconProps ) => (
<Icon { ...props } name='plus-outline' />
);
export const dbRefresh = () => {
SQLite.deleteDatabase( { name: 'dictionary.db', createFromLocation: 1 }, okDeletionCallback, errorDeletionCallback );
};
export type TSingleWord = {
de: string,
en: string,
wordType: string // TODO: we can be more specific here with types
}
export type TSingleWalletWord = TSingleWord & { dateAdded: number }
export type TWords = ReadonlyArray<TSingleWord>
export type TWordsWallet = ReadonlyArray<TSingleWalletWord>
export type TSingleCard = TSingleWord & { mastered: boolean };
export type TCards = TSingleCard[]
export type TDeck = {
id: number,
name: string,
createdTimestamp: number,
updatedTimestamp: number,
cards: TCards
};
export type TDecks = ReadonlyArray<TDeck>;
export type TEnrichedDecks = TDeck[];
type TAppData = {
wordsWallet: TWordsWallet;
decksData: TDecks;
selectedIndex: number;
hasShownAnimation: boolean;
deviceNotchSize: number;
db: any; // TODO: not sure if we can type here
customNavigate: ( route: string ) => void;
setHasShownAnimation: ( value: boolean ) => void;
onMenuClick: ( index: number ) => void;
setWordsWallet: ( value: TWordsWallet ) => void;
setDecksData: ( value: TDecks ) => void;
storeData: ( value: TWordsWallet ) => Promise<void>;
storeDecksData: ( value: TDecks ) => Promise<void>;
addSingleWord: ( word: TSingleWord ) => void;
addSingleDeck: ( deck: TDeck ) => void;
updateSingleDeck: ( deck: TDeck, deckKey: number ) => void;
markWordAsMastered: ( word: TSingleWord, deckKey: number, isMastered: boolean ) => void;
removeSingleDeck: ( deckKey: number ) => void;
increaseTapsCount: () => void;
};
export const AppContext = React.createContext( {} as TAppData );
const setHasShownAnimation = ( value: boolean ) => {
hasShownAnimation = value;
};
export const storeDBversion = async ( version: string ) => {
try {
await AsyncStorage.setItem( '@dbVersion', version );
} catch ( e ) {
console.error( 'Error:', e );
}
};
export const navigationRef = React.createRef() as any; // TODO: type
const customNavigate = ( route: string ) => {
navigationRef.current?.navigate( route );
};
// eslint-disable-next-line @typescript-eslint/no-unused-vars
let rerenderCount = 0;
// here I'm defining all the variables that don't actually need to be in the state
let hasShownAnimation = true;
//let isDecksDataUpdated = false;
let dbVersionWasChecked = false;
export const enrichDecksWithPlaceholder = ( decks: TEnrichedDecks ): TDecks => {
const DECKS_EXTRA = {
id: -1,
name: '__ADD_PLACEHOLDER__',
createdTimestamp: 1609757292,
updatedTimestamp: 1609757492,
cards: []
};
decks.push( DECKS_EXTRA );
return decks;
};
export default () => {
const [ selectedIndex, setSelectedIndex ] = useState( 0 );
const currentRouteObj = navigationRef.current?.getCurrentRoute();
const currentRoute = currentRouteObj?.name;
const [ tapsCount, setTapsCount ] = React.useState( 0 );
const increaseTapsCount = () => {
setTapsCount( tapsCount + 1 );
};
useEffect( () => {
if ( tapsCount >= 10 && currentRoute !== 'debug' ){
customNavigate( 'debug' );
}
}, [ tapsCount, currentRoute ] );
const WALLET_INITIAL_STATE = [
{
de: '__LOADING__WALLET__',
en: '__LOADING__WALLET__',
wordType: '__LOADING__WALLET__',
dateAdded: 0
}
];
const [ wordsWallet, setWordsWallet ] = React.useState( WALLET_INITIAL_STATE as TWordsWallet );
const [ decksData, setDecksData ] = React.useState( [] as any );
useEffect( () => {
const getDecksData = async () => {
try {
const value = await AsyncStorage.getItem( '@decks' );
if ( value !== null ) {
const dataAsArr = JSON.parse( value );
setDecksData( enrichDecksWithPlaceholder( dataAsArr ) );
}
else {
setDecksData( enrichDecksWithPlaceholder( [] ) );
}
} catch ( e ) {
// error reading value
}
};
getDecksData();
}, [] );
useEffect( () => {
const getData = async () => {
try {
const value = await AsyncStorage.getItem( '@wordsWallet' );
const derivedValue = value || JSON.stringify( [] );
setWordsWallet( JSON.parse( derivedValue ) );
} catch ( e ) {
// error reading value
}
};
getData();
}, [] );
const [ deviceNotchSize, setDeviceNotchSize ] = React.useState( 0 );
SafeArea.getSafeAreaInsetsForRootView()
.then( ( result: any ) => {
const safeAreaInsets: SafeAreaInsets = result.safeAreaInsets;
setDeviceNotchSize( safeAreaInsets.bottom );
} );
const storeData = async ( value: TWordsWallet ) => {
try {
const jsonValue = JSON.stringify( value );
await AsyncStorage.setItem( '@wordsWallet', jsonValue );
} catch ( e ) {
console.error( 'Error:', e );
}
};
const storeDecksData = async ( value: TDecks ) => {
try {
const jsonValue = JSON.stringify( value );
await AsyncStorage.setItem( '@decks', jsonValue );
} catch ( e ) {
console.error( 'Error:', e );
}
};
const addSingleWord = ( word: TSingleWord ) => {
const walletCopy = [...wordsWallet ];
const wordWithCurrentTimestamp = {
...word,
dateAdded: ( new Date() ).getTime()
};
walletCopy.unshift( wordWithCurrentTimestamp );
setHasShownAnimation( false );
storeData( walletCopy ).then( () => {
setWordsWallet( walletCopy );
} );
onMenuClick( 0 );
};
const addSingleDeck = ( deckData: TDeck ) => {
const decksClone = decksData.slice();
// removing the add placeholder row
decksClone.splice( -1, 1 );
decksClone.push( deckData );
storeDecksData( decksClone ).then( () => {
setDecksData( enrichDecksWithPlaceholder( decksClone ) );
} );
};
const updateSingleDeck = ( deckData: TDeck, deckKey: number ) => {
const decksClone = decksData.slice();
// removing the add placeholder row
decksClone.splice( -1, 1 );
decksClone[ deckKey ] = deckData;
storeDecksData( decksClone ).then( () => {
setDecksData( enrichDecksWithPlaceholder( decksClone ) );
} );
};
const markWordAsMastered = ( word: TSingleWord, deckKey: number, isMastered: boolean ) => {
const currentDeck = decksData.find( ( deck: TDeck ) => deck.id === deckKey );
const deckClone = { ...currentDeck } as TDeck;
const wordToUpdate = deckClone.cards.find( ( card ) => card.de === word.de && card.en === word.en );
wordToUpdate ? wordToUpdate.mastered = isMastered : null;
const decksClone = decksData.slice();
// removing the add placeholder row
decksClone.splice( -1, 1 );
decksClone[deckKey] = decksClone;
storeDecksData( decksClone ).then( () => {
setDecksData( enrichDecksWithPlaceholder( decksClone ) );
} );
};
const removeSingleDeck = ( deckKey: number ) => {
const decksClone = decksData.slice();
// removing the add placeholder row
decksClone.splice( -1, 1 );
// removing the specified key
decksClone.splice( deckKey, 1 );
storeDecksData( decksClone ).then( () => {
setDecksData( enrichDecksWithPlaceholder( decksClone ) );
} );
};
const setDbVersionWasChecked = ( newVal: boolean ) => {
dbVersionWasChecked = newVal;
};
const getDBversion = async () => {
setDbVersionWasChecked( true );
try {
const version = await AsyncStorage.getItem( '@dbVersion' );
if ( version !== DB_VERSION ) {
dbRefresh();
storeDBversion( DB_VERSION );
}
} catch ( e ) {
// error reading value
}
};
useEffect( () => {
if ( !dbVersionWasChecked ) {
getDBversion();
}
} );
const onMenuClick = ( index: number ) => {
switch ( index ) {
case 0:
default:
customNavigate( 'list' );
break;
case 1:
customNavigate( 'training-mode' );
break;
case 2:
customNavigate( 'add' );
break;
case 3:
customNavigate( 'challenge-mode' );
break;
case 4:
customNavigate( 'info' );
break;
}
setSelectedIndex( index );
setTapsCount( 0 );
};
const appData: TAppData = {
wordsWallet,
decksData,
selectedIndex,
hasShownAnimation,
db,
deviceNotchSize,
customNavigate,
setHasShownAnimation,
onMenuClick,
setWordsWallet,
setDecksData,
storeData,
storeDecksData,
addSingleDeck,
updateSingleDeck,
markWordAsMastered,
removeSingleDeck,
addSingleWord,
increaseTapsCount
};
const Tab = createBottomTabNavigator();
// uncomment this to debug the number of re-renders
// rerenderCount++;
// console.log( 'Re-render count: ', rerenderCount );
return (
<NavigationContainer ref={ navigationRef }>
<IconRegistry icons={ EvaIconsPack } />
<ApplicationProvider { ...eva } theme={ customTheme }>
<ActionSheetProvider>
<AppContext.Provider value={ appData }>
<Layout style={ styles.stackNavigatorWrapper } >
<Tab.Navigator
tabBarOptions={ {
showLabel: false,
style: {
height: 0
}
} }
>
<Tab.Screen
name='list'
component={ List }
options={ {
tabBarVisible: false
} }
/>
<Tab.Screen
name='training-mode'
component={ TrainingMode }
options={ {
tabBarVisible: false
} }
/>
<Tab.Screen
name='challenge-mode'
component={ ChallengeMode }
options={ {
tabBarVisible: false
} }
/>
<Tab.Screen
name='add'
component={ AddToWallet }
options={ {
tabBarVisible: false
} }
/>
<Tab.Screen
name='info'
component={ InfoView }
options={ {
tabBarVisible: false
} }
/>
<Tab.Screen
name='debug'
component={ DebugMode }
options={ {
tabBarVisible: false
} }
/>
</Tab.Navigator>
</Layout>
</AppContext.Provider>
</ActionSheetProvider>
</ApplicationProvider>
</NavigationContainer>
);
};