/
withNavigationPreventDuplicate.js
71 lines (59 loc) · 1.94 KB
/
withNavigationPreventDuplicate.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
import deepDiffer from 'react-native/lib/deepDiffer'
import {
NavigationActions,
StateUtils,
} from 'react-navigation'
export const getActiveRouteForState = navigationState => (
navigationState.routes ? (
getActiveRouteForState(navigationState.routes[navigationState.index])
) : (navigationState)
)
export const isEqualRoute = (route1, route2) => {
if (route1.routeName !== route2.routeName) {
return false
}
return !deepDiffer(route1.params, route2.params)
}
export const areDuplicateRoots = (routesStack, nextRouteName) => {
if (routesStack.length > 1 && routesStack[0].routes) {
let duplicateRootFlag = false
routesStack[0].routes.forEach((route) => {
// if next route being navigated to is a tab
// we should not render it because it will
// add another duplicate tabview to the stack
if (route.routeName === nextRouteName) duplicateRootFlag = true
})
return duplicateRootFlag
}
return false
}
const PATTERN_DRAWER_ROUTE_KEY = /^Drawer(Open|Close|Toggle)$/
export const isDrawerRoute = route => PATTERN_DRAWER_ROUTE_KEY.test(route.routeName)
const withNavigationPreventDuplicate = (getStateForAction) => {
const defaultGetStateForAction = getStateForAction
const getStateForActionWithoutDuplicates = (action, state) => {
if (action.type === NavigationActions.NAVIGATE) {
const previousRoute = getActiveRouteForState(StateUtils.back(state))
const currentRoute = getActiveRouteForState(state)
const nextRoute = action
if (
isDrawerRoute(currentRoute) &&
(
isEqualRoute(previousRoute, nextRoute) ||
areDuplicateRoots(state.routes, nextRoute.routeName)
)
) {
return StateUtils.back(state) // Close drawer
}
if (
isEqualRoute(currentRoute, nextRoute) ||
areDuplicateRoots(state.routes, nextRoute.routeName)
) {
return null
}
}
return defaultGetStateForAction(action, state)
}
return getStateForActionWithoutDuplicates
}
export default withNavigationPreventDuplicate